text:
struct MLMPCSolver <: Solver
    solver
    updater::Nullable{Any}
end
function set_rng!(s::MLMPCSolver, rng::AbstractRNG)
    set_rng!(s.solver, rng)
    set_rng!(get(s.updater), rng)
end

mutable struct MLMPCAgent <: Policy
    updater::Updater
    previous_belief::Nullable{Any}
    policy::POMDPs.Policy
    previous_action::Nullable{MLAction}
end

function solve(solver::MLMPCSolver, problem::MLMDP, up=get(solver.updater, nothing))
    internal_problem = MLPOMDP{MLState, MLAction, MLPhysicalState, typeof(problem.dmodel), typeof(problem.rmodel)}(problem.dmodel, problem.rmodel, problem.discount)
    policy = solve(solver.solver, problem)
#=
    if up == nothing
        up = POMDPs.updater(policy)
    else
        set_problem!(up, internal_problem)
    end
=#

    set_problem!(up, internal_problem)
    #up.problem = internal_problem
    return MLMPCAgent(up, nothing, policy, nothing)
    #return up, policy
    #return MLMPCAgent(policy)
end

function action(agent::MLMPCAgent, state::MLState)
    o = MLPhysicalState(state)
    if isnull(agent.previous_belief)
        belief = initialize_belief(agent.updater, ParticleGenerator(agent.policy.mdp, state))
    else
        belief = update(agent.updater, get(agent.previous_belief), get(agent.previous_action), o)
    end
    ml = most_likely_state(belief)
    a = action(agent.policy, ml)
    agent.previous_action = a
    agent.previous_belief = belief
    return a
end

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

################################heuristics

struct Simple <: Policy #
  mdp
  A::NoCrashActionSpace
  sweeping_up::Bool
end
type SimpleSolver <: Solver end

Simple(mdp) = Simple(mdp,actions(mdp),true)
solve(solver::SimpleSolver, problem::MDP) = Simple(problem)
solve(solver::SimpleSolver, problem::EmbeddedBehaviorMDP) = Simple(problem.base)
solve(solver::SimpleSolver, problem::POMDP) = Simple(problem)
POMDPs.updater(::Simple) = POMDPToolbox.FastPreviousObservationUpdater{MLObs}()
create_policy(s::SimpleSolver, problem::MDP) = Simple(problem)
create_policy(s::SimpleSolver, problem::POMDP) = Simple(problem)

set_rng!(solver::SimpleSolver, rng::AbstractRNG) = nothing

function action(p::Simple,s::Union{MLState,MLObs},a::MLAction=create_action(p.mdp))
# lane changes if there is an opportunity
    goal_lane = p.mdp.rmodel.target_lane
    y_desired = goal_lane
    dmodel = p.mdp.dmodel
    lc = sign(y_desired-s.cars[1].y) * dmodel.lane_change_rate
    acc = dmodel.adjustment_acceleration

    #if can't move towards desired lane sweep through accelerating and decelerating

    # TODO need an equivalent of is_safe that can operate on observations
    if is_safe(p.mdp, s, MLAction(0.,lc))
        return MLAction(0.,lc)
    end
    # maintain distance from other cars

    # maintain distance
    nbhd = get_neighborhood(dmodel.phys_param,s,1)

    if nbhd[2] == 0 && nbhd[5] == 0
        return MLAction(0.,0.)
    end

    dist_ahead = nbhd[2] != 0 ? s.cars[nbhd[2]].x - s.cars[1].x : Inf
    dist_behind = nbhd[5] != 0 ? s.cars[nbhd[5]].x - s.cars[1].x : Inf

    sgn = abs(dist_ahead) <= abs(dist_behind) ? -1 : 1

    accel = sgn * acc

    max_accel = max_safe_acc(p.mdp, s, 0.0)

    return MLAction(min(accel, max_accel),0.)
end
#action(p::Simple, b::BehaviorBelief, a::MLAction=create_action(p.mdp)) = action(p, b.physical, a)

struct BehaviorSolver <: Solver
    b::BehaviorModel
    keep_lane::Bool
    rng::AbstractRNG
end
struct BehaviorPolicy <: Policy
    problem::NoCrashProblem
    b::BehaviorModel
    keep_lane::Bool
    rng::AbstractRNG
end
solve(s::BehaviorSolver, p::NoCrashProblem) = BehaviorPolicy(p, s.b, s.keep_lane, s.rng)

function action(p::BehaviorPolicy, s::MLState, a::MLAction=MLAction(0.0,0.0))
    #println("LC")
    nbhd = get_neighborhood(p.problem.dmodel.phys_param, s, 1)
    acc = gen_accel(p.b, p.problem.dmodel, s, nbhd, 1, p.rng)
    if p.keep_lane
        lc = 0.0
    else
        #lc = 1.0

        lc = gen_lane_change(p.b, p.problem.dmodel, s, nbhd, 1, p.rng)
    end
    return MLAction(acc, lc)
end
#action(p::BehaviorPolicy, b::AggressivenessBelief, a::MLAction=MLAction(0.0,0.0)) = action(p, most_likely_state(b))
#action(p::BehaviorPolicy, b::BehaviorParticleBelief, a::MLAction=MLAction(0.0,0.0)) = action(p, most_likely_state(b))

type IDMLaneSeekingSolver <: Solver
    b::BehaviorModel
    rng::AbstractRNG
end

type IDMLaneSeekingPolicy <: Policy
    problem::NoCrashProblem
    b::BehaviorModel
    rng::AbstractRNG
end
solve(s::IDMLaneSeekingSolver, p::NoCrashProblem) = IDMLaneSeekingPolicy(p, s.b, s.rng)

function action(p::IDMLaneSeekingPolicy, s::MLState, a::MLAction=MLAction(0.0,0.0))
    nbhd = get_neighborhood(p.problem.dmodel.phys_param, s, 1)
    acc = gen_accel(p.b, p.problem.dmodel, s, nbhd, 1, p.rng)
    # try to positive lanechange
    # lc = problem.dmodel.lane_change_rate * !is_lanechange_dangerous(pp,s,nbhd,1,1)
    lc = p.problem.dmodel.lane_change_rate
    if is_safe(p.problem, s, MLAction(acc, lc))
        return MLAction(acc, lc)
    end
    return MLAction(acc, 0.0)
end

max_stars_repo_name: zhcao/HighwayExit

max_issues_repo_name: zhcao/HighwayExit

max_forks_repo_name: zhcao/HighwayExit


text:
#=
Part of this work is derived from astropy/photutils. The relevant derivations
are considered under a BSD 3-clause license. =#

"""
    EllipticalAperture(x, y, a, b, θ=0)
    EllipticalAperture(position, a, b, θ=0)

An elliptical aperture with semi-major axis `a`, semi-minor axis `b`, and position angle `θ`. `a` and `b` must be ≥ 0, `θ` is measured in degrees counter-clockwise the standard x-axis.

# Examples
```jldoctest
julia> ap = EllipticalAperture(0, 0, 4, 2, 35)
5×7 EllipticalAperture{Int64} with indices -2:2×-3:3:
 0.873382  1.0       1.0       0.796137  0.23968   0.0       0.0
 0.844185  1.0       1.0       1.0       0.990119  0.435284  0.0
 0.324917  0.997821  1.0       1.0       1.0       0.997821  0.324917
 0.0       0.435284  0.990119  1.0       1.0       1.0       0.844185
 0.0       0.0       0.23968   0.796137  1.0       1.0       0.873382
```
"""
struct EllipticalAperture{T <: Number} <: AbstractAperture{T}
    x::T
    y::T
    a::T
    b::T
    theta::T
end

EllipticalAperture(x::Number, y::Number, a, b, theta=0) = EllipticalAperture(promote(x, y, a, b, theta)...)
EllipticalAperture(center, a, b, theta=0) = EllipticalAperture(center..., a, b, theta)

function Base.show(io::IO, e::EllipticalAperture)
    print(io, "EllipticalAperture($(e.x), $(e.y), a=$(e.a), b=$(e.b), θ=$(e.theta)°)")
end

oblique_coefficients(ap::EllipticalAperture) = oblique_coefficients(ap.a, ap.b, ap.theta)
oblique_coefficients(ap::Subpixel{T,<:EllipticalAperture}) where {T} = oblique_coefficients(ap.ap)

function oblique_coefficients(a, b, theta)
    sintheta, costheta = sincosd(theta)
    a2 = a^2
    b2 = b^2
    cxx = costheta^2 / a2 + sintheta^2 / b2
    cyy = sintheta^2 / a2 + costheta^2 / b2
    cxy = 2 * costheta * sintheta * (1 / a2 - 1 / b2)
    return cxx, cyy, cxy
end

function overlap(ap::EllipticalAperture, i, j)
    cxx, cyy, cxy = oblique_coefficients(ap)
    flags = (
        inside_ellipse(j - 0.5, i - 0.5, ap.x, ap.y, cxx, cyy, cxy),
        inside_ellipse(j - 0.5, i + 0.5, ap.x, ap.y, cxx, cyy, cxy),
        inside_ellipse(j + 0.5, i - 0.5, ap.x, ap.y, cxx, cyy, cxy),
        inside_ellipse(j + 0.5, i + 0.5, ap.x, ap.y, cxx, cyy, cxy)
    )
    all(flags) && return Inside
    all(!, flags) && return Outside

    return Partial
end

function elliptical_bounds(cx, cy, a, b, theta)
    iszero(a) && return cx, cx, cy, cy
    sintheta, costheta = sincosd(theta)

    t = atan(-b * tand(theta), a)

    sint, cost = sincos(t)
    xmin = cx + a * cost * costheta - b * sint * sintheta
    xmax = xmin

    for n in -2:2
        sint, cost = sincos(t + n * pi)
        xmin = min(xmin, cx + a * cost * costheta - b * sint * sintheta)
        xmax = max(xmax, cx + a * cost * costheta - b * sint * sintheta)
    end

    t2 = atan(b * cotd(theta),  a)

    sint, cost = sincos(t2)
    ymin = cy + b * sint * costheta + a * cost * sintheta
    ymax = ymin

    for n in -2:2
        sint, cost = sincos(t2 + n * pi)
        ymin = min(ymin, cy + b * sint * costheta + a * cost * sintheta)
        ymax = max(ymax, cy + b * sint * costheta + a * cost * sintheta)
    end

    xmin = ceil(Int, xmin)
    xmax = floor(Int, xmax)
    ymin = ceil(Int, ymin)
    ymax = floor(Int, ymax)

    return xmin, xmax, ymin, ymax
end

bounds(e::EllipticalAperture) = elliptical_bounds(e.x, e.y, e.a, e.b, e.theta)

partial(ap::EllipticalAperture, x, y) = elliptical_overlap_exact(x - 0.5, y - 0.5, x + 0.5, y + 0.5, ap.a, ap.b, ap.theta)
partial(sub_ap::Subpixel{T,<:EllipticalAperture}, x, y) where {T} = elliptical_overlap_single_subpixel(x - 0.5, y - 0.5, x + 0.5, y + 0.5, oblique_coefficients(sub_ap.ap)..., sub_ap.N)

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

"""
    EllipticalAnnulus(x, y, a_in, a_out, b_out, θ=0)
    EllipticalAnnulus(position, a_in, a_out, b_out, θ=0)
An elliptical annulus with inner semi-major axis `a_in`, outer semi-major axis `a_out`, outer semi-minor axis `b_out`, and position angle `θ`.
`a_out` ≥ `a_in` ≥ 0 and `b_out` must be ≥ 0, `θ` is measured in degrees counter-clockwise the standard x-axis.

`b_in` will automatically be calculated from `(a_in / a_out) * b_out`. Note this may cause a type instability.
# Examples
```jldoctest
julia> ap = EllipticalAnnulus(0, 0, 4, 10, 5, 45)
15×15 EllipticalAnnulus{Float64} with indices -7:7×-7:7:
 0.594853   1.0       1.0       1.0         …  0.0       0.0       0.0
 1.0        1.0       1.0       1.0            0.0       0.0       0.0
 1.0        1.0       1.0       1.0            0.0       0.0       0.0
 1.0        1.0       1.0       1.0            0.0       0.0       0.0
 1.0        1.0       1.0       1.0            0.0       0.0       0.0
 0.814163   1.0       1.0       1.0         …  0.414163  0.0       0.0
 0.369432   1.0       1.0       1.0            0.975704  0.193728  0.0
 0.0112571  0.809079  1.0       1.0            1.0       0.809079  0.0112571
 0.0        0.193728  0.975704  1.0            1.0       1.0       0.369432
 0.0        0.0       0.414163  1.0            1.0       1.0       0.814163
 0.0        0.0       0.0       0.546165    …  1.0       1.0       1.0
 0.0        0.0       0.0       0.00252321     1.0       1.0       1.0
 0.0        0.0       0.0       0.0            1.0       1.0       1.0
 0.0        0.0       0.0       0.0            1.0       1.0       1.0
 0.0        0.0       0.0       0.0            1.0       1.0       0.594853
```
"""
struct EllipticalAnnulus{T <: Number} <: AbstractAperture{T}
    x::T
    y::T
    a_in::T
    b_in::T
    a_out::T
    b_out::T
    theta::T
end

EllipticalAnnulus(x::Number, y::Number, a_in, a_out, b_out, theta=0) = EllipticalAnnulus(promote(x, y, a_in, a_in / a_out * b_out, a_out, b_out, theta)...)
EllipticalAnnulus(center, a_in, a_out, b_out, theta=0) = EllipticalAnnulus(center..., a_in, a_out, b_out, theta)

function Base.show(io::IO, e::EllipticalAnnulus)
    print(io, "EllipticalAnnulus($(e.x), $(e.y), a_in=$(e.a_in), a_out=$(e.a_out), b_in=$(e.b_in), b_out=$(e.b_out), θ=$(e.theta)°)")
end

function overlap(ap::EllipticalAnnulus, i, j)
    coeffs_out = oblique_coefficients(ap.a_out, ap.b_out, ap.theta)
    flags_out = (
        inside_ellipse(j - 0.5, i - 0.5, ap.x, ap.y, coeffs_out...),
        inside_ellipse(j - 0.5, i + 0.5, ap.x, ap.y, coeffs_out...),
        inside_ellipse(j + 0.5, i - 0.5, ap.x, ap.y, coeffs_out...),
        inside_ellipse(j + 0.5, i + 0.5, ap.x, ap.y, coeffs_out...)
    )

    coeffs_in = oblique_coefficients(ap.a_in, ap.b_in, ap.theta)
    flags_in = (
        inside_ellipse(j - 0.5, i - 0.5, ap.x, ap.y, coeffs_in...),
        inside_ellipse(j - 0.5, i + 0.5, ap.x, ap.y, coeffs_in...),
        inside_ellipse(j + 0.5, i - 0.5, ap.x, ap.y, coeffs_in...),
        inside_ellipse(j + 0.5, i + 0.5, ap.x, ap.y, coeffs_in...)
    )

   all(flags_out) && all(!, flags_in) && return Inside
   all(flags_in) || all(!, flags_out) && return Outside

    return Partial
end

bounds(e::EllipticalAnnulus) =  elliptical_bounds(e.x, e.y, e.a_out, e.b_out, e.theta)

function partial(ap::EllipticalAnnulus, x, y)
    f1 = elliptical_overlap_exact(x - 0.5, y - 0.5, x + 0.5, y + 0.5, ap.a_out, ap.b_out, ap.theta)
    f2 = elliptical_overlap_exact(x - 0.5, y - 0.5, x + 0.5, y + 0.5, ap.a_in, ap.b_in, ap.theta)
    return f1 - f2
end

function partial(sub_ap::Subpixel{T,<:EllipticalAnnulus}, x, y) where T
    ap = sub_ap.ap
    coeffs_out = oblique_coefficients(ap.a_out, ap.b_out, ap.theta)
    f1 = elliptical_overlap_single_subpixel(x - 0.5, y - 0.5, x + 0.5, y + 0.5, coeffs_out..., sub_ap.N)
    coeffs_in = oblique_coefficients(ap.a_in, ap.b_in, ap.theta)
    f2 = elliptical_overlap_single_subpixel(x - 0.5, y - 0.5, x + 0.5, y + 0.5, coeffs_in..., sub_ap.N)
    return f1 - f2
end

ext: jl


text:
using Pkg
Pkg.activate(".")

using Plots
using Plots.PlotMeasures
using LaTeXStrings
using Printf
using JLD
using StatsPlots
using Base.Threads
nthreads()
using AdvancedMH
using AdaptiveMCMC
using MCMCChains
using Distributions

begin

include("plotting.jl")

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

TwoDeltaTheta = 0
phi = 2.5E-3
chi = 0.015*pi/180
include("set_up.jl")

# Define lattice vector
miller_vec = [0;0;1]

dir_str = "paper_figures\\"

# ================================================================
# Figure 2
# ================================================================
char = 2

# Find coordinates in dislocation frame for a 500nm off-set in image plane
bnt_sample, bnt_im, bnt_lab = get_bnt(phi, chi, TwoDeltaTheta, char)
dis_lab = get_dis_lab(char, phi, chi)

loc_d = [1;0]
loc_d_3 = -(dis_lab[1:2,3]'*loc_d)/dis_lab[3,3]

loc_lab = dis_lab'*[loc_d;loc_d_3]
v = [loc_lab[2]; loc_lab[1]/tan(2*theta)]
v = v/norm(v)

image_loc = 500*v

loc_lab = [image_loc[2]*tan(2*theta); image_loc[1]]

loc_d = dis_lab*[loc_lab;0]

# Figure 2a
im_true = compute_image(char, [0; 0], phi, chi, TwoDeltaTheta, [0;0;1])
dfxm_image_plot_base(im_true, char, [0; 0], dir_str*"base_char_2")

# Figure 2b
loc_center = [0; 0; 8*loc_d[1]; 0; -8*loc_d[1]; 0 ]
im_3 = compute_image(char, loc_center, phi, chi, TwoDeltaTheta, [0;0;1])
dfxm_image_plot_base(im_3, char, loc_center, dir_str*"base_char_2_3")

# Figure 2c
loc_center = [0; 0; 4*loc_d[1]; 0; -4*loc_d[1]; 0 ; 8*loc_d[1]; 0; -8*loc_d[1]; 0 ]
im_5 = compute_image(char, loc_center, phi, chi, TwoDeltaTheta, [0;0;1])
dfxm_image_plot_base(im_5, char, loc_center, dir_str*"base_char_2_5")

# Figure 2d
loc_center = [0; 0; 3*loc_d[1]; 0; -3*loc_d[1]; 0 ; 6*loc_d[1]; 0; -6*loc_d[1]; 0 ;9*loc_d[1]; 0; -9*loc_d[1]; 0 ]
im_7 = compute_image(char, loc_center, phi, chi, TwoDeltaTheta, [0;0;1])
dfxm_image_plot_base(im_7, char, loc_center, dir_str*"base_char_2_7")

# ================================================================
# Figure 3
# ================================================================
char = 6
im_true = compute_image(char, [0;0], phi, chi, TwoDeltaTheta, [0;0;1])

dfxm_image_plot_base(im_true, char, [0; 0], dir_str*"base_char_6")

noise_level = 0.01
background_percent = 0.05

noise_std = noise_level*maximum(im_true)
noise_var = noise_std^2
background = background_percent*maximum(im_true)
pixel_var = im_true .+ background .+ noise_var
im_obs = im_true .+ background + sqrt.(pixel_var).*randn(Npixels,Npixels)

# Example 1 at max
pv = findmax(im_true)[1]
idx_1 = findmax(im_true)[2]
mu = pv + background
sig = sqrt(mu + noise_var)
Ndist1 = Normal(mu,sig)
xs = LinRange(0.,500.,1000)

# Example 2 at edge of blob
idx_2 = [26,idx_1[2]]
pv = im_true[idx_2[1], idx_2[2]]
mu = pv + background
sig = sqrt(mu + noise_var)
Ndist2 = Normal(mu,sig)

plot(xs, pdf.(Ndist1,xs), label="pdf at pixel A", lw=4, ls=:dot, color=:blue, legend=:topright)
plot!(xs, pdf.(Ndist2,xs), label="pdf at pixel B", lw=4, ls=:solid, color=:orange)
xlabel!("pixel value", xtickfontsize=14, xguidefontsize=18, ytickfontsize=14, margin=5mm, legendfontsize=18)
plot!(size=(450,450))
savefig(dir_str*"likelihood_pixel_dists.pdf")

heatmap(y_im_vec, z_im_vec, im_obs, clim=(0,maximum(im_obs)), aspect_ratio=:equal, bbox=:tight)
scatter!([y_im_vec[idx_1[2]]], [z_im_vec[idx_1[1]]], marker=(4,:blue), markerfacecolor="None", label="pixel A")
scatter!([y_im_vec[idx_2[2]]], [z_im_vec[idx_2[1]]], marker=(4,:orange,:square), markerfacecolor="None", label="pixel B",legend=:bottomright)
xlims!(y_im_vec[1],y_im_vec[end])
ylims!(z_im_vec[1],z_im_vec[end])
xticks!([-1,0,1])
yticks!([-4,-2,0,2,4])
xlabel!(L"y_{\ell} \ (\mu \mathrm{m})", xtickfontsize=14, xguidefontsize=18, margin=5mm)
ylabel!(L"x_{\ell} \ (\mu \mathrm{m})", ytickfontsize=14, yguidefontsize=18)
plot!(size=(450,450))
Plots.savefig(dir_str*"likelihood_im_obs.pdf")

# ================================================================
# Figure 4
# ================================================================
for char = 1:12

    # noise-free image
    im_true = compute_image(char, [0; 0], phi, chi, TwoDeltaTheta, [0;0;1])

    # save with support of prior
    save_str = dir_str*"prior_char_$(char)"

    dfxm_image_plot_base(im_true, char, [0.,0.], save_str; prior=true)

end

# character and test number
char = 2
test = 1

dis_lab = get_dis_lab(char, phi, chi)

load_name = "paper_data//density_examples_char_$(char)_background_$(background_percent)_noise_$(noise_level)_test_$(test)"
load_name = replace(load_name, "."=>"p")

# Load data
im_obs = load(load_name*"_im_obs.jld","im_obs")
d = load(load_name*"_opt_data.jld")
true_loc_dis = d["true_loc"]
true_loc_im = dis_to_image(true_loc_dis, dis_lab)
loc_trace_dis =d["loc_trace"]
loc_trace_im = reshape(dis_to_image(loc_trace_dis,dis_lab),size(loc_trace_dis))
f_trace =d["f_trace"]
map_point_dis =d["map_point"]
map_point_im = dis_to_image(map_point_dis,dis_lab)
num_iter = d["num_iter"]
runtime = d["runtime"]
map_cov = d["map_cov"]

adaptive_rwhm_chains = load(load_name*"_mcmc.jld","chains")
all_chains = Chains(adaptive_rwhm_chains)
all_samples = Array(all_chains)
all_samples_im = reshape(dis_to_image(all_samples',dis_lab),size(all_samples'))'

d = load(load_name*"_mat_im.jld")
xs_im = d["xs_im"]
ys_im = d["ys_im"]
density_matrix_im = d["mat"]

d = load(load_name*"_mat_dis.jld")
xs_dis = d["xs_dis"]
ys_dis = d["ys_dis"]
density_matrix_dis = d["mat"]

d = load(load_name*"_mat_f_dis.jld")
xs_f_dis = d["xs_f_dis"]
ys_f_dis = d["ys_f_dis"]
density_matrix_f_dis = d["mat"]

d = load(load_name*"_mat_f_im.jld")
xs_f_im = d["xs_f_im"]
ys_f_im = d["ys_f_im"]
density_matrix_f_im = d["mat"]

# Plot evaluation image
dfxm_image_plot_base(im_obs, char, true_loc_dis, dir_str*"\\obs", prior=true, width=500)

# Figure 5c
contourf(xs_im, ys_im, density_matrix_im, levels=50, aspect_ratio=:equal, color=:reds)
rect = prior_bounds[char,:]
plot!(rectangle(rect...), opacity=.5, c=:gray, label=false, legend=:bottomright)
for t = 1:num_iter - 1
        plot!([loc_trace_im[1,t], loc_trace_im[1,t+1]], [loc_trace_im[2,t], loc_trace_im[2,t+1]],label=false,linewidth=3,c=:black)
end
scatter!(loc_trace_im[1,:],loc_trace_im[2,:], c=:orange, markershape = :utriangle, markersize = 4, label="iterates")
scatter!([map_point_im[1]],[map_point_im[2]],c=:lightgreen, markershape = :star5, markersize = 8, label=L"\xi^{\mathrm{MAP}}")
scatter!([true_loc_im[1]],[true_loc_im[2]], c=:cyan, markershape = :star7, markersize = 8, label=L"\xi^{\mathrm{true}}", legend=false)# outertop)
xlims!(-500,500)
ylims!(-600,600)
xticks!([-500,0,500])
yticks!([-500,0,500])
xlabel!(L"y_{\ell} \ (\mathrm{nm})", xtickfontsize=12, xguidefontsize=18, margin=5mm)
ylabel!(L"x_{\ell} \ (\mathrm{nm})", ytickfontsize=12, yguidefontsize=18)
plot!(size=(450,450),right_margin=15mm)
Plots.savefig(dir_str*"\\iters.pdf")

# Figure 5b
prior_corners = [250; 500; -250; 500; -250; -500; 250; -500]
prior_corners_dis = reshape(image_to_dis(prior_corners, dis_lab), (2,4))
s_prior = Shape(prior_corners_dis[1,:],prior_corners_dis[2,:])

contourf(xs_dis, ys_dis, density_matrix_dis, levels=10, aspect_ratio=:equal, color=cgrad(:grays,rev=true))
plot!(s_prior, opacity=.5, c=:gray, linecolor=:white, label=false)
#plot!(s_region, c=false, linecolor=:white, label=false)
for t = 1:num_iter - 1
        plot!([loc_trace_dis[1,t], loc_trace_dis[1,t+1]], [loc_trace_dis[2,t], loc_trace_dis[2,t+1]],label=false,linewidth=3,c=:black)
end
scatter!(loc_trace_dis[1,:],loc_trace_dis[2,:], c=:orange, markershape = :utriangle, markersize = 4, label="iterates")
scatter!([map_point_dis[1]],[map_point_dis[2]],c=:lightgreen, markershape = :star5, markersize = 8, label=L"\xi^{\mathrm{MAP}}")
scatter!([true_loc_dis[1]],[true_loc_dis[2]], c=:cyan, markershape = :star7, markersize = 8, label=L"\xi^{\mathrm{true}}", legend=false)# outertop)
xlabel!(L"x_{d} \mathrm{ \ (nm)}", xtickfontsize=12, xguidefontsize=18, margin=5mm)
ylabel!(L"y_{d} \mathrm{ \ (nm)}", ytickfontsize=12, yguidefontsize=18)
xlims!(xs_dis[1],xs_dis[end])
ylims!(ys_dis[1],ys_dis[end])
xticks!([-500,0,500])
yticks!([-400,0,400])
plot!(size=(450,450),right_margin=15mm)
Plots.savefig(dir_str*"\\iters_dis.pdf")

# Figure 6a
contourf(xs_f_dis,ys_f_dis,density_matrix_f_dis, levels=50, aspect_ratio=:equal,clims=(15600, 16100), color=cgrad(:grays,rev=true))
scatter!(all_samples[:,1],all_samples[:,2],c=:plum1, alpha=.1, label="MCMC samples")
covellipse!(vec(map_point_dis), map_cov, n_std=2, aspect_ratio=1, color=(:yellow), label=false, alpha=.5)
scatter!([map_point_dis[1]],[map_point_dis[2]],c=:lightgreen, markershape = :star5, markersize = 8, label=L"\xi^{\mathrm{MAP}}")
scatter!([true_loc_dis[1]],[true_loc_dis[2]], c=:cyan, markershape = :star7, markersize = 8, label=L"\xi^{\mathrm{true}}", legend=false)# outertop)
xlims!(200,220)
ylims!(30, 50)
xticks!([200,210,220])
yticks!([30,40,50])
xlabel!(L"x_{d} \mathrm{ \ (nm)}", xtickfontsize=14, xguidefontsize=18, margin=5mm)
ylabel!(L"y_{d} \mathrm{ \ (nm)}", ytickfontsize=14, yguidefontsize=18)
plot!(size=(450,450), right_margin=15mm)
Plots.savefig(dir_str*"\\uq_dis.pdf")

# Figure 6b
vals,vecs = eigen(map_cov)
vecs_im = reshape(dis_to_image(vecs,dis_lab),(2,2))
map_cov_im = vecs_im*diagm(vals)*vecs_im'

contourf(xs_f_im,ys_f_im,density_matrix_f_im, levels=50,aspect_ratio=:equal,clims=(15600, 16100), color=:reds)
scatter!(all_samples_im[:,1],all_samples_im[:,2], alpha=.2, c=:plum1, label="MCMC samples")
covellipse!(vec(map_point_im), map_cov_im, n_std=2, aspect_ratio=1, color=(:yellow), label=false, alpha=.5)
scatter!([map_point_im[1]],[map_point_im[2]],c=:lightgreen, markershape = :star5, markersize = 8, label=L"\xi^{\mathrm{MAP}}")
scatter!([true_loc_im[1]],[true_loc_im[2]], c=:cyan, markershape = :star7, markersize = 8, label=L"\xi^{\mathrm{true}}", legend=false)
xlims!(110,150)
ylims!(440,480)
xticks!([110,130,150])
yticks!([440,460,480])
xlabel!(L"y_{\ell} \mathrm{ \ (nm)}", xtickfontsize=14, xguidefontsize=18, margin=5mm)
ylabel!(L"x_{\ell} \mathrm{ \ (nm)}", ytickfontsize=14, yguidefontsize=18)
plot!(size=(450,450), right_margin=15mm)
Plots.savefig(dir_str*"\\uq_im.pdf")

# figure 7 low noise histogram
background_percent = 0.05
noise_level = 0.01

offset_vec_dis_norms = []
offset_vec_im_norms = []
runtimes = []

for char = 1:12
    dis_lab = get_dis_lab(char, phi, chi)
    load_str = "paper_data\\map_results\\map_data_custom_prior_char_$(char)_background_$(background_percent)_noise_$(noise_level)"
    load_str = replace(load_str, "."=>"p")

    d = load(load_str*".jld")

    finishes_dis = d["finishes"]
    finishes_im = reshape(dis_to_image(finishes_dis, dis_lab), size(finishes_dis))

    true_locs_dis = d["true_locs"]
    true_locs_im = reshape(dis_to_image(true_locs_dis, dis_lab), size(true_locs_dis))

    offset_vec_dis = finishes_dis - true_locs_dis
    append!(offset_vec_dis_norms, [norm(offset_vec_dis[1:2,i]) for i=1:length(offset_vec_dis[1,:])])

    offset_vec_im = finishes_im - true_locs_im
    append!(offset_vec_im_norms, [norm(offset_vec_im[1:2,i]) for i=1:length(offset_vec_im[1,:])])

    append!(runtimes, d["runtimes"])

end

# =====================================================

mean_error = mean(offset_vec_dis_norms)
median_error = median(offset_vec_dis_norms)

histogram(offset_vec_dis_norms, nbins=100, label=false, alpha=.8, color=:gray, xtickfontsize=12,
ytickfontsize=12,xguidefontsize=16)

vline!([median_error], label="median error: $(@sprintf("%.1F",median_error)) nm", color=:blue, linewidth=4, linestyle=:solid)
vline!([mean_error], label="mean error: $(@sprintf("%.1F",mean_error)) nm", color=:green, linewidth=4, linestyle=:dash)
vline!([psize], label="pixel length: $(@sprintf("%.1F",psize)) nm", color=:red, linewidth=4, linestyle=:dot)
vline!([2*psize], label="image res: $(@sprintf("%.1F",2*psize)) nm", color=:black, linewidth=4, linestyle=:dashdotdot)

xlabel!("Estimation error (nm)")
xlims!(0,2*psize+10, legendfontsize=16)
save_str = dir_str*"\\error_histo_dis_background_$(background_percent)_noise_$(noise_level)"
save_str = replace(save_str, "."=>"p")
savefig(save_str*".pdf")

# figure 7 high noise histogram
background_percent = 0.1
noise_level = 0.05

offset_vec_dis_norms = []
offset_vec_im_norms = []
runtimes = []

for char = 1:12
    dis_lab = get_dis_lab(char, phi, chi)
    load_str = "paper_data\\map_results\\map_data_custom_prior_char_$(char)_background_$(background_percent)_noise_$(noise_level)"
    load_str = replace(load_str, "."=>"p")

    d = load(load_str*".jld")

    finishes_dis = d["finishes"]
    finishes_im = reshape(dis_to_image(finishes_dis, dis_lab), size(finishes_dis))

    true_locs_dis = d["true_locs"]
    true_locs_im = reshape(dis_to_image(true_locs_dis, dis_lab), size(true_locs_dis))

    offset_vec_dis = finishes_dis - true_locs_dis
    append!(offset_vec_dis_norms, [norm(offset_vec_dis[1:2,i]) for i=1:length(offset_vec_dis[1,:])])

    offset_vec_im = finishes_im - true_locs_im
    append!(offset_vec_im_norms, [norm(offset_vec_im[1:2,i]) for i=1:length(offset_vec_im[1,:])])

    append!(runtimes, d["runtimes"])

end

mean_error = mean(offset_vec_dis_norms)
median_error = median(offset_vec_dis_norms)

histogram(offset_vec_dis_norms, nbins=100, label=false, alpha=.8, color=:gray, xtickfontsize=12,
ytickfontsize=12,xguidefontsize=16)

vline!([median_error], label="median error: $(@sprintf("%.1F",median_error)) nm", color=:blue, linewidth=4, linestyle=:solid)
vline!([mean_error], label="mean error: $(@sprintf("%.1F",mean_error)) nm", color=:green, linewidth=4, linestyle=:dash)
vline!([psize], label="pixel length: $(@sprintf("%.1F",psize)) nm", color=:red, linewidth=4, linestyle=:dot)
vline!([2*psize], label="image res: $(@sprintf("%.1F",2*psize)) nm", color=:black, linewidth=4, linestyle=:dashdotdot)

xlabel!("Estimation error (nm)")
xlims!(0,2*psize+10, legendfontsize=16)
save_str = dir_str*"\\error_histo_dis_background_$(background_percent)_noise_$(noise_level)"
save_str = replace(save_str, "."=>"p")
savefig(save_str*".pdf")
end

max_stars_repo_name: michael-c-brennan/DFXMTools

max_issues_repo_name: michael-c-brennan/DFXMTools

max_forks_repo_name: michael-c-brennan/DFXMTools


text:
module VectorizationBase

import ArrayInterface, LinearAlgebra, Libdl, Hwloc
using ArrayInterface: StaticInt, Zero, One, contiguous_axis, contiguous_axis_indicator, contiguous_batch_size, stride_rank,
    Contiguous, CPUPointer, ContiguousBatch, StrideRank, device,
    known_length, known_first, known_last, strides, offsets,
    static_first, static_last, static_length
import IfElse: ifelse
# using LinearAlgebra: Adjoint,

# const LLVM_SHOULD_WORK = Sys.ARCH !== :i686 && isone(length(filter(lib->occursin(r"LLVM\b", basename(lib)), Libdl.dllist())))

## Until SIMDPirates stops importing it
# isfile(joinpath(@__DIR__, "cpu_info.jl")) || throw("File $(joinpath(@__DIR__, "cpu_info.jl")) does not exist. Please run `using Pkg; Pkg.build()`.")

export Vec, Mask, MM, stridedpointer, vload, vstore!, StaticInt, vbroadcast, mask

# using Base: llvmcall
using Base: llvmcall, VecElement, HWReal
# @inline llvmcall(s::String, args...) = Base.llvmcall(s, args...)
# @inline llvmcall(s::Tuple{String,String}, args...) = Base.llvmcall(s, args...)

# export Vec, VE, Vec, Mask, MM,
#     gep, gesp,
#     data,
#     pick_vector_width,
#     pick_vector_width_shift,
#     stridedpointer,
#     PackedStridedPointer, RowMajorStridedPointer,
#     StaticIntStridedPointer, StaticIntStridedStruct,
#     vload, vstore!, vbroadcast, StaticInt, mask, masktable

# @static if VERSION < v"1.4"
#     # I think this is worth using, and simple enough that I may as well.
#     # I'll uncomment when I find a place to use it.
#     function only(x)
#         @boundscheck length(x) == 0 && throw(ArgumentError("Collection is empty, must contain exactly 1 element"))
#         @boundscheck length(x) > 1 && throw(ArgumentError("Collection has multiple elements, must contain exactly 1 element"))
#         @inbounds x[1]
#     end
#     export only
# end

# const IntTypes = Union{Int8, Int16, Int32, Int64} # Int128
# const UIntTypes = Union{UInt8, UInt16, UInt32, UInt64} # UInt128
# const IntegerTypes = Union{IntTypes, UIntTypes, Ptr, Bool}
const FloatingTypes = Union{Float32, Float64} # Float16
# const ScalarTypes = Union{IntegerTypes, FloatingTypes}
# const SUPPORTED_FLOATS = [Float32, Float64]
# const SUPPORTED_TYPES = [Float32, Float64, Int16, Int32, Int64, Int8, UInt16, UInt32, UInt64, UInt8]

const SignedHW = Union{Int8,Int16,Int32,Int64}
const UnsignedHW = Union{UInt8,UInt16,UInt32,UInt64}
const IntegerTypesHW = Union{SignedHW,UnsignedHW}
const IntegerTypes = Union{StaticInt,IntegerTypesHW}

struct Bit; data::Bool; end # Dummy for Ptr
const Boolean = Union{Bit,Bool}
const NativeTypesExceptBit = Union{Bool,HWReal}
const NativeTypes = Union{NativeTypesExceptBit, Bit}

const _Vec{W,T<:Number} = NTuple{W,Core.VecElement{T}}
# const _Vec{W,T<:Number} = Tuple{VecElement{T},Vararg{VecElement{T},W}}
# @eval struct StaticInt{N} <: Number
#     (f::Type{<:StaticInt})() = $(Expr(:new,:f))
# end
# Base.@pure StaticInt(N) = StaticInt{N}()

abstract type AbstractSIMD{W,T <: Union{<:StaticInt,NativeTypes}} <: Real end
abstract type AbstractSIMDVector{W,T} <: AbstractSIMD{W,T} end
const NativeTypesV = Union{AbstractSIMD,NativeTypes,StaticInt}
struct Vec{W,T} <: AbstractSIMDVector{W,T}
    data::NTuple{W,Core.VecElement{T}}
    @inline Vec{W,T}(x::NTuple{W,Core.VecElement{T}}) where {W,T<:Union{NativeTypes,StaticInt}} = new{W,T}(x)
    @generated function Vec(x::Tuple{Core.VecElement{T},Vararg{Core.VecElement{T},_W}}) where {_W,T<:Union{NativeTypes,StaticInt}}
        W = _W + 1
        # @assert W === pick_vector_width(W, T)# || W === 8
        Expr(:block, Expr(:meta,:inline), Expr(:call, Expr(:curly, :Vec, W, T), :x))
    end
    # @inline function Vec(x::NTuple{W,<:Core.VecElement}) where {W}
    #     T = eltype(x)
    #     @assert W === pick_vector_width(W, T)
    #     # @assert ispow2(W) && (W ≤ max(pick_vector_width(W, T), 8))
    #     new{W,T}(x)
    # end
end
struct VecUnroll{N,W,T,V<:AbstractSIMDVector{W,T}} <: AbstractSIMD{W,T}
    data::Tuple{V,Vararg{V,N}}
    @inline VecUnroll(data::Tuple{V,Vararg{V,N}}) where {N,W,T,V<:AbstractSIMDVector{W,T}} = new{N,W,T,V}(data)
end

@inline Base.copy(v::AbstractSIMDVector) = v
@inline asvec(x::_Vec) = Vec(x)
@inline asvec(x) = x
@inline data(vu::VecUnroll) = vu.data

# struct VecUnroll{N,W,T} <: AbstractSIMDVector{W,T}
#     data::NTuple{N,Vec{W,T}}
# end

@inline unrolleddata(x) = x
@inline unrolleddata(x::VecUnroll) = x.data
# struct VecTile{M,N,W,T} <: AbstractSIMDVector{W,T}
    # data::NTuple{N,VecUnroll{M,Vec{W,T}}}
# end
# description(::Type{T}) where {T <: NativeTypes} = (-1,-1,-1,T)
# description(::Type{Vec{W,T}}) where {W, T <: NativeTypes} = (-1,-1,W,T)
# description(::Type{VecUnroll{M,W,T}}) where {M, W, T <: NativeTypes} = (M,-1,W,T)
# description(::Type{VecTile{M,N,W,T}}) where {M, W, T <: NativeTypes} = (M,N,W,T)
# function description(::Type{T1}, ::Type{T2}) where {T1, T2}
#     M1,N1,W1,T1 = description(T1)
#     M2,N2,W2,T2 = description(T2)
# end

@generated function simd_vec(y::T, x::Vararg{T,_W}) where {T,_W}
    W = 1 + _W
    Wfull = nextpow2(W)
    ty = LLVM_TYPES[T]
    init = W == Wfull ? "undef" : "zeroinitializer"
    instrs = ["%v0 = insertelement <$Wfull x $ty> $init, $ty %0, i32 0"]
    Tup = Expr(:curly, :Tuple, T)
    for w ∈ 1:_W
        push!(instrs, "%v$w = insertelement <$Wfull x $ty> %v$(w-1), $ty %$w, i32 $w")
        push!(Tup.args, T)
    end
    push!(instrs, "ret <$Wfull x $ty> %v$_W")
    llvmc = :(llvmcall($(join(instrs,"\n")), _Vec{$Wfull,$T}, $Tup, y))
    for w ∈ 1:_W
        push!(llvmc.args, Expr(:ref, :x, w))
    end
    quote
        $(Expr(:meta,:inline))
        Vec($llvmc)
    end
end

function vec_quote(W, Wpow2, offset = 0)
    call = Expr(:call, :simd_vec); Wpow2 += offset
    iszero(offset) && push!(call.args, :y)
    foreach(w -> push!(call.args, Expr(:ref, :x, w)), max(1,offset):min(W,Wpow2)-1)
    # foreach(w -> push!(call.args, Expr(:call, :VecElement, Expr(:call, :zero, :T))), W+1:Wpow2)
    call
end
@generated function Vec(y::T, x::Vararg{T,_W}) where {_W, T <: NativeTypes}
    W = _W + 1
    Wpow2 = pick_vector_width(W, T)
    if W ≤ Wpow2
        vec_quote(W, Wpow2)
    else
        tup = Expr(:tuple)
        offset = 0
        while offset < W
            push!(tup.args, vec_quote(W, Wpow2, offset)); offset += Wpow2
        end
        Expr(:call, :VecUnroll, tup)
    end
end

struct Mask{W,U<:Unsigned} <: AbstractSIMDVector{W,Bit}
    u::U
    @inline function Mask{W,U}(u::Unsigned) where {W,U} # ignores U...
        U2 = mask_type(Val{W}())
        new{W,U2}(u % U2)
    end
end
const AbstractMask{W} = Union{Mask{W}, Vec{W,Bool}}
@inline Mask{W}(u::U) where {W,U<:Unsigned} = Mask{W,U}(u)
# Const prop is good enough; added an @inferred test to make sure.
# Removed because confusion can cause more harm than good.
# @inline Mask(u::U) where {U<:Unsigned} = Mask{sizeof(u)<<3,U}(u)

@inline Base.broadcastable(v::AbstractSIMDVector) = Ref(v)

# Vec{N,T}(x) where {N,T} = Vec(ntuple(i -> VE(T(x)), Val(N)))
# @inline function Vec{N,T}(x::Number) where {N,T}
    # Vec(ntuple(i -> VE(T(x)), Val(N)))
# end
# @inline function Vec{N,T}(x::Vararg{<:Number,N}) where {N,T}
    # Vec(ntuple(i -> VE(T(x[i])), Val(N)))
# end
# @inline function Vec(v::Vec{N,T}) where {N,T}
    # Vec{N,T}(v)
# end
# @inline Vec(u::Unsigned) = u # Unsigned integers are treated as vectors of bools
# @inline Vec{W}(u::U) where {W,U<:Unsigned} = Mask{W,U}(u) # Unsigned integers are treated as vectors of bools
# @inline Vec(v::Vec{W,T}) where {W,T} = v
# @inline Vec{W}(v::Vec{W,T}) where {W,T} = v
# @inline Vec{W,T}(v::Vec{W,T}) where {W,T} = v
# @inline Vec{W}(v::Vec{W,T}) where {W,T} = Vec{W,T}(v)
# @inline vbroadcast(::Val, b::Bool) = b

Vec{W,T}(x::Vararg{NativeTypes,W}) where {W,T<:NativeTypes} = Vec(ntuple(w -> Core.VecElement{T}(x[w]), Val{W}()))
Vec{1,T}(x::Union{Float32,Float64}) where {T<:NativeTypes} = T(x)
Vec{1,T}(x::Union{Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64,Bool}) where {T<:NativeTypes} = T(x)
# Vec{1,T}(x::Integer) where {T<:HWReal} = T(x)

@inline Base.length(::AbstractSIMDVector{W}) where W = W
@inline Base.size(::AbstractSIMDVector{W}) where W = (W,)
@inline Base.eltype(::AbstractSIMD{W,T}) where {W,T} = T
@inline Base.conj(v::AbstractSIMDVector) = v # so that things like dot products work.
@inline Base.adjoint(v::AbstractSIMDVector) = v # so that things like dot products work.
@inline Base.transpose(v::AbstractSIMDVector) = v # so that things like dot products work.
# @inline Base.getindex(v::Vec, i::Integer) = v.data[i].value

# Not using getindex/setindex as names to emphasize that these are generally treated as single objects, not collections.
@generated function extractelement(v::Vec{W,T}, i::I) where {W,I <: IntegerTypesHW,T}
    typ = LLVM_TYPES[T]
    instrs = """
        %res = extractelement <$W x $typ> %0, i$(8sizeof(I)) %1
        ret $typ %res
    """
    call = :(llvmcall($instrs, $T, Tuple{_Vec{$W,$T},$I}, data(v), i))
    Expr(:block, Expr(:meta, :inline), call)
end
@generated function insertelement(v::Vec{W,T}, x::T, i::I) where {W,I <: IntegerTypesHW,T}
    typ = LLVM_TYPES[T]
    instrs = """
        %res = insertelement <$W x $typ> %0, $typ %1, i$(8sizeof(I)) %2
        ret <$W x $typ> %res
    """
    call = :(Vec(llvmcall($instrs, _Vec{$W,$T}, Tuple{_Vec{$W,$T},$T,$I}, data(v), x, i)))
    Expr(:block, Expr(:meta, :inline), call)
end
@inline (v::AbstractSIMDVector)(i::IntegerTypesHW) = extractelement(v, i - one(i))
@inline (v::AbstractSIMDVector)(i::Integer) = extractelement(v, Int(i) - 1)
Base.@propagate_inbounds (vu::VecUnroll)(i::Integer, j::Integer) = vu.data[j](i)

# @inline function Vec{N,T}(v::Vec{N,T2}) where {N,T,T2}
    # @inbounds Vec(ntuple(n -> Core.VecElement{T}(T(v[n])), Val(N)))
# end

# @inline Base.one(::Type{<:AbstractSIMDVector{W,T}}) where {W,T} = Vec(vbroadcast(Vec{W,T}, one(T)))
# @inline Base.one(::AbstractSIMDVector{W,T}) where {W,T} = Vec(vbroadcast(Vec{W,T}, one(T)))
# @inline Base.zero(::Type{<:AbstractSIMDVector{W,T}}) where {W,T} = Vec(vbroadcast(Vec{W,T}, zero(T)))
# @inline Base.zero(::AbstractSIMDVector{W,T}) where {W,T} = Vec(vbroadcast(Vec{W,T}, zero(T)))

# Use with care in function signatures; try to avoid the `T` to stay clean on Test.detect_unbound_args

@inline data(v) = v
@inline data(v::Vec) = v.data
#@inline data(v::AbstractSIMDVector) = v.data
# @inline extract_value(v::Vec, i) = v[i].value
# @inline extract_value(v::Vec, i) = v.data[i].value

function Base.show(io::IO, v::AbstractSIMDVector{W,T}) where {W,T}
    print(io, "Vec{$W,$T}<")
    for w ∈ 1:W
        print(io, repr(extractelement(v, w-1)))
        w < W && print(io, ", ")
    end
    print(io, ">")
end
Base.bitstring(m::Mask{W}) where {W} = bitstring(data(m))[end-W+1:end]
function Base.show(io::IO, m::Mask{W}) where {W}
    bits = m.u
    print(io, "Mask{$W,Bool}<")
    for w ∈ 0:W-1
        print(io, bits & 1)
        bits >>= 1
        w < W-1 && print(io, ", ")
    end
    print(io, ">")
end
function Base.show(io::IO, vu::VecUnroll{N,W,T}) where {N,W,T}
    println(io, "$(N+1) x Vec{$W, $T}")
    for n in 1:N+1
        show(io, vu.data[n]);
        n > N || println(io)
    end
end

"""
The name `MM` type refers to _MM registers such as `XMM`, `YMM`, and `ZMM`.
`MMX` from the original MMX SIMD instruction set is a [meaningless initialism](https://en.wikipedia.org/wiki/MMX_(instruction_set)#Naming).

The `MM{W,X}` type is used to represent SIMD indexes of width `W` with stride `X`.
"""
struct MM{W,X,I<:Union{HWReal,StaticInt}} <: AbstractSIMDVector{W,I}
    i::I
    @inline MM{W,X}(i::T) where {W,X,T<:Union{HWReal,StaticInt}} = new{W,X::Int,T}(i)
end
@inline MM(i::MM{W,X}) where {W,X} = MM{W,X}(i.i)
@inline MM{W}(i::Union{HWReal,StaticInt}) where {W} = MM{W,1}(i)
@inline MM{W}(i::Union{HWReal,StaticInt}, ::StaticInt{X}) where {W,X} = MM{W,X}(i)
@inline data(i::MM) = i.i

@inline extractelement(i::MM{W,X}, j) where {W,X} = i.i + X * j

include("static.jl")
include("cartesianvindex.jl")
# include("vectorizable.jl")
# include("strideprodcsestridedpointers.jl")
const TOPOLOGY = try
    Hwloc.topology_load();
catch e
    @warn e
    @warn """
        Using Hwloc failed. Please file an issue with the above warning at: https://github.com/JuliaParallel/Hwloc.jl
        Proceeding with generic topology assumptions. This may result in reduced performance.
    """
    nothing
end
if TOPOLOGY === nothing
    include("topology_generic.jl")
else
    include("topology.jl")
end
@static if Sys.ARCH === :x86_64 || Sys.ARCH === :i686
    include("cpu_info_x86_llvm.jl")
else
    include("cpu_info_generic.jl")
end
include("vector_width.jl")
include("llvm_types.jl")
include("lazymul.jl")
include("strided_pointers/stridedpointers.jl")
# include("strided_pointers/bitpointers.jl")
include("strided_pointers/cartesian_indexing.jl")
include("strided_pointers/grouped_strided_pointers.jl")
include("strided_pointers/cse_stridemultiples.jl")
include("llvm_intrin/binary_ops.jl")
include("llvm_intrin/conversion.jl")
include("llvm_intrin/masks.jl")
include("llvm_intrin/intrin_funcs.jl")
include("llvm_intrin/memory_addr.jl")
include("llvm_intrin/unary_ops.jl")
include("llvm_intrin/vbroadcast.jl")
include("llvm_intrin/vector_ops.jl")
include("llvm_intrin/nonbroadcastingops.jl")
include("fmap.jl")
include("promotion.jl")
include("ranges.jl")
include("alignment.jl")
include("special/misc.jl")

function reduce_to_onevec_quote(Nm1)
    N = Nm1 + 1
    q = Expr(:block, Expr(:meta,:inline))
    assign = Expr(:tuple); syms = Vector{Symbol}(undef, N)
    for n ∈ 1:N
        x_n = Symbol(:x_, n)
        push!(assign.args, x_n); syms[n] = x_n;
    end
    push!(q.args, Expr(:(=), assign, :(data(vu))))
    while N > 1
        tz = trailing_zeros(N)
        for h ∈ 1:tz
            N >>= 1
            for n ∈ 1:N
                push!(q.args, Expr(:(=), syms[n], Expr(:call, :f, syms[n], syms[n+N])))
            end
        end
        if N > 1 # N must be odd
            push!(q.args, Expr(:(=), syms[N-1], Expr(:call, :f, syms[N-1], syms[N])))
            N -= 1
        end
    end
    push!(q.args, first(syms))
    q
end
@generated function reduce_to_onevec(f::F, vu::VecUnroll{Nm1}) where {F, Nm1}
    reduce_to_onevec_quote(Nm1)
end

include("precompile.jl")
_precompile_()

end # module


text:
"""
    _⛔()

Print UInts as decimal instead of hex.
This is type piracy, but shouldn't be a huge deal since it's just `show`.
"""
function _⛔()
    @eval Base.show(io::IO, x::T) where {T<:Union{UInt, UInt128, UInt64,
    UInt32, UInt16, UInt8}} = Base.print(io, x)
end


text:
type SDEProblem{uType,tType,isinplace,NP,F,G,C,MM,ND} <: AbstractSDEProblem{uType,tType,isinplace,ND}
  f::F
  g::G
  u0::uType
  tspan::Tuple{tType,tType}
  noise::NP
  callback::C
  mass_matrix::MM
  noise_rate_prototype::ND
end

function SDEProblem(f,g,u0,tspan;iip = isinplace(f,3),
        noise_rate_prototype = nothing,
        noise= nothing,
        callback = nothing,mass_matrix=I)

  SDEProblem{typeof(u0),eltype(tspan),iip,typeof(noise),typeof(f),typeof(g),typeof(callback),typeof(mass_matrix),typeof(noise_rate_prototype)}(
  f,g,u0,tspan,noise,callback,mass_matrix,noise_rate_prototype)
end

# Mu' = f[1] + f[2] + ...
type SplitSDEProblem{uType,tType,isinplace,NP,F,G,C,MM,ND} <: AbstractSDEProblem{uType,tType,isinplace,ND}
  f::F
  g::G
  u0::uType
  tspan::Tuple{tType,tType}
  noise::NP
  callback::C
  mass_matrix::MM
  noise_rate_prototype::ND
end

function SplitSDEProblem(f,g,u0,tspan; iip = isinplace(f[2],3),
                         noise = nothing,
                         noise_rate_prototype = nothing,
                         callback=nothing,mass_matrix=I)
  @assert typeof(f) <: Tuple
  SplitSDEProblem{typeof(u0),eltype(tspan),iip,typeof(noise),typeof(f),
                  typeof(g),typeof(callback),typeof(mass_matrix),
                  typeof(noise_rate_prototype)}(f,g,u0,tspan,noise,callback,mass_matrix,noise_rate_prototype)
end

# M[i]*u[i]' = f[i]
type PartitionedSDEProblem{uType,tType,isinplace,NP,F,G,C,MM,ND} <: AbstractSDEProblem{uType,tType,isinplace,ND}
  f::F
  g::G
  u0::uType
  tspan::Tuple{tType,tType}
  noise::NP
  callback::C
  mass_matrix::MM
  noise_rate_prototype::ND
end

function PartitionedSDEProblem(f,g,u0,tspan; iip = isinplace(f[1],3),
                               noise = nothing,
                               noise_rate_prototype = nothing,
                               callback=nothing,mass_matrix=nothing)
  @assert typeof(f) <: Tuple
  @assert typeof(g) <: Tuple
  @assert typeof(u0) <: Tuple
  if mass_matrix == nothing
    _mm = ((I for i in 1:length(f))...)
  end
  PartitionedSDEProblem{typeof(u0),eltype(tspan),iip,typeof(noise),typeof(f),typeof(g),
                        typeof(callback),typeof(_mm),typeof(noise_rate_prototype)}(
                        f,g,u0,tspan,noise,callback,_mm,noise_rate_prototype)
end


text:
export Goal, StateSpaceGoal, GoalState, ConfigSpaceGoal, GoalConfig

abstract type Goal end
# StateSpaceGoal
struct StateSpaceGoal{S} <: Goal
    set::S
end
const GoalState{S<:State} = StateSpaceGoal{SVector{1,S}}
GoalState(x::State) = StateSpaceGoal(SVector((x,)))
Base.in(x::State, G::StateSpaceGoal) = x in G.set
Base.rand(G::StateSpaceGoal) = rand(G.set)
@recipe function f(G::StateSpaceGoal; dims=(1, 2))#, goal_color=:green, goal_alpha=1, goal_markershape=:star)
    # dims  --> dims
    # color :=  goal_color
    # alpha :=  goal_alpha
    # label --> ""
    if G.set isa AbstractArray{<:State}
        seriestype  --> :scatter
        markercolor :=  :match
        # markershape :=  goal_markershape
        x, y = dims
        [q[x] for q in G.set], [q[y] for q in G.set]
    else
        dims  --> dims
        G.set
    end
end

# ConfigSpaceGoal
struct ConfigSpaceGoal{C,S2C,C2S} <: Goal
    projection::C
    state2config::S2C
    config2state::C2S
end
const GoalConfig{C<:Config,S2C,C2S} = ConfigSpaceGoal{SVector{1,C},S2C,C2S}
GoalConfig(q::Config, state2config, config2state) = ConfigSpaceGoal(SVector((q,)), state2config, config2state)
Base.in(x::State, G::ConfigSpaceGoal) = G.state2config(x) in G.projection
Base.rand(G::ConfigSpaceGoal) = G.config2state(rand(G.projection))
@recipe function f(G::ConfigSpaceGoal; dims=(1, 2))#, goal_color=:green, goal_alpha=1, goal_markershape=:star)
    dims  --> dims
    # color :=  goal_color
    # alpha :=  goal_alpha
    # label --> ""
    G.projection
end

max_stars_repo_name: pbpf/clean

max_issues_repo_name: pbpf/clean

max_forks_repo_name: pbpf/clean


text:
function manual_orbit(gens::Vector{GEl}, pt::T, op=^) where {GEl <: GroupElement, T}
    G = parent(gens[1])
    Δ = [pt]
    Δ_set = Set(Δ)
    for δ in Δ
        for g in gens
            γ = op(δ, g)
            if !(γ ∈ Δ_set)
                push!(Δ, γ)
                push!(Δ_set, γ)
            end
        end
    end
    return (Δ, Δ_set)
end

function test_orbit(OrbT::Type{T}) where T<: AbstractOrbit
    or = OrbT(1, Symbol("a"))
    @test length(or) == 1
    @test or[1] == :a
    push!(or, (3, :z))
    @test length(or) == 2
    @test collect(or) == [1, 3]
    @test or[1] == :a
    @test or[3] == :z
    push!(or, (2,:c))
    @test length(or) == 3
    push!(or, (5,:b))
    @test length(or) == 4
    @test collect(or) == [1,3,2,5]
    @test or[5] == :b

    orb = OrbT(7)
    @test orb isa OrbT{Int, Nothing}
    @test collect(orb) == [7]
    push!(orb, 5)
    push!(orb, 3)
    @test length(orb) == 3
    @test orb[3] == nothing
    @test orb[5] == nothing
    @test collect(orb) == [7,5,3]
end

@testset "Unit: perms actions" begin
    g = perm"(2,3,5)(8,9)"
    @test fixes(g, 1)
    @test !(fixes(g,2))
    @test fixes(g, 10)
    @test map(i->fixes(g, i), 1:11) == [true, false, false, true, false, true, true, false, false, true, true]
    @test fixedpoints(g) == [1,4,6,7]

    @test firstmoved(g) == 2
    @test firstmoved(Perm(5)) == nothing
    @test fixedpoints(perm"(1,2,3,4,5)") isa Vector{Int}
    @test nfixedpoints(perm"(1,2,3,4,5)") == 0
    @test fixedpoints(Perm(Int8[1,2,3,4,5])) isa Vector{Int8}
    @test fixedpoints(perm"(1,3,5)") == [2,4]
    @test nfixedpoints(perm"(1,3,5)") == 2
    @test nfixedpoints(perm"(1,3,5)(6)") == 3

    g = Perm(Int8[1,3,4,2]) # (1)(2,3,4)
    @test fixes(g, 1) == true
    @test fixes(g, 5) == true
    @test [2,1,1,1]^g isa Vector{Int}

    @test fixes(g, [2,1,1,1]) == true
    @test fixes(g, [2,2,1,1]) == false

    @test firstmoved(g) == 2
    @test firstmoved(g) isa Int8

    # g = (1)(2,3,4)
    @test [1,2,3].^Ref(g) isa Vector{Int}
    @test [1,2,3].^Ref(g) == [1,3,4]
    @test Int16[1,2,3].^Ref(g) isa Vector{Int16}

    @test (1,2,3).^Ref(g) isa NTuple{3, Int}
    @test tuple(Int16[1,2,3]...).^Ref(g) isa NTuple{3,Int16}
    @test (1,2,3).^Ref(g) == (1,3,4)

    @test isone(g) == false
    @test isone(Perm([1,2,3]))

    @test degree(perm"(1,3)") == 3
    @test degree(perm"(1,3)(5)") == 5

    @test PermutationGroups.emb(perm"(1,3)", 5) != perm"(1,3)"
    @test PermutationGroups.emb(perm"(1,3)", 5) == perm"(1,3)(5)"
    @test PermutationGroups.emb(perm"(1,3)", 5) != perm"(1,3)(6)"
end

import PermutationGroups: Orbit1, Orbit2, Orbit3, Orbit4, Orbit5
const OrbitTypes = [Orbit1, Orbit2, Orbit3, Orbit4, Orbit5]

@testset "Orbit Types" begin

    @test Orbit1([1,3,2]) isa Orbit1{Int}

    o = Orbit1([1,3,2])
    @test 1 in o
    @test 4 ∉ o
    push!(o, 4)
    @test 4 in o
    @test collect(o) == [1,3,2,4]

    orb = Orbit2(1, (2,(:b,nothing)), Dict{Int, Tuple{Symbol, Int}}(1=>(:a, 3), 3=>(:c, 2)))
    @test collect(orb) isa Vector{Int}
    @test collect(orb) == [1,3,2]
    @test 1 in orb
    @test 4 ∉ orb
    push!(orb, (4, :z))
    @test 4 in orb
    @test collect(o) == [1,3,2,4]

    orb = Orbit3(1, (2,:b ), Dict{Int, Tuple{Symbol, Int}}(1=>(:a, 3), 3=>(:c, 2)))
    @test collect(orb) isa Vector{Int}
    @test collect(orb) == [1,3,2]
    @test 1 in orb
    @test 4 ∉ orb
    push!(orb, (4, :z))
    @test 4 in orb
    @test collect(o) == [1,3,2,4]

    orb = Orbit4(1, 2, Dict{Int, Tuple{Symbol, Union{Int, Nothing}}}(1=>(:a, 3), 3=>(:c, 2), 2 =>(:b, nothing)))
    @test collect(orb) isa Vector{Int}
    @test collect(orb) == [1,3,2]
    @test 1 in orb
    @test 4 ∉ orb
    push!(orb, (4, :z))
    @test 4 in orb
    @test collect(o) == [1,3,2,4]

    orb = Orbit5(1, 2, Dict{Int, Tuple{Symbol, Int}}(1=>(:a, 3), 3=>(:c, 2), 2 =>(:b, 2)))
    @test collect(orb) isa Vector{Int}
    @test collect(orb) == [1,3,2]
    @test 1 in orb
    @test 4 ∉ orb
    push!(orb, (4, :z))
    @test 4 in orb
    @test collect(o) == [1,3,2,4]
end

@testset "Orbit definitions: elementary ops" begin

    Random.seed!(1);
    SIZE=30
    G = SymmetricGroup(SIZE);
    gens = [rand(G) for _ in 1:3];

    pt = 7
    Δ, _ = manual_orbit(gens, pt, ^)

    for OrbT in OrbitTypes
        test_orbit(OrbT)
        @test collect(OrbT(gens, pt, ^)) == Δ
        t = OrbT(Transversal, gens, pt, ^)
        @test length(t) == SIZE
    end

    t1 = Orbit1(Transversal, gens, pt, ^);

    for OrbT in OrbitTypes
        tr = OrbT(Transversal, gens, pt, ^)
        @test all([tr[o] == t1[o] for o in tr])
        @test all([pt^tr[o] == o for o in tr])
    end
end


text:
#Simulate a determinantally-thinned Poisson point process on a rectangle
#Author: H. Paul Keeler, 2019.

#Note: Need the .+ for adding a scalar to an array
#Also need . for sqrt, exp, cos, sin etc and assigning scalars to arrays
#Index and Boolean arrrays need to be vectors eg v=zeros(n),  NOT v=zeros(n,1)

#clearconsole(); #for clearing Julia REPL console

using Distributions #for random simulations
using LinearAlgebra;
using PyPlot #uses Python for plotting
PyPlot.close("all");  # close all PyPlot figures

#set random seed for reproducibility
#Random.seed!(1234)

###START -- Parameters -- ###START
#Poisson point process parameters
lambda=50; #intensity (ie mean density) of the Poisson process

#choose kernel
choiceKernel=1; #1 for Gaussian (ie squared exponetial );2 for Cauchy
sigma=1;# parameter for Gaussian and Cauchy kernel
alpha=1;# parameter for Cauchy kernel

#Simulation window parameters
xMin=0;xMax=1;yMin=0;yMax=1;
xDelta=xMax-xMin;yDelta=yMax-yMin; #rectangle dimensions
areaTotal=xDelta*yDelta; #area of rectangle
###END -- Parameters -- ###END

### START -- Simulate a Poisson point process on a rectangle ###START
#Simulate Poisson point process
numbPoints=rand(Poisson(areaTotal*lambda)); #Poisson number of points
xx=xDelta*(rand(numbPoints)).+xMin;#x coordinates of Poisson points
yy=xDelta*(rand(numbPoints)).+yMin;#y coordinates of Poisson points
### END -- Simulate a Poisson point process on a rectangle --END ###

#numbPoints=5; xx=-2:1:2; yy=3:7 #TEMP

### START -- CREATE L matrix -- START ###
#all squared distances of x/y difference pairs
xxDiff=kron(xx,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(xx));
yyDiff=kron(yy,ones(1,numbPoints))-kron(ones(numbPoints,1),transpose(yy));
rrDiffSquared=(xxDiff.^2+yyDiff.^2);
if choiceKernel==1
    ##Gaussian/squared exponential kernel
    L=lambda*exp.(-(rrDiffSquared)/sigma^2);
elseif choiceKernel==2
    ##Cauchy kernel
    L=lambda./(1+rrDiffSquared/sigma^2).^(alpha+1/2);
else
    println("choiceKernel has to be equal to 1 or 2.");
end

### END-- CREATE L matrix -- ### END
L=Symmetric(L); #convert to Symmetric marix

#START - Sampling/simulating DPP - START
# #Retrieve eigenvalues and eigenvectors
eigenVectL=eigvecs(L); #eigen decomposition -- vectors
eigenValL=(eigvals(L)); #eigen decomposition -- values
eigenVectK = (eigenVectL);
eigenValK = eigenValL./(1 .+eigenValL); #eigenvalues of K

#Bernoulli trials (ie coin flips) to determine number of points
booleEigen = (rand(length(eigenValK)) .<= eigenValK);

#number of points in the DPP realization
numbPointsDPP=sum(booleEigen);
#retrieve eigenvectors corresponding to successful Bernoulli trials
global spaceV = eigenVectK[:,booleEigen]; #subspace V
indexDPP = zeros(Int8,numbPointsDPP); #index for final DPP configuration

global numbPointsRemain=numbPointsDPP;
#Loop through for all points
for ii=1:numbPointsDPP
    #Compute probabilities for each point i
    global Prob_i=vec(sum(spaceV.^2,dims=2)); #sum across rows
    Prob_i=Prob_i./sum(Prob_i); #normalize

    #Choose a point (from 1 to numbPoints) using (prob mass function) Prob_i
    uRand=rand(1);
    indexCurrent= findall(x -> x> uRand[1], cumsum(Prob_i))[1];
    indexDPP[ii]=indexCurrent; #update index

    if ii<numbPointsDPP
        #Choose a vector to remove
        jj=findall(x-> x>0, abs.(spaceV[indexCurrent,:]))[1];
        columnVj=spaceV[:,jj]; #j-th column of V
        booleKeep_j=(jj).!=(1:numbPointsRemain);
        global spaceV=spaceV[:,booleKeep_j]; #remove column
        #probably a better way for removing columns

        #Update matrix V by removing Vj component from the space
        spaceV=spaceV-kron(columnVj, transpose(spaceV[indexCurrent,:]./columnVj[indexCurrent]));

        #Orthonormalize
        decompQR=qr(spaceV);
        spaceV=Matrix(decompQR.Q);
        #need Matrix function for properly sized matrix
    end

    global numbPointsRemain= numbPointsRemain-1; #update
end
indexDPP=sort(indexDPP);

#Plotting
#Plot Poisson point process
PyPlot.scatter(xx,yy, edgecolor="k", facecolor="none");
PyPlot.xlabel("x"); plt.ylabel("y");
#random color vector
vectorColor=rand(3);
#Plot determinantally-thinned Poisson point process
PyPlot.scatter(xx[indexDPP],yy[indexDPP],edgecolor="none",facecolor=vectorColor);

println("Program has ended.");


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

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

                     @variable(m, -37.14009556780016 <= q <= 48.365016418887166)

                     add_NL_constraint(m, :(1/(1 + exp(-(0.24902435571631587 + -0.02312729681609138*1/(1 + exp(-(-0.46870412880299783 + 0.1700038462852933*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.44738483682757924*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.5112184633122538*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.17714072857386487*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9529511507705823*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.5418072450548097*1/(1 + exp(-(0.5019192867350393 + 0.2997113620022893*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.5721484689942011*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.4073624372378828*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + -0.07630883358086304*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.3103910161241421*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.9789829058919253*1/(1 + exp(-(-0.652369829242545 + -0.998242239199818*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.041041478696029365*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.4348093907280841*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.7773011179238121*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7537599741964742*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.13446361488468206*1/(1 + exp(-(-0.40141742757451926 + 0.7289092837988314*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + 0.16077592157977172*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.6378484913808045*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9326240829024273*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9638370498324353*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.3069132295129271*1/(1 + exp(-(0.17680227033398044 + 0.8293506390949057*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.09356004658531791*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.16358082594109513*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9029174038261001*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7318887196209252*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3])))))))))) + 1/(1 + exp(-(-0.017552134571214406 + -0.41004797399293524*1/(1 + exp(-(-0.46870412880299783 + 0.1700038462852933*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.44738483682757924*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.5112184633122538*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.17714072857386487*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9529511507705823*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.47019448283071075*1/(1 + exp(-(0.5019192867350393 + 0.2997113620022893*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.5721484689942011*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.4073624372378828*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + -0.07630883358086304*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.3103910161241421*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.35795867979675133*1/(1 + exp(-(-0.652369829242545 + -0.998242239199818*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.041041478696029365*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.4348093907280841*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.7773011179238121*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7537599741964742*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.44715886126593407*1/(1 + exp(-(-0.40141742757451926 + 0.7289092837988314*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + 0.16077592157977172*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.6378484913808045*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9326240829024273*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9638370498324353*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.22638221307132733*1/(1 + exp(-(0.17680227033398044 + 0.8293506390949057*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.09356004658531791*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.16358082594109513*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9029174038261001*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7318887196209252*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3])))))))))) + 1/(1 + exp(-(-0.4029592795849051 + -0.6197606146665708*1/(1 + exp(-(-0.46870412880299783 + 0.1700038462852933*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.44738483682757924*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.5112184633122538*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.17714072857386487*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9529511507705823*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.8464388391219866*1/(1 + exp(-(0.5019192867350393 + 0.2997113620022893*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.5721484689942011*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.4073624372378828*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + -0.07630883358086304*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.3103910161241421*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.6262663939568953*1/(1 + exp(-(-0.652369829242545 + -0.998242239199818*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.041041478696029365*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.4348093907280841*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.7773011179238121*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7537599741964742*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.06090941414894013*1/(1 + exp(-(-0.40141742757451926 + 0.7289092837988314*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + 0.16077592157977172*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.6378484913808045*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9326240829024273*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9638370498324353*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.6699649674430836*1/(1 + exp(-(0.17680227033398044 + 0.8293506390949057*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.09356004658531791*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.16358082594109513*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9029174038261001*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7318887196209252*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3])))))))))) + 1/(1 + exp(-(0.6579858782021573 + -0.21911632564812766*1/(1 + exp(-(-0.46870412880299783 + 0.1700038462852933*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.44738483682757924*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.5112184633122538*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.17714072857386487*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9529511507705823*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.7292607357990395*1/(1 + exp(-(0.5019192867350393 + 0.2997113620022893*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.5721484689942011*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.4073624372378828*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + -0.07630883358086304*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.3103910161241421*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.23882038501163416*1/(1 + exp(-(-0.652369829242545 + -0.998242239199818*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.041041478696029365*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.4348093907280841*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.7773011179238121*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7537599741964742*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.6855544316424598*1/(1 + exp(-(-0.40141742757451926 + 0.7289092837988314*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + 0.16077592157977172*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.6378484913808045*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9326240829024273*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9638370498324353*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.2868272308560216*1/(1 + exp(-(0.17680227033398044 + 0.8293506390949057*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.09356004658531791*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.16358082594109513*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9029174038261001*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7318887196209252*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3])))))))))) + 1/(1 + exp(-(-0.10147744083820065 + -0.7175110849623545*1/(1 + exp(-(-0.46870412880299783 + 0.1700038462852933*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.44738483682757924*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.5112184633122538*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.17714072857386487*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9529511507705823*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.9583278917345623*1/(1 + exp(-(0.5019192867350393 + 0.2997113620022893*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.5721484689942011*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.4073624372378828*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + -0.07630883358086304*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.3103910161241421*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.7313133539296679*1/(1 + exp(-(-0.652369829242545 + -0.998242239199818*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.041041478696029365*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.4348093907280841*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.7773011179238121*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7537599741964742*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + 0.008349755673621395*1/(1 + exp(-(-0.40141742757451926 + 0.7289092837988314*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + 0.16077592157977172*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + 0.6378484913808045*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9326240829024273*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.9638370498324353*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3]))))))) + -0.13663535205769417*1/(1 + exp(-(0.17680227033398044 + 0.8293506390949057*1/(1 + exp(-(-0.07115429328131828 + -0.06282459839957566*$(x[1]) + 0.4662931752239805*$(x[2]) + -0.47993632100881634*$(x[3])))) + -0.09356004658531791*1/(1 + exp(-(-0.42367185224307535 + 0.829552620135646*$(x[1]) + -0.7267035823407642*$(x[2]) + 0.6637528273154039*$(x[3])))) + -0.16358082594109513*1/(1 + exp(-(0.6408115001973855 + -0.9252249601617657*$(x[1]) + 0.6902522661180681*$(x[2]) + 0.6531628217744303*$(x[3])))) + 0.9029174038261001*1/(1 + exp(-(0.3778204937005931 + 0.21019890124389518*$(x[1]) + -0.5904566970281198*$(x[2]) + -0.06968695857557394*$(x[3])))) + 0.7318887196209252*1/(1 + exp(-(0.7716365722893217 + 0.12636272698834716*$(x[1]) + 0.15699019471654063*$(x[2]) + -0.5007466869555728*$(x[3])))))))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
# Julia wrapper for header: /usr/include/libavutil/log.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

export
    av_vlog,
    av_log_get_level,
    av_log_set_level,
    av_log_set_callback,
    av_log_default_callback,
    av_default_item_name,
    av_default_get_category,
    av_log_format_line,
    av_log_format_line2,
    av_log_set_flags,
    av_log_get_flags

# function av_vlog(avcl, level::Integer, fmt, vl)
#     ccall((:av_vlog, libavutil), Cvoid, (Ptr{Cvoid}, Cint, Cstring, va_list), avcl, level, fmt, vl)
# end

function av_log_get_level()
    ccall((:av_log_get_level, libavutil), Cint, ())
end

function av_log_set_level(level::Integer)
    ccall((:av_log_set_level, libavutil), Cvoid, (Cint,), level)
end

function av_log_set_callback(callback)
    ccall((:av_log_set_callback, libavutil), Cvoid, (Ptr{Cvoid},), callback)
end

# function av_log_default_callback(avcl, level::Integer, fmt, vl)
#     ccall((:av_log_default_callback, libavutil), Cvoid, (Ptr{Cvoid}, Cint, Cstring, va_list), avcl, level, fmt, vl)
# end

function av_default_item_name(ctx)
    ccall((:av_default_item_name, libavutil), Cstring, (Ptr{Cvoid},), ctx)
end

function av_default_get_category(ptr)
    ccall((:av_default_get_category, libavutil), AVClassCategory, (Ptr{Cvoid},), ptr)
end

# function av_log_format_line(ptr, level::Integer, fmt, vl, line, line_size::Integer, print_prefix)
#     ccall((:av_log_format_line, libavutil), Cvoid, (Ptr{Cvoid}, Cint, Cstring, va_list, Cstring, Cint, Ptr{Cint}), ptr, level, fmt, vl, line, line_size, print_prefix)
# end

# function av_log_format_line2(ptr, level::Integer, fmt, vl, line, line_size::Integer, print_prefix)
#     ccall((:av_log_format_line2, libavutil), Cint, (Ptr{Cvoid}, Cint, Cstring, va_list, Cstring, Cint, Ptr{Cint}), ptr, level, fmt, vl, line, line_size, print_prefix)
# end

function av_log_set_flags(arg::Integer)
    ccall((:av_log_set_flags, libavutil), Cvoid, (Cint,), arg)
end

function av_log_get_flags()
    ccall((:av_log_get_flags, libavutil), Cint, ())
end


text:
import Dates
import SHA
import StaticArrays.SVector

################
# AbstNSCls
################

abstract type AbstNSCls <: Function end

################
# _NSCls
################

struct _NSCls{TYPE} <: AbstNSCls
    __args::Tuple{Vararg{Symbol}}
    __kargs
    __cls::NS
    __code::__NSX_CodeMode
    __type::DataType
    __instances
    __link_instances::Bool
    __init::Vector{Union{Nothing, NSTagFunc{:mth}}}
    __post::Vector{Union{Nothing, NSTagFunc{:mth}}}

    _NSCls{TYPE}(args...; __link_instances=false, kargs...) where TYPE =
        begin
            nsc = new{TYPE}(#= __args           =#
                            args,
                            #= __kargs          =#
                            kargs,
                            #= __cls            =#
                            NS(),
                            #= __code           =#
                            __NSX_CodeMode(),
                            #= __type           =#
                            TYPE,
                            #= __instances      =#
                            [],
                            #= __link_instances =#
                            __link_instances,
                            #= __init           =#
                            [nothing],
                            #= __post           =#
                            [nothing])
            push!(nsc.__code.__instances, nsc.__instances)
            nsc
        end
end

(nsc::_NSCls{<: __NSClsInstance})(args...; kargs...) =
    begin
        o = nsc.__type(nsc.__cls)

        na = length(nsc.__args)
        nka = length(nsc.__kargs)

        length(args) < na &&
            Base.error("number of args should be equal to or larger than $na")

        for (atr, val) ∈ zip(nsc.__args, args[1:na])
            Base.setproperty!(o, atr, val)
        end

        for (atr, val) ∈ nsc.__kargs
            Base.setproperty!(o, atr, atr ∈ keys(kargs) ? kargs[atr] : val)
        end

        isnothing(nsc.__init[1]) ||
            nsc.__init[1](o)(args[na+1:end]...;
                             Dict((k,v)
                                  for (k,v) ∈ kargs if k ∉ keys(nsc.__kargs))...)

        for (atr, val) ∈ nsc.__code.__code
            if atr == :exe
                Base.setproperty!(o, atr, val)
            else
                x = isa(val, NScst_item) ? Base.getproperty(o, :cst) : o
                y = (isa(val.obj, NSTagFunc)
                     ? Base.getproperty(x, typeof(val.obj).parameters[1])
                     : x)
                z = isa(val.obj, NSTagFunc) ? val.obj.fnc : val.obj
                Base.setproperty!(y, atr, z)
            end
        end
        isnothing(nsc.__post[1]) || nsc.__post[1](o)();

        nsc.__link_instances &&
            append!(nsc.__instances, [(a=args, k=values(kargs), o=o)])
        o
    end

(nsc::_NSCls{<: NSX})(args...; kargs...) =
    begin
        o = nsc.__type()

        na = length(nsc.__args)
        nka = length(nsc.__kargs)

        length(args) < na &&
            Base.error("number of args should be equal to or larger than $na")

        for (atr, val) ∈ zip(nsc.__args, args[1:na])
            Base.setproperty!(o, atr, val)
        end

        for (atr, val) ∈ nsc.__kargs
            Base.setproperty!(o, atr, atr ∈ keys(kargs) ? kargs[atr] : val)
        end

        isnothing(nsc.__init[1]) ||
            nsc.__init[1](o)(args[na+1:end]...;
                             Dict((k,v)
                                  for (k,v) ∈ kargs if k ∉ keys(nsc.__kargs))...)

        for (atr, val) ∈ nsc.__code.__code
            if atr == :exe
                Base.setproperty!(o, atr, val)
            else
                x = isa(val, NScst_item) ? Base.getproperty(o, :cst) : o
                y = (isa(val.obj, NSTagFunc)
                     ? Base.getproperty(x, typeof(val.obj).parameters[1])
                     : x)
                z = isa(val.obj, NSTagFunc) ? val.obj.fnc : val.obj
                Base.setproperty!(y, atr, z)
            end
        end
        isnothing(nsc.__post[1]) || nsc.__post[1](o)();

        nsc.__link_instances &&
            append!(nsc.__instances, [(a=args, k=values(kargs), o=o)])
        o
    end

Base.setproperty!(nsc::_NSCls{<: __NSClsInstance}, atr::Symbol, x) =
    begin
        hasfield(typeof(nsc), atr) && (Base.setfield!(nsc, atr, x); return)

        atr == :init && (nsc.__init[1] = NSTagFunc{:mth}(x); return)
        atr == :post && (nsc.__post[1] = NSTagFunc{:mth}(x); return)
        atr == :parallel && (nsc.__code.__parallel.obj = x; return)

        haskey(_NSClsdict0, atr) &&
            Base.error("""'$(atr)' can't be used for property""")

        nsc.__cls.haskey(atr) && (return Base.setproperty!(nsc.__cls, atr, x))
        Base.setproperty!(nsc.__code, atr, x)
    end

Base.setproperty!(nsc::_NSCls{<: NSX}, atr::Symbol, x) =
    begin
        hasfield(typeof(nsc), atr) && (Base.setfield!(nsc, atr, x); return)

        atr == :init && (nsc.__init[1] = NSTagFunc{:mth}(x); return)
        atr == :post && (nsc.__post[1] = NSTagFunc{:mth}(x); return)
        atr == :parallel && (nsc.__code.__parallel.obj = x; return)

        haskey(_NSClsdict0, atr) &&
            Base.error("""'$(atr)' can't be used for property""")

        Base.setproperty!(nsc.__code, atr, x)
    end

Base.propertynames(nsc::_NSCls{<:__NSClsInstance}, private::Bool=false) =
    tuple(Base.propertynames(nsc.__cls, private)...,
          Base.keys(_NSClsdict0)...,
          Base.fieldnames(typeof(nsc))...)

Base.propertynames(nsc::_NSCls{<:NSX}, private::Bool=false) =
    tuple(Base.keys(_NSClsdict0)...,
          Base.fieldnames(typeof(nsc))...)

Base.hasproperty(nsc::_NSCls{<: __NSClsInstance}, atr::Symbol) =
    Base.hasfield(typeof(nsc), atr) ||
    haskey(_NSClsdict0, atr) ||
    Base.hasproperty(nsc.__cls, atr)

Base.hasproperty(nsc::_NSCls{<: NSX}, atr::Symbol) =
    Base.hasfield(typeof(nsc), atr) ||
    haskey(_NSClsdict0, atr)

Base.getproperty(nsc::_NSCls{<: __NSClsInstance}, atr::Symbol) =
    begin
        Base.hasfield(typeof(nsc), atr) && (return Base.getfield(nsc, atr))
        haskey(_NSClsdict0, atr) && (return _NSClsdict0[atr](nsc))
        Base.getproperty(nsc.__cls, atr)
    end

Base.getproperty(nsc::_NSCls{<: NSX}, atr::Symbol) =
    begin
        Base.hasfield(typeof(nsc), atr) && (return Base.getfield(nsc, atr))
        haskey(_NSClsdict0, atr) && (return _NSClsdict0[atr](nsc))
        Base.error("""this NSCode does not have a property named '$(atr)'.""")
    end

NSCls(args...; __link_instances=false, kargs...) =
    _NSCls{__NSClsInstance{gensym()}}(args...;
                                      __link_instances=__link_instances, kargs...)
NSCode(args...; __link_instances=false, kargs...) =
    _NSCls{NSX{gensym()}}(args...; __link_instances=__link_instances, kargs...)


text:
# Helpful packages for working with images and factorizations
# using Pkg; Pkg.add("Images")
# using Pkg; Pkg.add("ImageMagick") # And this allows us to load JPEG-encoded images
using Images, LinearAlgebra

# ------------------------------------------------------------------------------------------
# ### Using a SVD to compress an image
#
# In this exercise, we'll use a singular value decomposition (SVD) to compress an image --
# so that we can store an image without keeping around "unnecessary" information.
#
# To start, let's define a singular value decomposition. In a SVD, we take a matrix $A$ and
# factorize it so that
#
# $$A = USV^T$$
#
# where matrices $U$ and $V$ are unitary and hold our singular vectors. Matrix $S$ is
# diagonal and stores our singular values in decreasing order from top/left to bottom/right.
#
# In Julia, our images are stored as arrays, so we can think of `yellowbanana` as a matrix
# ------------------------------------------------------------------------------------------

yellowbanana = load("images/104_100.jpg")

size(yellowbanana)

yellowbanana[60,50] # Each element in the array is a color

# ------------------------------------------------------------------------------------------
# That means we can take the SVD of this image. So, we can store this picture of a banana as
# sets of singular vectors and singular values.
#
# **The reason this is important** is that we'll find that we do **not** need to keep track
# of *all* the singular vectors and *all* the singular values to store an image that still
# looks like a banana! This means we can choose to keep only the important information,
# throw away the rest, and thereby "compress" the image.
#
# Working with grayscale images is a bit easier, so let's work with the gray version of this
# banana.
# ------------------------------------------------------------------------------------------

banana = Gray.(yellowbanana)

# ------------------------------------------------------------------------------------------
# Note that `banana` is a (100 x 100) matrix that stores a pixel -- information about the
# color -- at each entry.
# ------------------------------------------------------------------------------------------

size(banana)

# ------------------------------------------------------------------------------------------
# If we take the `channelview` of `banana`, we'll see the numbers that describe the color at
# each point in the array:
# ------------------------------------------------------------------------------------------

channelview(banana)

# ------------------------------------------------------------------------------------------
# Note that you can call `Gray` on the `channelview` of an image to display the image!
# ------------------------------------------------------------------------------------------

Gray.(channelview(banana))

# ------------------------------------------------------------------------------------------
# **So how can we use a SVD to determine what information in an image is really important?**
#
# The singular values tell us!
#
# If we have matrices $U$, $S$, and $V$ from our image, we can rebuild that image with the
# matrix product $USV^T$.
#
# Taking this matrix product is the same as adding together the outer products of each
# corresponding pair of vectors from $U$ and $V$, scaled by a singular value ($\sigma$) from
# $S$. In other words, for a (100 x 100) pixel image,
#
# $$A_{image} = USV^T = \sum_{i = 1}^{100} \sigma_i \mathbf{u_i}\mathbf{v_i'} $$
#
# Every outer product $u_i * v_i'$ creates a (100 x 100) matrix. Here we're summing together
# one hundred (100 x 100) matrices in order to create the original matrix $A_{image}$. The
# matrices at the beginning of the series -- those that are scaled by **large** singular
# values -- will be **much** more important in recreating the original matrix $A_{image}$.
#
# This means we can approximate $A_{image}$ as
#
# $$A_{image} \approx \sum_{i = 1}^{n} \sigma_i \mathbf{u_i}\mathbf{v_i'}$$
#
# where $n < 100$.
#
# For example, if we rebuild our image of a banana using only 30 (instead of all 100)
# singular values, we get
#
#
#
# Using 10, 5, and then 3 singular values, we get
#
#
#
#
#
# #### Exercise
#
# Write a function called `compress_image`. Its input arguments should be an image and the
# factor by which you want to compress the image. A compressed grayscale image should
# display when `compress_image` is called.
#
# For example,
#
# ```julia
# compress_image("images/104_100.jpg", 33)
# ```
#
# will return a compressed image of a grayscale banana built using 3 singular values. (This
# image has 100 singular values, so use `fld(100, 33)` to determine how many singular values
# to keep. `fld` performs "floor" division.)
#
# *Hints*:
#
# * Perform the SVD on the `channelview` of a grayscale image.
# * In an empty input cell, execute `?svd` to find a function that wil perform an SVD for
# you.
#
# ### Solution 1
# ------------------------------------------------------------------------------------------

function compress_image(img, factor)
    img = channelview(Gray.(img))
    img_svd = svd(img)
    U, S, V = img_svd.U, img_svd.S, img_svd.V
    num_sv = size(S)[1]
    use_sv = fld(num_sv, factor) # `fld` returns an integer
    # Reconstruct image via matrix multiplies
    compressed_image = U[:, 1:use_sv] * Diagonal(S[1:use_sv]) * V[:, 1:use_sv]'
    Gray.(compressed_image)
end

compress_image(banana, 10)

# ------------------------------------------------------------------------------------------
# ### Solution 2
# ------------------------------------------------------------------------------------------

function compress_image(img, factor)
    img = channelview(Gray.(img))
    img_svd = svd(img)
    U, S, V = img_svd.U, img_svd.S, img_svd.V
    num_sv = size(S)[1]
    use_sv = fld(num_sv, factor) # `fld` returns an integer
    # Reconstruct image with a `for` loop that sequentially performs outer products
    compressed_image = fill(zero(N0f8), (num_sv, num_sv))
    for i in 1:use_sv
       compressed_image += S[i] * U[:, i] * V[:, i]'
    end
    Gray.(compressed_image)
end

compress_image(banana, 20)

max_stars_repo_name: grenkoca/JuliaTutorials

max_issues_repo_name: grenkoca/JuliaTutorials

max_forks_repo_name: grenkoca/JuliaTutorials


text:
module Brownies

using UnPack
using Random
using RandomNumbers.PCG
using RandomNumbers.Xorshifts
using StaticArrays
using DataFrames

include("types.jl")
export ParticleSystem,
    SimulationSystem,
    Parameters,
    PairDistributionFunction,
    ZFactor,
    compute_z,
    StructureFactor,
    MeanSquaredDisplacement,
    SelfScatteringFunction
include("potentials.jl")
export PairwisePotential, PseudoHS, apply!
include("observables/rdf.jl")
export compute_rdf!, simple_rdf!
include("energy.jl")
export energy_force!
include("utils.jl")
export rng_matrix!, todataframe
include("move.jl")
export move!, thermalize!
include("algorithms/ermak.jl")
export ermak!
include("configurations.jl")
export initialize!
include("observables/structure.jl")
export compute_structure!
include("observables/msd.jl")
export record_positions!, difusion!

end # module


text:
# (Linear) algebraic functions for Chemical Reaction Nets.
# Compute conservation laws, cycles, emergent cycles.

using Nemo
using SparseArrays

full(a) = convert(Array,a)

"""
    stoichiometric_matrix(rn::ReactionNetwork)

Generate stoichiometric matrices from list of reactions.
Output matrices are of dimension: (`n_species`,`n_reactions`).

Two matrices are returned, for reactants and products.
"""
function stoichiometric_matrix(rn::ReactionNetwork)
    n_species = rn.n_species
    reactions = rn.reactions

    nr = length(reactions)

    ∇r = spzeros(Int, n_species, nr)
    ∇p = spzeros(Int, n_species, nr)

    for ri in 1:nr
        re = reactions[ri]
        for si in 1:length(re.reactants)
            s = re.reactants[si]
            c = re.stoichr[si]

            ∇r[s,ri] += c
        end

        for si in 1:length(re.products)
            s = re.products[si]
            c = re.stoichp[si]

            ∇p[s,ri] += c
        end
    end

    return ∇r,∇p
end

function findnz(l::AbstractVector)
    idx = findall(x->x!=0,l)
    return idx,l[idx]
end

"""
    from_stoichiometric_matrix(∇r, ∇p, kf, kr, names=[])

Generates a list of reactions from stoichiometric matrices.
Inputs:
- ∇r, ∇p: stoichiometric matrices for reactants and products, respectively.
- kf, kr: Forward and backward rate constants.
- names (optional): names of the species, to be included in output network.
Returns:
- ReactionNetwork
"""
function from_stoichiometric_matrix(∇r::AbstractMatrix, ∇p::AbstractMatrix, kf::Vector{T}, kr::Vector{T}, names=[]) where T<:Real
    @assert size(∇r)==size(∇p)
    nspecies,nreactions = size(∇r)

    reactions = Reaction[]
    for i = 1 : nreactions
        reactants,stoichr = findnz(∇r[:,i])
        products,stoichp  = findnz(∇p[:,i])
        push!(reactions, Reaction(reactants,stoichr,products,stoichp,kf[i],kr[i]))
    end

    return ReactionNetwork(nspecies,reactions,names)
end

"""
    normal_form(rn::ReactionNetwork)

Returns normalized form of reaction net.

For example, S1 + S1 → S2 becomes 2S1 → S2
and S3 + S1 → S2 becomes S1 + S3 → S2
"""
function normal_form(rn::ReactionNetwork)
    ∇r,∇p = stoichiometric_matrix(rn)
    kf = [r.kf for r in rn.reactions]
    kr = [r.kr for r in rn.reactions]
    return from_stoichiometric_matrix(∇r,∇p,kf,kr,rn.names)
end

# TODO: Bool arguments are a code smell
function stoichiometric_nullspace(rn::ReactionNetwork, tr::Bool)
    # We only want net stoichiometric matrix here.
    ∇r, ∇p = stoichiometric_matrix(rn)
    ∇ = ∇r - ∇p

    ∇ = tr ? transpose(∇) : ∇

    S = MatrixSpace(ZZ, size(∇)...)

    r,ns = nullspace(S(full(∇)))
    m,n = size(ns)

    nsm = sparse(Int[ns[i,j] for i=1:m,j=1:n])

    return tr ? transpose(nsm) : nsm
end

# returns dimensions of nullspace (dimension of kernel) without calculating
# the matrix explicitly. Used for
function stoichiometric_dimker(rn::ReactionNetwork, tr::Bool)
    ∇r, ∇p = stoichiometric_matrix(rn)
    ∇ = ∇r - ∇p

    ∇ = tr ? transpose(∇) : ∇

    return size(∇,2)-rank(full(∇))
end

"""
    conservation_laws(rn::ReactionNetwork)

Returns the list of 'conservation laws' of the network,
where each law is defined as a vector of length `n_species`.
"""
conservation_laws(rn::ReactionNetwork) =
    stoichiometric_nullspace(rn, true)

n_conservation_laws(rn::ReactionNetwork) =
    stoichiometric_dimker(rn, true)

"""
    cycles(rn::ReactionNetwork)

Returns the list of 'cycles' of the network,
where each law is defined as a vector of length `n_reactions`.
"""
cycles(rn::ReactionNetwork) =
    stoichiometric_nullspace(rn, false)

n_cycles(rn::ReactionNetwork) =
    stoichiometric_dimker(rn, false)

# The solution is based on equation (18) in the paper:
#   kf/kr = prod_s z[s]^del_s,r for all r
# We take the logarithm, giving:
#   log(kf/kr) = sum del_s,r log z[s]
# And then we also append the conservation laws.
# This gives a linear system which can be solved.
function log_equilibrium_state(rn::ReactionNetwork)
     # compute ratio of forward to backward reactions
    free_energy = log.([r.kf/r.kr for r in rn.reactions])

    dp,dn = stoichiometric_matrix(rn)
    del = dn-dp

    logz = full(del')\free_energy

    return logz, del
end
"""
    equilibrium_state(rn::ReactionNetwork)

Compute steady-states for both detailed-balanced and
complex-balanced states.

The steady state concentration is one where the conserved
moieties are distributed equally among all reactants.

The equilibrium state is a steady-state where all
concentration currents vanish.
"""
function equilibrium_state(rn::ReactionNetwork)
    logz, del = log_equilibrium_state(rn)
    return exp.(logz)
end

# The equilibrium state is often under-defined;
# this means we can add chemostats until it is fully defined,
# and get a unique solution.
# In addition, we can return the full solution space, which is:
# ss=nullspace(full(del'))
# Thus every solution can be written as:
# ss*x + logz0
# where x is some arbitrary vector and logz0=full(del')\log_k_ratio
function equilibrium_state_space(rn::ReactionNetwork)
    logz, del = log_equilibrium_state(rn)

    r,ss = nullspace(full(del'))
    return ss, logz
end

# -----------
function cycle_affinities(rn::ReactionNetwork, cycm::AbstractMatrix, z)
    cycaff = zeros(size(cycm,2))

    lnj = zeros(length(rn.reactions))
    for rho = 1:length(rn.reactions)
        ri = rn.reactions[rho]
        jf,jr = reaction_currents(ri, z)
        lnj[rho] = log(jf/jr)
    end

    return lnj'*cycm
end

function specificity(rn::ReactionNetwork, z)
    # remember: r is reactants, p is products
    ∇r, ∇p = stoichiometric_matrix(rn)
    ∇rp = cat(dims=2, ∇r, ∇p)

    cur = [reaction_current(r, z) for r in rn.reactions]

    # Concatenate forward/backward currents,
    # with order corresponding to ∇rp
    curfr = cat(dims=1,[c[1] for c in cur],[c[2] for c in cur])

    sumcur = ∇rp'*(∇rp*curfr)
    spec = curfr ./ sumcur

    return reshape(spec, length(rn.reactions), 2)
end


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

mutable struct NetworkRuleSet <: SwaggerModel
    bypass::Any # spec type: Union{ Nothing, String } # spec name: bypass
    virtualNetworkRules::Any # spec type: Union{ Nothing, Vector{VirtualNetworkRule} } # spec name: virtualNetworkRules
    ipRules::Any # spec type: Union{ Nothing, Vector{IPRule} } # spec name: ipRules
    defaultAction::Any # spec type: Union{ Nothing, String } # spec name: defaultAction

    function NetworkRuleSet(;bypass="AzureServices", virtualNetworkRules=nothing, ipRules=nothing, defaultAction="Allow")
        o = new()
        validate_property(NetworkRuleSet, Symbol("bypass"), bypass)
        setfield!(o, Symbol("bypass"), bypass)
        validate_property(NetworkRuleSet, Symbol("virtualNetworkRules"), virtualNetworkRules)
        setfield!(o, Symbol("virtualNetworkRules"), virtualNetworkRules)
        validate_property(NetworkRuleSet, Symbol("ipRules"), ipRules)
        setfield!(o, Symbol("ipRules"), ipRules)
        validate_property(NetworkRuleSet, Symbol("defaultAction"), defaultAction)
        setfield!(o, Symbol("defaultAction"), defaultAction)
        o
    end
end # type NetworkRuleSet

const _property_map_NetworkRuleSet = Dict{Symbol,Symbol}(Symbol("bypass")=>Symbol("bypass"), Symbol("virtualNetworkRules")=>Symbol("virtualNetworkRules"), Symbol("ipRules")=>Symbol("ipRules"), Symbol("defaultAction")=>Symbol("defaultAction"))
const _property_types_NetworkRuleSet = Dict{Symbol,String}(Symbol("bypass")=>"String", Symbol("virtualNetworkRules")=>"Vector{VirtualNetworkRule}", Symbol("ipRules")=>"Vector{IPRule}", Symbol("defaultAction")=>"String")
Base.propertynames(::Type{ NetworkRuleSet }) = collect(keys(_property_map_NetworkRuleSet))
Swagger.property_type(::Type{ NetworkRuleSet }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_NetworkRuleSet[name]))}
Swagger.field_name(::Type{ NetworkRuleSet }, property_name::Symbol) =  _property_map_NetworkRuleSet[property_name]

const _allowed_NetworkRuleSet_bypass = ["None", "Logging", "Metrics", "AzureServices"]

const _allowed_NetworkRuleSet_defaultAction = ["Allow", "Deny"]

function check_required(o::NetworkRuleSet)
    true
end

function validate_property(::Type{ NetworkRuleSet }, name::Symbol, val)
    if name === Symbol("bypass")
        Swagger.validate_param(name, "NetworkRuleSet", :enum, val, _allowed_NetworkRuleSet_bypass)
    end
    if name === Symbol("defaultAction")
        Swagger.validate_param(name, "NetworkRuleSet", :enum, val, _allowed_NetworkRuleSet_defaultAction)
    end
end