text:
"""
    dictionary(ds)

A dictionary of the variables `name` and `long_name` attributes.

Useful for development, `dictionary(ds)` allows me to provide shortcuts — and a
friendlier interface — for accessing GEOTRACES variables.
"""
function dictionary(ds::Dataset)
    Dict((k, longname(var)) for (k,var) in ds)
end

# Not all variables have a `long_name` attribute, so replace by ? if it's not there.
longname(var) = haskey(var.attrib,"long_name") ? var.attrib["long_name"] : "?"

# TODO check these are still useful
isconcentration(var) = occursin("CONC", longname(var))
isdissolvedconcentration(var) = occursin("D_CONC", longname(var))
islowleveldissolvedconcentration(var) = occursin("LL_D_CONC", longname(var))
isstandarddeviation(var) = occursin("Standard deviation", longname(var))

"""
    matchingvariables(ds::Dataset, str::String)

Lists names of variables that have `str` in their `long_name` attribute.
"""
function matchingvariables(ds::Dataset, str::String)
    return [p for p in dictionary(ds) if occursin(Regex(str, "i"), p[2])]
end

variable(ds::Dataset, tracer::String) = println(ds[varname(tracer)])

# Special treatment for metadata

metadatakeyvaluepair(v, idx) = @match name(v) begin
    "metavar1"  => (:cruise => reduce.(string, filter.(!=('\0'), eachcol(v.var[:,:])))[[i.I[2] for i in idx]])
    "metavar2"  => (:station => string.(reduce.(string, filter.(!=('\0'), eachcol(v.var[:,:])))[[i.I[2] for i in idx]]))
    "longitude" => (:lon => float.(v.var[[i.I[2] for i in idx]]))
    "latitude"  => (:lat => float.(v.var[[i.I[2] for i in idx]]))
    "var2"      => (:depth => unitfunction(v.attrib["units"]).(float.(v.var[idx])))
    "var1"      => (:pressure => unitfunction(v.attrib["units"]).(float.(v.var[idx])))
    "date_time" => (:date => DateTime.(v[[i.I[2] for i in idx]]))
    _           => (Symbol(name(v)) => float.(v.var[idx]))
end

"""
    varname(tracer)

Returns the GEOTRACES variable name that "matches" `tracer`.
"""
varname(tracer::String) = @match lowercase(tracer) begin
    "cruise"                                                              => "metavar1"
    "station"                                                             => "metavar2"
    "lat" || "latitude"                                                   => "latitude"
    "lon" || "longitude"                                                  => "longitude"
    "pressure"                                                            => "var1"
    "depth" || "depths"                                                   => "var2"
    "date" || "datetime" || "date/time" || "date and time" || "date time" => "date_time"
    "he" || "helium"                                                      => "var22"
    "o2" || "o₂" || "oxygen" || "dioxygen"                                => "var35"
    "p" || "po₄" || "po4" || "phosphate"                                  => "var37"
    "no₃" || "no3" || "nitrate"                                           => "var40"
    "si" || "si(oh)₄" || "silicate"                                       => "var39"
    "cd" || "cadmium"                                                     => "var85"
    "δcd" || "δ¹¹⁰cd" || "δ110cd" || "δcadmium"                           => "var158"
    "fe" || "iron" || "dissolved iron" || "dfe"                           => "var88"
    "δfe" || "δ⁵⁴fe" || "δ54fe" || "δiron"                                => "var160"
    "ni" || "nickel"                                                      => "var104"
    "nd" || "neodymium"                                                   => "var259"
    "end" || "εnd" || "eneodymium" || "εneodymium"                        => "var251"
    "v" || "vanadium"                                                     => "var109"
    _ => tracer
end

"""
    isotope(tracer)

Returns the GEOTRACES variable name of the isotope of tracer `str`.
"""
isotope(tracer::String) = @match lowercase(tracer) begin
    "cd" || "cadmium"       => "δcd"
    "fe" || "iron" || "dfe" => "δfe"
    _ => str
end
export isotope

"""
    stdvarname(tracer)

Returns the GEOTRACES variable name of the standard deviation of tracer `str`.
"""
stdvarname(tracer::String) = string(varname(tracer), "_STD")

"""
    qcvarname(tracer)

Returns the GEOTRACES variable name of the quality control of tracer `str`.
"""
qcvarname(tracer::String) = string(varname(tracer), "_qc")

# TODO add units
# - cell
# - TU
unitfunction(str::String) = @match str begin
    "degrees_east"                       => identity
    "degrees_north"                      => identity
    "days since 0006-01-01 00:00:00 UTC" => x -> Day(x) + DateTime(6,1,1,0,0,0)
    "dbar"                               => x -> x * u"dbar"
    "m"                                  => x -> x * u"m"
    "deg C"                              => x -> x * u"°C"
    "pmol/kg"                            => x -> x * u"pmol/kg"
    "fmol/kg"                            => x -> x * u"fmol/kg"
    "nmol/kg"                            => x -> x * u"nmol/kg"
    "umol/kg"                            => x -> x * u"μmol/kg"
    "per mil" || "per 10^3"              => x -> x * u"permille"
    "TU"                                 => x -> x * 0.118u"Bq/L"
    "per 10000" || "per 10^4"            => x -> x * u"pertenthousand"
    "uBq/kg"                             => x -> x * u"μBq/kg"
    "mBq/kg"                             => x -> x * u"mBq/kg"
    "atoms/kg"                           => x -> x * u"1/kg"
    "l"                                  => x -> x * u"L"
    "nmol P/kg"                          => x -> x * u"nmol/kg"
    "umol C/kg"                          => x -> x * u"μmol/kg"
    "nmol N/kg"                          => x -> x * u"nmol/kg"
    "nmol Si/kg"                         => x -> x * u"nmol/kg"
    "ug/kg"                              => x -> x * u"μg/kg"
    "ng/liter"                           => x -> x * u"μg/L"
    "um^3"                               => x -> x * u"μm^3"
    "amol/cell"                          => x -> x * u"amol"
    "fmol/cell"                          => x -> x * u"fmol"
    "fmol/liter"                         => x -> x * u"fmol/L"
end


text:
# @everywhere module_dir = "/Users/brandonbehring/Desktop/Leap_Frog_2019"
# @everywhere push!(LOAD_PATH, "/Users/brandonbehring/Desktop/Leap_Frog_2019")
# # @everywhere module_dir ="/Users/brandonbehring/Desktop/Leap_Frog_2019"
# # @everywhere push!(LOAD_PATH, $module_dir)
# # @everywhere thisDir = dirname(@__FILE__())
# # @everywhere any(path -> path == thisDir, LOAD_PATH) || push!(LOAD_PATH, thisDir)
# include("escape.jl")
# @everywhere using .escape

using ProgressMeter
using Printf
using MATLAB
include("escape.jl")

@everywhere begin
    include("escape.jl")
    push!(LOAD_PATH, "/Users/brandonbehring/Desktop/Leap_Frog_2019")
    # push!(LOAD_PATH, "/home/brandon_behring/Desktop/Leap_Frog_2019")
    using ProgressMeter
    using Printf
    using MATLAB
    using .escape
    t_end = 1e3
    width = 3; height = 1.5
    n_iter_Q = 40;n_iter_P = 80;N = n_iter_P * n_iter_Q;
    ArrP = range(-width, stop = width, length = n_iter_P)
    ArrQ = range(-height, stop = height, length = n_iter_Q)
    mesh = [(Q, P) for Q in ArrQ, P in ArrP]
    mesh_list = reshape(mesh, 1, :)
    t_end = t_end * ones(N);
    max_hits = 5 * ones(N);

    H = range(.24, stop = 0.3, length = 3)
    # location = "/mnt/bdd38f66-9ece-451a-b915-952523c139d2/Escape/"

    count = 1
end

while count <= length(H)
    println(count)
    println(H[count])
    @everywhere Energy = H[count] * ones(N)
    @everywhere h = replace(@sprintf("%.13f",H[count]), "." => "_")
    @everywhere file_name = "Escape_" * h * ".fig"
    println(file_name)
    num_until_exit = @showprogress pmap(escape.escape_exit_function_parallel, mesh_list, t_end, Energy)

    @everywhere begin
        Q_0 = zeros(0);P_0 = zeros(0)
        Q_1 = zeros(0);P_1 = zeros(0)
        Q_2 = zeros(0);P_2 = zeros(0)
        Q_3 = zeros(0);P_3 = zeros(0)
        Q_4 = zeros(0);P_4 = zeros(0)
        Q_5 = zeros(0);P_5 = zeros(0)
    end
    for i = 1:N
        Q, P = mesh_list[i]
        if num_until_exit[i] == 0
            push!(Q_0, Q)
            push!(P_0, P)
        elseif num_until_exit[i] == 1
            push!(Q_1, Q)
            push!(P_1, P)
        elseif num_until_exit[i] == 2
            push!(Q_2, Q)
            push!(P_2, P)
        elseif num_until_exit[i] == 3
            push!(Q_3, Q)
            push!(P_3, P)
        elseif num_until_exit[i] == 4
            push!(Q_4, Q)
            push!(P_4, P)
        elseif num_until_exit[i] == 5
            push!(Q_5, Q)
            push!(P_5, P)
        end
    end

    mat"figure(); hold on;"
    mat"axis([ -$width,$width,-$height,$height ])"
    mat"plot($P_0,$Q_0 ,'b.','MarkerSize',3)"
    mat"plot($P_1,$Q_1 ,'r.','MarkerSize',3)"
    mat"plot($P_2,$Q_2 ,'g.','MarkerSize',3)"
    mat"plot($P_4,$Q_4 ,'c.','MarkerSize',3)"
    mat"plot($P_5,$Q_5 ,'y.','MarkerSize',3)"
    mat"savefig($file_name)"
    @everywhere global count += 1
end

ext: jl


text:
# Test of binary heaps

using DataStructures
using Base.Test

# test make heap

vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
h = binary_minheap(vs)

@test length(h) == 10
@test !isempty(h)
@test top(h) == 1
@test isequal(h.valtree, [1, 2, 3, 4, 7, 9, 10, 14, 8, 16])

h = binary_maxheap(vs)

@test length(h) == 10
@test !isempty(h)
@test top(h) == 16
@test isequal(h.valtree, [16, 14, 10, 8, 7, 3, 9, 1, 4, 2])

# test push!

hmin = binary_minheap(Int)
@test length(hmin) == 0
@test isempty(hmin)

ss = {
    [4],
    [1, 4],
    [1, 4, 3],
    [1, 2, 3, 4],
    [1, 2, 3, 4, 16],
    [1, 2, 3, 4, 16, 9],
    [1, 2, 3, 4, 16, 9, 10],
    [1, 2, 3, 4, 16, 9, 10, 14],
    [1, 2, 3, 4, 16, 9, 10, 14, 8],
    [1, 2, 3, 4, 7, 9, 10, 14, 8, 16]}

for i = 1 : length(vs)
    push!(hmin, vs[i])
    @test length(hmin) == i
    @test !isempty(hmin)
    @test isequal(hmin.valtree, ss[i])
end

hmax = binary_maxheap(Int)
@test length(hmax) == 0
@test isempty(hmax)

ss = {
    [4],
    [4, 1],
    [4, 1, 3],
    [4, 2, 3, 1],
    [16, 4, 3, 1, 2],
    [16, 4, 9, 1, 2, 3],
    [16, 4, 10, 1, 2, 3, 9],
    [16, 14, 10, 4, 2, 3, 9, 1],
    [16, 14, 10, 8, 2, 3, 9, 1, 4],
    [16, 14, 10, 8, 7, 3, 9, 1, 4, 2]}

for i = 1 : length(vs)
    push!(hmax, vs[i])
    @test length(hmax) == i
    @test !isempty(hmax)
    @test isequal(hmax.valtree, ss[i])
end

# test pop!

@test isequal(extract_all!(hmin), [1, 2, 3, 4, 7, 8, 9, 10, 14, 16])
@test isempty(hmin)

@test isequal(extract_all!(hmax), [16, 14, 10, 9, 8, 7, 4, 3, 2, 1])
@test isempty(hmax)

# test hybrid add! and pop!

h = binary_minheap(Int)

push!(h, 5)
push!(h, 10)
@test isequal(h.valtree, [5, 10])

@test pop!(h) == 5
@test isequal(h.valtree, [10])

push!(h, 7)
push!(h, 2)
@test isequal(h.valtree, [2, 10, 7])

@test pop!(h) == 2
@test isequal(h.valtree, [7, 10])


text:
"""
Tools for computational aeroacoustics (preprocessing, calculations, and
postprocessing) developed at BYU's FLOW lab.

    # AUTHORSHIP
      * Author    : Eduardo J. Alvarez and Tyler Critchfield
      * Email     : Edo.AlvarezR@gmail.com
      * Created   : Nov 2019
      * License   : MIT
"""
module FLOWNoise

# ------------ FLOW CODES ------------------------------------------------------
# GeometricTools https://github.com/byuflowlab/GeometricTools.jl
import GeometricTools
gt = GeometricTools

# FLOWMath https://github.com/byuflowlab/FLOWMath.jl
import FLOWMath
math = FLOWMath

# ------------ GENERIC MODULES -------------------------------------------------
import FFTW
import WAV
import PyPlot.LaTeXStrings: @L_str
import PyPlot
import Dates
import DataFrames
import CSV
import LinearAlgebra: norm, dot, cross, I
import Statistics: mean
import Base: read
using Printf

# Plot Format
const plt = PyPlot
plt.rc("font", family="Times New Roman")            # Text font
plt.rc("mathtext", fontset="stix")                  # Math font
SMALL_SIZE = 12
MEDIUM_SIZE = 14
BIGGER_SIZE = 16
plt.rc("font", size=SMALL_SIZE)          # controls default text sizes
plt.rc("axes", titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc("axes", labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc("xtick", labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc("ytick", labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc("legend", fontsize=SMALL_SIZE)    # legend fontsize
plt.rc("figure", titlesize=BIGGER_SIZE)  # fontsize of the figure title

# ------------ GLOBAL VARIABLES ------------------------------------------------
const module_path = splitdir(@__FILE__)[1]                # Path to this module

const def_datasets_psw = Dict()     # Stores PSW data in this dictionary by default
const def_datasets_bpm = Dict()     # Stores BPM data in this dictionary by default

# ------------ HEADERS ---------------------------------------------------------
# Load headers
for module_name in ["observer", "wopwop", "wav", "processing",
                    "timedomain", "freqdomain", "postprocessing"]
    include("FLOWNoise_"*module_name*".jl")
end

function read(io, T, n)
    return [read(io, T) for i in 1:n]
end

# ---------- 1/3 Octave Bands --------------------
const fc_oto1 = [1, 1.25, 1.6, 2.0, 2.5, 3.15, 4, 5, 6.3, 8]     # (Hz) band center frequencies
const fc_oto = vcat(fc_oto1, fc_oto1*10, fc_oto1*100, fc_oto1*1000, fc_oto1*10000, 1e5)

const flow_oto1 = [0.88, 1.13, 1.414, 1.76, 2.25, 2.825, 3.53, 4.4, 5.65, 7.07] # (Hz) lower bound of 1/3-oct bins
const flow_oto = vcat(flow_oto1, flow_oto1*10, flow_oto1*100, flow_oto1*1000, flow_oto1*10000, 0.88e5)

const fhi_oto1 = [1.13, 1.414, 1.76, 2.25, 2.825, 3.53, 4.4, 5.65, 7.07, 8.8] # (Hz) upper bound of 1/3-oct bins
const fhi_oto = vcat(fhi_oto1, fhi_oto1*10, fhi_oto1*100, fhi_oto1*1000, fhi_oto1*10000, 1.13e5)

end # END OF MODULE

max_stars_repo_name: byuflowlab/FLOWNoise

max_issues_repo_name: byuflowlab/FLOWNoise

max_forks_repo_name: byuflowlab/FLOWNoise


text:
abstract type AbstractPathState end

include("astar.jl")
include("bellman-ford.jl")
include("dijkstra.jl")
include("floyd-warshall.jl")

"""
    shortest_paths(g, x...; kws...)

Computes shortest paths using Dijkstra's algorithm.
See [`dijkstra_shortest_paths`](ref).
"""
shortest_paths(g::AGraphOrDiGraph, x...; kws...) = dijkstra_shortest_paths(g, x...; kws...)

"""
    enumerate_paths(state::AbstractPathState)
    enumerate_paths(state::AbstractPathState, dest)

Given a path state `state` of type `AbstractPathState` (see below), returns a
vector (indexed by vertex) of the paths between the source vertex used to
compute the path state and a destination vertex `v`, a set of destination
vertices `vs`, or the entire graph. For multiple destination vertices, each
path is represented by a vector of vertices on the path between the source and
the destination. Nonexistent paths will be indicated by an empty vector. For
single destinations, the path is represented by a single vector of vertices,
and will be length 0 if the path does not exist.

For Floyd-Warshall path states, please note that the output is a bit different,
since this algorithm calculates all shortest paths for all pairs of vertices:
`enumerate_paths(state)` will return a vector (indexed by source vertex) of
vectors (indexed by destination vertex) of paths. `enumerate_paths(state, v)`
will return a vector (indexed by destination vertex) of paths from source `v`
to all other vertices. In addition, `enumerate_paths(state, v, d)` will return
a vector representing the path from vertex `v` to vertex `d`.
"""
enumerate_paths(state::AbstractPathState, dest) = enumerate_paths(state, [dest])[1]
enumerate_paths(state::AbstractPathState) = enumerate_paths(state, [1:length(state.parents);])

function enumerate_paths(state::AbstractPathState, dest::Vector{V}) where V
    parents = state.parents

    num_dest = length(dest)
    all_paths = Vector{Vector{V}}(undef, num_dest)
    for i=1:num_dest
        all_paths[i] = Vector{V}()
        index = dest[i]
        if parents[index] != 0 || parents[index] == index
            while parents[index] != 0
                push!(all_paths[i], index)
                index = parents[index]
            end
            push!(all_paths[i], index)
            reverse!(all_paths[i])
        end
    end
    return all_paths
end


text:
# https://pauladamsmith.com/blog/2015/01/how-to-get-started-with-llvm-c-api.html

using Test

using LLVM

if length(ARGS) == 2
    x, y = parse.([Int32], ARGS[1:2])
else
    x = Int32(1)
    y = Int32(2)
end

# set-up
mod = LLVM.Module("my_module")

param_types = [LLVM.Int32Type(), LLVM.Int32Type()]
ret_type = LLVM.Int32Type()
fun_type = LLVM.FunctionType(ret_type, param_types)
sum = LLVM.Function(mod, "sum", fun_type)

# generate IR
Builder() do builder
    entry = BasicBlock(sum, "entry")
    position!(builder, entry)

    tmp = add!(builder, parameters(sum)[1], parameters(sum)[2], "tmp")
    ret!(builder, tmp)

    println(mod)
    verify(mod)
end

# analysis and execution
Interpreter(mod) do engine
    args = [GenericValue(LLVM.Int32Type(), x),
            GenericValue(LLVM.Int32Type(), y)]

    res = LLVM.run(engine, sum, args)
    @test convert(Int, res) == x + y

    dispose.(args)
    dispose(res)
end


text:
## Copyright (c) 2017, Júlio Hoffimann Mendes <juliohm@stanford.edu>
##
## Permission to use, copy, modify, and/or distribute this software for any
## purpose with or without fee is hereby granted, provided that the above
## copyright notice and this permission notice appear in all copies.
##
## THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
## WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
## ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
## ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
## OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

"""
    ImgQuilt(var₁=>param₁, var₂=>param₂, ...)

Image quilting simulation solver as described in Hoffimann et al. 2017.

## Parameters

### Required

* `TI`       - Training image
* `template` - Template size in x, y and z

### Optional

* `overlap`  - Overlap size in x, y and z (default to (1/6, 1/6, 1/6))
* `cut`      - Boundary cut algorithm (:boykov (default) or :dijkstra)
* `path`     - Simulation path (:rasterup (default), :rasterdown, :dilation, or :random)
* `simplex`  - Whether to apply or not the simplex transform (default to false)
* `inactive` - Vector of inactive voxels (i.e. tuples (i,j,k)) in the grid
* `soft`     - A vector of `(data,dataTI)` pairs
* `tol`      - Initial relaxation tolerance in (0,1] (default to 0.1)

## Global parameters

### Optional

* `threads`      - Number of threads in FFT (default to number of physical CPU cores)
* `gpu`          - Whether to use the GPU or the CPU (default to false)
* `showprogress` - Whether to show or not the estimated time duration (default to false)
"""
@simsolver ImgQuilt begin
  @param TI
  @param template
  @param overlap       = (1/6, 1/6, 1/6)
  @param cut           = :boykov
  @param path          = :rasterup
  @param simplex       = false
  @param inactive      = nothing
  @param soft          = []
  @param tol           = .1
  @global threads      = CPU_PHYSICAL_CORES
  @global gpu          = false
  @global showprogress = false
end

function solve_single(problem::SimulationProblem, var::Symbol, solver::ImgQuilt)
  # retrieve problem info
  pdata = data(problem)
  pdomain = domain(problem)

  # sanity checks
  @assert pdomain isa RegularGrid "ImgQuilt solver only supports regular grids"
  @assert ndims(pdomain) ∈ [2,3] "Number of dimensions must be 2 or 3"
  @assert var ∈ keys(solver.params) "Parameters for variable `$var` not found"

  # get user parameters
  varparams = solver.params[var]

  # add ghost dimension to simulation grid if necessary
  sz = ndims(pdomain) == 2 ? (size(pdomain)..., 1) : size(pdomain)

  # create hard data object
  hd = HardData()
  for (loc, datloc) in datamap(problem, var)
    push!(hd, ind2sub(sz, loc) => value(pdata, datloc, var))
  end

  # disable inactive voxels
  shape = HardData()
  if varparams.inactive ≠ nothing
    for icoords in varparams.inactive
      push!(shape, icoords => NaN)
    end
  end

  # run image quilting core function
  reals = iqsim(varparams.TI, varparams.template..., sz...,
                soft=varparams.soft, hard=merge(hd, shape), tol=varparams.tol,
                cut=varparams.cut, path=varparams.path, simplex=varparams.simplex,
                threads=solver.threads, gpu=solver.gpu, showprogress=solver.showprogress)

  # return result
  reals[1][:]
end


text:
module Uncertainty

# adding methods to
import Base: promote_rule, convert, show, sqrt, +, *, -, /, ^, .*, ./, .^, ==, log, log10, exp, isapprox, signif

type Uncertain{T<:Number}
    v::T # value
    u::T # uncertainty standard deviation
end
Uncertain_(v,u) = u >= 0 ? Uncertain(v,u) : error("Uncertain(v=$v, u=$u) u>=0 required")
correlation(x::Uncertain,y::Uncertain) = 0.0
covariance(x::Uncertain,y::Uncertain)  = 0.0
Uncertain(x::Number, y::Number) = Uncertain(convert(AbstractFloat, x), convert(AbstractFloat, y))
Uncertain(x::Number) = Uncertain(x, convert(typeof(x), 0))

quadsum_neg(x::Number...) = sqrt(sum(sign([x...]).*([x...].^2)))
+(x::Uncertain, y::Uncertain) = Uncertain_(x.v+y.v, quadsum_neg(x.u,+y.u,covariance(x,y)))
+(x::Uncertain, y::Number) = x+Uncertain(y)
+(x::Number, y::Uncertain) = Uncertain(x)+y
-(x::Uncertain) = Uncertain(-x.v, x.u)
-(x::Uncertain, y::Uncertain) = x + -y
-(x::Uncertain, y::Number) = x-Uncertain(y)
-(x::Number, y::Uncertain) = Uncertain(x)-y
*(x::Uncertain, y::Uncertain) = (v = x.v*y.v; Uncertain_(v, v*quadsum_neg(x.u/x.v, y.u/y.v, 2*x.u*y.u*correlation(x,y)/(x.v*y.v))))
*(x::Uncertain, y::Number) = x*Uncertain(y)
*(x::Number, y::Uncertain) = Uncertain(x)*y
/(x::Uncertain, y::Uncertain) = (v = x.v/y.v; Uncertain_(v, v*quadsum_neg(x.u/x.v, y.u/y.v, -2*x.u*y.u*correlation(x,y)/(x.v*y.v))))
/(x::Uncertain, y::Number) = x/Uncertain(y)
/(x::Number, y::Uncertain) = Uncertain(x)/y
log(x::Uncertain) = (v = log(x.v); Uncertain_(v, x.u/x.v))
log(::Irrational{:e},x::Uncertain) = log(x)
log(base::Number, x::Uncertain) = (v = log(base,x.v); Uncertain_(v, x.u/(x.v*log(base))))
log10(x::Uncertain) = log(10, x)
^(x::Uncertain, y::Uncertain) = error("x^y with both ::Uncertain not implemented, don't know formula")
^(x::Uncertain, y::Integer) = (v = x.v^convert(AbstractFloat,y); Uncertain_(v, abs(v*y*x.u/x.v)))
^(x::Uncertain, y::Rational) = (v = x.v^convert(AbstractFloat,y); Uncertain_(v, abs(v*y*x.u/x.v)))
^(x::Uncertain, y::Number) = (v = x.v^y; Uncertain_(v, abs(v*y*x.u/x.v)))
^{T<:AbstractFloat}(x::Irrational{:e}, y::Uncertain{T}) = exp(y)
^{s,T<:AbstractFloat}(x::Irrational{s}, y::Uncertain{T}) = convert(T, eval(s))^y
^(x::Number, y::Uncertain) = (v = x^y.v; Uncertain_(v, abs(v*log(x)*y.u)))
exp(x::Uncertain) = (v = exp(x.v); Uncertain_(v, abs(v*x.u)))
^{T<:Number}(x::Irrational{:e},y::Uncertain{T}) = exp(y)
==(x::Uncertain, y::Uncertain) = ==(x.v,y.v) && ==(x.u,y.u)
isapprox(x::Uncertain, y::Uncertain) = isapprox(x.v, y.v) && isapprox(x.u, y.u)

promote_rule{T<:AbstractFloat, S<:AbstractFloat}(::Type{Uncertain{T}}, ::Type{Uncertain{S}}) = Uncertain{promote_type(T,S)}

convert{T<:AbstractFloat, S<:AbstractFloat}(::Type{Uncertain{T}}, x::Uncertain{S}) = Uncertain(convert(T,x.v), convert(T,x.u))
#convert(::Type{Uncertain{BigFloat}}, x::Uncertain) = Uncertain(convert(BigFloat, x.v), convert(BigFloat,x.u))

function show(io::IO, x::Uncertain)
	v, u = sprintf_signif(x)
    print(io, v)
    print(io, " ± ")
    print(io, u)
end
n_signif(x::Uncertain) = iceil(log10(x.v/x.u))
signif(x::Uncertain) = Uncertain(signif(x.v,n_signif(x)),x.u)

# try to show an appropriate number of significant digits
function sprintf_signif(x::Uncertain)
	n = n_signif(x)
	n <= 1 ? (return repr(x.v), repr(x.u)) : 0
	after_dec = iceil(-log10(x.u))
	if after_dec <= 0
		v = sprintf("%d", signif(x.v,n))
	elseif after_dec >= -3
		v = sprintf("%0.$(after_dec)f", x.v)
	else
		v = sprintf("%.$(n-1)e",x.v)
	end
	after_dec = iceil(1-log10(x.u))
	if after_dec <= 0
		u = sprintf("%d", signif(x.u,2))
	elseif after_dec <= 3
		u = sprintf("%0.$(after_dec)f", x.u)
	else
		u = sprintf("%.1e", x.u)
	end
	return v,u
end
sprintf(fmt::AbstractString,args...) = @eval @sprintf($fmt,$(args...))
# because of the macro @sprintf its hard to do dynamic precision strings https://groups.google.com/forum/#!msg/julia-dev/P50UdTGKkRI/KCPnQ6LqH44J
# more discussion: https://github.com/JuliaLang/julia/issues/4248#issuecomment-24196846

export Uncertain
end


text:
include("bee_dynamics.jl")

mutable struct ABC <: AbstractParameters
    N::Int
    Ne::Int
    No::Int
    limit::Int
end

"""
    ABC(;
        N = 50,
        Ne = div(N+1, 2),
        No = div(N+1, 2),
        limit=10,
        information = Information(),
        options = Options()
    )

ABC implements the original parameters for the Artificial Bee Colony Algorithm.
`N` is the population size, `Ne` is the number of employees, `No` is the
number of outlookers bees. `limit` is related to the times that a solution
is visited.

# Example

```jldoctest
julia> f(x) = sum(x.^2)
f (generic function with 1 method)

julia> optimize(f, [-1 -1 -1; 1 1 1.0], ABC())
+=========== RESULT ==========+
  iteration: 595
    minimum: 4.03152e-28
  minimizer: [1.489845115451046e-14, 1.2207275971717747e-14, -5.671872444705246e-15]
    f calls: 30020
 total time: 0.0360 s
+============================+

julia> optimize(f, [-1 -1 -1; 1 1 1.0], ABC(N = 80,  No = 20, Ne = 50, limit=5))
+=========== RESULT ==========+
  iteration: 407
    minimum: 8.94719e-08
  minimizer: [8.257485723496422e-5, 0.0002852795196258074, -3.5620824723352315e-5]
    f calls: 30039
 total time: 0.0432 s
+============================+
```

"""
function ABC(;
        N = 50,
        Ne = div(N+1, 2),
        No = div(N+1, 2),
        limit=10,
        information = Information(),
        options = Options()
    )

    parameters = ABC(N, Ne, No, limit)

    Algorithm(
        parameters,
        information = information,
        options = options,
    )

end

function initialize!(
        status,
        parameters::ABC,
        problem,
        information,
        options,
        args...;
        kargs...
    )

    D = size(problem.bounds, 2)

    if options.f_calls_limit == 0
        options.f_calls_limit = 10000D
        options.iterations = parameters.N + 10000D ÷ parameters.N
        options.debug && @info "Increasing f calls limit to $(options.f_calls_limit)"
    end

    bees = initialbees(parameters.N, problem)
    nevals = length(bees)

    best_sol = deepcopy(getBestBee(bees))
    population = bees
    f_calls = nevals

    return State(best_sol, population; f_calls = f_calls)
end

function update_state!(
        status,#::State{Bee},
        parameters::ABC,
        problem,
        information,
        options,
        args...;
        kargs...
    )

    D = size(problem.bounds, 2)
    fobj = problem.f
    bees = status.population
    Ne = parameters.Ne
    No = parameters.No
    bounds = problem.bounds
    a = view(bounds, 1,:)
    b = view(bounds, 2,:)

    employedPhase!(bees,problem,  Ne)
    outlookerPhase!(bees,problem, No)

    @inline genPos(D=D, a=Array(a), b = Array(b)) = a + (b - a) .* rand(D)
    best = chooseBest(bees, status.best_sol)

    status.f_calls += Ne + No + scoutPhase!(bees, problem, genPos, parameters.limit)
    status.best_sol = best
    stop_criteria!(status, parameters, problem, information, options)

end

function final_stage!(
        status,#::State{Bee{xf_indiv}},
        parameters::ABC,
        problem::AbstractProblem,
        information::Information,
        options::Options,
        args...;
        kargs...
    )
    status.final_time = time()
    # status.population = map(b -> b.sol, status.population)
    # status.best_sol = status.best_sol.sol
end

is_better_abc(bee1, bee2) = is_better(bee1.sol, bee2.sol)

function stop_criteria!(
        status,#::State{Bee},
        parameters::ABC,
        problem::AbstractProblem,
        information::Information,
        options::Options,
        args...;
        kargs...
    )
    cond_budget = call_limit_stop_check(status, information, options) ||
                  iteration_stop_check(status, information, options)

    if cond_budget
        return true
    end

    cond = !isnan(information.f_optimum) &&
           abs(status.best_sol.sol.f - information.f_optimum) < options.f_tol

    options.debug && cond && @info("Stopped since accuracy was met.")
    cond
end


text:
module ForegroundDebris

using ..Ahorn, Maple
using Random

const placements = Ahorn.PlacementDict(
    "Foreground Debris" => Ahorn.EntityPlacement(
        Maple.ForegroundDebris
    )
)

const rockTextures = Dict{String, Array{String, 1}}(
    "rock_a" => [
        "scenery/fgdebris/rock_a00",
        "scenery/fgdebris/rock_a01",
        "scenery/fgdebris/rock_a02"
    ],
    "rock_b" => [
        "scenery/fgdebris/rock_b00",
        "scenery/fgdebris/rock_b01"
    ]
)

function Ahorn.selection(entity::Maple.ForegroundDebris)
    x, y = Ahorn.position(entity)

    return Ahorn.Rectangle(x - 24, y - 24, 48, 48)
end

# Blame parallax for rendering being offset
function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::Maple.ForegroundDebris, room::Maple.Room)
    rng = Ahorn.getSimpleEntityRng(entity)
    key = rand(rng, keys(rockTextures))

    for texture in rockTextures[key]
        Ahorn.drawSprite(ctx, texture, 0, 0)
    end
end

end

max_stars_repo_name: asdfsdfadfasfasd/Ahorn

max_issues_repo_name: asdfsdfadfasfasd/Ahorn

max_forks_repo_name: asdfsdfadfasfasd/Ahorn


text:
module RigidBodyMotions

export RigidBodyMotion, Kinematics, d_dt

using DocStringExtensions
import ForwardDiff
import Base: +, *, -, >>, <<, show

"""
An abstract type for types that takes in time and returns `(ċ, c̈, α̇)`.
"""
abstract type Kinematics end

"""
An abstract type for real-valued functions of time.
"""
abstract type Profile end

"""
    RigidBodyMotion

A type to store the plate's current kinematics

# Fields

- `ċ`: current centroid velocity
- `c̈`: current centroid acceleration
- `α̇`: current angular velocity
- `α̈`: current angular acceleration
- `kin`: a [`Kinematics`](@ref) structure

The first three fields are meant as a cache of the current kinematics
while the `kin` field can be used to find the plate kinematics at any time.
"""
mutable struct RigidBodyMotion
    ċ::ComplexF64
    c̈::ComplexF64
    α̇::Float64
    α̈::Float64

    kin::Kinematics
end

RigidBodyMotion(ċ, α̇) = RigidBodyMotion(complex(ċ), 0.0im, float(α̇), 0.0, Constant(ċ, α̇))
RigidBodyMotion(ċ, c̈, α̇, α̈) = RigidBodyMotion(complex(ċ), complex(c̈), float(α̇), float(α̈), UnsteadyTransRot(ċ, c̈, α̇, α̈))
RigidBodyMotion(kin::Kinematics) = RigidBodyMotion(kin(0)..., kin)
(m::RigidBodyMotion)(t) = m.kin(t)

function show(io::IO, m::RigidBodyMotion)
    println(io, "Rigid Body Motion:")
    println(io, "  ċ = $(round(m.ċ, digits=2))")
    println(io, "  c̈ = $(round(m.c̈, digits=2))")
    println(io, "  α̇ = $(round(m.α̇, digits=2))")
    println(io, "  α̈ = $(round(m.α̈, digits=2))")
    print(io, "  $(m.kin)")
end

#=
Kinematics
=#

struct Constant{C <: Complex, A <: Real} <: Kinematics
    ċ::C
    α̇::A
end
Constant(ċ, α̇) = Constant(complex(ċ), α̇)
(c::Constant{C})(t) where C = c.ċ, zero(C), c.α̇, zero(C)
show(io::IO, c::Constant) = print(io, "Constant (ċ = $(c.ċ), α̇ = $(c.α̇))")

# Define Kinematic structure for unsteady translation and rotation
struct UnsteadyTransRot{C <: Complex, A <: Real} <: Kinematics
    ċ::C
    c̈::C
    α̇::A
    α̈::A
end
UnsteadyTransRot(ċ, c̈, α̇, α̈) = UnsteadyTransRot(complex(ċ), complex(c̈),  α̇, α̈)
(c::UnsteadyTransRot{C})(t) where C = c.ċ, c.c̈, c.α̇ , c.α̈
show(io::IO, c::UnsteadyTransRot) = print(io, "Unsteady translation and rotation  (ċ = $(c.ċ), c̈ = $(c.c̈), α̇ = $(c.α̇ ), α̈ = $(c.α̈)")

"""
    Pitchup <: Kinematics

Kinematics describing a pitchup motion (horizontal translation with rotation)

# Constructors
# Fields
$(FIELDS)
"""
struct Pitchup <: Kinematics
    "Freestream velocity"
    U₀::Float64
    "Axis of rotation, relative to the plate centroid"
    a::Float64

    "Non-dimensional pitch rate ``K = \\dot{\\alpha}_0\\frac{c}{2U_0}``"
    K::Float64

    "Initial angle of attack"
    α₀::Float64
    "Nominal start of pitch up"
    t₀::Float64

    "Total pitching angle"
    Δα::Float64

    α::Profile
    α̇::Profile
    α̈::Profile
end

function Pitchup(U₀, a, K, α₀, t₀, Δα, ramp)
    Δt = 0.5Δα/K
    p = ConstantProfile(α₀) + 2K*((ramp >> t₀) - (ramp >> (t₀ + Δt)))
    ṗ = d_dt(p)
    p̈ = d_dt(ṗ)
    Pitchup(U₀, a, K, α₀, t₀, Δα, p, ṗ, p̈)
end

function (p::Pitchup)(t)
    α = p.α(t)
    α̇ = p.α̇(t)
    α̈ = p.α̈(t)

    ċ = p.U₀ - p.a*im*α̇*exp(im*α)
    if (t - p.t₀) > p.Δα/p.K
        c̈ = 0.0im
    else
        c̈ = p.a*exp(im*α)*(α̇^2 - im*α̈)
    end

    return ċ, c̈, α̇, α̈
end

"""
    PitchHeave <: Kinematics

Kinematics describing an oscillatory pitching and heaving (i.e. plunging) motion

# Constructors
# Fields
$(FIELDS)
"""
struct PitchHeave <: Kinematics
    "Freestream velocity"
    U₀::Float64

    "Axis of pitch rotation, relative to the plate centroid"
    a::Float64

    "Reduced frequency ``K = \\frac{\\Omega c}{2U_0}``"
    K::Float64

    "Phase lag of pitch to heave (in radians)"
    ϕ::Float64

    "Mean angle of attack"
    α₀::Float64

    "Amplitude of pitching"
    Δα::Float64

    "Amplitude of translational heaving"
    A::Float64

    Y::Profile
    Ẏ::Profile
    Ÿ::Profile

    α::Profile
    α̇::Profile
    α̈::Profile
end

function PitchHeave(U₀, a, K, ϕ, α₀, Δα, A)
    p = A*Sinusoid(2K)
    ṗ = d_dt(p)
    p̈ = d_dt(ṗ)
    Δt = ϕ/(2K)
    α = ConstantProfile(α₀) + Δα*(Sinusoid(2K) >> Δt)
    α̇ = d_dt(α)
    α̈ = d_dt(α̇)
    PitchHeave(U₀, a, K, ϕ, α₀, Δα, A, p, ṗ, p̈, α, α̇, α̈)
end

function (p::PitchHeave)(t)
    α = p.α(t)
    α̇ = p.α̇(t)
    α̈ = p.α̈(t)

    # c will be update in the integration
    ċ = p.U₀ + im*p.Ẏ(t) - p.a*im*α̇*exp(im*α)
    c̈ = im*p.Ÿ(t) + p.a*exp(im*α)*(α̇^2 - im*α̈)

    return ċ, c̈, α̇, α̈
end

#=
Profiles
=#

"""
    ConstantProfile(c::Number)

Create a profile consisting of a constant `c`.

# Example

```jldoctest
julia> p = RigidBodyMotions.ConstantProfile(1.0)
Constant (1.0)
```
"""
struct ConstantProfile <: Profile
    c::Number
end

function show(io::IO, p::ConstantProfile)
    print(io, "Constant ($(p.c))")
end

(p::ConstantProfile)(t) = p.c

struct DerivativeProfile{P} <: Profile
    p::P
end

function show(io::IO, ṗ::DerivativeProfile)
    print(io, "d/dt ($(ṗ.p))")
end

(ṗ::DerivativeProfile)(t) = ForwardDiff.derivative(ṗ.p, t)

"""
    d_dt(p::Profile)

Take the time derivative of `p` and return it as a new profile.

# Example

```jldoctest
julia> s = RigidBodyMotions.Sinusoid(π)
Sinusoid (ω = 3.14)

julia> s.([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 0.0
 1.0
 0.7071067811865476

julia> c = RigidBodyMotions.d_dt(s)
d/dt (Sinusoid (ω = 3.14))

julia> c.([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
  3.141592653589793
  1.9236706937217898e-16
 -2.221441469079183

```
"""
d_dt(p::Profile) = DerivativeProfile(p)

struct ScaledProfile{N <: Real, P <: Profile} <: Profile
    s::N
    p::P
end
function show(io::IO, p::ScaledProfile)
    print(io, "$(p.s) × ($(p.p))")
end

"""
    s::Number * p::Profile

Returns a scaled profile with `(s*p)(t) = s*p(t)`

# Example

```jldoctest
julia> s = RigidBodyMotions.Sinusoid(π)
Sinusoid (ω = 3.14)

julia> 2s
2 × (Sinusoid (ω = 3.14))

julia> (2s).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 0.0
 2.0
 1.4142135623730951

```
"""
s::Number * p::Profile = ScaledProfile(s, p)

"""
    -(p₁::Profile, p₂::Profile)

```jldoctest
julia> s = RigidBodyMotions.Sinusoid(π)
Sinusoid (ω = 3.14)

julia> 2s
2 × (Sinusoid (ω = 3.14))

julia> (2s).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 0.0
 2.0
 1.4142135623730951

julia> s = RigidBodyMotions.Sinusoid(π);

julia> s.([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 0.0
 1.0
 0.7071067811865476

julia> (-s).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 -0.0
 -1.0
 -0.7071067811865476

julia> (s - s).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 0.0
 0.0
 0.0
```
"""
-(p::Profile) = ScaledProfile(-1, p)
(p::ScaledProfile)(t) = p.s*p.p(t)

struct ShiftedProfile{N <: Real, P <: Profile} <: Profile
    Δt::N
    p::P
end
function show(io::IO, p::ShiftedProfile)
    print(io, "$(p.p) >> $(p.Δt)")
end

(p::ShiftedProfile)(t) = p.p(t - p.Δt)

"""
    p::Profile >> Δt::Number

Shift the profile in time so that `(p >> Δt)(t) = p(t - Δt)`

# Example

```jldoctest
julia> s = RigidBodyMotions.Sinusoid(π);

julia> s >> 0.5
Sinusoid (ω = 3.14) >> 0.5

julia> (s >> 0.5).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
 -1.0
  0.0
  0.7071067811865475

julia> (s << 0.5).([0.0, 0.5, 0.75])
3-element Array{Float64,1}:
  1.0
  1.2246467991473532e-16
 -0.7071067811865475

```
"""
p::Profile >> Δt::Number = ShiftedProfile(Δt, p)
p::Profile << Δt::Number = ShiftedProfile(-Δt, p)

struct AddedProfiles{T <: Tuple} <: Profile
    ps::T
end
function show(io::IO, Σp::AddedProfiles)
    println(io, "AddedProfiles:")
    for p in Σp.ps
        println(io, "  $p")
    end
end

"""
    p₁::Profile + p₂::Profile

Add the profiles so that `(p₁ + p₂)(t) = p₁(t) + p₂(t)`.

# Examples

```jldoctest
julia> ramp₁ = RigidBodyMotions.EldredgeRamp(5)
logcosh ramp (aₛ = 5.0)

julia> ramp₂ = RigidBodyMotions.ColoniusRamp(5)
power series ramp (n = 5.0)

julia> ramp₁ + ramp₂
AddedProfiles:
  logcosh ramp (aₛ = 5.0)
  power series ramp (n = 5.0)

julia> ramp₁ + (ramp₂ + ramp₁) == ramp₁ + ramp₂ + ramp₁
true

```
"""
+(p::Profile, Σp::AddedProfiles) = AddedProfiles((p, Σp.ps...))
+(Σp::AddedProfiles, p::Profile) = AddedProfiles((Σp.ps..., p))
function +(Σp₁::AddedProfiles, Σp₂::AddedProfiles)
    AddedProfiles((Σp₁..., Σp₂...))
end

-(p₁::Profile, p₂::Profile) = p₁ + (-p₂)

+(p::Profile...) = AddedProfiles(p)

function (Σp::AddedProfiles)(t)
    f = 0.0
    for p in Σp.ps
        f += p(t)
    end
    f
end

struct Sinusoid <: Profile
    ω::Float64
end
(s::Sinusoid)(t) = sin(s.ω*t)
show(io::IO, s::Sinusoid) = print(io, "Sinusoid (ω = $(round(s.ω, digits=2)))")

struct EldredgeRamp <: Profile
    aₛ::Float64
end
(r::EldredgeRamp)(t) = 0.5(log(2cosh(r.aₛ*t)) + r.aₛ*t)/r.aₛ
show(io::IO, r::EldredgeRamp) = print(io, "logcosh ramp (aₛ = $(round(r.aₛ, digits=2)))")

struct ColoniusRamp <: Profile
    n::Int
end
function (r::ColoniusRamp)(t)
    Δt = t + 0.5
    if Δt ≤ 0
        0.0
    elseif Δt ≥ 1
        Δt - 0.5
    else
        f = 0.0
        for j = 0:r.n
            f += binomial(r.n + j, j)*(r.n - j + 1)*(1 - Δt)^j
        end
        f*Δt^(r.n + 2)/(2r.n + 2)
    end
end
show(io::IO, r::ColoniusRamp) = print(io, "power series ramp (n = $(round(r.n, digits=2)))")

end


text:
mutable struct GeneralLinearLeastSquares
  a::Vector{Float64}
  err::Vector{Float64}
  residuals::Vector{Float64}
  standardErrors::Vector{Float64}
end

function GeneralLinearLeastSquares(x::Vector{Float64}, y::Vector{Float64}, v::Vector{T}) where {T}
  n = length(v)

  a = zeros(n)
  err = zeros(n)
  residuals = zeros(length(y))
  standardErrors = zeros(n)
  glls = GeneralLinearLeastSquares(a, err, residuals, standardErrors)
  calculate!(glls, x, y, v)

  return glls
end

function calculate!(glls::GeneralLinearLeastSquares, x::Vector{Float64}, y::Vector{Float64}, v::Vector{T}) where {T}
  n = length(glls.residuals)
  m = length(glls.err)

  A = zeros(n, m)

  @inbounds @simd for i in eachindex(v)
    A[:, i] = map(v[i], x)
  end

  svdA = svd(A)
  V = svdA.V
  U = svdA.U
  w = svdA.S
  # svdA = SVD(A)
  # V = svdA.V
  # U = svdA.U
  # w = svdA.s
  threshold = n * eps()
  @inbounds @simd for i in eachindex(w)
    if w[i] > threshold
      u = dot(U[:, i], y) / w[i]
      @inbounds for j in eachindex(glls.a)
        glls.a[j] += u * V[j, i]
        glls.err[j] += V[j, i] * V[j, i] / (w[i] * w[i])
      end
    end
  end
  # println(glls.a)
  # error("DIE")
  glls.err = sqrt.(glls.err)
  tmp = A * glls.a
  glls.residuals = tmp - y

  chiSq = dot(glls.residuals, glls.residuals)

  glls.standardErrors = glls.err * sqrt(chiSq / (n - 2))

  return glls
end

get_coefficients(glls::GeneralLinearLeastSquares) = glls.a


text:
#Figure 5.4, 5.5
using Plots, SparseArrays, JLD2, LinearAlgebra, MultiscaleGraphSignalTransforms

JLD2.@load "../data/spie_data.jld2"
matrix = vars["barbara"]

#face
row_zoom = 1:180
col_zoom = 330:450

#right leg
row_zoom = 300:512
col_zoom = 400:512

#full image
row_zoom = 1:512
col_zoom = 1:512

heatmap(matrix[row_zoom, col_zoom],ratio=1, yaxis =:flip, axis = false, color = :grays)
#savefig("original.pdf")

### initialize the regular balanced binary partition and compute the expanding coefficients
dmatrix, GProws, GPcols = ghwt_tf_init_2d_Lindberg(matrix)

### Compute the coefficients of different basis we will compare
############# Haar
BS_haar_rows = bs_haar(GProws)
BS_haar_cols = bs_haar(GPcols)
dvec_haar, loc_haar = BS2loc(dmatrix, GProws, GPcols, BS_haar_rows, BS_haar_cols)

############# Walsh
BS_walsh_rows = bs_walsh(GProws)
BS_walsh_cols = bs_walsh(GPcols)
dvec_walsh, loc_walsh = BS2loc(dmatrix, GProws, GPcols, BS_walsh_rows, BS_walsh_cols)

############# GHWT (i.e., regular haar-walsh wavelet packet dictionary)
fcols, jmax_col = size(GProws.tag);
frows, jmax_row = size(GPcols.tag);
dmatrix_rows = reshape(dmatrix, (frows, jmax_row, fcols*jmax_col))
dmatrix_cols = Array{Float64,3}(reshape(dmatrix',(fcols, jmax_col, frows*jmax_row)))
############# c2f bestbasis
dvec_c2f_rows, BS_c2f_rows = ghwt_c2f_bestbasis(dmatrix_rows, GProws)
dvec_c2f_cols, BS_c2f_cols = ghwt_c2f_bestbasis(dmatrix_cols, GPcols)
dvec_c2f, loc_c2f = BS2loc(dmatrix, GProws, GPcols, BS_c2f_rows, BS_c2f_cols)

############# f2c bestbasis
dvec_f2c_rows, BS_f2c_rows = ghwt_f2c_bestbasis(dmatrix_rows, GProws)
dvec_f2c_cols, BS_f2c_cols = ghwt_f2c_bestbasis(dmatrix_cols, GPcols)
dvec_f2c, loc_f2c = BS2loc(dmatrix, GProws, GPcols, BS_f2c_rows, BS_f2c_cols)

#############

##################### tf bestbasis
dvec_tf, loc_tf = ghwt_tf_bestbasis_2d(matrix, GProws, GPcols)

################################################################################
##################### Visualize the results of synthesis########################
################################################################################

### function to plot the image synthesized by top p vectors
function top_vectors_synthesis_2d(p::Int64, dvec::Vector{Float64}, loc::Matrix{Int64}, GProws::GraphPart, GPcols::GraphPart, dmatrix::Matrix{Float64})
    sorted_dvec = sort(abs.(dvec[:]), rev = true)
    dvecT = copy(dvec)
    dvecT[abs.(dvec) .< sorted_dvec[p]].= 0

    matrix_syn = ghwt_tf_synthesis_2d(dvecT, loc, GProws, GPcols)
    heatmap(matrix_syn[row_zoom, col_zoom],ratio=1, yaxis =:flip, axis = false, color = :grays)
    mse = norm(matrix - matrix_syn,2)^2/length(matrix)
    psnr = -10*log10(mse)
    return psnr
end

################################################################################
percent = 1/32;
p = Int64(floor(percent*length(matrix)))

### haar
# Figure 5.4(a)
top_vectors_synthesis_2d(p, dvec_haar, loc_haar, GProws, GPcols, dmatrix)
#savefig("synthesis_haar_1_32.pdf")

### walsh
top_vectors_synthesis_2d(p, dvec_walsh, loc_walsh, GProws, GPcols, dmatrix)
#savefig("synthesis_walsh_1_32.pdf")

### c2f
# Figure 5.4(b)
top_vectors_synthesis_2d(p, dvec_c2f, loc_c2f, GProws, GPcols, dmatrix)
#savefig("synthesis_c2f_1_32.pdf")

### f2c
# Figure 5.4(c)
top_vectors_synthesis_2d(p, dvec_f2c, loc_f2c, GProws, GPcols, dmatrix)
#savefig("synthesis_f2c_1_32.pdf")

### tf
# Figure 5.4(d)
top_vectors_synthesis_2d(p, dvec_tf, loc_tf, GProws, GPcols, dmatrix)
#savefig("synthesis_tf_1_32.pdf")

# To generate Figure 5.5, just change the row_zoom, and col_zoom at the head of this file.

################################################################################
####################### Approximation error plot################################
################################################################################
function approx_error(DVEC::Array{Array{Float64,1},1})
    plot(xaxis = "Fraction of Coefficients Retained", yaxis = "Relative Approximation Error")
    frac = 0:0.01:0.3
    T = ["Haar","Walsh","GHWT_c2f", "GHWT_f2c", "eGHWT"]
    L = [(:dashdot,:orange),(:dashdot,:blue),(:solid, :red),(:solid, :green),(:solid, :black)]
    for i = 1:5
        dvec = DVEC[i]
        N = length(dvec)
        dvec_norm = norm(dvec,2)
        dvec_sort = sort(dvec.^2, rev = true)

        er = fill(0., length(frac))

        for j = 1:length(frac)
            p = Int64(floor(frac[j]*N))
            er[j] = sqrt(dvec_norm^2 - sum(dvec_sort[1:p]))/dvec_norm
        end

        plot!(frac, er, yaxis=:log, xlims = (0.,0.3), label = T[i], line = L[i])
    end
end

approx_error([dvec_haar, dvec_walsh, dvec_c2f, dvec_f2c, dvec_tf])
current()

#################
### Generate the relative l2 error when approximating by 1/32 coefficients
################
DVEC = [dvec_haar, dvec_walsh, dvec_c2f, dvec_f2c, dvec_tf];
for i = 1:5
    dvec = DVEC[i]
    N = length(dvec)
    dvec_norm = norm(dvec,2)
    dvec_sort = sort(dvec.^2, rev = true)
    p = Int64(floor(N./32))
    print(sqrt(dvec_norm^2 - sum(dvec_sort[1:p]))/dvec_norm)
end


text:
using MambaModels

## Data
line = Dict{Symbol, Any}()

df = DataFrame(CSV.read(joinpath(@__DIR__, "..", "..", "data", "Howell1.csv"),
  delim=';'));

# Use only adults

df2 = filter(row -> row[:age] >= 18, df);
mean_weight = mean(df2[:, :weight])
df2[!, :weight_c] = convert(Vector{Float64}, df2[:, :weight]) .- mean_weight ;
line[:x] = df2[:, :weight_c];
line[:y] = df2[:, :height];
line[:xmat] = convert(Array{Float64, 2}, [ones(length(line[:x])) line[:x]])

# Model Specification

model = Model(
  y = Stochastic(1,
    (xmat, beta, s2) -> MvNormal(xmat * beta, sqrt(s2)),
    false
  ),
  beta = Stochastic(1, () -> MvNormal([178, 0], [sqrt(10000), sqrt(100)])),
  s2 = Stochastic(() -> Uniform(0, 50))
)

# Initial Values

inits = [
  Dict{Symbol, Any}(
    :y => line[:y],
    :beta => [rand(Normal(178, 100)), rand(Normal(0, 10))],
    :s2 => rand(Uniform(0, 50))
  )
  for i in 1:3
]

# Tuning Parameters

scale1 = [0.5, 0.25]
summary1 = identity
eps1 = 0.5

scale2 = 0.5
summary2 = x -> [mean(x); sqrt(var(x))]
eps2 = 0.1

# Define sampling scheme

scheme = [
  Mamba.NUTS([:beta]),
  Mamba.Slice([:s2], 10)
]

setsamplers!(model, scheme)

# MCMC Simulation

chn = mcmc(model, line, inits, 10000, burnin=1000, chains=3)

# Show draws summary

describe(chn)

# Convert to MCMCChains.Chains object

chn2 = MCMCChains.Chains(chn.value, String.(chn.names))

# Describe the MCMCChains

MCMCChains.describe(chn2)

# End of `04/m4.1m.jl`


text:
# License for this file: MIT (expat)
# Copyright 2017-2021, DLR Institute of System Dynamics and Control
#
# This file is part of module
#   Modia3D.Composition (Modia3D/Composition/_module.jl)
#

"""
    obj = Fix(; obj1, obj2, translation=zeros(3), rotation=zeros(3))

Rigidly fix `obj2::`[`Object3D`](@ref) relatively to
`obj1::`[`Object3D`](@ref) via the relative position vector `translation` from
`obj1` to `obj2` (resolved in `obj1`) and the relative orientation angles
`rotation` from `obj1` to `obj2`.

Return `obj=obj1`, if `obj2` is directly or indirectly
connected to the `world` Object3D. Otherwise, return `obj=obj2`.

# Arguments
- `obj1::Object3D`: Parent object.

- `obj2::Object3D`: Object fixed relative to `obj1`.

- `r::AbstractVector`: Relative position vector from `obj1` to `obj2`
   resolved in `obj1`.

- `rot::AbstractVector`: Relative orientation from `obj1` to `obj2`
   in [Cardan (Tait–Bryan) angles](https://en.wikipedia.org/wiki/Euler_angles#Chained_rotations_equivalence)
   (rotation sequence x-y-z).
"""
function Fix(; obj1::Object3D,
               obj2::Object3D,
               translation::AbstractVector = Modia3D.ZeroVector3D,
               rotation::AbstractVector    = Modia3D.ZeroVector3D)::Object3D

    (parent, child, cutJoint) = attach(obj1, obj2)
    if cutJoint
        error("\nError from Fix joint connecting ", Modia3D.fullName(obj1), " with ", Modia3D.fullName(obj2), ":",
              "\nThis joint is a cut-joint which is not allowed.")
    end

    r_rel = Modia3D.convertAndStripUnit(SVector{3,Float64}, u"m", translation)
    rot   = Modia3D.convertAndStripUnit(SVector{3,Float64}, u"rad", rotation)

    if obj1 === parent
        # obj1/obj2 = parent/child
        obj2.r_rel      = r_rel
        obj2.jointIndex = 0
        obj2.ndof       = 0

        if rot == Modia3D.ZeroVector3D
            obj2.joint     = FixedTranslationJoint()
            obj2.jointKind = FixTranslationKind
            obj2.R_rel     = Frames.NullRotation
            obj2.R_abs     = obj1.R_abs
            obj2.r_abs     = obj1.r_abs + r_rel
        else
            obj2.joint     = FixedJoint()
            obj2.jointKind = FixKind
            obj2.R_rel     = Frames.rot123(rot[1], rot[2], rot[3])
            obj2.R_abs     = obj2.R_rel*obj1.R_abs
            obj2.r_abs     = obj1.r_abs + obj2.R_abs'*r_rel
        end
        return obj2

    else
        # obj1/obj2 = child/parent
        obj1.jointIndex = 0
        obj1.ndof       = 0

        if rot == Modia3D.ZeroVector3D
            obj1.joint     = FixedTranslationJoint()
            obj1.jointKind = FixTranslationKind
            obj1.R_rel     = Frames.NullRotation
            obj1.R_abs     = obj2.R_abs
            obj1.r_rel     = -r_rel
        else
            obj1.joint     = FixedJoint()
            obj1.jointKind = FixKind
            obj1.R_rel     = Frames.rot123(rot[1], rot[2], rot[3])'
            obj1.R_abs     = obj1.R_rel*obj2.R_abs
            obj1.r_rel     = -obj1.R_rel'*r_rel
            obj1.r_abs     = obj2.r_abs - obj2.R_abs*r_rel
        end
        return obj1
    end
end


text:
function local_update!(model::Ising, T::Real, Js::AbstractArray)
    rng = model.rng
    nsites = numsites(model)
    nbonds = numbonds(model)
    mbeta = -1.0/T

    @inbounds for site in 1:nsites
        center = model.spins[site]
        de = 0.0
        for (n,b) in neighbors(model, site)
            de += 2center * model.spins[n] * Js[bondtype(model,b)]
        end
        if rand(rng) < exp(mbeta*de)
            model.spins[site] *= -1
        end
    end

    return nothing
end

function SW_update!(model::Ising, T::Real, Js::AbstractArray)
    rng = model.rng
    ps = -expm1.((-2.0/T).*Js)
    nsites = numsites(model)
    nbonds = numbonds(model)
    nbt = numbondtypes(model)
    activated_bonds = zeros(Int,nbt)
    uf = UnionFind(nsites)
    @inbounds for bond in bonds(model)
        s1,s2 = source(bond), target(bond)
        bt = bondtype(bond)
        if model.spins[s1] == model.spins[s2] && rand(rng) < ps[bt]
            activated_bonds[bt] += 1
            unify!(uf, s1,s2)
        end
    end
    nc = clusterize!(uf)
    clustersize = zeros(Int, nc)
    clusterspin = rand(rng,[1,-1], nc)

    @inbounds for site in 1:nsites
        id = clusterid(uf, site)
        model.spins[site] = clusterspin[id]
        clustersize[id] += 1
    end
    return SWInfo(activated_bonds, clustersize, clusterspin)
end

function Wolff_update!(model::Ising, T::Real, Js::AbstractArray)
    rng = model.rng
    ps = -expm1.((-2.0/T).*Js)
    nsites = numsites(model)

    clustersize = 0
    st = Stack(Deque{Int}())
    center = rand(rng, 1:nsites)
    sp = model.spins[center]
    model.spins[center] *= -1
    push!(st, center)
    @inbounds while !isempty(st)
        clustersize += 1
        s = pop!(st)
        for (n,b) in neighbors(model, s)
            bt = bondtype(model,b)
            if model.spins[n] == sp && rand(rng) < ps[bt]
                model.spins[n] *= -1
                push!(st, n)
            end
        end
    end

    return nothing
end

@gen_convert_parameter(Ising, ("T", 1, 1.0), ("J", numbondtypes, 1.0))


text:
using Compat
using Docile
import Base.min
import Base.max
import Base.mean
import Base.var
import Base.std
import Base.count
import Base.sum
import Base.haskey
import Base.keys
import Base.values
import Base.show

include("types.jl")
include("aggr.jl")
include("statsaggr.jl")
include("groupby.jl")


text:
###############################################################################
# Code to use poll_fd() instead of sleep() whenever it becomes available
###############################################################################

type MultiCtxt
    s::curl_socket_t    # Socket
    events::Cint # Events to poll for
    timeout_ms::Cint
end

const  UV_READABLE = 1
const  UV_WRITABLE = 2

function curl_socket_cb(curl::Ptr{Void}, s::Cint, action::Cint, p_muctxt::Ptr{Void}, sctxt::Ptr{Void})
    if (action == CURL_POLL_REMOVE)
        # Out-of-order socket fds were causing problems in the case of HTTP redirects
        return 0
    end

    muctxt = unsafe_pointer_to_objref(p_muctxt)

    muctxt.s = s

    if (action == CURL_POLL_NONE)
        muctxt.events = 0

    elseif (action == CURL_POLL_IN)
        muctxt.events = UV_READABLE

    elseif (action == CURL_POLL_OUT)
        muctxt.events = UV_WRITABLE

    elseif (action == CURL_POLL_INOUT)
        muctxt.events = UV_READABLE | UV_WRITABLE

    end

    return 0
end

c_curl_socket_cb = cfunction(curl_socket_cb, Cint, (Ptr{Void}, Cint, Cint, Ptr{Void}, Ptr{Void}))

function curl_multi_timer_cb(curlm::Ptr{Void}, timeout_ms::Clong, p_muctxt::Ptr{Void})
    muctxt = unsafe_pointer_to_objref(p_muctxt)
    muctxt.timeout_ms = timeout_ms

    println("Requested timeout value : " * string(muctxt.timeout_ms))

    return 0
end

c_curl_multi_timer_cb = cfunction(curl_multi_timer_cb, Cint, (Ptr{Void}, Clong, Ptr{Void}))

immutable CURLMsg2
  msg::CURLMSG
  easy_handle::Ptr{CURL}
  data::Ptr{Any}
end

function get2(url, timeout)
    curlm = curl_multi_init()
    curl = 0
    response = nothing

    if (curlm == 0) error("Unable to initialize curl_multi_init()") end

#     try
        (curl, response) = setup_easy_get(url)

        cmc = curl_multi_add_handle(curlm, curl)
        if(cmc != CURLM_OK) error ("curl_multi_add_handle() failed: " * curl_multi_strerror(cmc)) end

        cmc = curl_multi_setopt(curlm, CURLMOPT_SOCKETFUNCTION, c_curl_socket_cb)
        if(cmc != CURLM_OK) error ("curl_multi_setopt() failed: " * curl_multi_strerror(cmc)) end

        cmc = curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, c_curl_multi_timer_cb)
        if(cmc != CURLM_OK) error ("curl_multi_setopt() failed: " * curl_multi_strerror(cmc)) end

        muctxt = MultiCtxt(0,0,0)
        p_muctxt = pointer_from_objref(muctxt)

        cmc = curl_multi_setopt(curlm, CURLMOPT_SOCKETDATA, p_muctxt)
        if(cmc != CURLM_OK) error ("curl_multi_setopt() failed: " * curl_multi_strerror(cmc)) end

        cmc = curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, p_muctxt)
        if(cmc != CURLM_OK) error ("curl_multi_setopt() failed: " * curl_multi_strerror(cmc)) end

        # start the multi session
        n_active = Array(Int32,1)
        curl_multi_socket_action(curlm, CURL_SOCKET_TIMEOUT, 0, n_active)

        n_active[1] = 1
        now  = int(time())
        till = now + timeout + 1
        while (n_active[1] > 0) && ((till - now) > 0)

            evt_got = 0
            if (muctxt.events > 0)
                t1 = int64(time() * 1000)

                @unix_only fd::OS_FD = OS_FD(muctxt.s)
                @windows_only fd::OS_SOCKET = OS_SOCKET(muctxt.s)

                ps_ret = poll_fd(fd, muctxt.events, muctxt.timeout_ms)
                t2 = int64(time() * 1000)
                println("poll_ time : " * string(t2-t1) * " millis, args : " * string((muctxt.events, muctxt.timeout_ms)) * ", ps_ret : " * string(ps_ret))

                if (ps_ret[1] == :poll)
                    if (ps_ret[2] == 0)
                        evt_got = (((ps_ret[3] & UV_READABLE) == UV_READABLE ) ? CURL_CSELECT_IN : 0) | (((ps_ret[3] & UV_WRITEABLE) == UV_WRITEABLE ) ? CURL_CSELECT_OUT : 0)
                    else
                        evt_got = CURL_CSELECT_ERR
                    end
                 end

            else
                println("muctxt.events < 0")
                # Read and print any messages
                msgs_in_queue = Array(Int32,1)
                p_msg::Ptr{CURLMsg2} = curl_multi_info_read(curlm, msgs_in_queue)

                while (p_msg != C_NULL)
                    println("Messages left in Q : " * string(msgs_in_queue[1]))
                    msg = unsafe_ref(p_msg)
                    println("Got message, data : " * string(msg.msg) * "," * string(msg.data))
                    p_msg = curl_multi_info_read(curlm, msgs_in_queue)
                end
            end

            if (evt_got == 0)
                cmc = curl_multi_socket_action(curlm, CURL_SOCKET_TIMEOUT, 0, n_active)
            else
                cmc = curl_multi_socket_action(curlm, muctxt.s, evt_got, n_active)
            end
            if(cmc != CURLM_OK) error ("curl_multi_perform() failed: " * curl_multi_strerror(cmc)) end

            now  = int(time())
        end

        if (n_active[1] == 0)
            process_response(curl, response)
            curlm_cleanup(curlm, curl)
        else
            error ("request timed out")
        end

#     catch e
#         if (curl != 0)
#             curl_multi_remove_handle(curlm, curl)
#             curl_easy_cleanup(curl)
#         end
#
#         curl_multi_cleanup(curlm)
#         throw (string(e))
#     end

    response
end


text:
# these definitions need to be at the top level
@testset "infer unsafe_load" begin
    @eval const a = pointer([42])
    tt = Tuple{typeof(a), typeof(1)}

    @inline @eval dub() = TinyCassette.execute(nothing, unsafe_load, a, 1)

    original_result_type = code_typed(unsafe_load, tt)[1][2]
    overdubbed_result_type = code_typed(dub, Tuple{})[1][2]

    @test original_result_type == overdubbed_result_type

    @code_warntype dub()
end


text:
export
    SynthRule,
    Synthesizer,
    SynthesizerOptions,
    DecodeRule,
    define!,
    dnaSize!,
    resultSize!,
    decodeAsContextArray,
    decode,
    decodeAt

abstract SynthRule

typealias StateDict Dict{Symbol, Any}

immutable DecodePars{C, A, S}
    ctx::C
    dnaFragment::A
    result::A
    resultSeq::S
    state
end

DecodePars{C, A, S}(ctx::C, dnaFragment::A, result::A, resultSeq::S, state) =
    DecodePars{C, A, S}(ctx, dnaFragment, result, resultSeq, state)

immutable DecodeRule{R}
    rule::R
    asContextArray::Bool
end

DecodeRule{R}(rule::R) = DecodeRule{R}(rule, false)

DecodeRule{R}(rule::R, asContextArray::Bool) = DecodeRule{R}(rule, asContextArray)

type Synthesizer{C}
    ctx::C
    rules::Vector{SynthRule}
    _states::Vector{StateDict}
    _dnaSize::Nullable{Int}
    _resultSize::Nullable{Int}
end

function Synthesizer{C}(ctx::C)
    Synthesizer{C}(
        ctx,
        Vector{SynthRule}(),
        Vector{StateDict}(),
        Nullable{Int}(),
        Nullable{Int}())
end

function define!(syn::Synthesizer, rule::SynthRule)
    push!(syn.rules, rule)
    state = StateDict()
    push!(syn._states, state)
    initialize!(rule, syn.ctx, state)
    syn._dnaSize = Nullable{Int}()
    syn._resultSize = Nullable{Int}()
end

function dnaSize!(syn::Synthesizer)
    isnull(syn._dnaSize) && (syn._dnaSize = sum(map(rule -> dnaSize(rule), syn.rules)))
    get(syn._dnaSize)
end

function resultSize!(syn::Synthesizer)
    isnull(syn._resultSize) && (syn._resultSize = sum(map(rule -> resultSize(rule), syn.rules)))
    get(syn._resultSize)
end

function decodeAsContextArray{C}(syn::Synthesizer{C}, dna::DNA{C})
    result = constant(syn.ctx, 0f0, resultSize!(syn))

    dnaBeginIndex = 0
    resultBeginIndex = 0

    ruleIndex = 1
    for rule in syn.rules
        scope!(syn.ctx) do this
            const ruleDnaSize = dnaSize(rule)
            const ruleResultSize = resultSize(rule)
            const dnaEndIndex = dnaBeginIndex + ruleDnaSize - 1
            const resultEndIndex = resultBeginIndex + ruleResultSize - 1

            pars = DecodePars(
                syn.ctx,
                dna.array[seq(syn.ctx, dnaBeginIndex, dnaEndIndex)],
                result,
                seq(syn.ctx, resultBeginIndex, resultEndIndex),
                syn._states[ruleIndex]
            )

            decode(rule, pars)

            dnaBeginIndex += ruleDnaSize
            resultBeginIndex += ruleResultSize
            ruleIndex += 1
        end
    end

    eval!(result)
    result
end

function decode{C}(syn::Synthesizer{C}, dna::DNA{C})
    scope!(syn.ctx) do this
        array = Array(decodeAsContextArray(syn, dna))

        result = Vector()
        outputIndex = 1
        for rule in syn.rules
            for value in asValues(rule, array, outputIndex)
                push!(result, value)
            end
            outputIndex += resultSize(rule)
        end
        result
    end
end

function decodeAt(syn::Synthesizer, array, items)
    all = Vector()
    for item in items
        local rule
        if isa(item.rule, Int)
            rule = syn.rules[item.rule]
        elseif isa(item.rule, SynthRule)
            rule = item.rule
        else
            error("Unknown rule: $(item.rule)")
        end

        outputIndex = 0
        found = false
        for curr in syn.rules
            if curr == rule
                scope!(syn.ctx) do this
                    sub = array[seq(syn.ctx, outputIndex, outputIndex + resultSize(rule) - 1)]
                    if item.asContextArray
                        this.result(sub)
                        push!(all, sub)
                    else
                        subValues = Array(sub)
                        result = Vector()
                        for value in asValues(rule, subValues, 1)
                            push!(result, value)
                        end
                        push!(all, result)
                    end
                end
                found = true
                break
            end
            outputIndex += resultSize(curr)
        end
        found || error("Rule hasn't found: $(item.rule)")
    end
    all
end

max_stars_repo_name: unbornchikken/julia-ml-proto

max_issues_repo_name: unbornchikken/julia-ml-proto

max_forks_repo_name: unbornchikken/julia-ml-proto


text:
#
# Uniform Sampler
#
# parameters:
# 	(1) a (lower bound)
#	(2) b (upper bound)
#

type UniformSampler <: ContinuousDistributionSampler
	paramranges::Vector{Tuple{Float64,Float64}}
	distribution::Union{Distribution,Float64}
	# to handle case where a==b (which raises error in Uniform), we
	# indicate this case by setting distribution to a fixed value
	function UniformSampler(params=Float64[])
		s = new( [(-realmax(Float64), realmax(Float64)), (-realmax(Float64), realmax(Float64))] )
		# rather than defaulting to entire float range, we use a 'pragmatic' (and arbitrary) range of [-1.0, 1.0]
		setparams!(s, isempty(params) ? [-1.0, 1.0] : params)
		s
	end
end

function setparams!(s::UniformSampler, params)
	checkparamranges(s, params)
	# swap parameters if necessary (as a silent repair during search)
	if params[1] <= params[2]
		a, b = params[[1,2]]
	else
		a, b = params[[2,1]]
	end
	# note that Distributions.Uniform samples from closed interval [a,b], but currently raises an error when a==b, temporary workaround:
	if a==b
		s.distribution = b
		# see note in type definition: this is workaround for error raised in Uniform constructor when a==b
	else
		m = robustmidpoint(a,b) # util function that avoids overflow to Inf
		if (m-a) < realmax(Float64)/2
			s.distribution = Uniform(a, b)
		else
			# Uniform only seems to support bounds that are at most realmax apart (returns 0 otherwise), so use a mixture model in other cases
			s.distribution = MixtureModel([Uniform(a,m), Uniform(nextfloat(m),b)])
		end
	end
end

getparams(s::UniformSampler) = typeof(s.distribution) <: Uniform ? [s.distribution.a, s.distribution.b] : [s.distribution, s.distribution]

function sample(s::UniformSampler, support, cc::ChoiceContext)
	x = isa(s.distribution, Float64) ? s.distribution : rand(s.distribution)
	# we return both the sampled value, and a dict as trace information
	x, Dict{Symbol, Any}(:rnd=>x)
end

function estimateparams!(s::UniformSampler, traces)
	samples = extractsamplesfromtraces(s, traces)
	if length(samples) >= 2 # minsamples
		if all(samples.==samples[1])
			# distribution gives error if all samples are the same
			s.distribution = samples[1]
		else
			s.distribution = fit(Uniform, samples)
		end
	end
end


text:
module ForwardDiffOverMeasurements

using ForwardDiff: Dual
using Measurements: Measurement
import Base: +,-,/,*,promote_rule

function promote_rule(::Type{Measurement{V}}, ::Type{Dual{T, V, N}}) where {T,V,N}
    Dual{Measurement{T}, V, N}
end

function promote_rule(::Type{Measurement{V1}}, ::Type{Dual{T, V2, N}}) where {V1<:AbstractFloat, T, V2, N}
    Vx = promote_rule(Measurement{V1},V2)
    return Dual{T , Vx, N}
end

#+
@inline function Base.:+(x::Dual{Tx,V}, y::Measurement{V}) where {Tx,V}
    y = Dual{Tx}(y)
    +(x,y)
end

@inline function Base.:+(x::Measurement{V},y::Dual{Ty,V}) where {V,Ty}
    x = Dual{Ty}(x)
    +(x,y)
end

@inline function Base.:+(x::Dual{Tx}, y::Measurement) where {Tx}
    y = Dual{Tx}(y)
    +(x,y)
end

@inline function Base.:+(x::Measurement,y::Dual{Ty}) where {Ty}
    x = Dual{Ty}(x)
    +(x,y)
end
#-

@inline function Base.:-(x::Dual{Tx,V}, y::Measurement{V}) where {Tx,V}
    y = Dual{Tx}(y)
    -(x,y)
end

@inline function Base.:-(x::Measurement{V},y::Dual{Ty,V}) where {V,Ty}
    x = Dual{Ty}(x)
    -(x,y)
end

@inline function Base.:-(x::Dual{Tx}, y::Measurement) where {Tx}
    y = Dual{Tx}(y)
    -(x,y)
end

@inline function Base.:-(x::Measurement,y::Dual{Ty}) where {Ty}
    x = Dual{Ty}(x)
    -(x,y)
end

#*
@inline function Base.:*(x::Dual{Tx,V}, y::Measurement{V}) where {Tx,V}
    y = Dual{Tx}(y)
    *(x,y)
end

@inline function Base.:*(x::Measurement{V},y::Dual{Ty,V}) where {V,Ty}
    x = Dual{Ty}(x)
    *(x,y)
end

@inline function Base.:*(x::Dual{Tx}, y::Measurement) where {Tx}
    y = Dual{Tx}(y)
    *(x,y)
end

@inline function Base.:*(x::Measurement,y::Dual{Ty}) where {Ty}
    x = Dual{Ty}(x)
    *(x,y)
end

#/
@inline function Base.:/(x::Dual{Tx,V}, y::Measurement{V}) where {Tx,V}
    y = Dual{Tx}(y)
    /(x,y)
end

@inline function Base.:/(x::Measurement{V},y::Dual{Ty,V}) where {V,Ty}
    x = Dual{Ty}(x)
    /(x,y)
end

@inline function Base.:/(x::Dual{Tx}, y::Measurement) where {Tx}
    y = Dual{Tx}(y)
    /(x,y)
end

@inline function Base.:/(x::Measurement,y::Dual{Ty}) where {Ty}
    x = Dual{Ty}(x)
    /(x,y)
end

end #module


text:
@testset "optimizer_accessors.jl" begin
    @testset "MOI.get(::Optimizer, ::MOI.SolverName)" begin
        model = SeaPearl.Optimizer()
        @test MOI.get(model, MOI.SolverName()) == "SeaPearl Solver"
    end
end


text:
"""
  Main API module for AiEmpires.
"""
module AiEmpires

"""
  greet()

  This is an example documentation.
"""
greet() = print("Hello World!")

end # module


text:
module TestOuter

using Test
using SARA
using SARA: get_global_data

@testset "outer loop" begin
    @test true
end

end


text:
## TODO:
##  - general cleanup (API...)
## - remove RJProp

module JLCM

using ProgressMeter
using ArgCheck
using DataFrames
using MCMCDiagnostics
using Statistics
using StatsFuns
using StatsBase
using Parameters
using LinearAlgebra
using Roots
using DataFrames
using Distributions
using Combinatorics
using Distributed
using RCall
using SharedArrays
using DynamicHMC
using TransformVariables

using MCMCChains
using MLDataUtils

using LKJ
using SplineHazard
import SplineHazard.Spline

include("MCMC.jl")
using .MCMC

include("NUTS.jl")
using .NUTSGibbs

import Base: show, size, length, summary

export show, size, length, summary

abstract type AbstractData end
abstract type AbstractParam end
abstract type AbstractFit end
abstract type AbstractPrior end

include("data.jl")
include("spline.jl")
include("param.jl")
include("prior.jl")
include("sampling.jl")
include("mcmc_chains.jl")
include("relabel.jl")
include("summary.jl")
include("cp.jl")
include("survival.jl")
include("predict.jl")
include("ic.jl")
include("xval.jl")
include("nuts_surv.jl")
include("nuts_cov.jl")
include("nuts_mlogit.jl")
include("loglik.jl")

end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

"""
    Generator(f, iter)

Given a function `f` and an iterator `iter`, construct an iterator that yields
the values of `f` applied to the elements of `iter`.
The syntax for constructing an instance of this type is `f(x) for x in iter [if cond(x)::Bool] `.
The `[if cond(x)::Bool]` expression is optional and acts as a "guard", effectively
filtering out values where the condition is false.

```jldoctest
julia> g = (abs2(x) for x in 1:5 if x != 3);

julia> for x in g
           println(x)
       end
1
4
16
25

julia> collect(g)
4-element Array{Int64,1}:
  1
  4
 16
 25
```
"""
struct Generator{I,F}
    f::F
    iter::I
end

Generator(f, I1, I2, Is...) = Generator(a->f(a...), zip(I1, I2, Is...))

Generator(::Type{T}, iter::I) where {T,I} = Generator{I,Type{T}}(T, iter)

Generator(::Type{T}, I1, I2, Is...) where {T} = Generator(a->T(a...), zip(I1, I2, Is...))

function iterate(g::Generator, s...)
    @_inline_meta
    y = iterate(g.iter, s...)
    y === nothing && return nothing
    y = y::Tuple{Any, Any} # try to give inference some idea of what to expect about the behavior of the next line
    return (g.f(y[1]), y[2])
end

length(g::Generator) = length(g.iter)
size(g::Generator) = size(g.iter)
axes(g::Generator) = axes(g.iter)
ndims(g::Generator) = ndims(g.iter)

## iterator traits

abstract type IteratorSize end
struct SizeUnknown <: IteratorSize end
struct HasLength <: IteratorSize end
struct HasShape{N} <: IteratorSize end
struct IsInfinite <: IteratorSize end

"""
    IteratorSize(itertype::Type) -> IteratorSize

Given the type of an iterator, return one of the following values:

* `SizeUnknown()` if the length (number of elements) cannot be determined in advance.
* `HasLength()` if there is a fixed, finite length.
* `HasShape{N}()` if there is a known length plus a notion of multidimensional shape (as for an array).
   In this case `N` should give the number of dimensions, and the [`axes`](@ref) function is valid
   for the iterator.
* `IsInfinite()` if the iterator yields values forever.

The default value (for iterators that do not define this function) is `HasLength()`.
This means that most iterators are assumed to implement [`length`](@ref).

This trait is generally used to select between algorithms that pre-allocate space for their
result, and algorithms that resize their result incrementally.

```jldoctest
julia> Base.IteratorSize(1:5)
Base.HasShape{1}()

julia> Base.IteratorSize((2,3))
Base.HasLength()
```
"""
IteratorSize(x) = IteratorSize(typeof(x))
IteratorSize(::Type) = HasLength()  # HasLength is the default

IteratorSize(::Type{<:AbstractArray{<:Any,N}})  where {N} = HasShape{N}()
IteratorSize(::Type{Generator{I,F}}) where {I,F} = IteratorSize(I)

IteratorSize(::Type{Any}) = SizeUnknown()

haslength(iter) = IteratorSize(iter) isa Union{HasShape, HasLength}

abstract type IteratorEltype end
struct EltypeUnknown <: IteratorEltype end
struct HasEltype <: IteratorEltype end

"""
    IteratorEltype(itertype::Type) -> IteratorEltype

Given the type of an iterator, return one of the following values:

* `EltypeUnknown()` if the type of elements yielded by the iterator is not known in advance.
* `HasEltype()` if the element type is known, and [`eltype`](@ref) would return a meaningful value.

`HasEltype()` is the default, since iterators are assumed to implement [`eltype`](@ref).

This trait is generally used to select between algorithms that pre-allocate a specific
type of result, and algorithms that pick a result type based on the types of yielded
values.

```jldoctest
julia> Base.IteratorEltype(1:5)
Base.HasEltype()
```
"""
IteratorEltype(x) = IteratorEltype(typeof(x))
IteratorEltype(::Type) = HasEltype()  # HasEltype is the default

IteratorEltype(::Type{Generator{I,T}}) where {I,T} = EltypeUnknown()

IteratorEltype(::Type{Any}) = EltypeUnknown()

max_stars_repo_name: TimoLarson/julia

max_issues_repo_name: TimoLarson/julia

max_forks_repo_name: TimoLarson/julia


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

using Markdown
using InteractiveUtils

# ╔═╡ c2f327e8-3ca5-11ec-023b-c9dd2baf6fc6
using RDatasets, Gadfly

# ╔═╡ 94f753ad-9d6b-451d-961f-c350b85e0e97
iris = dataset("datasets", "iris")

# ╔═╡ 19e57dd6-a043-491b-8e34-b7df4b9cb76d
plot(iris, x="PetalLength", y="PetalWidth")

# ╔═╡ 84bbfed7-43d3-4672-88cc-bb703abfc332
plot(iris, x="PetalLength", y="PetalWidth", Geom.point)

# ╔═╡ 614f2ac8-f38c-4ef9-a3f3-4cb3ff4b2aa0
categorical = plot(iris,
	x="PetalLength", y="PetalWidth",
	color="Species",
	Geom.point)

# ╔═╡ 621bed20-826e-43ad-9b8a-989476684a54
ordered = plot(iris,
	x="PetalLength", y="PetalWidth",
	color="SepalLength",
	Geom.point)

# ╔═╡ 1083d501-695b-4e07-8004-36feb7f97f07
hstack(categorical, ordered)

# ╔═╡ 5947d231-5b27-434e-a193-b40b60b2f989
plot(iris,
	x="PetalLength", y="PetalWidth", color="Species",
	Geom.point, Geom.line)

# ╔═╡ 352d990d-dde4-47a4-b4d4-d6f1050f97af
plot(iris, x="PetalLength", y="PetalWidth",
	layer(color="Species", Geom.point), Geom.line)

# ╔═╡ 98ceb4c5-dbae-4371-b0ff-0fb52c871f9a
plot(iris,
	x="PetalLength", y="PetalWidth", color="Species",
	Stat.smooth)

# ╔═╡ a458f86d-9e55-4493-8e72-fe2de9585352
plot(iris,
	x="PetalLength", y="PetalWidth", color="Species",
	layer(Stat.smooth, Geom.line), Geom.point)

# ╔═╡ b00c8db5-a04c-4fd6-9931-1dad47c0420b
plot(iris, x="PetalLength", y="PetalWidth", size="SepalLength", Geom.point)

# ╔═╡ 6c36fb90-86ec-41ca-a7bc-2f2f892d333d
min_sl, max_sl = extrema(iris.SepalLength)

# ╔═╡ 653abd92-7f98-4414-a45e-3451eefffe18
sizemap(p::Float64; min=1mm, max=2.5mm) = min + p*(max-min)

# ╔═╡ 0167c092-1a2a-48c7-95db-6b3b143fdfe8
plot(iris,
	x="PetalLength", y="PetalWidth",
	size="SepalLength",
	Geom.point,
	Scale.size_radius(sizemap,
		minvalue=min_sl, maxvalue=max_sl))

# ╔═╡ b9149116-5a25-4d7c-818e-bde09c65d5b5
plot(iris,
	x="PetalLength", y="PetalWidth",
	ygroup="Species",
	Geom.subplot_grid(Geom.point))

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Gadfly = "c91e804a-d5a3-530f-b6f0-dfbca275c004"
RDatasets = "ce6b1742-4840-55fa-b093-852dadbb1d8b"

[compat]
Gadfly = "~1.3.4"
RDatasets = "~0.7.6"
"""

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

[[AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "485ee0867925449198280d4af84bdb46a2a404d0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.0.1"

[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"

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

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

[[AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.0.1"

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

[[CSV]]
deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings"]
git-tree-sha1 = "74147e877531d7c172f70b492995bc2b5ca3a843"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.9.10"

[[CategoricalArrays]]
deps = ["DataAPI", "Future", "Missings", "Printf", "Requires", "Statistics", "Unicode"]
git-tree-sha1 = "fbc5c413a005abdeeb50ad0e54d85d000a1ca667"
uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597"
version = "0.10.1"

[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "f885e7e7c124f8c92650d61b9477b9ac2ee607dd"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.11.1"

[[CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"

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

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

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

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

[[Compose]]
deps = ["Base64", "Colors", "DataStructures", "Dates", "IterTools", "JSON", "LinearAlgebra", "Measures", "Printf", "Random", "Requires", "Statistics", "UUIDs"]
git-tree-sha1 = "c6461fc7c35a4bb8d00905df7adafcff1fe3a6bc"
uuid = "a81c6b42-2e10-5240-aca2-a61377ecd94b"
version = "0.9.2"

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

[[CoupledFields]]
deps = ["LinearAlgebra", "Statistics", "StatsBase"]
git-tree-sha1 = "6c9671364c68c1158ac2524ac881536195b7e7bc"
uuid = "7ad07ef1-bdf2-5661-9d2b-286fd4296dac"
version = "0.2.0"

[[Crayons]]
git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.0.4"

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

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

[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"

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

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

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

[[Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "837c83e5574582e07662bbbba733964ff7c26b9d"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.6"

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

[[Distributions]]
deps = ["ChainRulesCore", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns"]
git-tree-sha1 = "72dcda9e19f88d09bf21b5f9507a0bb430bce2aa"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.24"

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

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

[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"

[[FFTW]]
deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"]
git-tree-sha1 = "463cb335fa22c4ebacfd1faba5fde14edb80d96c"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "1.4.5"

[[FFTW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea"
uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a"
version = "3.3.10+0"

[[FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "2db648b6712831ecb333eae76dbfd1c156ca13bb"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.11.2"

[[FilePathsBase]]
deps = ["Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "d962b5a47b6d191dbcd8ae0db841bc70a05a3f5b"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.13"

[[FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]
git-tree-sha1 = "8756f9935b7ccc9064c6eef0bff0ad643df733a3"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.12.7"

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

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

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

[[Gadfly]]
deps = ["Base64", "CategoricalArrays", "Colors", "Compose", "Contour", "CoupledFields", "DataAPI", "DataStructures", "Dates", "Distributions", "DocStringExtensions", "Hexagons", "IndirectArrays", "IterTools", "JSON", "Juno", "KernelDensity", "LinearAlgebra", "Loess", "Measures", "Printf", "REPL", "Random", "Requires", "Showoff", "Statistics"]
git-tree-sha1 = "13b402ae74c0558a83c02daa2f3314ddb2d515d3"
uuid = "c91e804a-d5a3-530f-b6f0-dfbca275c004"
version = "1.3.4"

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

[[Hexagons]]
deps = ["Test"]
git-tree-sha1 = "de4a6f9e7c4710ced6838ca906f81905f7385fd6"
uuid = "a1b4810d-1bce-5fbd-ac56-80944d57a21f"
version = "0.2.0"

[[IndirectArrays]]
git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f"
uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959"
version = "1.0.0"

[[InlineStrings]]
deps = ["Parsers"]
git-tree-sha1 = "19cb49649f8c41de7fea32d089d37de917b553da"
uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48"
version = "1.0.1"

[[IntelOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c"
uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0"
version = "2018.0.3+2"

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

[[Interpolations]]
deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"]
git-tree-sha1 = "61aa005707ea2cebf47c8d780da8dc9bc4e0c512"
uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
version = "0.13.4"

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

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

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

[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"

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

[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"

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

[[Juno]]
deps = ["Base64", "Logging", "Media", "Profile"]
git-tree-sha1 = "07cb43290a840908a771552911a6274bc6c072c7"
uuid = "e5e0dc1b-0480-54bc-9374-aad01c23163d"
version = "0.8.4"

[[KernelDensity]]
deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"]
git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707"
uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b"
version = "0.6.3"

[[LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"

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

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

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

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

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

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

[[Loess]]
deps = ["Distances", "LinearAlgebra", "Statistics"]
git-tree-sha1 = "b5254a86cf65944c68ed938e575f5c81d5dfe4cb"
uuid = "4345ca2d-374a-55d4-8d30-97f9976e7612"
version = "0.5.3"

[[LogExpFunctions]]
deps = ["ChainRulesCore", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "6193c3815f13ba1b78a51ce391db8be016ae9214"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.4"

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

[[MKL_jll]]
deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"]
git-tree-sha1 = "5455aef09b40e5020e1520f551fa3135040d4ed0"
uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7"
version = "2021.1.1+2"

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

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

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

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

[[Media]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "75a54abd10709c01f1b86b84ec225d26e840ed58"
uuid = "e89f7d12-3494-54d1-8411-f7d8b9ae1f27"
version = "0.5.0"

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

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

[[Mocking]]
deps = ["Compat", "ExprTools"]
git-tree-sha1 = "29714d0a7a8083bba8427a4fbfb00a540c681ce7"
uuid = "78c3b35d-d492-501b-9361-3d52fe80e533"
version = "0.7.3"

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

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

[[OffsetArrays]]
deps = ["Adapt"]
git-tree-sha1 = "c0e9e582987d36d5a61e650e6e543b9e44d9914b"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.10.7"

[[OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"

[[OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"

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

[[PDMats]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "82041e63725d156bf61c6302dd7635ea13e3d5e7"
uuid = "90014a1f-27ba-587c-ab20-58faa44d9150"
version = "0.11.2"

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

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

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

[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"

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

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

[[Profile]]
deps = ["Printf"]
uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79"

[[QuadGK]]
deps = ["DataStructures", "LinearAlgebra"]
git-tree-sha1 = "78aadffb3efd2155af139781b8a8df1ef279ea39"
uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
version = "2.4.2"

[[RData]]
deps = ["CategoricalArrays", "CodecZlib", "DataFrames", "Dates", "FileIO", "Requires", "TimeZones", "Unicode"]
git-tree-sha1 = "19e47a495dfb7240eb44dc6971d660f7e4244a72"
uuid = "df47a6cb-8c03-5eed-afd8-b6050d6c41da"
version = "0.8.3"

[[RDatasets]]
deps = ["CSV", "CodecZlib", "DataFrames", "FileIO", "Printf", "RData", "Reexport"]
git-tree-sha1 = "d3780d4626d6104068c151e22965d9209ea41938"
uuid = "ce6b1742-4840-55fa-b093-852dadbb1d8b"
version = "0.7.6"

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

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

[[Ratios]]
deps = ["Requires"]
git-tree-sha1 = "01d341f502250e81f6fec0afe662aa861392a3aa"
uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439"
version = "0.4.2"

[[RecipesBase]]
git-tree-sha1 = "44a75aa7a527910ee3d1751d1f0e4148698add9e"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.1.2"

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

[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"

[[Rmath]]
deps = ["Random", "Rmath_jll"]
git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f"
uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa"
version = "0.7.0"

[[Rmath_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7"
uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f"
version = "0.3.0+0"

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

[[SentinelArrays]]
deps = ["Dates", "Random"]
git-tree-sha1 = "f45b34656397a1f6e729901dc9ef679610bd12b5"
uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c"
version = "1.3.8"

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

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

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

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

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

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

[[SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "f0bccf98e16759818ffc5d97ac3ebf87eb950150"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.8.1"

[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3c76dde64d03699e074ac02eb2e8ba8254d428da"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.13"

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

[[StatsAPI]]
git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.0.0"

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

[[StatsFuns]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
git-tree-sha1 = "95072ef1a22b057b1e80f73c2a89ad238ae4cfff"
uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
version = "0.9.12"

[[SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"

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

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

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

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

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

[[TimeZones]]
deps = ["Dates", "Downloads", "InlineStrings", "LazyArtifacts", "Mocking", "Pkg", "Printf", "RecipesBase", "Serialization", "Unicode"]
git-tree-sha1 = "8de32288505b7db196f36d27d7236464ef50dba1"
uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53"
version = "1.6.2"

[[TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.6"

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

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

[[WeakRefStrings]]
deps = ["DataAPI", "InlineStrings", "Parsers"]
git-tree-sha1 = "c69f9da3ff2f4f02e811c3323c22e5dfcb584cfa"
uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5"
version = "1.4.1"

[[WoodburyMatrices]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "de67fa59e33ad156a590055375a30b23c40299d3"
uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6"
version = "0.5.5"

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

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

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

# ╔═╡ Cell order:
# ╠═c2f327e8-3ca5-11ec-023b-c9dd2baf6fc6
# ╠═94f753ad-9d6b-451d-961f-c350b85e0e97
# ╠═19e57dd6-a043-491b-8e34-b7df4b9cb76d
# ╠═84bbfed7-43d3-4672-88cc-bb703abfc332
# ╠═614f2ac8-f38c-4ef9-a3f3-4cb3ff4b2aa0
# ╠═621bed20-826e-43ad-9b8a-989476684a54
# ╠═1083d501-695b-4e07-8004-36feb7f97f07
# ╠═5947d231-5b27-434e-a193-b40b60b2f989
# ╠═352d990d-dde4-47a4-b4d4-d6f1050f97af
# ╠═98ceb4c5-dbae-4371-b0ff-0fb52c871f9a
# ╠═a458f86d-9e55-4493-8e72-fe2de9585352
# ╠═b00c8db5-a04c-4fd6-9931-1dad47c0420b
# ╠═6c36fb90-86ec-41ca-a7bc-2f2f892d333d
# ╠═653abd92-7f98-4414-a45e-3451eefffe18
# ╠═0167c092-1a2a-48c7-95db-6b3b143fdfe8
# ╠═b9149116-5a25-4d7c-818e-bde09c65d5b5
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
function sum_vectors_simd!(x, y, z)
n = length(x)
@inbounds @simd for i = 1:n
x[i] = y[i] + z[i]
end
end

max_stars_repo_path: Module 2/Chapter06/inbound_SIMD.jl

max_issues_repo_path: Module 2/Chapter06/inbound_SIMD.jl

max_forks_repo_path: Module 2/Chapter06/inbound_SIMD.jl


text:
module Mill
using Flux, MLDataPattern, SparseArrays, Statistics, Combinatorics, Zygote
using Zygote: @adjoint
import Base.reduce

const COLORS = [:blue, :red, :green, :yellow, :cyan, :magenta]

MLDataPattern.nobs(::Missing) = nothing

function paddedprint(io, s...; color=:default, pad=[])
    for (c, p) in pad
        printstyled(io, p, color=c)
    end
    printstyled(io, s..., color=color)
end

key_labels(data::NamedTuple) = ["$k: " for k in keys(data)]
key_labels(data) = ["" for _ in 1:length(data)]

const VecOrRange = Union{UnitRange{Int},AbstractVector{Int}}

"""
	catobs(xs...)

	concatenates all observations from all xs together
"""
function catobs end;

include("bags.jl")
export AlignedBags, ScatteredBags

include("util.jl")
include("threadfuns.jl")

include("datanodes/datanode.jl")
export AbstractNode, AbstractTreeNode, AbstractBagNode
export ArrayNode, BagNode, WeightedBagNode, TreeNode
export NGramMatrix, NGramIterator
export catobs, removeinstances

include("aggregations/aggregation.jl")
# agg. types exported in aggregation.jl
export Aggregation

include("modelnodes/modelnode.jl")
export MillModel, ArrayModel, BagModel, ProductModel
export reflectinmodel

include("traversal_encoding.jl")
export show_traversal, encode_traversal

include("conv.jl")
export bagconv, BagConv

include("bagchain.jl")
export BagChain

include("replacein.jl")
export replacein

end


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.

"""
    SOCtoRSOCBridge{T} <: Bridges.Variable.SetMapBridge{T,MOI.RotatedSecondOrderCone,MOI.SecondOrderCone}

Same transformation as [`MOI.Bridges.Constraint.SOCtoRSOCBridge`](@ref).
"""
struct SOCtoRSOCBridge{T} <:
       SetMapBridge{T,MOI.RotatedSecondOrderCone,MOI.SecondOrderCone}
    variables::Vector{MOI.VariableIndex}
    constraint::MOI.ConstraintIndex{
        MOI.VectorOfVariables,
        MOI.RotatedSecondOrderCone,
    }
end

const SOCtoRSOC{T,OT<:MOI.ModelLike} =
    SingleBridgeOptimizer{SOCtoRSOCBridge{T},OT}

"""
    RSOCtoSOCBridge{T} <: Bridges.Variable.SetMapBridge{T,MOI.SecondOrderCone,MOI.RotatedSecondOrderCone}

Same transformation as [`MOI.Bridges.Constraint.RSOCtoSOCBridge`](@ref).
"""
struct RSOCtoSOCBridge{T} <:
       SetMapBridge{T,MOI.SecondOrderCone,MOI.RotatedSecondOrderCone}
    variables::Vector{MOI.VariableIndex}
    constraint::MOI.ConstraintIndex{MOI.VectorOfVariables,MOI.SecondOrderCone}
end

const RSOCtoSOC{T,OT<:MOI.ModelLike} =
    SingleBridgeOptimizer{RSOCtoSOCBridge{T},OT}

max_stars_repo_name: JuliaOpt/MathOptInterface

max_issues_repo_name: JuliaOpt/MathOptInterface

max_forks_repo_name: JuliaOpt/MathOptInterface