text
stringlengths 5
1.02M
|
---|
prunes = [false, false, false, true, true]
L1arr = [false, true, false, true, false]
constant_vel = [false, true, true, true, true] # First is just stack avg
stackavgarr = .!constant_vel
for (doprune, isl1, constvel, stackavg) in zip(prunes, L1arr, constant_vel, stackavgarr)
soltype = isl1 ? "l1" : (stackavg ? "stackavg" : "l2")
prunestr = doprune ? "prune" : "noprune"
outfile = "velocities_$(prunestr)_$soltype.h5"
@show outfile
try
@time InsarTimeseries.run_inversion(
constant_velocity = constvel,
stack_average = stackavg,
max_temporal_baseline = 500,
ignore_geo_file = "geolist_ignore.txt",
L1 = isl1,
prune = doprune,
outfile = outfile,
)
catch
println("Skipping $outfile")
continue
end
# stackavg && continue
# try
# InsarTimeseries._save_std_attrs(outfile, "velos/1")
# catch
# print()
# end
# for ds in ["stddev_raw/1", "stddev/1"]
# tmp = h5read(outfile, ds)
# h5open(outfile, "cw") do f
# tmp = abs(InsarTimeseries.PHASE_TO_CM) .* read(f, ds)
# o_delete(f[ds])
# f[ds] = tmp
# end
# end
end
|
1 # 整数,在 64 位系统中等价于 Int64
1.0 # 64 位浮点数
true # 布尔型,可以是 true 或 false
'c' # 字符,可以是 Unicode
"abc" # 抽象字符串,可以有 Unicode,参见下述字符串(String)
1::Int # 正确,1 确实是 Int 类型
1::Float # 错误,1 不是 Float 类型
Float64(1) # 将 1 转化为浮点数的正确方式
Int64(1.2) # 试图将 1.2 转化为整数,但会报错
parse(Int64, "1") # 以 Int64 类型解读字符串 "1"
promote(true, BigInt(1)//3, 1.0)
# BigFloat 类型元组(参见 Tuple) , true 转换为 1.0
|
"""
collocationalchains(text::Strings; mode = "forward")
A function that takes text and returns ngram sequences of words with lexical gravity score above 5.5.
For more details, cf. (2004).
# Examples
```julia-repl
julia> collocationalchains(text)
sample output
```
"""
function collocationalchains(lowertextdata)
intermediatearray = Array{String,1}()
finalarray = Array{Array{String},1}()
for ngram in ngram(tokenizestr(lowertextdata)[4:end - 3], 2)
# i need to first clean and normalize the data before applying the lexicalgravitypair() function.
ngram = lowercase.(ngram)
# println(ngram)
if lexicalgravitypair(ngram[1], ngram[2], lowertextdata) <= 5.5
println("next")
intermediatearray = Array{String,1}()
else
push!(intermediatearray, ngram[1], ngram[2])
push!(finalarray, intermediatearray)
println("ngram")
end
end
end |
struct DocumentFolder <: Rewriter
dir::AbstractPath
paths::Vector{<:AbstractPath}
dirty::BitVector
end
function DocumentFolder(
dir::AbstractPath;
prefix = "",
extensions = ("ipynb", "md"),
includehidden = false,
filterfn = (p) -> true)
dir = absolute(dir)
paths = AbstractPath[
joinpath(relative(absolute(p), dir)) for p in walkpath(dir)
if extension(p) in extensions && filterfn(p) && (includehidden || !ishidden(relative(absolute(p), dir)))]
return DocumentFolder(dir, paths, trues(length(paths)))
end
function createsources!(folder::DocumentFolder)
docs = Dict{AbstractPath, XNode}()
for (i, p) in enumerate(folder.paths)
if folder.dirty[i]
docs[p] = parse(joinpath(folder.dir, p))
folder.dirty[i] = false
end
end
return docs
end
function geteventsource(folder::DocumentFolder, ch)
watcher = LiveServer.SimpleWatcher() do filename
@info "$filename was udpated"
p = Path(filename)
doc = parse(p)
event = DocUpdated(relative(p, folder.dir), doc)
put!(ch, event)
end
for p in folder.paths
LiveServer.watch_file!(watcher, string(joinpath(folder.dir, p)))
end
return watcher
end
function filehandlers(folder::DocumentFolder, ::Project, ::Builder)
return Dict(() => Dict(relative(p, folder.dir) => Pollen.parse(p)) for p in folder.paths)
end
ishidden(p::AbstractPath) = any(startswith(s, '.') && s != "." for s in p.segments)
|
__precompile__()
module BeetleWay
using Gtk.ShortNames, GtkReactive, DataStructures#, HDF5
# const src = @__DIR__
const src = joinpath(Pkg.dir("BeetleWay"), "src")
# patches
# include(joinpath(@__DIR__, "patches.jl"))
include(joinpath(src, "log", "gui.jl"))
include(joinpath(src, "log", "preliminary_report.jl"))
include(joinpath(src, "track", "segment.jl"))
b = Builder(filename=joinpath(src, "head.glade"))
# folder = open_dialog("Select Video Folder", action=Gtk.GtkFileChooserAction.SELECT_FOLDER)
folder = joinpath(src, "..", "test", "videofolder")
# test the folder for any problems with the metadata
assert_metadata(folder)
id1 = signal_connect(_ -> log_gui(folder), b["start.log"], :clicked)
id2 = signal_connect(_ -> report_gui(folder), b["preliminary.report"], :activate)
id3 = signal_connect(_ -> fragment(folder), b["segment.videos"], :activate)
id4 = signal_connect(_ -> coordinates_gui(folder), b["track"], :clicked)
showall(b["head.window"])
end # module
# TODO:
# check the integratiy of the metadata
# maybe clearer error messages
# fix the travis errors!!!
|
using .Gadfly
export plotICX, plotICXRatio, plotICXRatio2
function plotICX(z::Integer)
colors = [ "red", "green", "blue", "yellow", "lightgreen", "purple", "brown", "orange", "lightblue"]
name = [ "K", "L1", "L2", "L3", "M1", "M2", "M3", "M4", "M5" ]
lyr(bs, i, color) =
Gadfly.layer(loge->log10(max(0.1, ionizationcrosssection(bs.z, i, 10.0^loge) / 1.0e-24)), log10(bs.edge[i]), log10(1.0e9), Gadfly.Theme(default_color = color))
bs = BoteSalvatElectron[z]
idx = eachindex(bs.edge)
layers = [ lyr(bs, i, colors[i]) for i in idx]
Gadfly.plot(layers...,
Gadfly.Guide.manual_color_key("Shell", name[idx], colors[idx]),
Gadfly.Guide.xlabel("log(E) (eV)"), Guide.ylabel("log(σ) (barns)"), Guide.title("Z = $z"),
Gadfly.Coord.cartesian(xmin = round(log10(minimum(bs.edge)) - 0.5), xmax = 9.0, ymin = 0.0))
end
function plotICXRatio(z::Integer)
colors = [ "red", "green", "blue", "yellow", "lightgreen", "purple", "brown", "orange", "lightblue"]
name = [ "K", "L1", "L2", "L3", "M1", "M2", "M3", "M4", "M5" ]
lyr(i, ip, color) =
Gadfly.layer(u->ionizationcrosssection(z, i, u*edgeenergy(z,i)) / ionizationcrosssection(z, ip, u*edgeenergy(z,ip)), 1.2, 10.0, Gadfly.Theme(default_color = color))
layers = ( lyr(i, i>4 ? 5 : (i>1 ? 2 : 1), colors[i]) for i in eachindex(name) )
Gadfly.plot(layers...,
Gadfly.Guide.manual_color_key("Shell", name[eachindex(name)], colors[eachindex(name)]),
Gadfly.Guide.xlabel("U (eV/eV)"), Guide.ylabel("σ/σ' (barns/barns)"), Guide.title("Z = $z"),
Gadfly.Coord.cartesian(xmin = 1.0, xmax = 10.0, ymin = 0.0))
end
function plotICXRatio2(u::AbstractFloat)
colors = [ "red", "green", "blue", "yellow", "lightgreen", "purple", "brown", "orange", "lightblue"]
name = [ "K", "L1", "L2", "L3", "M1", "M2", "M3", "M4", "M5" ]
function lyr(i, ip)
zs = filter(z->( hasedge(z,i) && hasedge(z, ip)),1:92)
xs = map(z->ionizationcrosssection(z, i, u*edgeenergy(z,i)) / ionizationcrosssection(z, ip, u*edgeenergy(z,ip)),zs)
Gadfly.layer(x=zs, y=xs, Gadfly.Theme(default_color = colors[i]))
end
layers = ( lyr(i, i>4 ? 5 : (i>1 ? 2 : 1)) for i in eachindex(name) )
Gadfly.plot(layers..., Guide.title("U = $u"),
Gadfly.Guide.manual_color_key("Shell", name[eachindex(name)], colors[eachindex(name)]),
Gadfly.Guide.xlabel("Atomic Number"), Guide.ylabel("σ/σ' (barns/barns)"),
Gadfly.Coord.cartesian(xmin = 1.0, xmax = 92.0, ymin = 0.0))
end
|
using Conda
# Install Jupyter kernel-spec file.
include("kspec.jl")
kernelpath = installkernel("Julia")
# make it easier to get more debugging output by setting JULIA_DEBUG=1
# when building.
IJULIA_DEBUG = lowercase(get(ENV, "IJULIA_DEBUG", "0"))
IJULIA_DEBUG = IJULIA_DEBUG in ("1", "true", "yes")
# remember the user's Jupyter preference, if any; empty == Conda
prefsfile = joinpath(first(DEPOT_PATH), "prefs", "IJulia")
mkpath(dirname(prefsfile))
jupyter = get(ENV, "JUPYTER", isfile(prefsfile) ? readchomp(prefsfile) : Sys.isunix() && !Sys.isapple() ? "jupyter" : "")
condajupyter = normpath(Conda.SCRIPTDIR, exe("jupyter"))
if isempty(jupyter) || dirname(jupyter) == abspath(Conda.SCRIPTDIR)
jupyter = condajupyter # will be installed if needed
elseif isabspath(jupyter)
if !Sys.isexecutable(jupyter)
@warn("ignoring non-executable JUPYTER=$jupyter")
jupyter = condajupyter
end
elseif jupyter != basename(jupyter) # relative path
@warn("ignoring relative path JUPYTER=$jupyter")
jupyter = condajupyter
elseif Sys.which(jupyter) === nothing
@warn("JUPYTER=$jupyter not found in PATH")
end
function write_if_changed(filename, contents)
if !isfile(filename) || read(filename, String) != contents
write(filename, contents)
end
end
# Install the deps.jl file:
deps = """
const IJULIA_DEBUG = $(IJULIA_DEBUG)
const JUPYTER = $(repr(jupyter))
"""
write_if_changed("deps.jl", deps)
write_if_changed(prefsfile, jupyter)
|
# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).
# Since these FMAs can increase the performance of many numerical algorithms,
# we need to opt-in explicitly.
# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.
@muladd begin
function rhs!(du, u, t,
mesh::StructuredMesh{2}, equations,
initial_condition, boundary_conditions, source_terms,
dg::DG, cache)
# Reset du
@trixi_timeit timer() "reset ∂u/∂t" du .= zero(eltype(du))
# Calculate volume integral
@trixi_timeit timer() "volume integral" calc_volume_integral!(
du, u, mesh,
have_nonconservative_terms(equations), equations,
dg.volume_integral, dg, cache)
# Calculate interface fluxes
@trixi_timeit timer() "interface flux" calc_interface_flux!(
cache, u, mesh,
have_nonconservative_terms(equations), equations,
dg.surface_integral, dg)
# Calculate boundary fluxes
@trixi_timeit timer() "boundary flux" calc_boundary_flux!(
cache, u, t, boundary_conditions, mesh, equations, dg.surface_integral, dg)
# Calculate surface integrals
@trixi_timeit timer() "surface integral" calc_surface_integral!(
du, u, mesh, equations, dg.surface_integral, dg, cache)
# Apply Jacobian from mapping to reference element
@trixi_timeit timer() "Jacobian" apply_jacobian!(
du, mesh, equations, dg, cache)
# Calculate source terms
@trixi_timeit timer() "source terms" calc_sources!(
du, u, t, source_terms, equations, dg, cache)
return nothing
end
function calc_volume_integral!(du, u,
mesh::Union{StructuredMesh{2}, UnstructuredMesh2D, P4estMesh{2}},
nonconservative_terms::Val{false}, equations,
volume_integral::VolumeIntegralWeakForm,
dg::DGSEM, cache)
@unpack derivative_dhat = dg.basis
@unpack contravariant_vectors = cache.elements
@threaded for element in eachelement(dg, cache)
for j in eachnode(dg), i in eachnode(dg)
u_node = get_node_vars(u, equations, dg, i, j, element)
flux1 = flux(u_node, 1, equations)
flux2 = flux(u_node, 2, equations)
# Compute the contravariant flux by taking the scalar product of the
# first contravariant vector Ja^1 and the flux vector
Ja11, Ja12 = get_contravariant_vector(1, contravariant_vectors, i, j, element)
contravariant_flux1 = Ja11 * flux1 + Ja12 * flux2
for ii in eachnode(dg)
multiply_add_to_node_vars!(du, derivative_dhat[ii, i], contravariant_flux1, equations, dg, ii, j, element)
end
# Compute the contravariant flux by taking the scalar product of the
# second contravariant vector Ja^2 and the flux vector
Ja21, Ja22 = get_contravariant_vector(2, contravariant_vectors, i, j, element)
contravariant_flux2 = Ja21 * flux1 + Ja22 * flux2
for jj in eachnode(dg)
multiply_add_to_node_vars!(du, derivative_dhat[jj, j], contravariant_flux2, equations, dg, i, jj, element)
end
end
end
return nothing
end
function calc_interface_flux!(cache, u,
mesh::StructuredMesh{2},
nonconservative_terms, # can be Val{true}/Val{false}
equations, surface_integral, dg::DG)
@unpack elements = cache
@threaded for element in eachelement(dg, cache)
# Interfaces in negative directions
# Faster version of "for orientation in (1, 2)"
# Interfaces in x-direction (`orientation` = 1)
calc_interface_flux!(elements.surface_flux_values,
elements.left_neighbors[1, element],
element, 1, u, mesh,
nonconservative_terms, equations,
surface_integral, dg, cache)
# Interfaces in y-direction (`orientation` = 2)
calc_interface_flux!(elements.surface_flux_values,
elements.left_neighbors[2, element],
element, 2, u, mesh,
nonconservative_terms, equations,
surface_integral, dg, cache)
end
return nothing
end
@inline function calc_interface_flux!(surface_flux_values, left_element, right_element,
orientation, u,
mesh::StructuredMesh{2},
nonconservative_terms::Val{false}, equations,
surface_integral, dg::DG, cache)
# This is slow for LSA, but for some reason faster for Euler (see #519)
if left_element <= 0 # left_element = 0 at boundaries
return nothing
end
@unpack surface_flux = surface_integral
@unpack contravariant_vectors, inverse_jacobian = cache.elements
right_direction = 2 * orientation
left_direction = right_direction - 1
for i in eachnode(dg)
if orientation == 1
u_ll = get_node_vars(u, equations, dg, nnodes(dg), i, left_element)
u_rr = get_node_vars(u, equations, dg, 1, i, right_element)
# If the mapping is orientation-reversing, the contravariant vectors' orientation
# is reversed as well. The normal vector must be oriented in the direction
# from `left_element` to `right_element`, or the numerical flux will be computed
# incorrectly (downwind direction).
sign_jacobian = sign(inverse_jacobian[1, i, right_element])
# First contravariant vector Ja^1 as SVector
normal_direction = sign_jacobian * get_contravariant_vector(1, contravariant_vectors,
1, i, right_element)
else # orientation == 2
u_ll = get_node_vars(u, equations, dg, i, nnodes(dg), left_element)
u_rr = get_node_vars(u, equations, dg, i, 1, right_element)
# See above
sign_jacobian = sign(inverse_jacobian[i, 1, right_element])
# Second contravariant vector Ja^2 as SVector
normal_direction = sign_jacobian * get_contravariant_vector(2, contravariant_vectors,
i, 1, right_element)
end
# If the mapping is orientation-reversing, the normal vector will be reversed (see above).
# However, the flux now has the wrong sign, since we need the physical flux in normal direction.
flux = sign_jacobian * surface_flux(u_ll, u_rr, normal_direction, equations)
for v in eachvariable(equations)
surface_flux_values[v, i, right_direction, left_element] = flux[v]
surface_flux_values[v, i, left_direction, right_element] = flux[v]
end
end
return nothing
end
@inline function calc_interface_flux!(surface_flux_values, left_element, right_element,
orientation, u,
mesh::StructuredMesh{2},
nonconservative_terms::Val{true}, equations,
surface_integral, dg::DG, cache)
# See comment on `calc_interface_flux!` with `nonconservative_terms::Val{false}`
if left_element <= 0 # left_element = 0 at boundaries
return nothing
end
@unpack surface_flux = surface_integral
@unpack contravariant_vectors, inverse_jacobian = cache.elements
right_direction = 2 * orientation
left_direction = right_direction - 1
for i in eachnode(dg)
if orientation == 1
u_ll = get_node_vars(u, equations, dg, nnodes(dg), i, left_element)
u_rr = get_node_vars(u, equations, dg, 1, i, right_element)
# If the mapping is orientation-reversing, the contravariant vectors' orientation
# is reversed as well. The normal vector must be oriented in the direction
# from `left_element` to `right_element`, or the numerical flux will be computed
# incorrectly (downwind direction).
sign_jacobian = sign(inverse_jacobian[1, i, right_element])
# First contravariant vector Ja^1 as SVector
normal_direction = sign_jacobian * get_contravariant_vector(1, contravariant_vectors,
1, i, right_element)
else # orientation == 2
u_ll = get_node_vars(u, equations, dg, i, nnodes(dg), left_element)
u_rr = get_node_vars(u, equations, dg, i, 1, right_element)
# See above
sign_jacobian = sign(inverse_jacobian[i, 1, right_element])
# Second contravariant vector Ja^2 as SVector
normal_direction = sign_jacobian * get_contravariant_vector(2, contravariant_vectors,
i, 1, right_element)
end
# If the mapping is orientation-reversing, the normal vector will be reversed (see above).
# However, the flux now has the wrong sign, since we need the physical flux in normal direction.
flux = sign_jacobian * surface_flux(u_ll, u_rr, normal_direction, equations)
# Call pointwise nonconservative term; Done twice because left/right orientation matters
# See Bohm et al. 2018 for details on the nonconservative diamond "flux"
# Scale with sign_jacobian to ensure that the normal_direction matches that from the flux above
noncons_primary = sign_jacobian * noncons_interface_flux(u_ll, u_rr, normal_direction, :weak, equations)
noncons_secondary = sign_jacobian * noncons_interface_flux(u_rr, u_ll, normal_direction, :weak, equations)
for v in eachvariable(equations)
surface_flux_values[v, i, right_direction, left_element] = flux[v] + noncons_primary[v]
surface_flux_values[v, i, left_direction, right_element] = flux[v] + noncons_secondary[v]
end
end
return nothing
end
# TODO: Taal dimension agnostic
function calc_boundary_flux!(cache, u, t, boundary_condition::BoundaryConditionPeriodic,
mesh::StructuredMesh{2}, equations, surface_integral, dg::DG)
@assert isperiodic(mesh)
end
function calc_boundary_flux!(cache, u, t, boundary_condition,
mesh::StructuredMesh{2}, equations, surface_integral, dg::DG)
calc_boundary_flux!(cache, u, t,
(boundary_condition, boundary_condition,
boundary_condition, boundary_condition),
mesh, equations, surface_integral, dg)
end
function calc_boundary_flux!(cache, u, t, boundary_conditions::Union{NamedTuple,Tuple},
mesh::StructuredMesh{2}, equations, surface_integral, dg::DG)
@unpack surface_flux_values = cache.elements
linear_indices = LinearIndices(size(mesh))
for cell_y in axes(mesh, 2)
# Negative x-direction
direction = 1
element = linear_indices[begin, cell_y]
for j in eachnode(dg)
calc_boundary_flux_by_direction!(surface_flux_values, u, t, 1,
boundary_conditions[direction],
mesh, equations, surface_integral, dg, cache,
direction, (1, j), (j,), element)
end
# Positive x-direction
direction = 2
element = linear_indices[end, cell_y]
for j in eachnode(dg)
calc_boundary_flux_by_direction!(surface_flux_values, u, t, 1,
boundary_conditions[direction],
mesh, equations, surface_integral, dg, cache,
direction, (nnodes(dg), j), (j,), element)
end
end
for cell_x in axes(mesh, 1)
# Negative y-direction
direction = 3
element = linear_indices[cell_x, begin]
for i in eachnode(dg)
calc_boundary_flux_by_direction!(surface_flux_values, u, t, 2,
boundary_conditions[direction],
mesh, equations, surface_integral, dg, cache,
direction, (i, 1), (i,), element)
end
# Positive y-direction
direction = 4
element = linear_indices[cell_x, end]
for i in eachnode(dg)
calc_boundary_flux_by_direction!(surface_flux_values, u, t, 2,
boundary_conditions[direction],
mesh, equations, surface_integral, dg, cache,
direction, (i, nnodes(dg)), (i,), element)
end
end
end
function apply_jacobian!(du,
mesh::Union{StructuredMesh{2}, UnstructuredMesh2D, P4estMesh{2}},
equations, dg::DG, cache)
@unpack inverse_jacobian = cache.elements
@threaded for element in eachelement(dg, cache)
for j in eachnode(dg), i in eachnode(dg)
factor = -inverse_jacobian[i, j, element]
for v in eachvariable(equations)
du[v, i, j, element] *= factor
end
end
end
return nothing
end
end # @muladd
|
# Methods to more easily handle financial data
# Check for various key financial field names
has_open(x::TS)::Bool = any(occursin.(r"(op)"i, String.(x.fields)))
has_high(x::TS)::Bool = any(occursin.(r"(hi)"i, String.(x.fields)))
has_low(x::TS)::Bool = any(occursin.(r"(lo)"i, String.(x.fields)))
has_volume(x::TS)::Bool = any(occursin.(r"(vo)"i, String.(x.fields)))
function has_close(x::TS; allow_settle::Bool=true, allow_last::Bool=true)::Bool
columns = String.(x.fields)
if allow_settle && allow_last
return any([occursin(r"(cl)|(last)|(settle)"i, column) for column in columns])
end
if allow_last && !allow_settle
return any([occursin(r"(cl)|(last)"i, column) for column in columns])
end
if allow_settle && !allow_last
return any([occursin(r"(cl)|(settle)"i, column) for column in columns])
end
if !allow_last && !allow_settle
return any([occursin(r"(cl)"i, column) for column in columns])
end
return false
end
# Identify OHLC(V) formats
is_ohlc(x::TS)::Bool = has_open(x) && has_high(x) && has_low(x) && has_close(x)
is_ohlcv(x::TS)::Bool = is_ohlc(x) && has_volume(x)
# Extractor functions
op(x::TS)::TS = x[:,findfirst([occursin(r"(op)"i, String(field)) for field in x.fields])]
hi(x::TS)::TS = x[:,findfirst([occursin(r"(hi)"i, String(field)) for field in x.fields])]
lo(x::TS)::TS = x[:,findfirst([occursin(r"(lo)"i, String(field)) for field in x.fields])]
vo(x::TS)::TS = x[:,findfirst([occursin(r"(vo)"i, String(field)) for field in x.fields])]
function cl(x::TS; use_adj::Bool=true, allow_settle::Bool=true, allow_last::Bool=true)::TS
columns = String.(x.fields)
if use_adj
j = findfirst([occursin(r"(adj((usted)|\s|)+)?(cl)"i, column) for column in columns])
if !isa(j, Nothing)
return x[:,j]
end
else
j = findfirst([occursin(r"(?!adj)*(cl(ose|))"i, column) for column in columns])
if !isa(j, Nothing)
return x[:,j]
end
end
if allow_settle
j = findfirst([occursin(r"(settle)"i, column) for column in columns])
if !isa(j, Nothing)
return x[:,j]
end
end
if allow_last
j = findfirst([occursin(r"(last)"i, column) for column in columns])
if !isa(j, Nothing)
return x[:,j]
end
end
error("No closing prices found.")
end
ohlc(x::TS)::TS = [op(x) hi(x) lo(x) cl(x)]
ohlcv(x::TS)::TS = [op(x) hi(x) lo(x) cl(x) vo(x)]
hlc(x::TS)::TS = [hi(x) lo(x) cl(x)]
hl(x::TS)::TS = [hi(x) lo(x)]
hl2(x::TS)::TS = (hi(x) + lo(x)) * 0.5
hlc3(x::TS; args...)::TS = (hi(x) + lo(x) + cl(x; args...)) * 0.3333333333333333
ohlc4(x::TS; args...)::TS = (op(x) + hi(x) + lo(x) + cl(x; args...)) * 0.25
|
using Test, Convex, Cliffords, SCS, SchattenNorms, Distributions, QuantumInfo
import Random
import Base.kron
set_default_solver(SCSSolver(verbose=0, eps=1e-6, max_iters=5_000))
function paulichannel(p::Vector{T}) where T <: Real
n_ = log(4,length(p))
if !isinteger(n_)
error("Probability vector must have length 4^n for some integer n")
end
n = round(Int,n_)
allpaulisops = map(m->liou(complex(m)),allpaulis(n))
return reduce(+,map(*,p,allpaulisops))
end
function randp(n)
return rand(Dirichlet(ones(4^n)))
end
function dnormp(p1,p2)
return norm(p1-p2,1)
end
Random.seed!(123456)
p1 = randp(2)
p2 = randp(2)
pc1 = paulichannel(p1)
pc2 = paulichannel(p2)
dnormcptp(pc1,pc2)
SchattenNorms.dnormcptp2(pc1,pc2)
dnorm(pc1-pc2)
times = Vector[]
results = Vector[]
for i in 1:100
println("Iteration ",i)
p1 = randp(2)
p2 = randp(2)
pc1 = paulichannel(p1)
pc2 = paulichannel(p2)
tic()
r1 = dnormcptp(pc1,pc2)
te1 = toc()
tic()
r2 = SchattenNorms.dnormcptp2(pc1,pc2)
te2 = toc()
tic()
r3 = dnorm(pc1-pc2)
te3 = toc()
push!(times, [te1, te2, te3])
push!(results, [r1, r2, r3, dnormp(p1,p2)])
end
times = reduce(hcat,times)'
results = reduce(hcat,results)'
results = results .- results[:,4]
|
using KernelRidgeRegression
using StatsBase
using MLKernels
N = 5000
x = rand(1, N) * 4π - 2π
yy = sinc.(x) # vec(sinc.(4 .* x) .+ 0.2 .* sin.(30 .* x))
y = squeeze(yy + 0.1randn(1, N), 1)
xnew = collect(-2.5π:0.01:2.5π)'
@time mykrr = fit(KRR, x, y, 1e-3/5000, GaussianKernel(1.0))
showcompact(mykrr)
show(mykrr)
@time mynystkrr = fit(KernelRidgeRegression.NystromKRR, x, y, 1e-3/5000, 280, MLKernels.GaussianKernel(100.0))
showcompact(mynystkrr)
show(mynystkrr)
@time myfastkrr = fit(KernelRidgeRegression.FastKRR, x, y, 4/5000, 11, MLKernels.GaussianKernel(100.0))
showcompact(myfastkrr)
show(myfastkrr)
@time mytnkrr = fit(KernelRidgeRegression.TruncatedNewtonKRR, x, y, 4/5000, MLKernels.GaussianKernel(100.0), 0.5, 200)
showcompact(mytnkrr)
show(mytnkrr)
@time myrandkrr = fit(KernelRidgeRegression.RandomFourierFeatures, x, y, 1e-3/5000, 200 , 1.0)
showcompact(myrandkrr)
show(myrandkrr)
|
using CSV
const defdir = joinpath(dirname(@__FILE__), "..", "datasets")
function get1cdtdata(dir)
mkpath(joinpath(defdir, "synthetic"))
path = download("https://raw.githubusercontent.com/Conradox/datastreams/master/sinthetic/1CDT.csv")
mv(path, joinpath(defdir, "synthetic/1CDT.csv"))
end
function getug2c5ddata(dir)
mkpath(joinpath(defdir, "synthetic"))
path = download("https://raw.githubusercontent.com/Conradox/datastreams/master/sinthetic/UG_2C_5D.csv")
mv(path, joinpath(defdir, "synthetic/UG_2C_5D.csv"))
end
function Dataset1CDT(batch::Int)::BatchStream
filename = "$(defdir)/synthetic/1CDT.csv"
isfile(filename) || get1cdtdata(defdir)
data = CSV.read(filename; header = false)
conn = EasyStream.TablesConnector(data)
stream = BatchStream(conn; batch = batch)
return stream
end
Dataset1CDT() = Dataset1CDT(1)
function DatasetUG_2C_5D(batch::Int)::BatchStream
filename = "$(defdir)/synthetic/UG_2C_5D.csv"
isfile(filename) || getug2c5ddata(defdir)
data = CSV.read(filename; header = false)
conn = EasyStream.TablesConnector(data)
stream = BatchStream(conn, batch)
return stream
end
DatasetUG_2C_5D() = DatasetUG_2C_5D(1) |
# https://www.codewars.com/kata/50654ddff44f800200000004
module Solution
export multiply
function multiply(a, b)
a * b
end
end
|
# Configuration for nearly neutral simuation
# Run with small values of N, ngens for testing
# Example run from command line: julia run.jl examples/ia_example0
function dfemod(x)
dfe_mod(x,fit_inc=1.2)
end
const nn_simtype = 1 # nearly neutral infinite alleles
const type_str = "MD"
@everywhere const N_list = [8] # sample size n list, popsize N may be larger
const N_mu_list= [2.0] # Mutation rate as a multiple of 1.0/N
const L = 1 # number of loci
const ngens = 6 # Generations after burn-in
const burn_in= 0.0 # generations of burn_in as a multiple of 1/mu
const use_poplist=false # save a list of populations as a check of correctness
dfe=dfemod
dfe_str = "dfe_mod fit_inc: 1.2"
|
using BAT
using Test
using Statistics
using StatsBase
using Distributions
using HypothesisTests
@testset "Funnel Distribution" begin
#Tests different forms of instantiate Funnel Distribution
@test @inferred(BAT.FunnelDistribution(1., 2., 3)) isa BAT.FunnelDistribution
@test @inferred(BAT.FunnelDistribution()) isa BAT.FunnelDistribution
@test @inferred(BAT.FunnelDistribution(a = 1.0, b = 0.5, n = 3)) isa BAT.FunnelDistribution
funnel = BAT.FunnelDistribution(a = Float32(1.0), b = Float32(0.5), n = Int32(3))
#Check Parameters
@test @inferred(StatsBase.params(funnel)) == (Float32(1.0), Float32(0.5), Int32(3))
@test @inferred(Base.length(funnel)) == 3 #Number of dimensions
@test @inferred(Base.eltype(funnel)) == Float32 #Element Type
#Check mean and covariance
@test @inferred(Statistics.mean(funnel)) == [0.0, 0.0, 0.0] #Check mean
@test isapprox(@inferred(Statistics.cov(funnel)), [1.00256 -0.0124585 -0.00373376;
-0.0124585 7.04822 -0.165097; -0.00373376 -0.165097 7.1126], rtol = 1e-1, atol = 0)
#logpdf
@test isapprox(@inferred(Distributions._logpdf(funnel, [0., 0., 0.])), -2.75681, atol = 1e-5)
#KS Test
#Test the constant-variance Gaussian
funnel = BAT.FunnelDistribution(a = 1., b = 0., n = 1)
ks_test = HypothesisTests.ExactOneSampleKSTest(rand(funnel, 10^6)[:], Normal(0., 1.))
@test pvalue(ks_test) > 0.05
#Test the variable-variance Gaussian
funnel = BAT.FunnelDistribution(a = 0., b = 0., n = 2)
ks_test = HypothesisTests.ExactOneSampleKSTest(rand(funnel, 10^6)[2,:], Normal(0., 1.))
@test pvalue(ks_test) > 0.05
end |
"""
LDA Slater exchange (DOI: 10.1017/S0305004100016108 and 10.1007/BF01340281)
"""
energy_per_particle(::Val{:lda_x}, ρ) = -3/4 * cbrt(3/π * ρ)
|
"""
ConjugateModel <: ProbabilisticModel
`ConjugateModel` is a `ProbabilisticModel` with a conjugate prior of the
corresponding likelihood function.
"""
abstract type ConjugateModel <: ProbabilisticModel end
function Base.show(io::IO, model::ConjugateModel)
modelinfo = replace(string(model.dist), "Distributions."=>"", count=1)
message = "$(typeof(model)) : $(modelinfo)"
print(io, message)
end
"""
ConjugateBernoulli <: ConjugateModel
Bernoulli likelihood with Beta distribution as the conjugate prior.
```julia
ConjugateBernoulli(α, β) # construct a ConjugateBernoulli
update!(model, stats) # update model with statistics from data
samplepost(model, numsamples) # sampling from the posterior distribution
samplestats(model, numsamples) # sampling statistics from the data generating distribution
```
"""
mutable struct ConjugateBernoulli <: ConjugateModel
dist::Beta
function ConjugateBernoulli(α, β)
return new(Beta(α, β))
end
end
defaultparams(::ConjugateBernoulli) = [:θ]
function update!(model::ConjugateBernoulli, stats::BetaStatistics)
numsuccesses = stats.s
numtrials = stats.n
α = model.dist.α + numsuccesses
β = model.dist.β + numtrials - numsuccesses
model.dist = Beta(α, β)
return nothing
end
"""
ConjugateExponential <: ConjugateModel
Exponential likelihood with Gamma distribution as the conjugate prior.
```julia
ConjugateExponential(α, β) # construct a ConjugateExponential
update!(model, stats) # update model with statistics from data
samplepost(model, numsamples) # sampling from the posterior distribution
samplestats(model, numsamples) # sampling statistics from the data generating distribution
```
"""
mutable struct ConjugateExponential <: ConjugateModel
dist::Gamma
function ConjugateExponential(α, θ)
return new(Gamma(α, θ))
end
end
defaultparams(::ConjugateExponential) = [:θ]
mutable struct ConjugatePoisson <: ConjugateModel
dist::Gamma
function ConjugatePoisson(α, θ)
return new(Gamma(α, θ))
end
end
defaultparams(::ConjugatePoisson) = [:λ]
function update!(model::T, stats::S) where
{T<:Union{ConjugateExponential, ConjugatePoisson},
S<:Union{GammaStatistics}}
n = stats.n
x̄ = stats.x̄
α = model.dist.α + n
θ = model.dist.θ / (1 + model.dist.θ * n * x̄)
model.dist = Gamma(α, θ)
return nothing
end
"""
ConjugateNormal <: ConjugateModel
Normal likelihood and Normal Inverse Gamma distribution as the
conjugate prior.
## Parameters
- μ: mean of normal distribution
- v: scale variance of Normal
- α: shape of Gamma distribution
- θ: scale of Gamma distribution
```julia
ConjugateNormal(μ, v, α, θ) # construct a ConjugateNormal
update!(model, stats) # update model with statistics from data
samplepost(model, numsamples) # sampling from the posterior distribution
samplestats(model, numsamples) # sampling statistics from the data generating distribution
```
## References
- The update rule for Normal distribution is based on this
[lecture notes](https://people.eecs.berkeley.edu/~jordan/courses/260-spring10/other-readings/chapter9.pdf).
"""
mutable struct ConjugateNormal{S} <: ConjugateModel
dist::S
function ConjugateNormal{Normal}(μ::Real, σ::Real)
T = promote_type(typeof(μ), typeof(σ))
return new(Normal{T}(μ, σ))
end
function ConjugateNormal{NormalInverseGamma}(μ::Real, v::Real, α::Real, θ::Real)
return new(NormalInverseGamma(μ, v, α, θ))
end
end
ConjugateNormal(μ::T, v::T, α::T, θ::T) where T <: Real = ConjugateNormal{NormalInverseGamma}(μ, v, α, θ)
ConjugateNormal(μ::T, σ::T) where T <: Real = ConjugateNormal{Normal}(μ, σ)
defaultparams(::ConjugateNormal{NormalInverseGamma}) = [:μ]
"""
ConjugateLogNormal(μ, v, α, θ)
A model with Normal likelihood and Normal Inverse distribution with log transformed data.
Notice `LogNormal` in `Distributions.jl` takes mean and standard deviation of \$\\log(x)\$
instead of \$x\$ as the input parameters.
```julia
ConjugateLogNormal(μ, v, α, θ) # construct a ConjugateLogNormal
lognormalparams(μ_logx, σ²_logx) # convert normal parameters to log-normal parameters
update!(model, stats) # update model with statistics from data
samplepost(model, numsamples) # sampling from the posterior distribution
samplestats(model, numsamples) # sampling statistics from the data generating distributio
```
"""
mutable struct ConjugateLogNormal{S} <: ConjugateModel
dist::S
function ConjugateLogNormal{NormalInverseGamma}(μ::Real, v::Real, α::Real, θ::Real)
return new(NormalInverseGamma(μ, v, α, θ))
end
end
ConjugateLogNormal(μ::T, v::T, α::T, θ::T) where T <: Real = ConjugateLogNormal{NormalInverseGamma}(μ, v, α, θ)
function lognormalparams(μ_logx, σ²_logx)
μ_x = @. exp(μ_logx + σ²_logx / 2)
σ²_x = @. (exp(σ²_logx) - 1) * exp(2 * μ_logx + σ²_logx)
return (μ_x, σ²_x)
end
defaultparams(::ConjugateLogNormal{NormalInverseGamma}) = [:μ_x]
function update!(model::Union{ConjugateNormal{NormalInverseGamma},ConjugateLogNormal{NormalInverseGamma}},
stats::Union{NormalStatistics,LogNormalStatistics})
n, x̄, sdx = getall(stats)
ΣΔx² = sdx^2 * (n - 1)
μ0 = model.dist.μ
v0 = model.dist.v
α0 = model.dist.α
θ0 = model.dist.θ
inv_v0 = 1.0 / v0
inv_v = inv_v0 + n
μ = (inv_v0 * μ0 + n * x̄) / inv_v
v = 1 / inv_v
α = α0 + n / 2
θ = θ0 + 0.5 * (ΣΔx² + (n * inv_v0) * (x̄ - μ0)^2 * v)
model.dist = NormalInverseGamma(μ, v, α, θ)
return nothing
end
abstract type ChainOperator end
struct MultiplyOperator <: ChainOperator end
(m::MultiplyOperator)(a, b) = .*(a, b)
"""
ChainedModel <: ProbabilisticModel
`ChainedModel` is a combination of `ConjugateModel`s chained by the specified operator.
It can be used to model a multiple step process.
"""
struct ChainedModel <: ProbabilisticModel
models::Vector{ConjugateModel}
operators::Vector{ChainOperator}
function ChainedModel(models::Vector{ConjugateModel}, operators)
length(models) - 1 == length(operators) || error("need to specify (number of model - 1) chaining operators")
return new(models, operators)
end
end
function ChainedModel(models::Vector{ConjugateModel})
operators = [MultiplyOperator() for _ in 1:(length(models) -1)]
return ChainedModel(models, operators)
end
function update!(chainedmodel::ChainedModel, listofstats::Vector{T}) where T <: ModelStatistics
@assert(length(chainedmodel.models) == length(listofstats),
"Number of model should be equal to number of statistics.")
for (model, stats) = zip(chainedmodel.models, listofstats)
update!(model, stats)
end
return nothing
end
function defaultparams(chainedmodel::ChainedModel)
params = Symbol[]
for model in chainedmodel.models
push!(params, defaultparams(model)[1])
end
return params
end
"""
samplepost(model, numsamples)
Sample from the posterior distribution of the model.
"""
function samplepost(model::ConjugateBernoulli, numsamples::Int)
return BernoulliPosteriorSample(rand(model.dist, numsamples))
end
function samplepost(model::ConjugateExponential, numsamples::Int)
# Gamma distribution generates the rate (λ) of Exponential distribution
# convert it to scale θ to make it consistent with Distributions.jl
λs = rand(model.dist, numsamples)
θs = 1 ./ λs
return ExponentialPosteriorSample(θs)
end
function samplepost(model::ConjugatePoisson, numsamples::Int)
inv_rates = rand(model.dist, numsamples)
λs = 1 ./ inv_rates
return PoissonPosteriorSample(λs)
end
function samplepost(model::ConjugateNormal{NormalInverseGamma}, numsamples::Int)
μ, σ² = rand(model.dist, numsamples)
return NormalPosteriorSample(μ, σ²)
end
function samplepost(model::ConjugateLogNormal{NormalInverseGamma}, numsamples::Int)
# sample for normal means and variances
μ_logx, σ²_logx = rand(model.dist, numsamples)
μ_x, σ²_x = lognormalparams(μ_logx, σ²_logx)
return LogNormalPosteriorSample(μ_logx, σ²_logx, μ_x, σ²_x)
end
function samplepost(model::T, parameter::Symbol, numsamples::Int) where T <: ConjugateModel
samples = samplepost(model, numsamples)
return getfield(samples, parameter)
end
function samplepost(model::T, parameters::Vector{Symbol}, numsamples::Int) where T <: ConjugateModel
parameter = toparameter(parameters)
return samplepost(model, parameter, numsamples)
end
function samplepost(models::Vector{T}, parameters::Vector{Symbol}, numsamples::Int) where T <: ProbabilisticModel
samples = Array{Float64,2}(undef, numsamples, length(models))
for (modelindex, model) in enumerate(models)
sample = samplepost(model, parameters, numsamples)
samples[:, modelindex] = sample
end
return samples
end
function samplepost(chainedmodel::ChainedModel, parameters::Vector{Symbol}, numsamples::Int)
length(parameters) == length(chainedmodel.models) ||
throw(ArgumentError("Number of parameters must be equal to number of chained models"))
models = chainedmodel.models
operators = chainedmodel.operators
post_samples = [samplepost(model, parameter, numsamples) for (model, parameter) in zip(models, parameters)]
chainedsample = post_samples[1]
for i = 2:length(post_samples)
chainedsample = operators[i - 1](chainedsample, post_samples[i])
end
return chainedsample
end
"""
samplestats(model, dist, numsamples)
Sample from the distribution of the data generating process, and
calculate the corresponding statistics for the model.
"""
function samplestats(::ConjugateBernoulli, dist::Bernoulli, numsamples::Integer)
return BetaStatistics(rand(dist, numsamples))
end
function samplestats(::ConjugateExponential, dist::Exponential, numsamples::Integer)
return GammaStatistics(rand(dist, numsamples))
end
function samplestats(::ConjugatePoisson, dist::Poisson, numsamples::Integer)
return GammaStatistics(rand(dist, numsamples))
end
function samplestats(::ConjugateNormal{NormalInverseGamma}, dist::Normal, numsamples::Integer)
return NormalStatistics(rand(dist, numsamples))
end
function samplestats(::ConjugateLogNormal{NormalInverseGamma}, dist::LogNormal, numsamples::Integer)
return LogNormalStatistics(rand(dist, numsamples))
end
function samplestats(chainedmodel::ChainedModel, dists::Vector{T}, listofnumsamples::Vector{Int}) where T
listofstats = Vector{ModelStatistics}()
for (model, dist, numsamples) in zip(chainedmodel.models, dists, listofnumsamples)
push!(listofstats, samplestats(model, dist, numsamples))
end
return listofstats
end
|
module MatOp
using Blocks
using Compat
importall Blocks
importall Base
export MatOpBlock, Block, RandomMatrix, op, convert, *
##
# RamdomMatrix: A way to represent distributed memory random matrix that is easier to work with blocks
# Actually just a placeholder for eltype, dims and rng seeds, with a few AbstractMatrix methods defined on it
type RandomMatrix{T} <: AbstractMatrix{T}
t::Type{T}
dims::NTuple{2,Int}
seed::Int
end
eltype{T}(m::RandomMatrix{T}) = T
size(m::RandomMatrix) = m.dims
##
# MatrixSplits hold remote refs of parts of the matrix, along with the matrix definition
type MatrixSplits
m::AbstractMatrix
splitrefs::Dict
end
##
# Block definition on DenseMatrix.
# Each part contains the part dimensions.
# Parts are fetched from master node on first use, and their resusable references are stored at master node.
# This is not a terribly useful type, just used as an example implementation.
type DenseMatrixPart
r::RemoteRef
split::Tuple
end
function Block(A::DenseMatrix, splits::Tuple)
msplits = MatrixSplits(A, Dict())
r = RemoteRef()
put!(r, msplits)
blks = [DenseMatrixPart(r, split) for split in splits]
Block(A, blks, Blocks.no_affinity, as_it_is, as_it_is)
end
##
# Block definition on RandomMatrix.
# Each part contains the type, part dimensions, and rng seed.
# Parts are created locally on first use, and their resusable references are stored at master node
# This is not a terribly useful type, just used as an example implementation.
type RandomMatrixPart
r::RemoteRef
t::Type
split::Tuple
splitseed::Int
end
function Block(A::RandomMatrix, splits::Tuple)
msplits = MatrixSplits(A, Dict())
r = RemoteRef()
put!(r, msplits)
splitseeds = A.seed + (1:length(splits))
blks = [RandomMatrixPart(r, eltype(A), splits[idx], splitseeds[idx]) for idx in 1:length(splits)]
Block(A, blks, Blocks.no_affinity, as_it_is, as_it_is)
end
function matrixpart_get(blk)
refpid = blk.r.where # get the pid of the master process
# TODO: need a way to avoid unnecessary remotecalls after the initial fetch
remotecall_fetch(()->matrixpart_get(blk, myid()), refpid)
end
function matrixpart_get(blk, pid)
msplits = fetch(blk.r)
splitrefs = msplits.splitrefs
key = (pid, blk.split)
get(splitrefs, key, nothing)
end
function matrixpart_set(blk, part_ref)
refpid = blk.r.where # get the pid of the master process
remotecall_wait(()->matrixpart_set(blk, myid(), part_ref), refpid)
end
function matrixpart_set(blk, pid, part_ref)
msplits = fetch(blk.r)
splitrefs = msplits.splitrefs
key = (pid, blk.split)
splitrefs[key] = part_ref
nothing
end
function matrixpart(blk)
# check at the master process if we already have this chunk, and get its ref
chunk_ref = matrixpart_get(blk)
(chunk_ref === nothing) || (return fetch(chunk_ref))
# create the chunk
part = matrixpart_create(blk)
part_ref = RemoteRef()
put!(part_ref, part)
# update its reference
matrixpart_set(blk, part_ref)
# return the chunk
part
end
function matrixpart_create(blk::RandomMatrixPart)
part_size = map(length, blk.split)
srand(blk.splitseed)
rand(blk.t, part_size...)
end
function matrixpart_create(blk::DenseMatrixPart)
splits = fetch(blk.r)
A = splits.m
part_range = blk.split
A[part_range...]
end
convert{T}(::Type{DenseMatrix}, r::Block{RandomMatrix{T}}) = convert(DenseMatrix{T}, r)
function convert{T}(::Type{DenseMatrix{T}}, r::Block{RandomMatrix{T}})
A = r.source
ret = zeros(eltype(A), size(A))
for blk in blocks(r)
part_range = blk.split
ret[part_range...] = matrixpart_create(blk)
end
ret
end
# Blocked operations on matrices
type MatOpBlock
mb1::Block
mb2::Block
oper::Symbol
function MatOpBlock(m1::AbstractMatrix, m2::AbstractMatrix, oper::Symbol, np::Int=0)
s1 = size(m1)
s2 = size(m2)
(0 == np) && (np = nworkers())
np = min(max(s1...), max(s2...), np)
(splits1, splits2) = (oper == :*) ? matop_block_mul(s1, s2, np) : error("operation $oper not supported")
mb1 = Block(m1, splits1)
mb2 = Block(m2, splits2)
new(mb1, mb2, oper)
end
end
function Block(mb::MatOpBlock)
(mb.oper == :*) && return block_mul(mb)
error("operation $(mb.oper) not supported")
end
op{T<:MatOpBlock}(blk::Block{T}) = (eval(blk.source.oper))(blk)
##
# internal methods
function common_factor_around(around::Int, nums::Int...)
gf = gcd(nums...)
((gf == 1) || (gf < around)) && return gf
factors = Int[]
n = @compat(Int(floor(gf/around)))+1
while n < gf
(0 == (gf%n)) && (push!(factors, @compat(round(Int,gf/n))); break)
n += 1
end
n = @compat(Int(floor(gf/around)))
while n > 0
(0 == (gf%n)) && (push!(factors, @compat(round(Int,gf/n))); break)
n -= 1
end
(length(factors) == 1) && (return factors[1])
((factors[2]-around) > (around-factors[1])) ? factors[1] : factors[2]
end
function mat_split_ranges(dims::Tuple, nrsplits::Int, ncsplits::Int)
row_splits = Base.splitrange(dims[1], nrsplits)
col_splits = Base.splitrange(dims[2], ncsplits)
splits = Array(Tuple,0)
for cidx in 1:ncsplits
for ridx in 1:nrsplits
push!(splits, (row_splits[ridx],col_splits[cidx]))
end
end
splits
end
# Input:
# - two matrices (or their dimensions)
# - number of processors to split over
# Output:
# - tuples of ranges to split each matrix into, suitable for block multiplication
function matop_block_mul(s1::Tuple, s2::Tuple, np::Int)
fc = common_factor_around(round(Int,min(s1[2],s2[1])/np), s1[2], s2[1])
f1 = common_factor_around(round(Int,s1[1]/np), s1[1])
f2 = common_factor_around(round(Int,s2[2]/np), s2[2])
splits1 = mat_split_ranges(s1, round(Int,s1[1]/f1), round(Int,s1[2]/fc)) # splits1 is f1 x fc blocks
splits2 = mat_split_ranges(s2, round(Int,s2[1]/fc), round(Int,s2[2]/f2)) # splits2 is fc x f2 blocks
(tuple(splits1...), tuple(splits2...))
end
function block_mul(mb::MatOpBlock)
blklist = Any[]
afflist = Any[]
proclist = workers()
# distribute by splits on m1
for blk1 in blocks(mb.mb1)
split1 = blk1.split
proc = shift!(proclist)
push!(proclist, proc)
for blk2 in blocks(mb.mb2)
split2 = blk2.split
(split1[2] != split2[1]) && continue
result_range = (split1[1], split2[2])
push!(blklist, (result_range, blk1, blk2, proc))
# set affinities of all blocks each split of m1 needs to same processor
push!(afflist, proc)
end
end
Block(mb, blklist, afflist, as_it_is, as_it_is)
end
##
# operations
function *{T<:MatOpBlock}(blk::Block{T})
mb = blk.source
m1 = mb.mb1.source
m2 = mb.mb2.source
m1size = size(m1)
m2size = size(m2)
restype = promote_type(eltype(m1), eltype(m2))
res = zeros(restype, m1size[1], m2size[2])
pmapreduce((t)->(t[1], matrixpart(t[2])*matrixpart(t[3])), (v,t)->begin v[t[1]...] += t[2]; v; end, res, blk)
res
end
end # module MatOP
|
@testset "Test OpCode" begin
@testset "Test Make" begin
for (op, operands, expected) in [
(m.OpConstant, [65534], [UInt8(m.OpConstant), 255, 254]),
(m.OpAdd, [], [UInt8(m.OpAdd)]),
(m.OpSub, [], [UInt8(m.OpSub)]),
(m.OpMul, [], [UInt8(m.OpMul)]),
(m.OpDiv, [], [UInt8(m.OpDiv)]),
(m.OpEqual, [], [UInt8(m.OpEqual)]),
(m.OpNotEqual, [], [UInt8(m.OpNotEqual)]),
(m.OpLessThan, [], [UInt8(m.OpLessThan)]),
(m.OpGreaterThan, [], [UInt8(m.OpGreaterThan)]),
(m.OpGetLocal, [255], [UInt8(m.OpGetLocal), 255]),
(m.OpGetFree, [1], [UInt8(m.OpGetFree), 1]),
(m.OpGetOuter, [1, 2, 3], [UInt8(m.OpGetOuter), 1, 2, 3]),
(m.OpClosure, [65534, 255], [UInt8(m.OpClosure), 255, 254, 255]),
(m.OpIllegal, [], []),
]
@test begin
instruction = m.make(op, operands...)
@assert length(instruction) == length(expected) "Instruction has wrong length. Expected $(length(expected)), got $(length(instruction)) instead."
for (i, e) in enumerate(expected)
@assert instruction[i] == e "Instruction has wrong value at index $(i). Expected $(e), got $(instruction[i]) instead."
end
true
end
end
end
@testset "Test Stringifying Instructions" begin
for (instructions, expected) in [
(
[
m.make(m.OpConstant, 1),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
],
"0000 OpConstant 1\n0003 OpConstant 2\n0006 OpConstant 65535\n",
),
(
[m.make(m.OpAdd), m.make(m.OpConstant, 2), m.make(m.OpConstant, 65535)],
"0000 OpAdd\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[m.make(m.OpSub), m.make(m.OpConstant, 2), m.make(m.OpConstant, 65535)],
"0000 OpSub\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[m.make(m.OpMul), m.make(m.OpConstant, 2), m.make(m.OpConstant, 65535)],
"0000 OpMul\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[m.make(m.OpDiv), m.make(m.OpConstant, 2), m.make(m.OpConstant, 65535)],
"0000 OpDiv\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[m.make(m.OpEqual), m.make(m.OpConstant, 2), m.make(m.OpConstant, 65535)],
"0000 OpEqual\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[
m.make(m.OpNotEqual),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
],
"0000 OpNotEqual\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[
m.make(m.OpLessThan),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
],
"0000 OpLessThan\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[
m.make(m.OpGreaterThan),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
],
"0000 OpGreaterThan\n0001 OpConstant 2\n0004 OpConstant 65535\n",
),
(
[
m.make(m.OpAdd),
m.make(m.OpGetLocal, 1),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
],
"0000 OpAdd\n0001 OpGetLocal 1\n0003 OpConstant 2\n0006 OpConstant 65535\n",
),
(
[
m.make(m.OpAdd),
m.make(m.OpGetLocal, 1),
m.make(m.OpConstant, 2),
m.make(m.OpConstant, 65535),
m.make(m.OpClosure, 65535, 255),
],
"0000 OpAdd\n0001 OpGetLocal 1\n0003 OpConstant 2\n0006 OpConstant 65535\n0009 OpClosure 65535 255\n",
),
([m.Instructions([UInt8(m.OpIllegal)])], "ERROR: unknown opcode: 36\n"),
]
@test string(vcat(instructions...)) == expected
end
end
@testset "Test Reading Operands" begin
for (op, operands, bytes_read) in [
(m.OpConstant, [65535], 2),
(m.OpGetLocal, [255], 1),
(m.OpClosure, [65535, 255], 3),
]
@test begin
instruction = m.make(op, operands...)
def = m.lookup(Integer(op))
@assert !isnothing(def) "Definition for $op not found."
operands_read, n = m.read_operands(def, instruction[2:end])
@assert n == bytes_read "Wrong number of bytes read. Expected $bytes_read, got $n instead."
for (i, want) in enumerate(operands)
@assert want == operands_read[i] "Wrong operand at index $i. Expected $(want), got $(operands_read[i]) instead."
end
true
end
end
end
end
|
# ---
# title: 29. Divide Two Integers
# id: problem29
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Math, Binary Search
# link: <https://leetcode.com/problems/divide-two-integers/description/>
# hidden: true
# ---
#
# Given two integers `dividend` and `divisor`, divide two integers without using
# multiplication, division, and mod operator.
#
# Return the quotient after dividing `dividend` by `divisor`.
#
# The integer division should truncate toward zero, which means losing its
# fractional part. For example, `truncate(8.345) = 8` and `truncate(-2.7335) =
# -2`.
#
# **Note:**
#
# * Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function **returns 2 31 − 1 when the division result overflows**.
#
#
#
# **Example 1:**
#
#
#
# Input: dividend = 10, divisor = 3
# Output: 3
# Explanation: 10/3 = truncate(3.33333..) = 3.
#
#
# **Example 2:**
#
#
#
# Input: dividend = 7, divisor = -3
# Output: -2
# Explanation: 7/-3 = truncate(-2.33333..) = -2.
#
#
# **Example 3:**
#
#
#
# Input: dividend = 0, divisor = 1
# Output: 0
#
#
# **Example 4:**
#
#
#
# Input: dividend = 1, divisor = 1
# Output: 1
#
#
#
#
# **Constraints:**
#
# * `-231 <= dividend, divisor <= 231 - 1`
# * `divisor != 0`
#
#
## @lc code=start
using LeetCode
## add your code here:
## @lc code=end
|
function LogPredict(θ;μ=0,σ=1,ξ=0.5)
P=function (X)
m=size(X,1)
s=zeros(m)
X=(X.-μ)./σ
X=[ones(m) X]
p=Sigmoid(X*θ)
s[p.>=ξ] .=1
return s
end
return P
end
|
function [d_time]=GH_greens_funct(rd,dt,nt,c,src,opt)
% Inputs:
% f: frequency [Hz]
% rd: zeros(ns,nr);src and rev distance [m].
% src: zeros(1,nt);usually Ricker.
%
% Outputs:
% d_time: data (Greens function) in the time domain.
%
% Copyright (C) 2019, Exploration and Environmental Geophysics (EEG) at
% ETH Zurich
src=reshape(src,[1,nt]);
ff = 1/dt; % [Hz] Sampling rate
fs = linspace(0,ff,nt); % [Hz] frequency vector
k = 2*pi*fs/c;
if strcmp(opt,'greens1d')
greens = @(r,f) -1i./(2*k) .* exp(-1i*r*k);
elseif strcmp(opt,'greens2d_1st')
greens = @(r,f) 1i/4 * besselh(0,2, r*k) .* (-2*pi*fs*1i); % first-order system
elseif strcmp(opt,'greens2d_2nd')
greens = @(r,f) 1i/4 * besselh(0,2, r*k); % second-order system
elseif strcmp(opt,'greens3d')
greens = @(r,f) exp(-1i*r*k)./(4*pi*r);
else
error('opt not supported.\n');
end
%% ---------
SRC=fft(src);
d_f = zeros(length(fs),length(rd));
for l=1:length(rd)
d_f(:,l) = SRC .* sum( greens(rd(:,l),fs) , 1 );
end
d_f( isnan(d_f) ) = 0;
%% 6. Display in time domain
d_time = ifft( d_f, [], 1, 'symmetric' );
end
|
#****************************************************************************
# Molecular Dynamics Potentials (MDP)
# CESMIX-MIT Project
#
# Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
#****************************************************************************
function writeregion(reg,filename)
tmp = [reg.triclinic];
nsize = zeros(4,1);
nsize[1] = length(tmp);
nsize[2] = length(reg.boxlo[:]);
nsize[3] = length(reg.boxhi[:]);
nsize[4] = length(reg.boxtilt[:]);
fileID = open(filename,"w");
write(fileID,Float64(length(nsize[:])));
write(fileID,Float64.(nsize[:]));
write(fileID,Float64.(tmp[:]));
write(fileID,Float64.(reg.boxlo[:]));
write(fileID,Float64.(reg.boxhi[:]));
write(fileID,Float64.(reg.boxtilt[:]));
close(fileID);
end
|
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENCE in the project root.
# ------------------------------------------------------------------
const GPU = nothing
function get_imfilter_impl(GPU)
if GPU ≠ nothing
imfilter_gpu
else
imfilter_cpu
end
end
function convdist(img::AbstractArray, kern::AbstractArray;
weights::AbstractArray=fill(1.0, size(kern)))
imfilter_impl = get_imfilter_impl(GPU)
wkern = weights.*kern
A² = imfilter_impl(img.^2, weights)
AB = imfilter_impl(img, wkern)
B² = sum(wkern .* kern)
parent(@. abs(A² - 2AB + B²))
end
cart2lin(dims, ind) = LinearIndices(dims)[ind]
lin2cart(dims, ind) = CartesianIndices(dims)[ind]
function event!(buff, hard::Dict, tile::CartesianIndices)
@inbounds for (i, coord) in enumerate(tile)
h = get(hard, coord, NaN)
buff[i] = ifelse(isnan(h), 0.0, h)
end
end
function event(hard::Dict, tile::CartesianIndices)
buff = Array{Float64}(undef, size(tile))
event!(buff, hard, tile, def)
buff
end
function indicator!(buff, hard::Dict, tile::CartesianIndices)
@inbounds for (i, coord) in enumerate(tile)
nan = isnan(get(hard, coord, NaN))
buff[i] = ifelse(nan, false, true)
end
end
function indicator(hard::Dict, tile::CartesianIndices)
buff = Array{Bool}(undef, size(tile))
indicator!(buff, hard, tile)
buff
end
function activation!(buff, hard::Dict, tile::CartesianIndices)
@inbounds for (i, coord) in enumerate(tile)
cond = coord ∈ keys(hard) && isnan(hard[coord])
buff[i] = ifelse(cond, false, true)
end
end
function activation(hard::Dict, tile::CartesianIndices)
buff = Array{Bool}(undef, size(tile))
activation!(buff, hard, tile)
buff
end
function preprocess_images(trainimg::AbstractArray{T,N}, soft::AbstractVector,
geoconfig::NamedTuple) where {T,N}
padsize = geoconfig.padsize
TI = Float64.(trainimg)
replace!(TI, NaN => 0.)
SOFT = map(soft) do (aux, auxTI)
prepend = ntuple(i->0, N)
append = padsize .- min.(padsize, size(aux))
padding = Pad(:symmetric, prepend, append)
AUX = Float64.(padarray(aux, padding))
AUXTI = Float64.(auxTI)
replace!(AUX, NaN => 0.)
replace!(AUXTI, NaN => 0.)
AUX, AUXTI
end
TI, SOFT
end
function find_disabled(trainimg::AbstractArray{T,N}, geoconfig::NamedTuple) where {T,N}
TIsize = geoconfig.TIsize
tilesize = geoconfig.tilesize
distsize = geoconfig.distsize
disabled = falses(distsize)
for ind in findall(isnan, trainimg)
start = @. max(ind.I - tilesize + 1, 1)
finish = @. min(ind.I, distsize)
tile = CartesianIndex(start):CartesianIndex(finish)
disabled[tile] .= true
end
disabled
end
function find_skipped(hard::Dict, geoconfig::NamedTuple)
ntiles = geoconfig.ntiles
tilesize = geoconfig.tilesize
spacing = geoconfig.spacing
simsize = geoconfig.simsize
skipped = Set{Int}()
datainds = Vector{Int}()
for tileind in CartesianIndices(ntiles)
# tile corners are given by start and finish
start = @. (tileind.I - 1)*spacing + 1
finish = @. start + tilesize - 1
tile = CartesianIndex(start):CartesianIndex(finish)
# skip tile if either
# 1) tile is beyond true simulation size
# 2) all values in the tile are NaN
if any(start .> simsize) || !any(activation(hard, tile))
push!(skipped, cart2lin(ntiles, tileind))
elseif any(indicator(hard, tile))
push!(datainds, cart2lin(ntiles, tileind))
end
end
skipped, datainds
end
function genpath(rng::AbstractRNG, extent::Dims{N}, kind::Symbol, datainds::AbstractVector{Int}) where {N}
path = Vector{Int}()
if isempty(datainds)
if kind == :raster
for ind in LinearIndices(extent)
push!(path, ind)
end
end
if kind == :random
path = randperm(rng, prod(extent))
end
if kind == :dilation
nelm = prod(extent)
pivot = rand(rng, 1:nelm)
grid = falses(extent)
grid[pivot] = true
push!(path, pivot)
while !all(grid)
dilated = dilate(grid)
append!(path, findall(vec(dilated .& .!grid)))
grid = dilated
end
end
else
# data-first path
shuffle!(rng, datainds)
grid = falses(extent)
for pivot in datainds
grid[pivot] = true
push!(path, pivot)
end
while !all(grid)
dilated = dilate(grid)
append!(path, findall(vec(dilated .& .!grid)))
grid = dilated
end
end
path
end
|
makepath(p) = joinpath("subdir", p)
@testset "included" begin
@test true
end
# test that ReTest can handle non-literal arguments in include
SUB="sub"
include(makepath("$SUB.jl"))
|
module HistogramThresholding
using LinearAlgebra
using ImageBase
# TODO: port ThresholdAPI to ImagesAPI
include("ThresholdAPI/ThresholdAPI.jl")
import .ThresholdAPI: AbstractThresholdAlgorithm,
find_threshold, build_histogram
include("common.jl")
include("algorithms/otsu.jl")
include("algorithms/yen.jl")
include("algorithms/minimum_error.jl")
include("algorithms/unimodal.jl")
include("algorithms/moments.jl")
include("algorithms/minimum.jl")
include("algorithms/intermodes.jl")
include("algorithms/balancedthreshold.jl")
include("algorithms/entropy_thresholding.jl")
include("deprecations.jl")
export
# main functions
find_threshold,
build_histogram,
Otsu,
UnimodalRosin,
Moments,
MinimumIntermodes,
Intermodes,
MinimumError,
Balanced,
Yen,
Entropy
end # module
|
using TSML
using TSMLextra
using TSML.ArgumentParsers
Base.@ccallable function julia_main(ARGS::Vector{String})::Cint
tsmlmain()
end
|
# TODO: I cound that "utils.jl" has been `include`ed in the main `VectorSphericalWaves` module. Is there a more neat way? when I `include("utils.jl")` here, I get lots of warnings.
# exporting functions that calculate for all m,n combinations
export M_N_wave_all_m_n
export B_C_P_mn_of_θ_ϕ_for_all_m_n
export πₘₙ_τₘₙ_all_all_m_n
#############################################################################################
# This version is different from "VectorSphericalHarmonics.jl", as it calculate VSWF for all m,n and all kr, θ, ϕ in one call
# This should be more stable and faster, as it employs recurrence relations in calculating πₘₙ and τₘₙ
# using recurrence relations in calculating πₘₙ and τₘₙ
#############################################################################################
# calculate π(θ) and τ(θ) using recurrence relations
function πₘₙ_τₘₙ_all_all_m_n(n_max::I, θ::R; verbose=false) where {R <: Real, I <: Integer}
# calculate A with recurrence relation
A = SortedDict(0 => 1.0)
for m = 0:n_max - 1
A[m + 1] = A[m] * sqrt((2m + 1) / (2 * (m + 1)))
end
# calculate πₘₙ with recurrence relation
πₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))
for m = 1:n_max # TODO: I think I need to start m from 0, not 1.
n = m
πₘₙ_all[single_index_from_m_n(m, n)] = m * A[m] * sin(θ)^(m - 1)
if verbose; println("m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])"); end
# calculate π₋ₘₙ from πₘₙ
if m != 0
πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]
if verbose; println("m=$(-m), n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(-m, n)])"); end
end
for n = (m + 1):n_max
if n == m + 1
πₘₙ_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(θ) * πₘₙ_all[single_index_from_m_n(m, n - 1)])
if verbose; println("m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])"); end
else
πₘₙ_all[single_index_from_m_n(m, n)] = 1 / sqrt(n^2 - m^2) * ((2n - 1) * cos(θ) * πₘₙ_all[single_index_from_m_n(m, n - 1)]) - sqrt((n - 1)^2 - m^2) * πₘₙ_all[single_index_from_m_n(m, n - 2)]
if verbose; println("m=$m, n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(m, n)])"); end
end
# calculate π₋ₘₙ from πₘₙ
if m != 0
πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]
if verbose; println("m=$(-m), n=$n, πₘₙ_all=$(πₘₙ_all[single_index_from_m_n(-m, n)])"); end
end
end
end
τₘₙ_all = 0 # TODO: add the code for it
return πₘₙ_all, τₘₙ_all
end
#############################################################################################
# Legendre and Associated Legendre
function Legendre_polynomials_Pn_array(n_max::I, x::NN) where {I <: Integer, NN <: Number}
"""
Calculate all Legendre polynomials Pₙ(x) from n = 1 up to n=n_max using recurrence relation
https://en.wikipedia.org/wiki/Legendre_polynomials
returns
dictionary. TODO: find a better way if this cause adjoint calculation trouble
"""
P = SortedDict(
0 => 1,
1 => x,
)
for n = 1:(n_max - 1)
P[n + 1] = ((2n + 1) * x * P[n] - n * P[n - 1]) / (n + 1)
end
return P
end
function Legendre_polynomials_Pn(n::I, x::NN) where {I <: Integer, NN <: Number}
"""
Calculate Legendre polynomials Pₙ(x) at a given n
"""
return Legendre_polynomials_Pn_array(n, x)[n]
end
function Associated_Legendre_polynomials_Pmn_array(m::I, n_max::I, x) where {I <: Integer}
"""
Associated Legendre polynomials Pᵐₙ(x) from n = m up to n=n_max using recurrence relation
https://en.wikipedia.org/wiki/Associated_Legendre_polynomials#Recurrence_formula
returns
dictionary. TODO: find a better way if this cause adjoint calculation trouble
"""
n = m
P = SortedDict(
n => (-1)^n * factorial(factorial(2n - 1)) * (1 - x^2)^(n / 2),
)
P[n + 1] = x * (2n + 1) * P[n]
for n = (m + 1):(n_max - 1)
P[n + 1] = ( (2n + 1) * x * P[n] - (n + m) * P[n - 1] ) / (n - m + 1)
end
return P
end
function Associated_Legendre_polynomials_Pmn(m::I, n::I, x) where {I <: Integer}
"""
Associated Legendre polynomials Pᵐₙ(x) at a given n
"""
return Associated_Legendre_polynomials_Pmn_array(m, n, x)[n]
end
#############################################################################################
# Wigner-d, using recurrence
# TODO: I think this will not work for large s,m,n values, try to fix it as in `wignerdjmn_ELZOUKA`
function wignerd_and_∂wignerd_for_all_s(s_max::I, m::I, n::I, θ::R; get_derivatives=true, verbose=false) where {R <: Real, I <: Integer}
"""
Calculate dˢₘₙ(θ) and ∂(dˢₘₙ(θ))/∂θ for all values of s, where s starts from s_min up to s_max. s_min is the maximum of |m| and |n|
"""
# TODO: special case of m=0, n=0 (eq. B.27)
s_min = max(abs(m), abs(n))
# calculate ξ from eq. B.16
if n >= m
ξ_mn = 1
else
ξ_mn = (-1)^(m - n)
end
x = cos(θ)
# calculate d^s_min__m_n(θ) from eq. B.24
d_smin_m_n =
ξ_mn * 2.0^(-s_min) * sqrt(
factorial(BigInt(2s_min)) / (factorial(BigInt(abs(m - n))) * factorial(BigInt(abs(m + n))))
) *
(1 - x)^(abs(m - n) / 2) *
(1 + x)^(abs(m + n) / 2)
d = SortedDict(
s_min - 1 => 0.0,
s_min => d_smin_m_n
)
# applying the recurrence relation
if n == 0
if m == 0
if verbose; println("m=$m, n=$n, I will use Legendre_polynomials_Pn_array"); end
P_s = Legendre_polynomials_Pn_array(s_max + 1, x)
for s = s_min:s_max + 1
d[s] = P_s[s]
end
else
if verbose; println("m=$m, n=$n, I will use Associated_Legendre_polynomials_Pmn_array"); end
P_m_s = Associated_Legendre_polynomials_Pmn_array(m, s_max + 1, x)
for s = s_min:s_max + 1
d[s] = sqrt(factorial(s - m) / factorial(s + m)) * P_m_s[s]
end
end
else
for s = s_min:s_max + 1
if verbose; println("m=$m, n=$n, I will use the general recurrence"); end
d[s + 1] = 1 / (s * sqrt((s + 1)^2 - m^2) * sqrt((s + 1)^2 - n^2)) * (
(2s + 1) * (s * (s + 1) * x - m * n) * d[s]
- 1 * (s + 1) * sqrt(s^2 - m^2) * sqrt(s^2 - n^2) * d[s - 1]
) # eq. B.22
end
end
# calculate the derivative ∂(dˢₘₙ(θ))/∂θ
if get_derivatives
∂d_∂θ = SortedDict(
s_min - 1 => 0.0,
s_min => 0.0
)
sin_theta = sin(θ)
for s = s_min:s_max
if verbose; println("s=$s"); end
∂d_∂θ[s] = 1 / sin_theta * (
-1 * ((s + 1) * sqrt((s^2 - m^2) * (s^2 - n^2))) / (s * (2s + 1)) * d[s - 1]
- 1 * (m * n) / (s * (s + 1)) * d[s]
+ 1 * (
s *
sqrt((s + 1)^2 - m^2) *
sqrt((s + 1)^2 - n^2)
) /
((s + 1) * (2s + 1)) * d[s + 1]
)
end
return d, ∂d_∂θ
else
return d
end
end
#############################################################################################
# calculate π(θ) and τ(θ) using Wigner-d that was calculated using recurrence relations
function πₘₙ_τₘₙ_all_all_m_n_using_wigner(n_max::I, θ::R; verbose=false) where {R <: Real, I <: Integer}
πₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))
τₘₙ_all = zeros(get_max_single_index_from_n_max(n_max))
for m = 0:n_max # TODO: special case of m=0
d_rec_all_n, ∂d_∂θ_rec_all_n = wignerd_and_∂wignerd_for_all_s(n_max, 0, m, θ)
for n = m:n_max
if n != 0
if verbose; println("m=$m, n=$n, calculate πₘₙ_all, τₘₙ_all"); end
πₘₙ_all[single_index_from_m_n(m, n)] = m / sin(θ) * d_rec_all_n[n]
τₘₙ_all[single_index_from_m_n(m, n)] = ∂d_∂θ_rec_all_n[n]
if m != 0
πₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m + 1) * πₘₙ_all[single_index_from_m_n(m, n)]
τₘₙ_all[single_index_from_m_n(-m, n)] = (-1)^(m) * τₘₙ_all[single_index_from_m_n(m, n)]
end
end
end
end
return πₘₙ_all, τₘₙ_all
end
function B_C_mn_of_θ_for_all_m_n(n_max::I, θ::R) where {R <: Real, I <: Integer}
"""
Calculate Bₙₘ(θ), Cₙₘ(θ), Pₙₘ(θ) equations C.19, C.20, C.21
The order of m,n is according to the function "single_index_from_m_n"
"""
πₘₙ_all, τₘₙ_all = πₘₙ_τₘₙ_all_all_m_n_using_wigner(n_max, θ)
B = (_ -> zero(SVector{3,Complex})).(πₘₙ_all)
C = (_ -> zero(SVector{3,Complex})).(πₘₙ_all)
for idx in eachindex(πₘₙ_all)
B[idx] = [0, τₘₙ_all[idx], im * πₘₙ_all[idx] ]
C[idx] = [0, im * πₘₙ_all[idx], -1 * τₘₙ_all[idx] ]
end
return B, C
end
function P_mn_of_θ_for_all_m_n(n_max::I, θ::R) where {R <: Real, I <: Integer}
"""
Calculate Pₙₘ(θ) using equations C.19, C.20
The order of m,n is according to the function "single_index_from_m_n"
"""
P = fill(zero(SVector{3,Complex}), get_max_single_index_from_n_max(n_max))
for m = 0:n_max
d_rec_all_n = wignerd_and_∂wignerd_for_all_s(n_max, 0, m, θ; get_derivatives=false)
for n = m:n_max
if n != 0
P[single_index_from_m_n(m, n)] = [d_rec_all_n[n], 0, 0]
P[single_index_from_m_n(-m, n)] = [(-1)^m * d_rec_all_n[n], 0, 0] # using symmetry relation B.5, we can get d_(0,-m) from d_(0,m)
end
end
end
return P
end
function B_C_P_mn_of_θ_ϕ_for_all_m_n(n_max::I, θ::R, ϕ::R) where {R <: Real, I <: Integer}
"""
Calculate Bₙₘ(θ,ϕ), Cₙₘ(θ,ϕ), Pₙₘ(θ,ϕ) for all m and n
"""
B_of_θ, C_of_θ = B_C_mn_of_θ_for_all_m_n(n_max, θ)
P_of_θ = P_mn_of_θ_for_all_m_n(n_max, θ)
for n = 1:n_max
for m = -n:n
factor = (-1)^m * convert(R, sqrt_factorial_n_plus_m_over_factorial_n_minus_m(m,n)) * exp(im * m * ϕ)
B_of_θ[single_index_from_m_n(m, n)] *= factor
C_of_θ[single_index_from_m_n(m, n)] *= factor
P_of_θ[single_index_from_m_n(m, n)] *= factor
end
end
return B_of_θ, C_of_θ, P_of_θ
end
function M_N_wave_all_m_n(n_max::I, kr::NN, θ::R, ϕ::R; kind="regular") where {R <: Real, I <: Integer, NN <: Number}
"""
Parameters
==========
kind: string, either ["regular" or "incoming"] or ["irregular" or "outgoing"]
"""
radial_function, radial_function_special_derivative = get_radial_function_and_special_derivative_given_kind(kind)
B_of_θ_ϕ, C_of_θ_ϕ, P_of_θ_ϕ = B_C_P_mn_of_θ_ϕ_for_all_m_n(n_max, θ, ϕ)
M = 0 .* B_of_θ_ϕ
N = 0 .* B_of_θ_ϕ
for n = 1:n_max
for m = -n:n
M[single_index_from_m_n(m, n)] = convert(R, γ_mn(m, n)) * radial_function(n, kr) * C_of_θ_ϕ[single_index_from_m_n(m, n)]
N[single_index_from_m_n(m, n)] = convert(R, γ_mn(m, n)) * (
n * (n + 1) / kr * radial_function(n, kr) * P_of_θ_ϕ[single_index_from_m_n(m, n)]
+ (radial_function_special_derivative(n, kr) * B_of_θ_ϕ[single_index_from_m_n(m, n)])
)
end
end
return M, N
end
|
module FrostHelperFallingBlockIgnoreSolids
using ..Ahorn, Maple
@mapdef Entity "FrostHelper/FallingBlockIgnoreSolids" FallingBlockIgnoreSolids(x::Integer, y::Integer, width::Integer=16, height::Integer=16, tiletype::String="3", climbFall::Bool=true, behind::Bool=false)
const placements = Ahorn.PlacementDict(
"Falling Block (Ignore Solids, Frost Helper)" => Ahorn.EntityPlacement(
FallingBlockIgnoreSolids,
"rectangle",
Dict{String, Any}(),
Ahorn.tileEntityFinalizer
),
)
Ahorn.editingOptions(entity::FallingBlockIgnoreSolids) = Dict{String, Any}(
"tiletype" => Ahorn.tiletypeEditingOptions()
)
Ahorn.minimumSize(entity::FallingBlockIgnoreSolids) = 8, 8
Ahorn.resizable(entity::FallingBlockIgnoreSolids) = true, true
Ahorn.selection(entity::FallingBlockIgnoreSolids) = Ahorn.getEntityRectangle(entity)
Ahorn.renderAbs(ctx::Ahorn.Cairo.CairoContext, entity::FallingBlockIgnoreSolids, room::Maple.Room) = Ahorn.drawTileEntity(ctx, room, entity)
end |
using Printf
using Dates: AbstractTime
using Oceananigans.Units
maybe_int(t) = isinteger(t) ? Int(t) : t
"""
prettytime(t, longform=true)
Convert a floating point value `t` representing an amount of time in
SI units of seconds to a human-friendly string with three decimal places.
Depending on the value of `t` the string will be formatted to show `t` in
nanoseconds (ns), microseconds (μs), milliseconds (ms),
seconds, minutes, hours, days, or years.
With `longform=false`, we use s, m, hrs, d, and yrs in place of seconds,
minutes, hours, and years.
"""
function prettytime(t, longform=true)
# Modified from: https://github.com/JuliaCI/BenchmarkTools.jl/blob/master/src/trials.jl
# Some shortcuts
s = longform ? "seconds" : "s"
iszero(t) && return "0 $s"
t < 1e-9 && return @sprintf("%.3e %s", t, s) # yah that's small
t = maybe_int(t)
value, units = prettytimeunits(t, longform)
if isinteger(value)
return @sprintf("%d %s", value, units)
else
return @sprintf("%.3f %s", value, units)
end
end
function prettytimeunits(t, longform=true)
t < 1e-9 && return t, "" # just _forget_ picoseconds!
t < 1e-6 && return t * 1e9, "ns"
t < 1e-3 && return t * 1e6, "μs"
t < 1 && return t * 1e3, "ms"
if t < minute
value = t
!longform && return value, "s"
units = value == 1 ? "second" : "seconds"
return value, units
elseif t < hour
value = maybe_int(t / minute)
!longform && return value, "m"
units = value == 1 ? "minute" : "minutes"
return value, units
elseif t < day
value = maybe_int(t / hour)
units = value == 1 ? (longform ? "hour" : "hr") :
(longform ? "hours" : "hrs")
return value, units
elseif t < year
value = maybe_int(t / day)
!longform && return value, "d"
units = value == 1 ? "day" : "days"
return value, units
else
value = maybe_int(t / year)
units = value == 1 ? (longform ? "year" : "yr") :
(longform ? "years" : "yrs")
return value, units
end
end
prettytime(dt::AbstractTime) = "$dt"
|
"""
dirichlet_beta()
Calculates Dirichlet beta function,
[https://en.wikipedia.org/wiki/Dirichlet_beta_function](https://en.wikipedia.org/wiki/Dirichlet_beta_function)
## Arguments
* ``s`` `::Number`: it should work for any type of number, but mainly tested for `Complex{Float64}`
## Examples
```jldoctest; setup = :(using Polylogarithms)
julia> dirichlet_beta(1.5)
0.8645026534612017
```
"""
function dirichlet_beta(s::Number)
β = 4.0^(-s) * ( SpecialFunctions.zeta(s,0.25) - SpecialFunctions.zeta(s,0.75) )
end
|
using ReachabilityBenchmarks, MathematicalSystems, Reachability, Plots
include(@relpath "linearSwitching_model.jl")
include(@relpath "linearSwitching_specifications.jl")
S = linearSwitching_model()
X0, options = linearSwitching_specification()
options = Options(options)
# initial value problem
problem = InitialValueProblem(S, X0)
# reachability algorithm
algorithm_continuous = BFFPS19(:δ => 1e-4, :partition=>[1:2, 3:3, 4:4, 5:5])
algorithm_hybrid = DecomposedDiscretePost(:out_vars=>[1, 2], :clustering=>:none)
# compute flowpipe
options[:mode] = "reach"
solution = solve(problem, options, algorithm_continuous, algorithm_hybrid)
# project flowpipe to x₁ and x₂
solution.options[:plot_vars] = [1, 2]
solution_proj = project(solution)
# plot projection
plot(solution_proj)
savefig("linearSwitching")
|
function str_quote(str::AbstractString, delim::Char, na::AbstractString)::String
do_quote = false
for c in str
if c in [QUOTE_CHAR, delim, '\n', '\r']
do_quote = true
break
end
end
do_quote || str == na || return str
io = IOBuffer(sizehint=sizeof(str)+8)
write(io, QUOTE_CHAR)
for c in str
write(io, c)
if c == QUOTE_CHAR
write(io, QUOTE_CHAR)
had_q = true
end
end
write(io, QUOTE_CHAR)
String(take!(io))
end
quote_with_missing(val, delim, na) =
ismissing(val) ? na : str_quote(string(val), delim, na)
"""
write_csv(filename::AbstractString, df::DataFrame;
delim::Char=',', na::AbstractString="")
Writes `df` to disk as `filename` CSV file using `delim` separator
and `na` as string for representing missing value.
`"` character is used for quoting fields. In quoted field use `""` to
represent `"`.
`na` is written to CSV verbatim when `DataFrame` contains `missing`.
If a string is equal to `na` then it is written to CSV quoted as `"na"`.
"""
function write_csv(filename::AbstractString, df::DataFrame;
delim::Char=',', na::AbstractString="")
if delim in [QUOTE_CHAR, '\n', '\r']
throw(ArgumentError("delim is a quote char or a newline"))
end
if any(occursin.([QUOTE_CHAR, delim, '\n', '\r'], na))
throw(ArgumentError("na contains quote, separator or a newline"))
end
open(filename, "w") do io
if length(names(df)) > 0
println(io, join(str_quote.(string.(names(df)), delim, na), delim))
for i in 1:nrow(df)
line = [quote_with_missing(df[i,j], delim, na) for j in 1:ncol(df)]
println(io, join(line, delim))
end
end
end
end
|
__precompile__()
module BufferedStream
import Base: getindex, length, push!, eltype, linearindexing, size, similar, show
export LinkedStream, StreamView
export shift_origin!
# The foundation of a linked-list of chunks
type StreamChunk{T}
data::Array{T,1}
next::Nullable{StreamChunk{T}}
StreamChunk() = new(T[], Nullable{StreamChunk{T}}())
StreamChunk(data::Array{T,1}) = new(data, Nullable{StreamChunk{T}}())
end
# Just return the length of this chunk.
length(chunk::StreamChunk) = length(chunk.data)
# Show something well-behaved
function show(io::IO, chunk::StreamChunk)
write(io, "StreamChunk")
Base.showlimited(io, chunk.data)
if isnull(chunk.next)
write(io, " -> <null>")
else
write(io, " -> StreamChunk")
end
end
# The object that keeps track of the last chunk in the linked list
type LinkedStream{T}
# This is where our lovely loving data gets stored
latest::StreamChunk{T}
# How many samples have we discarded?
samples_past::Int64
# We can only create one that initializes with an empty list
LinkedStream() = new(StreamChunk{T}(), 0)
end
# Pushes a new chunk onto the end of the stream. Julia should automatically garbage collect
# the chunks any views have moved past, since they will no longer be accessible.
function push!{T}(stream::LinkedStream{T}, data::Array{T,1})
# Create a new chunk based off of this data
chunk = StreamChunk{T}(data)
# Account for the samples we're putting behind us
stream.samples_past += length(stream.latest)
# Move the new chunk into the lead position
stream.latest.next = Nullable(chunk)
stream.latest = chunk
return
end
function show{T}(io::IO, stream::LinkedStream{T})
write(io, "LinkedStream{$(string(T))}, $(stream.samples_past) samples post-origin")
end
# A view that acts like an array, but that you can move forward in the stream
type StreamView{T} <: DenseArray{T, 1}
# Where is our origin?
chunk::StreamChunk{T}
sample_offset::Int64
# What is our origin's absolute index?
abs_idx::Int64
end
# Define stuff for AbstractArray
linearindexing(::StreamView) = Base.LinearFast()
# Calculates how many samples after our origin there are buffered up
function length(view::StreamView)
# Count total length of all chunks after the origin of this guy
len = length(view.chunk)
chunk = view.chunk
while !isnull(chunk.next)
chunk = chunk.next.value
len += length(chunk)
end
# Subtract sample_offset, and ensure that zero is the smallest we will ever return
return max(len - view.sample_offset, 0)
end
size(view::StreamView) = (length(view),)
eltype{T}(view::StreamView{T}) = T
# Construct a new view off of a stream, with an optional offset
function StreamView{T}(stream::LinkedStream{T})
offset = length(stream.latest)
return StreamView{T}(stream.latest, offset, stream.samples_past + offset)
end
# Construct a new view off of another view (easy peasey; just a straight copy)
StreamView{T}(v::StreamView{T}) = StreamView{T}(v.chunk, v.sample_offset, v.abs_idx)
# Move this view forward `offset` samples; we only support positive offsets!
function shift_origin!(view::StreamView, offset::Integer)
if offset < 0
throw(DomainError())
end
# Bump up the absolute index immediately
view.abs_idx += offset
# Move through chunks until offset lands within this current chunk, or we run out of chunks
while (offset >= length(view.chunk) - view.sample_offset) && !isnull(view.chunk.next)
offset -= length(view.chunk) - view.sample_offset
# sample_offset can be greater than length(view.chunk), if we had shifted past the end of
# buffered data previously; this will move us forward as far as we can
view.sample_offset = max(view.sample_offset - length(view.chunk), 0)
view.chunk = view.chunk.next.value
end
# Once our offset lands within this chunk, update the sample_offset and call it good! If we are
# past the end of the current offset (e.g. we are shifting into the great unknown) do the same,
# simply leaving sample_offset greater than length(view.chunk)
view.sample_offset += offset
return
end
# If someone asks for an index, serve it if we can!
function getindex(view::StreamView, idx::Integer)
# Scoot us forward as much as the sample_offset requires
idx += view.sample_offset
# Zoom through chunks as much as we need
chunk = view.chunk
while idx > length(chunk)
# If we can't move forward anymore, throw a BoundsError!
if isnull(chunk.next)
throw(BoundsError())
end
idx -= length(chunk)
chunk = chunk.next.value
end
# If we got to the correct chunk, index into it and yield the data!
return chunk.data[idx]
end
# Don't define setindex!() for now; that may or may not be a great idea.
end # module
|
import CartesianGrids: curl!, Laplacian
import LinearAlgebra: Diagonal, norm
import Base: show
export VortexModel, streamfunction, streamfunction!, vorticity, vorticity!, vortexvelocities!, _computeregularizationmatrix, setvortexstrengths!, setvortexpositions!, getvortexpositions, setvortices!, pushvortices!, setU∞, impulse, addedmass, solve, solve!
# TODO: mention frame of reference for computeimpulse
# TODO: consider no deepcopy for new vortices in the methods and use deepcopy in the scripts instead
# TODO: redo PotentialFlow.jl solution in example 6 with uniform flow instead of moving plate
# TODO: check computef̃limit for multiple bodies (f₀). Maybe Γ₀ needs to be a vector.
# TODO: check if systems can be reduced to basic one and other one for all the relevant cases.
# TODO: set vortex strengths in script? Then warn in impulse that it does not regularize
# TODO: case where steady regularized bodies are next to unregularized bodies with circulation.
# TODO: change vortexvelocities to accept w and don't set vortices to 0 anymore.
# TODO: add parameter to VortexModel constructor to make model unsteady even if no vortices are provided.
# TODO: remove w from solve! arguments and calculate it in the function body. Then also remove it from solve
"""
$(TYPEDEF)
Defines a grid-based vortex model with `Nb` bodies and `Ne` edges that are regularized. If `isshedding` is `true`, the strengths of the last `Ne` vortices in `vortices` can be computed in order to regularized the `Ne` edges.
# Fields
$(TYPEDFIELDS)
# Examples
(under construction)
"""
mutable struct VortexModel{Nb,Ne,TS<:Union{AbstractPotentialFlowSystem,Laplacian},TU<:Nodes,TE<:Edges,TF<:ScalarData,TX<:VectorData}
"""g: The grid on which the vortex model is defined."""
g::PhysicalGrid
"""bodies: Bodies in the vortex model."""
bodies::Vector{PotentialFlowBody}
"""vortices: Point vortices in the vortex model."""
vortices::StructVector{Vortex}
"""U∞: Uniform flow in the vortex model."""
U∞::Tuple{Float64,Float64}
"""system: Potential flow system that has to be solved with an `AbstractPotentialFlowRHS` and an `AbstractPotentialFlowSolution` to compute the potential flow that governs the vortex model.
"""
system::TS
"""Internal fields"""
_nodedata::TU
_edgedata::TE
_bodyvectordata::TX
_ψ::TU
_f::TF
_w::TU
_ψb::TF
end
"""
$(TYPEDSIGNATURES)
Constructs a vortex model using the given function.
"""
function VortexModel(g::PhysicalGrid, bodies::Vector{PotentialFlowBody}, vortices::StructVector{Vortex}, U∞::Tuple{Float64,Float64})
vortices = deepcopy(vortices)
e_idx = getregularizededges(bodies)
Nb = length(bodies)
Ne = length(e_idx)
if isempty(bodies)
sizef = 0
else
sizef = sum(length.(bodies))
end
# Initialize data structures for internal use
_nodedata = Nodes(Dual,size(g))
_edgedata = Edges(Primal,size(g))
_bodyvectordata = VectorData(sizef)
_ψ = Nodes(Dual,size(g))
_f = ScalarData(sizef)
_w = Nodes(Dual,size(g))
_ψb = ScalarData(sizef)
L = plan_laplacian(size(_nodedata),with_inverse=true)
if Nb == 0
system = L
else
regop = Regularize(VectorData(collect(bodies)), cellsize(g), I0=origin(g), ddftype = CartesianGrids.Yang3, issymmetric=true)
Rmat,_ = RegularizationMatrix(regop, _f, _nodedata)
Emat = InterpolationMatrix(regop, _nodedata, _f)
one_vec = [ScalarData(sizef) for i in 1:Nb]
for i in 1:Nb
one_vec[i][getrange(bodies,i)] .= 1.0
end
if Ne == 0 # System without regularized edges. Enforce circulation constraints.
system = ConstrainedIBPoisson(L, Rmat, Emat, one_vec, one_vec)
else # System with regularized edges. Enforce edge constraints.
e_vec = [ScalarData(sizef) for i in 1:Ne]
k = 0
for i in 1:Nb
for id in getregularizededges(bodies,i)
k += 1
e_vec[k][id] = 1.0
end
end
if isempty(vortices) # With regularized edges, but no vortices. This is a steady case.
system = SteadyRegularizedIBPoisson(L, Rmat, Emat, one_vec, e_vec)
else # With regularized edges and vortices. This is an unsteady case with vortex shedding.
vidx_vec = Vector{Vector{Int64}}()
vidx = collect(1:Ne)
for i in 1:Nb
vidx_i = [pop!(vidx) for k in 1:length(bodies[i].edges)]
push!(vidx_vec, vidx_i)
end
system = UnsteadyRegularizedIBPoisson(L, Rmat, Emat, one_vec, e_vec, vidx_vec)
end
end
end
VortexModel{Nb,Ne,typeof(system),typeof(_ψ),typeof(_edgedata),typeof(_f),typeof(_bodyvectordata)}(g, bodies, vortices, U∞, system, _nodedata, _edgedata, _bodyvectordata, _ψ, _f, _w, _ψb)
end
function VortexModel(g::PhysicalGrid; bodies::Vector{PotentialFlowBody}=Vector{PotentialFlowBody}(), vortices::Vector{Vortex}=Vector{Vortex}(), U∞::Tuple{Float64,Float64}=(0.0,0.0))
return VortexModel(g, bodies, StructVector(vortices), U∞)
end
"""
$(SIGNATURES)
Replaces the vortices of the vortex model `vm` by a copy of `newvortices`.
"""
function setvortices!(vm::VortexModel{Nb,Ne}, newvortices::Vector{Vortex}) where {Nb,Ne}
vm.vortices = StructArray(deepcopy(newvortices))
end
function setvortices!(vm::VortexModel{Nb,Ne}, newvortices::StructArray{Vortex}) where {Nb,Ne}
vm.vortices = newvortices
end
"""
$(SIGNATURES)
Adds `newvortices` to the existing vortices in the vortex model `vm`.
"""
function pushvortices!(vm::VortexModel{Nb,Ne}, newvortices...) where {Nb,Ne}
push!(vm.vortices, newvortices...)
end
"""
$(SIGNATURES)
Sets the positions of the vortices in the vortex model `vm` to the provided `X`.
"""
function setvortexpositions!(vm::VortexModel{Nb,Ne}, X::VectorData{Nv}) where {Nb,Ne,Nv}
setpositions!(vm.vortices, X.u, X.v)
end
"""
$(SIGNATURES)
Sets the strenghts of the vortices in the vortex model `vm` to the provided `Γ`. Indices can be provided in `idx` to specify the indices of the vortices whose strengths have to be set, in which case the length of `Γ` must be the same as the number of indices.
"""
function setvortexstrengths!(vm::VortexModel{Nb,Ne}, Γ::TΓ, idx=nothing) where {Nb,Ne,TΓ<:AbstractVector}
setstrengths!(vm.vortices, Γ, idx)
end
"""
$(SIGNATURES)
Returns the positions of the vortices in the vortex model `vm`.
"""
function getvortexpositions(vm::VortexModel{Nb,Ne}) where {Nb,Ne}
return getpositions(vm.vortices)
end
"""
$(SIGNATURES)
Sets the uniform flow of the vortex model `vm` to `U∞`.
"""
function setU∞(vm::VortexModel, U∞)
vm.U∞ = U∞
end
function _updatesystemd_vec!(vm::VortexModel{Nb,Ne,UnsteadyRegularizedIBPoisson{Nb,Ne,TU,TF}}, idx::Vector{Int}) where {Nb,Ne,TU,TF}
v = view(vm.vortices,idx)
H = Regularize(getpositions(v), cellsize(vm.g), I0=origin(vm.g), ddftype=CartesianGrids.M4prime, issymmetric=true)
Γ = deepcopy(getstrengths(v))
for i in 1:Ne
Γ .= 0
Γ[i] = 1.0
H(vm.system.d_vec[i],Γ)
end
end
"""
$(SIGNATURES)
Computes and stores in `Ẋ_vortices` the flow velocity, associated with the discrete vector potential field `ψ`, as `VectorData` at the locations of the vortices stored in the vortex model `vm`.
"""
function vortexvelocities!(Ẋ_vortices::VectorData, vm::VortexModel{Nb,Ne,TS,TU}, ψ::TU) where {Nb,Ne,TS,TU}
H = Regularize(getpositions(vm.vortices), cellsize(vm.g), I0=origin(vm.g), ddftype=CartesianGrids.M4prime, issymmetric=true)
# Velocity is the curl of the vector potential
# The discrete curl operator requires dividing by the cellsize to account for the grid spacing
curl!(vm._edgedata, ψ)
vm._edgedata ./= cellsize(vm.g)
# For consistent interpolation, first interpolate the velocity to the nodes and use H to interpolate from the nodes to the vortices
grid_interpolate!(vm._nodedata, vm._edgedata.u);
H(Ẋ_vortices.u, vm._nodedata)
grid_interpolate!(vm._nodedata, vm._edgedata.v);
H(Ẋ_vortices.v, vm._nodedata)
return Ẋ_vortices
end
"""
$(SIGNATURES)
Returns the flow velocity as `VectorData` at the locations of the vortices stored in the vortex model `vm`, accounting for bodies in `vm`. If the `vm` has `Ne` regularized edges and vortices, the strengths of the last `Ne` vortices will be computed and set in `vm` and the circulation of the shedded vortices will be subtracted from the bound circulation of each body.
"""
function vortexvelocities!(vm::VortexModel{Nb,Ne}) where {Nb,Ne}
if Nb == 0
sol = PoissonSolution(vm._ψ)
solve!(sol, vm)
else
sol = ConstrainedIBPoissonSolution(vm._ψ, vm._f, zeros(Float64,Nb), zeros(Float64,Ne))
solve!(sol, vm)
end
Ẋ_vortices = VectorData(length(vm.vortices))
for k in 1:Ne
vm.vortices.Γ[end-Ne+k] = sol.δΓ_vec[k]
end
if Ne > 0
subtractcirculation!(vm.bodies, sol.δΓ_vec)
end
return vortexvelocities!(Ẋ_vortices, vm, sol.ψ)
end
"""
$(SIGNATURES)
Computes the vorticity field `w` associated with the vortices stored in the vortex model `vm` on the physical grid. If the extra boolean keyword `onlybulk` is set to `true`, the function ignores the vorticity from the last `Ne` vortices in `vm`.
"""
function vorticity!(wphysical::TU, vm::VortexModel{Nb,Ne,TS,TU,TE,TF}; onlybulk::Bool=false) where {Nb,Ne,TS,TU,TE,TF}
if onlybulk
vortices = view(vm.vortices,1:length(vm.vortices)-Ne)
else
vortices = vm.vortices
end
H = Regularize(getpositions(vortices), cellsize(vm.g), I0=origin(vm.g), ddftype=CartesianGrids.M4prime, issymmetric=true)
if isempty(vortices)
wphysical .= 0.0
return wphysical
end
Γ = getstrengths(vortices)
H(wphysical,Γ)
wphysical ./= cellsize(vm.g)^2 # Divide by the Δx² to ensure that ∫wdA = ΣΓ
return wphysical
end
"""
$(SIGNATURES)
Computes the vorticity field associated with the vortices stored in the vortex model `vm` on the physical grid.
"""
function vorticity(vm::VortexModel{Nb,Ne,TS,TU,TE,TF}) where {Nb,Ne,TS,TU,TE,TF}
w = TU()
vorticity!(w,vm)
return w
end
"""
$(SIGNATURES)
Solves the saddle point system associated with the vortex model `vm` and stores the solution in `sol`. If the vortex model contains bodies with regularized edges and a number of vortices which is greater than or equal to the number of regularized edges, the returned solution contains the computed strengths of the last N vortices in `vm`, with N the number of regularized edges.
"""
function solve!(sol::PoissonSolution, vm::VortexModel{0,0,TS,TU}) where {Nb,TU,TS<:Laplacian}
vorticity!(vm._w, vm)
rhs = PoissonRHS(vm._w)
_scaletoindexspace!(rhs, cellsize(vm.g))
vm._nodedata .= .-rhs.w
ldiv!(sol.ψ, vm.system, vm._nodedata)
_scaletophysicalspace!(sol, cellsize(vm.g))
_addψ∞!(sol.ψ, vm) # Add the uniform flow to the approximation to the continuous stream function field
return sol
end
function solve!(sol::ConstrainedIBPoissonSolution, vm::VortexModel{Nb,0,ConstrainedIBPoisson{Nb,TU,TF}}) where {Nb,TU,TF}
vorticity!(vm._w, vm)
_streamfunctionbcs!(vm._ψb, vm)
Γb = deepcopy(getΓ.(vm.bodies)) # deepcopy because _scaletoindexspace mutates
rhs = ConstrainedIBPoissonRHS(vm._w, vm._ψb, Γb)
_scaletoindexspace!(rhs, cellsize(vm.g))
ldiv!(sol, vm.system, rhs)
_scaletophysicalspace!(sol, cellsize(vm.g))
_addψ∞!(sol.ψ, vm) # Add the uniform flow to the approximation to the continuous stream function field
return sol
end
function solve!(sol::ConstrainedIBPoissonSolution, vm::VortexModel{Nb,Ne,SteadyRegularizedIBPoisson{Nb,Ne,TU,TF}}) where {Nb,Ne,TU,TF}
vorticity!(vm._w, vm)
_streamfunctionbcs!(vm._ψb, vm)
f̃lim_vec = Vector{f̃Limit}()
for i in 1:Nb
append!(f̃lim_vec, _computef̃limit.(vm.bodies[i].σ, Ref(vm.bodies[i].points), sum(vm.system.f₀_vec[i])))
end
rhs = ConstrainedIBPoissonRHS(vm._w, vm._ψb, f̃lim_vec)
_scaletoindexspace!(rhs, cellsize(vm.g))
ldiv!(sol, vm.system, rhs)
_scaletophysicalspace!(sol, cellsize(vm.g))
_addψ∞!(sol.ψ, vm) # Add the uniform flow to the approximation to the continuous stream function field
return sol
end
function solve!(sol::ConstrainedIBPoissonSolution, vm::VortexModel{Nb,Ne,UnsteadyRegularizedIBPoisson{Nb,Ne,TU,TF}}) where {Nb,Ne,TU,TF}
vorticity!(vm._w, vm, onlybulk=true)
_streamfunctionbcs!(vm._ψb, vm)
_updatesystemd_vec!(vm,collect(length(vm.vortices)-(Ne-1):length(vm.vortices))) # Update the system.d_vec to agree with the latest vortex positions
f̃lim_vec = Vector{f̃Limits}()
for i in 1:Nb
append!(f̃lim_vec, _computef̃range.(vm.bodies[i].σ, Ref(vm.bodies[i].points), sum(vm.system.f₀_vec[i])))
end
Γw = -deepcopy(getΓ.(vm.bodies)) # deepcopy because _scaletoindexspace mutates
rhs = UnsteadyRegularizedIBPoissonRHS(vm._w, vm._ψb, f̃lim_vec, Γw)
_scaletoindexspace!(rhs, cellsize(vm.g))
ldiv!(sol, vm.system, rhs)
_scaletophysicalspace!(sol, cellsize(vm.g))
_addψ∞!(sol.ψ, vm) # Add the uniform flow to the approximation to the continuous stream function field
return sol
end
"""
$(SIGNATURES)
Solves the saddle point system associated with the vortex model `vm` and returns the solution. If the vortex model contains bodies with regularized edges and a number of vortices which is greater than or equal to the number of regularized edges, the returned solution contains the computed strengths of the last N vortices in `vm`, with N the number of regularized edges.
"""
function solve(vm::VortexModel{0,0,TS,TU}) where {Nb,Ne,TS<:Laplacian,TU}
sol = PoissonSolution(TU())
solve!(sol, vm)
return sol
end
function solve(vm::VortexModel{Nb,Ne,TS,TU,TE,TF}) where {Nb,Ne,TS<:AbstractPotentialFlowSystem,TU,TE,TF}
sol = ConstrainedIBPoissonSolution(TU(), TF(), zeros(Float64,Nb), zeros(Float64,Ne))
solve!(sol, vm)
return sol
end
"""
$(SIGNATURES)
Computes the stream function field `ψ` on the physical grid for the potential flow associated with the current state of the vortex model `vm`.
"""
function streamfunction!(ψ::TU, vm::VortexModel{0,0,TS,TU}) where {Nb,Ne,TS<:Laplacian,TU}
sol = PoissonSolution(ψ)
solve!(sol, vm)
return sol.ψ
end
function streamfunction!(ψ::TU, vm::VortexModel{Nb,Ne,TS,TU,TE,TF}) where {Nb,Ne,TS<:AbstractPotentialFlowSystem,TU,TE,TF}
sol = ConstrainedIBPoissonSolution(ψ, vm._f, zeros(Float64,Nb), zeros(Float64,Ne))
solve!(sol, vm)
return sol.ψ
end
"""
$(SIGNATURES)
Computes and returns the stream function field on the physical grid for the potential flow associated with the current state of the vortex model `vm`.
"""
function streamfunction(vm::VortexModel{Nb,Ne,TS,TU,TE,TF}) where {Nb,Ne,TS,TU,TE,TF}
ψ = TU()
streamfunction!(ψ, vm)
return ψ
end
"""
$(SIGNATURES)
Computes the impulse associated with the vorticity `wphysical`, the bound vortex sheet strength `fphysical`, and the velocities of the discrete points of the bodies in `vm`.
"""
function impulse(vm::VortexModel{Nb,Ne}, wphysical::Nodes{Dual}, fphysical::ScalarData) where {Nb,Ne}
xg, yg = coordinates(wphysical, vm.g)
Δx = cellsize(vm.g)
_bodypointsvelocity!(vm._bodyvectordata, vm.bodies)
# Formula 61 (see formula 6.16 in book)
p = [Δx^2*sum(wphysical.*yg'),Δx^2*sum(-wphysical.*xg)]
for i in 1:Nb
r = getrange(vm.bodies,i)
p += _impulsesurfaceintegral(vm.bodies[i].points, fphysical[r], vm._bodyvectordata.u[r], vm._bodyvectordata.v[r])
end
return p[1], p[2]
end
"""
$(SIGNATURES)
Computes the impulse associated with the body motions in the vortex model `vm` and the vortex sheet strength in `sol`. Note that newly inserted vortices should have their strengths set prior to calling this function to be included in the impulse calculation.
"""
function impulse(sol::TS, vm::VortexModel) where {TS<:AbstractIBPoissonSolution}
# Compute vorticity field again, because now it can contain the vorticity of newly shedded vortices
vorticity!(vm._nodedata, vm)
impulse(vm, vm._nodedata, sol.f)
end
"""
$(SIGNATURES)
Computes the impulse associated with the current state vortices and bodies in the vortex model `vm`. Note that newly inserted vortices should have their strengths set prior to calling this function to be included in the impulse calculation.
"""
function impulse(vm::VortexModel)
sol = solve(vm)
impulse(sol, vm)
end
"""
$(SIGNATURES)
Computes the translational coefficients of the added mass matrix of the bodies in the vortex model `vm`.
"""
function addedmass(vm::VortexModel{Nb,Ne}) where {Nb,Ne}
# Deepcopy bodies because we will change the velocities one by one
origbodies = deepcopy(vm.bodies)
# For now only translational
M = zeros(Nb*2,Nb*2)
for movingbodyindex in 1:Nb
for dir in 1:2
for i in 1:Nb
setU(vm.bodies[i], (0.0,0.0))
end
if dir == 1
setU(vm.bodies[movingbodyindex], (1.0,0.0))
else
setU(vm.bodies[movingbodyindex], (0.0,1.0))
end
_bodypointsvelocity!(vm._bodyvectordata, vm.bodies)
sol = solve(vm)
for i in 1:Nb
r = getrange(vm.bodies,i)
M[(i-1)*2+1:(i-1)*2+2,(movingbodyindex-1)*2+dir] .= _impulsesurfaceintegral(vm.bodies[i].points, sol.f[r], vm._bodyvectordata.u[r], vm._bodyvectordata.v[r])
end
end
end
vm.bodies = origbodies
return M
end
function _impulsesurfaceintegral(body::Body{N,RigidBodyTools.ClosedBody}, f, u, v) where {N}
nx,ny = normalmid(body)
Δs = dlengthmid(body)
return _crossproductsurfaceintegral(body,(f./Δs + nx.*v - ny.*u).*Δs)
end
function _impulsesurfaceintegral(body::Body{N,RigidBodyTools.OpenBody}, f, u, v) where {N}
return _crossproductsurfaceintegral(body,f)
end
function _crossproductsurfaceintegral(body::Body, z)
rx,ry = collect(body)
return [ry'*z, -rx'*z]
end
function _bodypointsvelocity!(v::VectorData, bodies)
bodypointsvelocity!(v.u, bodies, 1)
bodypointsvelocity!(v.v, bodies, 2)
return v
end
function _addψ∞!(ψ, vm::VortexModel)
xg,yg = coordinates(ψ,vm.g)
ψ .+= vm.U∞[1].*yg' .- vm.U∞[2].*xg
return ψ
end
function _streamfunctionbcs!(ψb::ScalarData, vm::VortexModel)
_bodypointsvelocity!(vm._bodyvectordata, vm.bodies) # Convert U into VectorData corresponding to the body points
# The discrete streamfunction field is constrained to a prescribed streamfunction on the body that describes the body motion. The body presence in the uniform flow is taken into account by subtracting its value from the body motion (i.e. a body motion in the -U∞ direction) and adding the uniform flow at the end of the solve routine.
ψb .= -vm.U∞[1]*(collect(vm.bodies)[2]) .+ vm.U∞[2]*(collect(vm.bodies)[1]);
ψb .+= vm._bodyvectordata.u .* collect(vm.bodies)[2] .- vm._bodyvectordata.v .* collect(vm.bodies)[1]
return ψb
end
function _streamfunctionbcs!(ψb::ScalarData, vm::VortexModel{0})
return
end
function show(io::IO, model::VortexModel{Nb,Ne,isshedding}) where {Nb,Ne,isshedding}
NX = model.g.N[1]
NY = model.g.N[2]
N = length(model._f)
Nv = length(model.vortices)
println(io, "Vortex model on a grid of size $NX x $NY and $N immersed points with $((Nv == 1) ? "1 vortex" : "$Nv vortices"), $((Nb == 1) ? "1 body" : "$Nb bodies"), and $((Ne == 1) ? "1 regularized edge" : "$Ne regularized edges")")
end
@recipe function f(h::VortexModel)
xlims := h.g.xlim[1]
ylims := h.g.xlim[2]
legend := :false
grid := :false
aspect_ratio := 1
@series begin
seriestype := :scatter
markersize := 3
markerstrokewidth := 0
marker_z := h.vortices.Γ
h.vortices.x, h.vortices.y
end
for b in h.bodies
@series begin
b.points
end
end
end
|
using Distributed
@everywhere using WhiskerTracking, Gtk.ShortNames, Distributed, Knet
println("Whisker Tracking Loaded")
Knet.cuallocator()=false
myhandles=make_gui();
println("GUI Made")
WhiskerTracking.add_callbacks(myhandles.b,myhandles)
if !isinteractive()
c=Condition()
signal_connect(myhandles.b["win"],:destroy) do c_widget
notify(c)
end
wait(c)
end
|
using Mux
using Test
using Lazy
using HTTP
@test Mux.notfound()(d())[:status] == 404
# Test basic server
@app test = (
Mux.defaults,
page("/",respond("<h1>Hello World!</h1>")),
page("/about", respond("<h1>Boo!</h1>")),
page("/user/:user", req -> "<h1>Hello, $(req[:params][:user])!</h1>"),
Mux.notfound())
serve(test)
@test String(HTTP.get("http://localhost:8000").body) ==
"<h1>Hello World!</h1>"
@test String(HTTP.get("http://localhost:8000/about").body) ==
"<h1>Boo!</h1>"
@test String(HTTP.get("http://localhost:8000/user/julia").body) ==
"<h1>Hello, julia!</h1>"
# Issue #68
@test Mux.fileheaders("foo.css")["Content-Type"] == "text/css"
@test Mux.fileheaders("foo.html")["Content-Type"] == "text/html"
@test Mux.fileheaders("foo.js")["Content-Type"] == "application/javascript"
|
module BitCircuits
export Operation, Constant, Variable, evaluate, equal
typealias BitString Uint64
typealias VarIdx Uint64
typealias Context Uint64
abstract Node
# ----------
# Operations
# ----------
immutable Operation <: Node
sym::String
left::Node
right::Node
cache::BitString
end
function Operation(func::Function, left::Node, right::Node)
sym = string(func)
cache = func(left.cache, right.cache)
return Operation(sym, left, right, cache)
end
# ---------
# Constants
# ---------
immutable Constant <: Node
val::Bool
sym::String
cache::BitString
function Constant(val::Bool)
if val
cache = 2 ^ 64 - 1
sym = "TRUE"
else
cache = 0
sym = "FALSE"
end
return new(val, sym, cache |> uint64)
end
end
# ---------
# Variables
# ---------
immutable Variable <: Node
idx::VarIdx
sym::String
cache::BitString
function Variable(idx::Uint64)
if idx > 5
error("idx must be in [0, 5]")
end
cache = uint64(0)
for ctxval = uint64(0):uint64(63)
varmask = 2 ^ idx |> uint64
if (ctxval & varmask) > 0
cache = cache | (uint64(2) ^ ctxval)
end
end
return new(idx, "X$(idx)", cache)
end
end
Variable(idx::Int64) = Variable(uint64(idx))
# ---------------
# Tree evaluation
# ---------------
function evaluate(root::Node, ctxval::Context)
mask = 2 ^ ctxval |> uint64
return root.cache & mask > 0
end
evaluate(root::Node, ctxval::Uint8) = evaluate(root, ctxval |> uint64)
# ---------------
# Tree comparison
# ---------------
function equal(left::Node, right::Node)
return left.cache == right.cache
end
end
|
@test LogNum(5.5, 0) == LogNum()
@test LogNum(-Inf, 0) == LogNum()
@test LogNum(-Inf, 43) == LogNum()
@test iszero(LogNum())
@test iszero(LogNum(0))
@test !iszero(LogNum(1))
@test !iszero(LogNum(-1))
@test isfinite(LogNum(0))
@test isfinite(LogNum(1))
@test isfinite(LogNum(-1))
@test !isfinite(LogNum(Inf))
@test !isfinite(LogNum(-Inf))
@test isinf(LogNum(Inf))
@test !isinf(LogNum(0))
@test isnan(LogNum(NaN))
@test isnan(LogNum(NaN, 1))
@test isnan(LogNum(NaN, -1))
@test !isnan(LogNum(1.))
@test isnan(LogNum(NaN) + LogNum(1))
@test isnan(LogNum(NaN) - LogNum(1))
@test isnan(LogNum(NaN) * LogNum(1))
@test isnan(LogNum(NaN) / LogNum(1))
@test isnan(LogNum(NaN) ^ LogNum(1))
@test convert(Float64, LogNum(1.)) == 1.
for x = -10.:10.
@test LogNum(x) == LogNum(x) == x
@test LogNum(x) ≥ LogNum(x) ≥ x
@test LogNum(x) ≤ LogNum(x) ≤ x
@test LogNum(x) < LogNum(x + 1)
@test LogNum(x + 1) > LogNum(x)
end
@test sign(LogNum(1)) == 1
@test sign(LogNum(-42.1)) == -1
@test sign(LogNum(0.)) == 0
@test LogNum(2) > LogNum(1)
@test LogNum(-1) < LogNum(1)
@test LogNum(3.4) ≤ LogNum(3.4)
@test LogNum(-10) ≈ LogNum(-20) + LogNum(10)
@test LogNum(-200) ≈ LogNum(20) * LogNum(-10)
@test LogNum(-30) ≈ LogNum(-10) - LogNum(20)
@test LogNum(-2) ≈ LogNum(20) / LogNum(-10)
@test LogNum(5) - 1 ≈ LogNum(4)
@test 1 - LogNum(5) ≈ LogNum(-4)
@test LogNum(5) + 1 ≈ LogNum(6)
@test 1 + LogNum(5) ≈ LogNum(6)
@test 2 * LogNum(5) ≈ LogNum(10)
@test LogNum(5) * 2 ≈ LogNum(10)
@test LogNum(4) / 2 ≈ LogNum(2)
@test 4 / LogNum(2) ≈ LogNum(2)
@test LogNum(2) > 1
@test 2 > LogNum(1)
@test convert(Float64, LogNum(5)) ≈ 5
@test LogNum(3) * LogNum(-5) ≈ -15
@test exp(LogNum(3)) ≈ exp(3)
@test exp(LogNum(-3)) ≈ exp(-3)
for x = 0.:10.
@test log(LogNum(x)) ≈ log(x)
end
for x = -10.:10.
@test convert(Float64, LogNum(x)) ≈ x
@test abs(LogNum(x)) ≈ abs(x)
@test exp(LogNum(x)) ≈ exp(x)
@test sign(LogNum(x)) == sign(x)
end
for x = 0.:5., y = -5.:5.
if x ≠ 0 || y ≠ 0
@test isapprox(LogNum(x) ^ LogNum(y), x ^ y; atol=1e-12)
@test isapprox(LogNum(x) ^ y, x ^ y; atol=1e-12)
@test isapprox(x ^ LogNum(y), x ^ y; atol=1e-12)
end
end
for x = -10.:10., y = -10.:10.
@test LogNum(x) + LogNum(y) ≈ x + y
@test LogNum(x) - LogNum(y) ≈ x - y
@test LogNum(x) * LogNum(y) ≈ x * y
if x ≠ 0 || y ≠ 0
@test LogNum(x) / LogNum(y) ≈ x / y
end
end
@test LogNum(5.)^LogNum(2.) ≈ 5.^2.
@test LogNum(5.)^LogNum(-2.) ≈ 5.^-2.
@test LogNum(5.)^LogNum(0) ≈ 1
@test LogNum(0)^LogNum(1) ≈ 0
@test LogNum(0) ^ LogNum(0) == 1
@test LogNum(4) ^ 2 ≈ 4^2 |
export Device, DeviceParams, deviceID, params, dependencies, dependency, hasDependency, init, checkDependencies
abstract type VirtualDevice <: Device end
"""
Abstract type for all device parameters
Every device must implement a parameter struct allowing for
automatic instantiation from the configuration file.
"""
abstract type DeviceParams end
"Retrieve the ID of a device."
deviceID(device::Device) = :deviceID in fieldnames(typeof(device)) ? device.deviceID : error("The device struct for `$(typeof(device))` must have a field `deviceID`.")
"Retrieve the parameters of a device."
params(device::Device) = :params in fieldnames(typeof(device)) ? device.params : error("The device struct for `$(typeof(device))` must have a field `params`.")
"Check whether the device is optional."
isOptional(device::Device) = :optional in fieldnames(typeof(device)) ? device.optional : error("The device struct for `$(typeof(device))` must have a field `optional`.")
"Check whether the device is present."
isPresent(device::Device) = :present in fieldnames(typeof(device)) ? device.present : error("The device struct for `$(typeof(device))` must have a field `present`.")
"Retrieve the dependencies of a device."
dependencies(device::Device) = :dependencies in fieldnames(typeof(device)) ? device.dependencies : error("The device struct for `$(typeof(device))` must have a field `dependencies`.")
"Retrieve all dependencies of a certain type."
dependencies(device::Device, type::DataType) = [dependency for dependency in values(dependencies(device)) if dependency isa type]
"Retrieve a single dependency of a certain type and error if there are more dependencies."
function dependency(device::Device, type::DataType)
dependencies_ = dependencies(device, type)
if length(dependencies_) > 1
throw(ScannerConfigurationError("Retrieving a dependency of type `$type` for the device with the ID `$(deviceID(device))` "*
"returned more than one item and can therefore not be retrieved unambiguously."))
else
return dependencies_[1]
end
end
"Check whether the device has a dependency of the given `type`."
hasDependency(device::Device, type::DataType) = length(dependencies(device, type)) > 0
"Retrieve all expected dependencies of a device."
expectedDependencies(device::Device)::Vector{DataType} = vcat(neededDependencies(device), optionalDependencies(device))
"Check if a device is an expected dependency of another device."
function isExpectedDependency(device::Device, dependency::Device)
for expectedDependency in expectedDependencies(device)
if typeof(dependency) <: expectedDependency
return true
end
end
return false
end
@mustimplement init(device::Device)
@mustimplement neededDependencies(device::Device)::Vector{DataType}
@mustimplement optionalDependencies(device::Device)::Vector{DataType}
function checkDependencies(device::Device)
# Check if all needed dependencies are assigned
for neededDependency in neededDependencies(device)
if !hasDependency(device, neededDependency)
throw(ScannerConfigurationError("The device with ID `$(deviceID(device))` "*
"needs a dependency of type $(neededDependency) "*
"but it is not assigned."))
return false
end
end
# Check if superfluous dependencies are assigned
for (dependencyID, dependency) in dependencies(device)
if !isExpectedDependency(device, dependency)
@warn "The device with ID `$(deviceID(device))` has a superfluous dependency "*
"to a device with ID `$dependencyID`."
end
end
return true
end |
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: managedblockchain
using AWS.Compat
using AWS.UUIDs
"""
create_member(client_request_token, invitation_id, member_configuration, network_id)
create_member(client_request_token, invitation_id, member_configuration, network_id, params::Dict{String,<:Any})
Creates a member within a Managed Blockchain network. Applies only to Hyperledger Fabric.
# Arguments
- `client_request_token`: A unique, case-sensitive identifier that you provide to ensure
the idempotency of the operation. An idempotent operation completes no more than one time.
This identifier is required only if you make a service request directly using an HTTP
client. It is generated automatically if you use an AWS SDK or the AWS CLI.
- `invitation_id`: The unique identifier of the invitation that is sent to the member to
join the network.
- `member_configuration`: Member configuration parameters.
- `network_id`: The unique identifier of the network in which the member is created.
"""
function create_member(
ClientRequestToken,
InvitationId,
MemberConfiguration,
networkId;
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/members",
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"InvitationId" => InvitationId,
"MemberConfiguration" => MemberConfiguration,
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function create_member(
ClientRequestToken,
InvitationId,
MemberConfiguration,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/members",
Dict{String,Any}(
mergewith(
_merge,
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"InvitationId" => InvitationId,
"MemberConfiguration" => MemberConfiguration,
),
params,
),
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
create_network(client_request_token, framework, framework_version, member_configuration, name, voting_policy)
create_network(client_request_token, framework, framework_version, member_configuration, name, voting_policy, params::Dict{String,<:Any})
Creates a new blockchain network using Amazon Managed Blockchain. Applies only to
Hyperledger Fabric.
# Arguments
- `client_request_token`: A unique, case-sensitive identifier that you provide to ensure
the idempotency of the operation. An idempotent operation completes no more than one time.
This identifier is required only if you make a service request directly using an HTTP
client. It is generated automatically if you use an AWS SDK or the AWS CLI.
- `framework`: The blockchain framework that the network uses.
- `framework_version`: The version of the blockchain framework that the network uses.
- `member_configuration`: Configuration properties for the first member within the network.
- `name`: The name of the network.
- `voting_policy`: The voting rules used by the network to determine if a proposal is
approved.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: An optional description for the network.
- `"FrameworkConfiguration"`: Configuration properties of the blockchain framework
relevant to the network configuration.
- `"Tags"`: Tags to assign to the network. Each tag consists of a key and optional value.
When specifying tags during creation, you can specify multiple key-value pairs in a single
request, with an overall maximum of 50 tags added to each resource. For more information
about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer
Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer
Guide.
"""
function create_network(
ClientRequestToken,
Framework,
FrameworkVersion,
MemberConfiguration,
Name,
VotingPolicy;
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks",
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"Framework" => Framework,
"FrameworkVersion" => FrameworkVersion,
"MemberConfiguration" => MemberConfiguration,
"Name" => Name,
"VotingPolicy" => VotingPolicy,
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function create_network(
ClientRequestToken,
Framework,
FrameworkVersion,
MemberConfiguration,
Name,
VotingPolicy,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks",
Dict{String,Any}(
mergewith(
_merge,
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"Framework" => Framework,
"FrameworkVersion" => FrameworkVersion,
"MemberConfiguration" => MemberConfiguration,
"Name" => Name,
"VotingPolicy" => VotingPolicy,
),
params,
),
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
create_node(client_request_token, node_configuration, network_id)
create_node(client_request_token, node_configuration, network_id, params::Dict{String,<:Any})
Creates a node on the specified blockchain network. Applies to Hyperledger Fabric and
Ethereum.
# Arguments
- `client_request_token`: A unique, case-sensitive identifier that you provide to ensure
the idempotency of the operation. An idempotent operation completes no more than one time.
This identifier is required only if you make a service request directly using an HTTP
client. It is generated automatically if you use an AWS SDK or the AWS CLI.
- `node_configuration`: The properties of a node configuration.
- `network_id`: The unique identifier of the network for the node. Ethereum public networks
have the following NetworkIds: n-ethereum-mainnet n-ethereum-rinkeby
n-ethereum-ropsten
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MemberId"`: The unique identifier of the member that owns this node. Applies only to
Hyperledger Fabric.
- `"Tags"`: Tags to assign to the node. Each tag consists of a key and optional value. When
specifying tags during creation, you can specify multiple key-value pairs in a single
request, with an overall maximum of 50 tags added to each resource. For more information
about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum Developer
Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer
Guide.
"""
function create_node(
ClientRequestToken,
NodeConfiguration,
networkId;
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/nodes",
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"NodeConfiguration" => NodeConfiguration,
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function create_node(
ClientRequestToken,
NodeConfiguration,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/nodes",
Dict{String,Any}(
mergewith(
_merge,
Dict{String,Any}(
"ClientRequestToken" => ClientRequestToken,
"NodeConfiguration" => NodeConfiguration,
),
params,
),
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
create_proposal(actions, client_request_token, member_id, network_id)
create_proposal(actions, client_request_token, member_id, network_id, params::Dict{String,<:Any})
Creates a proposal for a change to the network that other members of the network can vote
on, for example, a proposal to add a new member to the network. Any member can create a
proposal. Applies only to Hyperledger Fabric.
# Arguments
- `actions`: The type of actions proposed, such as inviting a member or removing a member.
The types of Actions in a proposal are mutually exclusive. For example, a proposal with
Invitations actions cannot also contain Removals actions.
- `client_request_token`: A unique, case-sensitive identifier that you provide to ensure
the idempotency of the operation. An idempotent operation completes no more than one time.
This identifier is required only if you make a service request directly using an HTTP
client. It is generated automatically if you use an AWS SDK or the AWS CLI.
- `member_id`: The unique identifier of the member that is creating the proposal. This
identifier is especially useful for identifying the member making the proposal when
multiple members exist in a single AWS account.
- `network_id`: The unique identifier of the network for which the proposal is made.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description for the proposal that is visible to voting members, for
example, \"Proposal to add Example Corp. as member.\"
- `"Tags"`: Tags to assign to the proposal. Each tag consists of a key and optional value.
When specifying tags during creation, you can specify multiple key-value pairs in a single
request, with an overall maximum of 50 tags added to each resource. If the proposal is for
a network invitation, the invitation inherits the tags added to the proposal. For more
information about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum
Developer Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric
Developer Guide.
"""
function create_proposal(
Actions,
ClientRequestToken,
MemberId,
networkId;
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/proposals",
Dict{String,Any}(
"Actions" => Actions,
"ClientRequestToken" => ClientRequestToken,
"MemberId" => MemberId,
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function create_proposal(
Actions,
ClientRequestToken,
MemberId,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/proposals",
Dict{String,Any}(
mergewith(
_merge,
Dict{String,Any}(
"Actions" => Actions,
"ClientRequestToken" => ClientRequestToken,
"MemberId" => MemberId,
),
params,
),
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
delete_member(member_id, network_id)
delete_member(member_id, network_id, params::Dict{String,<:Any})
Deletes a member. Deleting a member removes the member and all associated resources from
the network. DeleteMember can only be called for a specified MemberId if the principal
performing the action is associated with the AWS account that owns the member. In all other
cases, the DeleteMember action is carried out as the result of an approved proposal to
remove a member. If MemberId is the last member in a network specified by the last AWS
account, the network is deleted also. Applies only to Hyperledger Fabric.
# Arguments
- `member_id`: The unique identifier of the member to remove.
- `network_id`: The unique identifier of the network from which the member is removed.
"""
function delete_member(
memberId, networkId; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"DELETE",
"/networks/$(networkId)/members/$(memberId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function delete_member(
memberId,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"DELETE",
"/networks/$(networkId)/members/$(memberId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
delete_node(network_id, node_id)
delete_node(network_id, node_id, params::Dict{String,<:Any})
Deletes a node that your AWS account owns. All data on the node is lost and cannot be
recovered. Applies to Hyperledger Fabric and Ethereum.
# Arguments
- `network_id`: The unique identifier of the network that the node is on. Ethereum public
networks have the following NetworkIds: n-ethereum-mainnet n-ethereum-rinkeby
n-ethereum-ropsten
- `node_id`: The unique identifier of the node.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"memberId"`: The unique identifier of the member that owns this node. Applies only to
Hyperledger Fabric and is required for Hyperledger Fabric.
"""
function delete_node(networkId, nodeId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"DELETE",
"/networks/$(networkId)/nodes/$(nodeId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function delete_node(
networkId,
nodeId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"DELETE",
"/networks/$(networkId)/nodes/$(nodeId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
get_member(member_id, network_id)
get_member(member_id, network_id, params::Dict{String,<:Any})
Returns detailed information about a member. Applies only to Hyperledger Fabric.
# Arguments
- `member_id`: The unique identifier of the member.
- `network_id`: The unique identifier of the network to which the member belongs.
"""
function get_member(memberId, networkId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)/members/$(memberId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function get_member(
memberId,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/members/$(memberId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
get_network(network_id)
get_network(network_id, params::Dict{String,<:Any})
Returns detailed information about a network. Applies to Hyperledger Fabric and Ethereum.
# Arguments
- `network_id`: The unique identifier of the network to get information about.
"""
function get_network(networkId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function get_network(
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
get_node(network_id, node_id)
get_node(network_id, node_id, params::Dict{String,<:Any})
Returns detailed information about a node. Applies to Hyperledger Fabric and Ethereum.
# Arguments
- `network_id`: The unique identifier of the network that the node is on.
- `node_id`: The unique identifier of the node.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"memberId"`: The unique identifier of the member that owns the node. Applies only to
Hyperledger Fabric and is required for Hyperledger Fabric.
"""
function get_node(networkId, nodeId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)/nodes/$(nodeId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function get_node(
networkId,
nodeId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/nodes/$(nodeId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
get_proposal(network_id, proposal_id)
get_proposal(network_id, proposal_id, params::Dict{String,<:Any})
Returns detailed information about a proposal. Applies only to Hyperledger Fabric.
# Arguments
- `network_id`: The unique identifier of the network for which the proposal is made.
- `proposal_id`: The unique identifier of the proposal.
"""
function get_proposal(
networkId, proposalId; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals/$(proposalId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function get_proposal(
networkId,
proposalId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals/$(proposalId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_invitations()
list_invitations(params::Dict{String,<:Any})
Returns a list of all invitations for the current AWS account. Applies only to Hyperledger
Fabric.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of invitations to return.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
"""
function list_invitations(; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET", "/invitations"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
)
end
function list_invitations(
params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"GET",
"/invitations",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_members(network_id)
list_members(network_id, params::Dict{String,<:Any})
Returns a list of the members in a network and properties of their configurations. Applies
only to Hyperledger Fabric.
# Arguments
- `network_id`: The unique identifier of the network for which to list members.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"isOwned"`: An optional Boolean value. If provided, the request is limited either to
members that the current AWS account owns (true) or that other AWS accounts own (false). If
omitted, all members are listed.
- `"maxResults"`: The maximum number of members to return in the request.
- `"name"`: The optional name of the member to list.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
- `"status"`: An optional status specifier. If provided, only members currently in this
status are listed.
"""
function list_members(networkId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)/members";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function list_members(
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/members",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_networks()
list_networks(params::Dict{String,<:Any})
Returns information about the networks in which the current AWS account participates.
Applies to Hyperledger Fabric and Ethereum.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"framework"`: An optional framework specifier. If provided, only networks of this
framework type are listed.
- `"maxResults"`: The maximum number of networks to list.
- `"name"`: The name of the network.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
- `"status"`: An optional status specifier. If provided, only networks currently in this
status are listed. Applies only to Hyperledger Fabric.
"""
function list_networks(; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET", "/networks"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
)
end
function list_networks(
params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"GET", "/networks", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
)
end
"""
list_nodes(network_id)
list_nodes(network_id, params::Dict{String,<:Any})
Returns information about the nodes within a network. Applies to Hyperledger Fabric and
Ethereum.
# Arguments
- `network_id`: The unique identifier of the network for which to list nodes.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of nodes to list.
- `"memberId"`: The unique identifier of the member who owns the nodes to list. Applies
only to Hyperledger Fabric and is required for Hyperledger Fabric.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
- `"status"`: An optional status specifier. If provided, only nodes currently in this
status are listed.
"""
function list_nodes(networkId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)/nodes";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function list_nodes(
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/nodes",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_proposal_votes(network_id, proposal_id)
list_proposal_votes(network_id, proposal_id, params::Dict{String,<:Any})
Returns the list of votes for a specified proposal, including the value of each vote and
the unique identifier of the member that cast the vote. Applies only to Hyperledger Fabric.
# Arguments
- `network_id`: The unique identifier of the network.
- `proposal_id`: The unique identifier of the proposal.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of votes to return.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
"""
function list_proposal_votes(
networkId, proposalId; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals/$(proposalId)/votes";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function list_proposal_votes(
networkId,
proposalId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals/$(proposalId)/votes",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_proposals(network_id)
list_proposals(network_id, params::Dict{String,<:Any})
Returns a list of proposals for the network. Applies only to Hyperledger Fabric.
# Arguments
- `network_id`: The unique identifier of the network.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"maxResults"`: The maximum number of proposals to return.
- `"nextToken"`: The pagination token that indicates the next set of results to retrieve.
"""
function list_proposals(networkId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function list_proposals(
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/networks/$(networkId)/proposals",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
list_tags_for_resource(resource_arn)
list_tags_for_resource(resource_arn, params::Dict{String,<:Any})
Returns a list of tags for the specified resource. Each tag consists of a key and optional
value. For more information about tags, see Tagging Resources in the Amazon Managed
Blockchain Ethereum Developer Guide, or Tagging Resources in the Amazon Managed Blockchain
Hyperledger Fabric Developer Guide.
# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource. For more information
about ARNs and their format, see Amazon Resource Names (ARNs) in the AWS General Reference.
"""
function list_tags_for_resource(
resourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"GET",
"/tags/$(resourceArn)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function list_tags_for_resource(
resourceArn,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"GET",
"/tags/$(resourceArn)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
reject_invitation(invitation_id)
reject_invitation(invitation_id, params::Dict{String,<:Any})
Rejects an invitation to join a network. This action can be called by a principal in an AWS
account that has received an invitation to create a member and join a network. Applies only
to Hyperledger Fabric.
# Arguments
- `invitation_id`: The unique identifier of the invitation to reject.
"""
function reject_invitation(invitationId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"DELETE",
"/invitations/$(invitationId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function reject_invitation(
invitationId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"DELETE",
"/invitations/$(invitationId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
tag_resource(tags, resource_arn)
tag_resource(tags, resource_arn, params::Dict{String,<:Any})
Adds or overwrites the specified tags for the specified Amazon Managed Blockchain resource.
Each tag consists of a key and optional value. When you specify a tag key that already
exists, the tag value is overwritten with the new value. Use UntagResource to remove tag
keys. A resource can have up to 50 tags. If you try to create more than 50 tags for a
resource, your request fails and returns an error. For more information about tags, see
Tagging Resources in the Amazon Managed Blockchain Ethereum Developer Guide, or Tagging
Resources in the Amazon Managed Blockchain Hyperledger Fabric Developer Guide.
# Arguments
- `tags`: The tags to assign to the specified resource. Tag values can be empty, for
example, \"MyTagKey\" : \"\". You can specify multiple key-value pairs in a single request,
with an overall maximum of 50 tags added to each resource.
- `resource_arn`: The Amazon Resource Name (ARN) of the resource. For more information
about ARNs and their format, see Amazon Resource Names (ARNs) in the AWS General Reference.
"""
function tag_resource(Tags, resourceArn; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"POST",
"/tags/$(resourceArn)",
Dict{String,Any}("Tags" => Tags);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function tag_resource(
Tags,
resourceArn,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/tags/$(resourceArn)",
Dict{String,Any}(mergewith(_merge, Dict{String,Any}("Tags" => Tags), params));
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
untag_resource(resource_arn, tag_keys)
untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})
Removes the specified tags from the Amazon Managed Blockchain resource. For more
information about tags, see Tagging Resources in the Amazon Managed Blockchain Ethereum
Developer Guide, or Tagging Resources in the Amazon Managed Blockchain Hyperledger Fabric
Developer Guide.
# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource. For more information
about ARNs and their format, see Amazon Resource Names (ARNs) in the AWS General Reference.
- `tag_keys`: The tag keys.
"""
function untag_resource(
resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"DELETE",
"/tags/$(resourceArn)",
Dict{String,Any}("tagKeys" => tagKeys);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function untag_resource(
resourceArn,
tagKeys,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"DELETE",
"/tags/$(resourceArn)",
Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params));
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
update_member(member_id, network_id)
update_member(member_id, network_id, params::Dict{String,<:Any})
Updates a member configuration with new parameters. Applies only to Hyperledger Fabric.
# Arguments
- `member_id`: The unique identifier of the member.
- `network_id`: The unique identifier of the Managed Blockchain network to which the member
belongs.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LogPublishingConfiguration"`: Configuration properties for publishing to Amazon
CloudWatch Logs.
"""
function update_member(
memberId, networkId; aws_config::AbstractAWSConfig=global_aws_config()
)
return managedblockchain(
"PATCH",
"/networks/$(networkId)/members/$(memberId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function update_member(
memberId,
networkId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"PATCH",
"/networks/$(networkId)/members/$(memberId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
update_node(network_id, node_id)
update_node(network_id, node_id, params::Dict{String,<:Any})
Updates a node configuration with new parameters. Applies only to Hyperledger Fabric.
# Arguments
- `network_id`: The unique identifier of the network that the node is on.
- `node_id`: The unique identifier of the node.
# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"LogPublishingConfiguration"`: Configuration properties for publishing to Amazon
CloudWatch Logs.
- `"MemberId"`: The unique identifier of the member that owns the node. Applies only to
Hyperledger Fabric.
"""
function update_node(networkId, nodeId; aws_config::AbstractAWSConfig=global_aws_config())
return managedblockchain(
"PATCH",
"/networks/$(networkId)/nodes/$(nodeId)";
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function update_node(
networkId,
nodeId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"PATCH",
"/networks/$(networkId)/nodes/$(nodeId)",
params;
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
"""
vote_on_proposal(vote, voter_member_id, network_id, proposal_id)
vote_on_proposal(vote, voter_member_id, network_id, proposal_id, params::Dict{String,<:Any})
Casts a vote for a specified ProposalId on behalf of a member. The member to vote as,
specified by VoterMemberId, must be in the same AWS account as the principal that calls the
action. Applies only to Hyperledger Fabric.
# Arguments
- `vote`: The value of the vote.
- `voter_member_id`: The unique identifier of the member casting the vote.
- `network_id`: The unique identifier of the network.
- `proposal_id`: The unique identifier of the proposal.
"""
function vote_on_proposal(
Vote,
VoterMemberId,
networkId,
proposalId;
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/proposals/$(proposalId)/votes",
Dict{String,Any}("Vote" => Vote, "VoterMemberId" => VoterMemberId);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
function vote_on_proposal(
Vote,
VoterMemberId,
networkId,
proposalId,
params::AbstractDict{String};
aws_config::AbstractAWSConfig=global_aws_config(),
)
return managedblockchain(
"POST",
"/networks/$(networkId)/proposals/$(proposalId)/votes",
Dict{String,Any}(
mergewith(
_merge,
Dict{String,Any}("Vote" => Vote, "VoterMemberId" => VoterMemberId),
params,
),
);
aws_config=aws_config,
feature_set=SERVICE_FEATURE_SET,
)
end
|
"""
Naive implementation of Dynamic Mode Decomposition with control (DMDc)
Defaults to predicting the second input as a function of the first.
Can also be passed a 'mode', "discrete" or "continuous" to process the
data 'X' to produce the variable to be solved for
"""
function dmdc(X, X_grad=nothing, U=nothing; mode="discrete")
if X_grad == nothing
if mode=="discrete"
X_grad = X[:,2:end]
X = X[:,1:end-1]
elseif mode=="continuous"
X_grad = numerical_derivative(X)
end
end
U == nothing ? (Ω = X) : (Ω = vcat(X,U))
# Solve for dynamics and separate out
AB = X_grad / Ω
if U == nothing
A = AB
B = nothing
else
n, m = size(X)
A = AB[:, 1:n]
B = AB[:, n+1:end]
end
return (A=A, B=B)
end
export dmdc
|
using PyPlot
figure(figsize=(8,5))
fill_between(X.tt, first.(Xmeanm + 1.96*Xstdm), first.(Xmeanm - 1.96*Xstdm), edgecolor=:darkblue, facecolor=:lightblue, hatch="X", label="95% cred. band")
plot(X.tt, first.(X.yy), label=L"X_1", color=:darkviolet)
plot(X.tt, first.(Xmeanm), label=L"x_1", color=:darkgreen)
if partial
plot(V.tt, V.yy, "*", label=L"V", color=:darkviolet)
else
plot(V.tt, first.(V.yy), ",", label=L"V_1", color=:darkviolet)
end
PyPlot.legend()
figure(figsize=(8,5))
for i in 1:length(Paths)
plot(X.tt[1:end-1], first.(Paths[i]), color=:lightblue)
end
plot(X.tt, first.(X.yy), label=L"X_1", color=:darkviolet)
plot(X.tt, first.(Xmeanm), label=L"x_1", color=:darkgreen)
if partial
plot(V.tt, V.yy, "*", label=L"V", color=:darkviolet)
else
plot(V.tt, first.(V.yy), ",", label=L"V_1", color=:darkviolet)
end
PyPlot.legend()
figure(figsize=(5,5))
for i in 1:length(Paths)
plot(first.(Paths[i]), last.(Paths[i]), color=:lightblue)
end
plot(first.(X.yy), last.(X.yy), label=L"X", color=:darkviolet)
plot(first.(Xmeanm), last.(Xmeanm), label=L"x_1", color=:darkgreen)
PyPlot.legend()
figure(figsize=(8,5))
plot(X.tt, last.(X.yy), label=L"X_2", linewidth=0.2, color=:darkviolet)
plot(X.tt, last.(Xmeanm), ":", label=L"x_2", color=:darkgreen)
fill_between(X.tt, last.(Xmeanm + 1.96*Xstdm), last.(Xmeanm - 1.96*Xstdm), edgecolor=:darkblue, facecolor=:lightblue, hatch="X", label="95% cred. band")
if !partial
plot(V.tt, last.(V.yy), "*", label=L"V_2", color=:darkviolet)
end
PyPlot.legend()
|
"""
restrict(img[, region]) -> imgr
Reduce the size of `img` by approximately two-fold along the dimensions listed in
`region`, or all spatial coordinates if `region` is not specified.
The term `restrict` is taken from the coarsening operation of algebraic multigrid
methods; it is the adjoint of "prolongation" (which is essentially interpolation).
`restrict` anti-aliases the image as it goes, so is better than a naive summation
over 2x2 blocks.
The implementation of `restrict` has been tuned for performance, and should be
a fast method for constructing [pyramids](https://en.wikipedia.org/wiki/Pyramid_(image_processing)).
If `l` is the size of `img` along a particular dimension, `restrict` produces an
array of size `(l+1)÷2` for odd `l`,
and `l÷2 + 1` for even `l`. See the example below for an explanation.
See also [`imresize`](@ref).
# Example
```julia
a_course = [0, 1, 0.3]
```
If we were to interpolate this at the halfway points, we'd get
```julia
a_fine = [0, 0.5, 1, 0.65, 0.3]
```
Note that `a_fine` is obtained from `a_course` via the *prolongation* operator `P` as
`P*a_course`, where
```julia
P = [1 0 0; # this line "copies over" the first point
0.5 0.5 0; # this line takes the mean of the first and second point
0 1 0; # copy the second point
0 0.5 0.5; # take the mean of the second and third
0 0 1] # copy the third
```
`restrict` is the adjoint of prolongation. Consequently,
```julia
julia> restrict(a_fine)
3-element Array{Float64,1}:
0.125
0.7875
0.3125
julia> (P'*a_fine)/2
3-element Array{Float64,1}:
0.125
0.7875
0.3125
```
where the division by 2 approximately preserves the mean intensity of the input.
As we see here, for odd-length `a_fine`, restriction is the adjoint of interpolation at half-grid points.
When `length(a_fine)` is even, restriction is the adjoint of interpolation at 1/4 and 3/4-grid points.
This turns out to be the origin of the `l->l÷2 + 1` behavior.
One consequence of this definition is that the edges move towards zero:
```julia
julia> restrict(ones(11))
6-element Array{Float64,1}:
0.75
1.0
1.0
1.0
1.0
0.75
```
In some applications (e.g., image registration), you may find it useful to trim the edges.
"""
restrict(img::AbstractArray, ::Tuple{}) = img
restrict(A::AbstractArray, region::Vector{Int}) = restrict(A, (region...,))
restrict(A::AbstractArray) = restrict(A, coords_spatial(A))
function restrict(A::AbstractArray, region::Dims)
restrict(restrict(A, region[1]), Base.tail(region))
end
function restrict(A::AbstractArray{T,N}, dim::Integer) where {T,N}
indsA = axes(A)
newinds = ntuple(i->i==dim ? restrict_indices(indsA[dim]) : indsA[i], Val(N))
out = similar(Array{restrict_eltype(first(A)),N}, newinds)
restrict!(out, A, dim)
out
end
restrict_eltype_default(x) = typeof(x/4 + x/2)
restrict_eltype(x) = restrict_eltype_default(x)
restrict_eltype(x::AbstractGray) = restrict_eltype_default(x)
restrict_eltype(x::AbstractRGB) = restrict_eltype_default(x)
restrict_eltype(x::Color) = restrict_eltype_default(convert(RGB, x))
restrict_eltype(x::TransparentGray) = restrict_eltype_default(x)
restrict_eltype(x::TransparentRGB) = restrict_eltype_default(x)
restrict_eltype(x::Colorant) = restrict_eltype_default(convert(ARGB, x))
function restrict!(out::AbstractArray{T,N}, A::AbstractArray, dim) where {T,N}
if dim > N
return copyto!(out, A)
end
indsout, indsA = axes(out), axes(A)
ndims(out) == ndims(A) || throw(DimensionMismatch("input and output must have the same number of dimensions"))
for d = 1:length(indsA)
target = d==dim ? restrict_indices(indsA[d]) : indsA[d]
indsout[d] == target || error("input and output must have corresponding indices; to be consistent with the input indices,\ndimension $d should be $target, got $(indsout[d])")
end
indspre, indspost = indsA[1:dim-1], indsA[dim+1:end]
_restrict!(out, indsout[dim], A, indspre, indsA[dim], indspost)
end
@generated function _restrict!(out, indout, A,
indspre::NTuple{Npre,AbstractUnitRange},
indA,
indspost::NTuple{Npost,AbstractUnitRange}) where {Npre,Npost}
Ipre = [Symbol(:ipre_, d) for d = 1:Npre]
Ipost = [Symbol(:ipost_, d) for d = 1:Npost]
quote
$(Expr(:meta, :noinline))
T = eltype(out)
if isodd(length(indA))
half = convert(eltype(T), 0.5)
quarter = convert(eltype(T), 0.25)
@nloops $Npost ipost d->indspost[d] begin
iout = first(indout)
@nloops $Npre ipre d->indspre[d] begin
out[$(Ipre...), iout, $(Ipost...)] = zero(T)
end
ispeak = true
for iA in indA
if ispeak
@inbounds @nloops $Npre ipre d->indspre[d] begin
out[$(Ipre...), iout, $(Ipost...)] +=
half*convert(T, A[$(Ipre...), iA, $(Ipost...)])
end
else
@inbounds @nloops $Npre ipre d->indspre[d] begin
tmp = quarter*convert(T, A[$(Ipre...), iA, $(Ipost...)])
out[$(Ipre...), iout, $(Ipost...)] += tmp
out[$(Ipre...), iout+1, $(Ipost...)] = tmp
end
end
ispeak = !ispeak
iout += ispeak
end
end
else
threeeighths = convert(eltype(T), 0.375)
oneeighth = convert(eltype(T), 0.125)
z = zero(T)
fill!(out, zero(T))
@nloops $Npost ipost d->indspost[d] begin
peakfirst = true
iout = first(indout)
for iA in indA
if peakfirst
@inbounds @nloops $Npre ipre d->indspre[d] begin
tmp = convert(T, A[$(Ipre...), iA, $(Ipost...)])
out[$(Ipre...), iout, $(Ipost...)] += threeeighths*tmp
out[$(Ipre...), iout+1, $(Ipost...)] += oneeighth*tmp
end
else
@inbounds @nloops $Npre ipre d->indspre[d] begin
tmp = convert(T, A[$(Ipre...), iA, $(Ipost...)])
out[$(Ipre...), iout, $(Ipost...)] += oneeighth*tmp
out[$(Ipre...), iout+1, $(Ipost...)] += threeeighths*tmp
end
end
peakfirst = !peakfirst
iout += peakfirst
end
end
end
out
end
end
# If we're restricting along dimension 1, there are some additional efficiencies possible
@generated function _restrict!(out, indout, A, ::NTuple{0,AbstractUnitRange},
indA, indspost::NTuple{Npost,AbstractUnitRange}) where Npost
Ipost = [Symbol(:ipost_, d) for d = 1:Npost]
quote
$(Expr(:meta, :noinline))
T = eltype(out)
if isodd(length(indA))
half = convert(eltype(T), 0.5)
quarter = convert(eltype(T), 0.25)
@inbounds @nloops $Npost ipost d->indspost[d] begin
iout, iA = first(indout), first(indA)
nxt = convert(T, A[iA+1, $(Ipost...)])
out[iout, $(Ipost...)] = half*convert(T, A[iA, $(Ipost...)]) + quarter*nxt
for iA in first(indA)+2:2:last(indA)-2
prv = nxt
nxt = convert(T, A[iA+1, $(Ipost...)])
out[iout+=1, $(Ipost...)] = quarter*(prv+nxt) + half*convert(T, A[iA, $(Ipost...)])
end
out[iout+1, $(Ipost...)] = quarter*nxt + half*convert(T, A[last(indA), $(Ipost...)])
end
else
threeeighths = convert(eltype(T), 0.375)
oneeighth = convert(eltype(T), 0.125)
z = zero(T)
@inbounds @nloops $Npost ipost d->indspost[d] begin
c = d = z
iA = first(indA)
for iout = first(indout):last(indout)-1
a, b = c, d
c, d = convert(T, A[iA, $(Ipost...)]), convert(T, A[iA+1, $(Ipost...)])
iA += 2
out[iout, $(Ipost...)] = oneeighth*(a+d) + threeeighths*(b+c)
end
out[last(indout), $(Ipost...)] = oneeighth*c + threeeighths*d
end
end
out
end
end
restrict_size(len::Integer) = isodd(len) ? (len+1)>>1 : (len>>1)+1
function restrict_indices(r::AbstractUnitRange)
f, l = first(r), last(r)
isodd(f) && return (f+1)>>1:restrict_size(l)
f>>1 : (isodd(l) ? (l+1)>>1 : l>>1)
end
restrict_indices(r::Base.OneTo) = Base.OneTo(restrict_size(length(r)))
function restrict_indices(r::UnitRange)
f, l = first(r), last(r)
isodd(f) && return (f+1)>>1:restrict_size(l)
f>>1 : (isodd(l) ? (l+1)>>1 : l>>1)
end
# imresize
imresize(original::AbstractArray, dim1::T, dimN::T...) where T<:Union{Integer,AbstractUnitRange} = imresize(original, (dim1,dimN...))
function imresize(original::AbstractArray; ratio)
all(ratio .> 0) || throw(ArgumentError("ratio $ratio should be positive"))
new_size = ceil.(Int, size(original) .* ratio) # use ceil to avoid 0
imresize(original, new_size)
end
function imresize(original::AbstractArray, short_size::Union{Indices{M},Dims{M}}) where M
len_short = length(short_size)
len_short > ndims(original) && throw(DimensionMismatch("$short_size has too many dimensions for a $(ndims(original))-dimensional array"))
new_size = ntuple(i -> (i > len_short ? odims(original, i, short_size) : short_size[i]), ndims(original))
imresize(original, new_size)
end
odims(original, i, short_size::Tuple{Integer,Vararg{Integer}}) = size(original, i)
odims(original, i, short_size::Tuple{}) = axes(original, i)
odims(original, i, short_size) = oftype(first(short_size), axes(original, i))
"""
imresize(img, sz) -> imgr
imresize(img, inds) -> imgr
imresize(img; ratio) -> imgr
Change `img` to be of size `sz` (or to have indices `inds`). If `ratio` is used, then
`sz = ceil(Int, size(img).*ratio)`. This interpolates the values at sub-pixel locations.
If you are shrinking the image, you risk aliasing unless you low-pass filter `img` first.
# Examples
```julia
julia> img = testimage("lena_gray_256") # 256*256
julia> imresize(img, 128, 128) # 128*128
julia> imresize(img, 1:128, 1:128) # 128*128
julia> imresize(img, (128, 128)) # 128*128
julia> imresize(img, (1:128, 1:128)) # 128*128
julia> imresize(img, (1:128, )) # 128*256
julia> imresize(img, 128) # 128*256
julia> imresize(img, ratio = 0.5) #
julia> imresize(img, ratio = (2, 1)) # 256*128
σ = map((o,n)->0.75*o/n, size(img), sz)
kern = KernelFactors.gaussian(σ) # from ImageFiltering
imgr = imresize(imfilter(img, kern, NA()), sz)
```
See also [`restrict`](@ref).
"""
function imresize(original::AbstractArray{T,0}, new_inds::Tuple{}) where T
Tnew = imresize_type(first(original))
copyto!(similar(original, Tnew), original)
end
function imresize(original::AbstractArray{T,N}, new_size::Dims{N}) where {T,N}
Tnew = imresize_type(first(original))
inds = axes(original)
if map(length, inds) == new_size
dest = similar(original, Tnew, new_size)
if axes(dest) == inds
copyto!(dest, original)
else
copyto!(dest, CartesianIndices(axes(dest)), original, CartesianIndices(inds))
end
else
imresize!(similar(original, Tnew, new_size), original)
end
end
function imresize(original::AbstractArray{T,N}, new_inds::Indices{N}) where {T,N}
Tnew = imresize_type(first(original))
if axes(original) == new_inds
copyto!(similar(original, Tnew), original)
else
imresize!(similar(original, Tnew, new_inds), original)
end
end
# To choose the output type, rather than forcing everything to
# Float64 by multiplying by 1.0, we exploit the fact that the scale
# changes correspond to integer ratios. We mimic ratio arithmetic
# without actually using Rational (which risks promoting to a
# Rational type, too slow for image processing).
imresize_type(c::Colorant) = base_colorant_type(c){eltype(imresize_type(Gray(c)))}
imresize_type(c::Gray) = Gray{imresize_type(gray(c))}
imresize_type(c::FixedPoint) = typeof(c)
imresize_type(c) = typeof((c*1)/1)
function imresize!(resized::AbstractArray{T,N}, original::AbstractArray{S,N}) where {T,S,N}
# FIXME: avoid allocation for interpolation
itp = interpolate(original, BSpline(Linear()))
imresize!(resized, itp)
end
function imresize!(resized::AbstractArray{T,N}, original::AbstractInterpolation{S,N}) where {T,S,N}
# Define the equivalent of an affine transformation for mapping
# locations in `resized` to the corresponding position in
# `original`. We take the viewpoint that a pixel at `i, j` is a
# sensor that *integrates* the intensity over an area spanning
# `i±0.5, j±0.5` (this is a good model of how a camera pixel
# actually works). We then map the *outer corners* of the two
# images to each other, i.e., in typical cases
# (0.5, 0.5) -> (0.5, 0.5) (outer corner, top left)
# size(resized)+0.5 -> size(original)+0.5 (outer corner, lower right)
# This ensures that both images cover exactly the same area.
Ro, Rr = CartesianIndices(axes(original)), CartesianIndices(axes(resized))
sf = map(/, (last(Ro)-first(Ro)).I .+ 1, (last(Rr)-first(Rr)).I .+ 1) # +1 for outer corners
offset = map((io,ir,s)->io - 0.5 - s*(ir-0.5), first(Ro).I, first(Rr).I, sf)
if all(x->x >= 1, sf)
@inbounds for I in Rr
I_o = map3((i,s,off)->s*i+off, I.I, sf, offset)
resized[I] = original(I_o...)
end
else
@inbounds for I in Rr
I_o = clampR(map3((i,s,off)->s*i+off, I.I, sf, offset), Ro)
resized[I] = original(I_o...)
end
end
resized
end
# map isn't optimized for 3 tuple-arguments, so do it here
@inline map3(f, a, b, c) = (f(a[1], b[1], c[1]), map3(f, tail(a), tail(b), tail(c))...)
@inline map3(f, ::Tuple{}, ::Tuple{}, ::Tuple{}) = ()
function clampR(I::NTuple{N}, R::CartesianIndices{N}) where N
map3(clamp, I, first(R).I, last(R).I)
end
|
# This file is based on rowvector.jl in Julia. License is MIT: https://julialang.org/license
# The motivation for this file is to allow RowVector which doesn't transpose the entries
import Base: convert, similar, length, size, axes, IndexStyle,
IndexLinear, @propagate_inbounds, getindex, setindex!,
broadcast, hcat, typed_hcat, map, parent
"""
RowVector(vector)
A lazy-view wrapper of an `AbstractVector`, which turns a length-`n` vector into a `1×n`
shaped row vector and represents the transpose of a vector (the elements are also transposed
recursively).
By convention, a vector can be multiplied by a matrix on its left (`A * v`) whereas a row
vector can be multiplied by a matrix on its right (such that `transpose(v) * A = transpose(transpose(A) * v)`). It
differs from a `1×n`-sized matrix by the facts that its transpose returns a vector and the
inner product `transpose(v1) * v2` returns a scalar, but will otherwise behave similarly.
"""
struct RowVector{T,V<:AbstractVector} <: AbstractMatrix{T}
vec::V
function RowVector{T,V}(v::V) where V<:AbstractVector where T
new(v)
end
end
# Constructors that take a vector
@inline RowVector(vec::AbstractVector{T}) where {T} = RowVector{T,typeof(vec)}(vec)
@inline RowVector{T}(vec::AbstractVector{T}) where {T} = RowVector{T,typeof(vec)}(vec)
# Constructors that take a size and default to Array
@inline RowVector{T}(n::Int) where {T} = RowVector{T}(Vector{T}(n))
@inline RowVector{T}(n1::Int, n2::Int) where {T} = n1 == 1 ?
RowVector{T}(Vector{T}(n2)) :
error("RowVector expects 1×N size, got ($n1,$n2)")
@inline RowVector{T}(n::Tuple{Int}) where {T} = RowVector{T}(Vector{T}(n[1]))
@inline RowVector{T}(n::Tuple{Int,Int}) where {T} = n[1] == 1 ?
RowVector{T}(Vector{T}(n[2])) :
error("RowVector expects 1×N size, got $n")
# Conversion of underlying storage
convert(::Type{RowVector{T,V}}, rowvec::RowVector) where {T,V<:AbstractVector} =
RowVector{T,V}(convert(V,rowvec.vec))
# similar tries to maintain the RowVector wrapper and the parent type
@inline similar(rowvec::RowVector) = RowVector(similar(parent(rowvec)))
@inline similar(rowvec::RowVector, ::Type{T}) where {T} = RowVector(similar(parent(rowvec), transpose_type(T)))
# Resizing similar currently loses its RowVector property.
@inline similar(rowvec::RowVector, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(rowvec), T, dims)
parent(rowvec::RowVector) = rowvec.vec
# AbstractArray interface
@inline length(rowvec::RowVector) = length(rowvec.vec)
@inline size(rowvec::RowVector) = (1, length(rowvec.vec))
@inline size(rowvec::RowVector, d) = ifelse(d==2, length(rowvec.vec), 1)
@inline axes(rowvec::RowVector) = (Base.OneTo(1), axes(rowvec.vec)[1])
@inline axes(rowvec::RowVector, d) = ifelse(d == 2, axes(rowvec.vec)[1], Base.OneTo(1))
IndexStyle(::RowVector) = IndexLinear()
IndexStyle(::Type{<:RowVector}) = IndexLinear()
@propagate_inbounds getindex(rowvec::RowVector, i) = rowvec.vec[i]
@propagate_inbounds setindex!(rowvec::RowVector, v, i) = setindex!(rowvec.vec, v, i)
# Cartesian indexing is distorted by getindex
# Furthermore, Cartesian indexes don't have to match shape, apparently!
@inline function getindex(rowvec::RowVector, i::CartesianIndex)
@boundscheck if !(i.I[1] == 1 && i.I[2] ∈ axes(rowvec.vec)[1] && check_tail_indices(i.I...))
throw(BoundsError(rowvec, i.I))
end
@inbounds return rowvec.vec[i.I[2]]
end
@inline function setindex!(rowvec::RowVector, v, i::CartesianIndex)
@boundscheck if !(i.I[1] == 1 && i.I[2] ∈ axes(rowvec.vec)[1] && check_tail_indices(i.I...))
throw(BoundsError(rowvec, i.I))
end
@inbounds rowvec.vec[i.I[2]] = v
end
@propagate_inbounds getindex(rowvec::RowVector, ::CartesianIndex{0}) = getindex(rowvec)
@propagate_inbounds getindex(rowvec::RowVector, i::CartesianIndex{1}) = getindex(rowvec, i.I[1])
@propagate_inbounds setindex!(rowvec::RowVector, v, ::CartesianIndex{0}) = setindex!(rowvec, v)
@propagate_inbounds setindex!(rowvec::RowVector, v, i::CartesianIndex{1}) = setindex!(rowvec, v, i.I[1])
# helper function for below
@inline to_vec(rowvec::RowVector) = rowvec.vec
# map: Preserve the RowVector by un-wrapping and re-wrapping, but note that `f`
# expects to operate within the transposed domain, so to_vec transposes the elements
@inline map(f, rowvecs::RowVector...) = RowVector(map(f, to_vecs(rowvecs...)...))
# broacast (other combinations default to higher-dimensional array)
@inline broadcast(f, rowvecs::Union{Number,RowVector}...) =
RowVector(broadcast(f, to_vecs(rowvecs...)...))
# Horizontal concatenation #
@inline hcat(X::RowVector...) = RowVector(vcat(X...))
@inline hcat(X::Union{RowVector,Number}...) = RowVector(vcat(X...))
@inline typed_hcat(::Type{T}, X::RowVector...) where {T} =
RowVector(typed_vcat(T, X...))
@inline typed_hcat(::Type{T}, X::Union{RowVector,Number}...) where {T} =
RowVector(typed_vcat(T, X...))
# Multiplication #
# inner product -> dot product specializations
@inline *(rowvec::RowVector{T}, vec::AbstractVector{T}) where {T<:Real} = dotu(parent(rowvec), vec)
# Generic behavior
@inline function *(rowvec::RowVector, vec::AbstractVector)
if length(rowvec) != length(vec)
throw(DimensionMismatch("A has dimensions $(size(rowvec)) but B has dimensions $(size(vec))"))
end
sum(@inbounds(rowvec[i]*vec[i]) for i = 1:length(vec))
end
@inline *(rowvec::RowVector, mat::AbstractMatrix) = RowVector(transpose(transpose()mat) * rowvec.vec)
*(::RowVector, ::RowVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors"))
@inline *(vec::AbstractVector, rowvec::RowVector) = vec .* rowvec
## Removed A_* overrides for now
|
"""
Supertype for all prior distributions
"""
abstract type Prior end
"""
logpdf(::Prior, θ)
Evaluate the log-probability density function at `θ` for a given prior.
"""
function Distributions.logpdf(::T, θ) where {T<:Prior}
error("logpdf not implemented for prior $T.")
end
"""
Flat prior
"""
struct ImproperPrior <: Prior end
Distributions.logpdf(::ImproperPrior, θ) = 0.0
"""
Flat prior for positive coordinates
"""
struct ImproperPosPrior <: Prior end
Distributions.logpdf(::ImproperPosPrior, θ) = -sum(log.(θ))
"""
struct StandardPrior{T} <: Prior
dist::T
end
A standard prior π(θ).
"""
struct StandardPrior{T} <: Prior
dist::T
StandardPrior(dist::T) where T = new{T}(dist)
end
Distributions.logpdf(prior::StandardPrior, θ) = logpdf(prior.dist, θ)
@doc raw"""
struct ProductPrior{T,K} <: Prior
dists::T
idx::K
end
Generic prior distribution over parameter vector θ written in a facorized form.
For instance if the prior may be written as
```math
π(θ) = π_1(θ_{1:k})π_2(θ_{(k+1):n}),
```
then `dists` would correspond to a list containing `π_1` and `π_2` and `idx`
would be a list containing `1:k` and `(k+1):n`.
ProductPrior(dists, dims)
Base consructor specifying a list of prior dsitributions `dists` and a
corresponding number of dimensions to which each prior distribution refers to.
"""
struct ProductPrior{T,K} <: Prior
dists::T
idx::K
function ProductPrior(dists, dims)
dims_reformatted = Any[]
last_idx = 1
for dim in dims
if dim == 1
push!(dims_reformatted, dim)
last_idx += 1
else
push!(dims_reformatted, last_idx:last_idx+dim-1)
last_idx += dim
end
end
idx = tuple(dims_reformatted...)
dists = tuple(dists...)
new{typeof(dists), typeof(idx)}(dists, idx)
end
end
function Distributions.logpdf(prior::ProductPrior, θ)
lp = 0.0
for (dist, idx) in zip(prior.dists, prior.idx)
lp += logpdf(dist, θ[idx])
end
lp
end
|
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
abstract type AbstractProgressiveHedgingExecution end
# Execution API #
# ------------------------------------------------------------
initialize_subproblems!(ph::AbstractProgressiveHedging, scenarioproblems::AbstractScenarioProblems, penaltyterm::AbstractPenaltyTerm) = initialize_subproblems!(ph, ph.execution, scenarioproblems, penaltyterm)
finish_initilization!(ph::AbstractProgressiveHedging, penalty::AbstractFloat) = finish_initilization!(ph.execution, penalty)
restore_subproblems!(ph::AbstractProgressiveHedging) = restore_subproblems!(ph, ph.execution)
iterate!(ph::AbstractProgressiveHedging) = iterate!(ph, ph.execution)
start_workers!(ph::AbstractProgressiveHedging) = start_workers!(ph, ph.execution)
close_workers!(ph::AbstractProgressiveHedging) = close_workers!(ph, ph.execution)
resolve_subproblems!(ph::AbstractProgressiveHedging) = resolve_subproblems!(ph, ph.execution)
update_iterate!(ph::AbstractProgressiveHedging) = update_iterate!(ph, ph.execution)
update_subproblems!(ph::AbstractProgressiveHedging) = update_subproblems!(ph, ph.execution)
update_dual_gap!(ph::AbstractProgressiveHedging) = update_dual_gap!(ph, ph.execution)
calculate_objective_value(ph::AbstractProgressiveHedging) = calculate_objective_value(ph, ph.execution)
scalar_subproblem_reduction(value::Function, ph::AbstractProgressiveHedging) = scalar_subproblem_reduction(value, ph.execution)
vector_subproblem_reduction(value::Function, ph::AbstractProgressiveHedging, n::Integer) = scalar_subproblem_reduction(value, ph.execution, n)
# ------------------------------------------------------------
include("common.jl")
include("serial.jl")
include("channels.jl")
include("distributed.jl")
include("synchronous.jl")
include("asynchronous.jl")
|
# Before running this, please make sure to activate and instantiate the environment
# corresponding to [this `Project.toml`](https://raw.githubusercontent.com/alan-turing-institute/DataScienceTutorials.jl/master/Project.toml) and [this `Manifest.toml`](https://raw.githubusercontent.com/alan-turing-institute/DataScienceTutorials.jl/master/Manifest.toml)
# so that you get an environment which matches the one used to generate the tutorials:
#
# ```julia
# cd("DataScienceTutorials") # cd to folder with the *.toml
# using Pkg; Pkg.activate("."); Pkg.instantiate()
# ```
# **Main author**: Yaqub Alwan (IQVIA).## ## Getting started
using MLJ
using PrettyPrinting
import DataFrames
import Statistics
using PyPlot
using StableRNGs
@load LGBMRegressor
# Let us try LightGBM out by doing a regression task on the Boston house prices dataset.# This is a commonly used dataset so there is a loader built into MLJ.
# Here, the objective is to show how LightGBM can do better than a Linear Regressor# with minimal effort.## We start out by taking a quick peek at the data itself and its statistical properties.
features, targets = @load_boston
features = DataFrames.DataFrame(features)
@show size(features)
@show targets[1:3]
first(features, 3) |> pretty
# We can also describe the dataframe
DataFrames.describe(features)
# Do the usual train/test partitioning. This is important so we can estimate generalisation.
train, test = partition(eachindex(targets), 0.70, shuffle=true,
rng=StableRNG(52))
# Let us investigation some of the commonly tweaked LightGBM parameters. We start with looking at a learning curve for number of boostings.
lgb = LGBMRegressor() #initialised a model with default params
lgbm = machine(lgb, features[train, :], targets[train, 1])
boostrange = range(lgb, :num_iterations, lower=2, upper=500)
curve = learning_curve!(lgbm, resampling=CV(nfolds=5),
range=boostrange, resolution=100,
measure=rms)
figure(figsize=(8,6))
plot(curve.parameter_values, curve.measurements)
xlabel("Number of rounds", fontsize=14)
ylabel("RMSE", fontsize=14)
# \fig{lgbm_hp1.svg}
# It looks like that we don't need to go much past 100 boosts
# Since LightGBM is a gradient based learning method, we also have a learning rate parameter which controls the size of gradient updates.# Let us look at a learning curve for this parameter too
lgb = LGBMRegressor() #initialised a model with default params
lgbm = machine(lgb, features[train, :], targets[train, 1])
learning_range = range(lgb, :learning_rate, lower=1e-3, upper=1, scale=:log)
curve = learning_curve!(lgbm, resampling=CV(nfolds=5),
range=learning_range, resolution=100,
measure=rms)
figure(figsize=(8,6))
plot(curve.parameter_values, curve.measurements)
xscale("log")
xlabel("Learning rate (log scale)", fontsize=14)
ylabel("RMSE", fontsize=14)
# \fig{lgbm_hp2.svg}
# It seems like near 0.5 is a reasonable place. Bearing in mind that for lower# values of learning rate we possibly require more boosting in order to converge, so the default# value of 100 might not be sufficient for convergence. We leave this as an exercise to the reader.# We can still try to tune this parameter, however.
# Finally let us check number of datapoints required to produce a leaf in an individual tree. This parameter# controls the complexity of individual learner trees, and too low a value might lead to overfitting.
lgb = LGBMRegressor() #initialised a model with default params
lgbm = machine(lgb, features[train, :], targets[train, 1])
# dataset is small enough and the lower and upper sets the tree to have certain number of leaves
leaf_range = range(lgb, :min_data_in_leaf, lower=1, upper=50)
curve = learning_curve!(lgbm, resampling=CV(nfolds=5),
range=leaf_range, resolution=50,
measure=rms)
figure(figsize=(8,6))
plot(curve.parameter_values, curve.measurements)
xlabel("Min data in leaf", fontsize=14)
ylabel("RMSE", fontsize=14)
# \fig{lgbm_hp3.svg}
# It does not seem like there is a huge risk for overfitting, and lower is better for this parameter.
# Using the learning curves above we can select some small-ish ranges to jointly search for the best# combinations of these parameters via cross validation.
r1 = range(lgb, :num_iterations, lower=50, upper=100)
r2 = range(lgb, :min_data_in_leaf, lower=2, upper=10)
r3 = range(lgb, :learning_rate, lower=1e-1, upper=1e0)
tm = TunedModel(model=lgb, tuning=Grid(resolution=5),
resampling=CV(rng=StableRNG(123)), ranges=[r1,r2,r3],
measure=rms)
mtm = machine(tm, features, targets)
fit!(mtm, rows=train);
# Lets see what the cross validation best model parameters turned out to be?
best_model = fitted_params(mtm).best_model
@show best_model.learning_rate
@show best_model.min_data_in_leaf
@show best_model.num_iterations
# Great, and now let's predict using the held out data.
predictions = predict(mtm, rows=test)
rms_score = round(rms(predictions, targets[test, 1]), sigdigits=4)
@show rms_score
# This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl
|
using Makie
using MakieLayout
begin
scene = Scene(camera=campixel!)
display(scene)
outergrid = GridLayout(scene, alignmode=Outside(30))
innergrid = outergrid[1, 1] = GridLayout(3, 3)
las = innergrid[:, 1] = [LAxis(scene) for i in 1:3]
alignedgrid1 = innergrid[:, 2] = GridLayout(2, 1; rowsizes=Relative(0.33), valign=:center)
alignedgrid1[1, 1] = LAxis(scene, yaxisposition=:right, yticklabelalign=(:left, :center))
alignedgrid1[2, 1] = LAxis(scene)
alignedgrid2 = innergrid[:, 3] = GridLayout(rowsizes=Relative(0.5); valign=:bottom)
alignedgrid2[1, 1] = LAxis(scene, xaxisposition=:top, xticklabelalign=(:center, :bottom))
buttonsgl = innergrid[end+1, :] = GridLayout()
valigns = (:bottom, :top, :center)
buttons = buttonsgl[1, 1:3] = [LButton(scene; height=40, label="$v") for v in valigns]
for (button, align) in zip(buttons, valigns)
on(button.clicks) do c
alignedgrid1.valign[] = align
alignedgrid2.valign[] = align
end
end
end
|
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: connect
using AWS.Compat
using AWS.UUIDs
"""
AssociateApprovedOrigin()
Associates an approved origin to an Amazon Connect instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Origin`: The domain to add to your allow list.
"""
associate_approved_origin(InstanceId, Origin; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/approved-origin", Dict{String, Any}("Origin"=>Origin); aws_config=aws_config)
associate_approved_origin(InstanceId, Origin, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/approved-origin", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Origin"=>Origin), args)); aws_config=aws_config)
"""
AssociateInstanceStorageConfig()
Associates a storage resource type for the first time. You can only associate one type of storage configuration in a single call. This means, for example, that you can't define an instance with multiple S3 buckets for storing chat transcripts. This API does not create a resource that doesn't exist. It only associates it to the instance. Ensure that the resource being specified in the storage configuration, like an Amazon S3 bucket, exists when being used for association.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `ResourceType`: A valid resource type.
- `StorageConfig`: A valid storage type.
"""
associate_instance_storage_config(InstanceId, ResourceType, StorageConfig; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/storage-config", Dict{String, Any}("ResourceType"=>ResourceType, "StorageConfig"=>StorageConfig); aws_config=aws_config)
associate_instance_storage_config(InstanceId, ResourceType, StorageConfig, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/storage-config", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ResourceType"=>ResourceType, "StorageConfig"=>StorageConfig), args)); aws_config=aws_config)
"""
AssociateLambdaFunction()
Allows the specified Amazon Connect instance to access the specified Lambda function.
# Required Parameters
- `FunctionArn`: The Amazon Resource Name (ARN) for the Lambda function being associated. Maximum number of characters allowed is 140.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
associate_lambda_function(FunctionArn, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/lambda-function", Dict{String, Any}("FunctionArn"=>FunctionArn); aws_config=aws_config)
associate_lambda_function(FunctionArn, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/lambda-function", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FunctionArn"=>FunctionArn), args)); aws_config=aws_config)
"""
AssociateLexBot()
Allows the specified Amazon Connect instance to access the specified Amazon Lex bot.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `LexBot`: The Amazon Lex box to associate with the instance.
"""
associate_lex_bot(InstanceId, LexBot; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/lex-bot", Dict{String, Any}("LexBot"=>LexBot); aws_config=aws_config)
associate_lex_bot(InstanceId, LexBot, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/lex-bot", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("LexBot"=>LexBot), args)); aws_config=aws_config)
"""
AssociateRoutingProfileQueues()
Associates a set of queues with a routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `QueueConfigs`: The queues to associate with this routing profile.
- `RoutingProfileId`: The identifier of the routing profile.
"""
associate_routing_profile_queues(InstanceId, QueueConfigs, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/associate-queues", Dict{String, Any}("QueueConfigs"=>QueueConfigs); aws_config=aws_config)
associate_routing_profile_queues(InstanceId, QueueConfigs, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/associate-queues", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("QueueConfigs"=>QueueConfigs), args)); aws_config=aws_config)
"""
AssociateSecurityKey()
Associates a security key to the instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Key`: A valid security key in PEM format.
"""
associate_security_key(InstanceId, Key; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/security-key", Dict{String, Any}("Key"=>Key); aws_config=aws_config)
associate_security_key(InstanceId, Key, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance/$(InstanceId)/security-key", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Key"=>Key), args)); aws_config=aws_config)
"""
CreateContactFlow()
Creates a contact flow for the specified Amazon Connect instance. You can also create and update contact flows using the Amazon Connect Flow language.
# Required Parameters
- `Content`: The content of the contact flow.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Name`: The name of the contact flow.
- `Type`: The type of the contact flow. For descriptions of the available types, see Choose a Contact Flow Type in the Amazon Connect Administrator Guide.
# Optional Parameters
- `Description`: The description of the contact flow.
- `Tags`: One or more tags.
"""
create_contact_flow(Content, InstanceId, Name, Type; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact-flows/$(InstanceId)", Dict{String, Any}("Content"=>Content, "Name"=>Name, "Type"=>Type); aws_config=aws_config)
create_contact_flow(Content, InstanceId, Name, Type, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact-flows/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Content"=>Content, "Name"=>Name, "Type"=>Type), args)); aws_config=aws_config)
"""
CreateInstance()
Initiates an Amazon Connect instance with all the supported channels enabled. It does not attach any storage (such as Amazon S3, or Kinesis) or allow for any configurations on features such as Contact Lens for Amazon Connect.
# Required Parameters
- `IdentityManagementType`: The type of identity management for your Amazon Connect users.
- `InboundCallsEnabled`: Whether your contact center handles incoming contacts.
- `OutboundCallsEnabled`: Whether your contact center allows outbound calls.
# Optional Parameters
- `ClientToken`: The idempotency token.
- `DirectoryId`: The identifier for the directory.
- `InstanceAlias`: The name for your instance.
"""
create_instance(IdentityManagementType, InboundCallsEnabled, OutboundCallsEnabled; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance", Dict{String, Any}("IdentityManagementType"=>IdentityManagementType, "InboundCallsEnabled"=>InboundCallsEnabled, "OutboundCallsEnabled"=>OutboundCallsEnabled); aws_config=aws_config)
create_instance(IdentityManagementType, InboundCallsEnabled, OutboundCallsEnabled, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/instance", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityManagementType"=>IdentityManagementType, "InboundCallsEnabled"=>InboundCallsEnabled, "OutboundCallsEnabled"=>OutboundCallsEnabled), args)); aws_config=aws_config)
"""
CreateRoutingProfile()
Creates a new routing profile.
# Required Parameters
- `DefaultOutboundQueueId`: The default outbound queue for the routing profile.
- `Description`: Description of the routing profile. Must not be more than 250 characters.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `MediaConcurrencies`: The channels agents can handle in the Contact Control Panel (CCP) for this routing profile.
- `Name`: The name of the routing profile. Must not be more than 127 characters.
# Optional Parameters
- `QueueConfigs`: The inbound queues associated with the routing profile. If no queue is added, the agent can only make outbound calls.
- `Tags`: One or more tags.
"""
create_routing_profile(DefaultOutboundQueueId, Description, InstanceId, MediaConcurrencies, Name; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/routing-profiles/$(InstanceId)", Dict{String, Any}("DefaultOutboundQueueId"=>DefaultOutboundQueueId, "Description"=>Description, "MediaConcurrencies"=>MediaConcurrencies, "Name"=>Name); aws_config=aws_config)
create_routing_profile(DefaultOutboundQueueId, Description, InstanceId, MediaConcurrencies, Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/routing-profiles/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DefaultOutboundQueueId"=>DefaultOutboundQueueId, "Description"=>Description, "MediaConcurrencies"=>MediaConcurrencies, "Name"=>Name), args)); aws_config=aws_config)
"""
CreateUser()
Creates a user account for the specified Amazon Connect instance. For information about how to create user accounts using the Amazon Connect console, see Add Users in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `PhoneConfig`: The phone settings for the user.
- `RoutingProfileId`: The identifier of the routing profile for the user.
- `SecurityProfileIds`: The identifier of the security profile for the user.
- `Username`: The user name for the account. For instances not using SAML for identity management, the user name can include up to 20 characters. If you are using SAML for identity management, the user name can include up to 64 characters from [a-zA-Z0-9_-.@]+.
# Optional Parameters
- `DirectoryUserId`: The identifier of the user account in the directory used for identity management. If Amazon Connect cannot access the directory, you can specify this identifier to authenticate users. If you include the identifier, we assume that Amazon Connect cannot access the directory. Otherwise, the identity information is used to authenticate users from your directory. This parameter is required if you are using an existing directory for identity management in Amazon Connect when Amazon Connect cannot access your directory to authenticate users. If you are using SAML for identity management and include this parameter, an error is returned.
- `HierarchyGroupId`: The identifier of the hierarchy group for the user.
- `IdentityInfo`: The information about the identity of the user.
- `Password`: The password for the user account. A password is required if you are using Amazon Connect for identity management. Otherwise, it is an error to include a password.
- `Tags`: One or more tags.
"""
create_user(InstanceId, PhoneConfig, RoutingProfileId, SecurityProfileIds, Username; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/users/$(InstanceId)", Dict{String, Any}("PhoneConfig"=>PhoneConfig, "RoutingProfileId"=>RoutingProfileId, "SecurityProfileIds"=>SecurityProfileIds, "Username"=>Username); aws_config=aws_config)
create_user(InstanceId, PhoneConfig, RoutingProfileId, SecurityProfileIds, Username, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/users/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PhoneConfig"=>PhoneConfig, "RoutingProfileId"=>RoutingProfileId, "SecurityProfileIds"=>SecurityProfileIds, "Username"=>Username), args)); aws_config=aws_config)
"""
CreateUserHierarchyGroup()
Creates a new user hierarchy group.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Name`: The name of the user hierarchy group. Must not be more than 100 characters.
# Optional Parameters
- `ParentGroupId`: The identifier for the parent hierarchy group. The user hierarchy is created at level one if the parent group ID is null.
"""
create_user_hierarchy_group(InstanceId, Name; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/user-hierarchy-groups/$(InstanceId)", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
create_user_hierarchy_group(InstanceId, Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/user-hierarchy-groups/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), args)); aws_config=aws_config)
"""
DeleteInstance()
Deletes the Amazon Connect instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
delete_instance(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)"; aws_config=aws_config)
delete_instance(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)", args; aws_config=aws_config)
"""
DeleteUser()
Deletes a user account from the specified Amazon Connect instance. For information about what happens to a user's data when their account is deleted, see Delete Users from Your Amazon Connect Instance in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `UserId`: The identifier of the user.
"""
delete_user(InstanceId, UserId; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/users/$(InstanceId)/$(UserId)"; aws_config=aws_config)
delete_user(InstanceId, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/users/$(InstanceId)/$(UserId)", args; aws_config=aws_config)
"""
DeleteUserHierarchyGroup()
Deletes an existing user hierarchy group. It must not be associated with any agents or have any active child groups.
# Required Parameters
- `HierarchyGroupId`: The identifier of the hierarchy group.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
delete_user_hierarchy_group(HierarchyGroupId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)"; aws_config=aws_config)
delete_user_hierarchy_group(HierarchyGroupId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)", args; aws_config=aws_config)
"""
DescribeContactFlow()
Describes the specified contact flow. You can also create and update contact flows using the Amazon Connect Flow language.
# Required Parameters
- `ContactFlowId`: The identifier of the contact flow.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
describe_contact_flow(ContactFlowId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact-flows/$(InstanceId)/$(ContactFlowId)"; aws_config=aws_config)
describe_contact_flow(ContactFlowId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact-flows/$(InstanceId)/$(ContactFlowId)", args; aws_config=aws_config)
"""
DescribeInstance()
Returns the current state of the specified instance identifier. It tracks the instance while it is being created and returns an error status if applicable. If an instance is not created successfully, the instance status reason field returns details relevant to the reason. The instance in a failed state is returned only for 24 hours after the CreateInstance API was invoked.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
describe_instance(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)"; aws_config=aws_config)
describe_instance(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)", args; aws_config=aws_config)
"""
DescribeInstanceAttribute()
Describes the specified instance attribute.
# Required Parameters
- `AttributeType`: The type of attribute.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
describe_instance_attribute(AttributeType, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/attribute/$(AttributeType)"; aws_config=aws_config)
describe_instance_attribute(AttributeType, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/attribute/$(AttributeType)", args; aws_config=aws_config)
"""
DescribeInstanceStorageConfig()
Retrieves the current storage configurations for the specified resource type, association ID, and instance ID.
# Required Parameters
- `AssociationId`: The existing association identifier that uniquely identifies the resource type and storage config for the given instance ID.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `resourceType`: A valid resource type.
"""
describe_instance_storage_config(AssociationId, InstanceId, resourceType; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}("resourceType"=>resourceType); aws_config=aws_config)
describe_instance_storage_config(AssociationId, InstanceId, resourceType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceType"=>resourceType), args)); aws_config=aws_config)
"""
DescribeRoutingProfile()
Describes the specified routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `RoutingProfileId`: The identifier of the routing profile.
"""
describe_routing_profile(InstanceId, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)"; aws_config=aws_config)
describe_routing_profile(InstanceId, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)", args; aws_config=aws_config)
"""
DescribeUser()
Describes the specified user account. You can find the instance ID in the console (it’s the final part of the ARN). The console does not display the user IDs. Instead, list the users and note the IDs provided in the output.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `UserId`: The identifier of the user account.
"""
describe_user(InstanceId, UserId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/users/$(InstanceId)/$(UserId)"; aws_config=aws_config)
describe_user(InstanceId, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/users/$(InstanceId)/$(UserId)", args; aws_config=aws_config)
"""
DescribeUserHierarchyGroup()
Describes the specified hierarchy group.
# Required Parameters
- `HierarchyGroupId`: The identifier of the hierarchy group.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
describe_user_hierarchy_group(HierarchyGroupId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)"; aws_config=aws_config)
describe_user_hierarchy_group(HierarchyGroupId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)", args; aws_config=aws_config)
"""
DescribeUserHierarchyStructure()
Describes the hierarchy structure of the specified Amazon Connect instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
describe_user_hierarchy_structure(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-structure/$(InstanceId)"; aws_config=aws_config)
describe_user_hierarchy_structure(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-structure/$(InstanceId)", args; aws_config=aws_config)
"""
DisassociateApprovedOrigin()
Revokes access to integrated applications from Amazon Connect.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `origin`: The domain URL of the integrated application.
"""
disassociate_approved_origin(InstanceId, origin; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/approved-origin", Dict{String, Any}("origin"=>origin); aws_config=aws_config)
disassociate_approved_origin(InstanceId, origin, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/approved-origin", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("origin"=>origin), args)); aws_config=aws_config)
"""
DisassociateInstanceStorageConfig()
Removes the storage type configurations for the specified resource type and association ID.
# Required Parameters
- `AssociationId`: The existing association identifier that uniquely identifies the resource type and storage config for the given instance ID.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `resourceType`: A valid resource type.
"""
disassociate_instance_storage_config(AssociationId, InstanceId, resourceType; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}("resourceType"=>resourceType); aws_config=aws_config)
disassociate_instance_storage_config(AssociationId, InstanceId, resourceType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceType"=>resourceType), args)); aws_config=aws_config)
"""
DisassociateLambdaFunction()
Remove the Lambda function from the drop-down options available in the relevant contact flow blocks.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance..
- `functionArn`: The Amazon Resource Name (ARN) of the Lambda function being disassociated.
"""
disassociate_lambda_function(InstanceId, functionArn; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/lambda-function", Dict{String, Any}("functionArn"=>functionArn); aws_config=aws_config)
disassociate_lambda_function(InstanceId, functionArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/lambda-function", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("functionArn"=>functionArn), args)); aws_config=aws_config)
"""
DisassociateLexBot()
Revokes authorization from the specified instance to access the specified Amazon Lex bot.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `botName`: The name of the Amazon Lex bot. Maximum character limit of 50.
- `lexRegion`: The Region in which the Amazon Lex bot has been created.
"""
disassociate_lex_bot(InstanceId, botName, lexRegion; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/lex-bot", Dict{String, Any}("botName"=>botName, "lexRegion"=>lexRegion); aws_config=aws_config)
disassociate_lex_bot(InstanceId, botName, lexRegion, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/lex-bot", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("botName"=>botName, "lexRegion"=>lexRegion), args)); aws_config=aws_config)
"""
DisassociateRoutingProfileQueues()
Disassociates a set of queues from a routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `QueueReferences`: The queues to disassociate from this routing profile.
- `RoutingProfileId`: The identifier of the routing profile.
"""
disassociate_routing_profile_queues(InstanceId, QueueReferences, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/disassociate-queues", Dict{String, Any}("QueueReferences"=>QueueReferences); aws_config=aws_config)
disassociate_routing_profile_queues(InstanceId, QueueReferences, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/disassociate-queues", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("QueueReferences"=>QueueReferences), args)); aws_config=aws_config)
"""
DisassociateSecurityKey()
Deletes the specified security key.
# Required Parameters
- `AssociationId`: The existing association identifier that uniquely identifies the resource type and storage config for the given instance ID.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
disassociate_security_key(AssociationId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/security-key/$(AssociationId)"; aws_config=aws_config)
disassociate_security_key(AssociationId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/instance/$(InstanceId)/security-key/$(AssociationId)", args; aws_config=aws_config)
"""
GetContactAttributes()
Retrieves the contact attributes for the specified contact.
# Required Parameters
- `InitialContactId`: The identifier of the initial contact.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
get_contact_attributes(InitialContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact/attributes/$(InstanceId)/$(InitialContactId)"; aws_config=aws_config)
get_contact_attributes(InitialContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact/attributes/$(InstanceId)/$(InitialContactId)", args; aws_config=aws_config)
"""
GetCurrentMetricData()
Gets the real-time metric data from the specified Amazon Connect instance. For a description of each metric, see Real-time Metrics Definitions in the Amazon Connect Administrator Guide.
# Required Parameters
- `CurrentMetrics`: The metrics to retrieve. Specify the name and unit for each metric. The following metrics are available. For a description of all the metrics, see Real-time Metrics Definitions in the Amazon Connect Administrator Guide. AGENTS_AFTER_CONTACT_WORK Unit: COUNT Name in real-time metrics report: ACW AGENTS_AVAILABLE Unit: COUNT Name in real-time metrics report: Available AGENTS_ERROR Unit: COUNT Name in real-time metrics report: Error AGENTS_NON_PRODUCTIVE Unit: COUNT Name in real-time metrics report: NPT (Non-Productive Time) AGENTS_ON_CALL Unit: COUNT Name in real-time metrics report: On contact AGENTS_ON_CONTACT Unit: COUNT Name in real-time metrics report: On contact AGENTS_ONLINE Unit: COUNT Name in real-time metrics report: Online AGENTS_STAFFED Unit: COUNT Name in real-time metrics report: Staffed CONTACTS_IN_QUEUE Unit: COUNT Name in real-time metrics report: In queue CONTACTS_SCHEDULED Unit: COUNT Name in real-time metrics report: Scheduled OLDEST_CONTACT_AGE Unit: SECONDS When you use groupings, Unit says SECONDS but the Value is returned in MILLISECONDS. For example, if you get a response like this: { \"Metric\": { \"Name\": \"OLDEST_CONTACT_AGE\", \"Unit\": \"SECONDS\" }, \"Value\": 24113.0 } The actual OLDEST_CONTACT_AGE is 24 seconds. Name in real-time metrics report: Oldest SLOTS_ACTIVE Unit: COUNT Name in real-time metrics report: Active SLOTS_AVAILABLE Unit: COUNT Name in real-time metrics report: Availability
- `Filters`: The queues, up to 100, or channels, to use to filter the metrics returned. Metric data is retrieved only for the resources associated with the queues or channels included in the filter. You can include both queue IDs and queue ARNs in the same request. Both VOICE and CHAT channels are supported.
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `Groupings`: The grouping applied to the metrics returned. For example, when grouped by QUEUE, the metrics returned apply to each queue rather than aggregated for all queues. If you group by CHANNEL, you should include a Channels filter. Both VOICE and CHAT channels are supported. If no Grouping is included in the request, a summary of metrics is returned.
- `MaxResults`: The maximimum number of results to return per page.
- `NextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. The token expires after 5 minutes from the time it is created. Subsequent requests that use the token must use the same request parameters as the request that generated the token.
"""
get_current_metric_data(CurrentMetrics, Filters, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/metrics/current/$(InstanceId)", Dict{String, Any}("CurrentMetrics"=>CurrentMetrics, "Filters"=>Filters); aws_config=aws_config)
get_current_metric_data(CurrentMetrics, Filters, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/metrics/current/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("CurrentMetrics"=>CurrentMetrics, "Filters"=>Filters), args)); aws_config=aws_config)
"""
GetFederationToken()
Retrieves a token for federation.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
get_federation_token(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user/federate/$(InstanceId)"; aws_config=aws_config)
get_federation_token(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user/federate/$(InstanceId)", args; aws_config=aws_config)
"""
GetMetricData()
Gets historical metric data from the specified Amazon Connect instance. For a description of each historical metric, see Historical Metrics Definitions in the Amazon Connect Administrator Guide.
# Required Parameters
- `EndTime`: The timestamp, in UNIX Epoch time format, at which to end the reporting interval for the retrieval of historical metrics data. The time must be specified using an interval of 5 minutes, such as 11:00, 11:05, 11:10, and must be later than the start time timestamp. The time range between the start and end time must be less than 24 hours.
- `Filters`: The queues, up to 100, or channels, to use to filter the metrics returned. Metric data is retrieved only for the resources associated with the queues or channels included in the filter. You can include both queue IDs and queue ARNs in the same request. Both VOICE and CHAT channels are supported.
- `HistoricalMetrics`: The metrics to retrieve. Specify the name, unit, and statistic for each metric. The following historical metrics are available. For a description of each metric, see Historical Metrics Definitions in the Amazon Connect Administrator Guide. ABANDON_TIME Unit: SECONDS Statistic: AVG AFTER_CONTACT_WORK_TIME Unit: SECONDS Statistic: AVG API_CONTACTS_HANDLED Unit: COUNT Statistic: SUM CALLBACK_CONTACTS_HANDLED Unit: COUNT Statistic: SUM CONTACTS_ABANDONED Unit: COUNT Statistic: SUM CONTACTS_AGENT_HUNG_UP_FIRST Unit: COUNT Statistic: SUM CONTACTS_CONSULTED Unit: COUNT Statistic: SUM CONTACTS_HANDLED Unit: COUNT Statistic: SUM CONTACTS_HANDLED_INCOMING Unit: COUNT Statistic: SUM CONTACTS_HANDLED_OUTBOUND Unit: COUNT Statistic: SUM CONTACTS_HOLD_ABANDONS Unit: COUNT Statistic: SUM CONTACTS_MISSED Unit: COUNT Statistic: SUM CONTACTS_QUEUED Unit: COUNT Statistic: SUM CONTACTS_TRANSFERRED_IN Unit: COUNT Statistic: SUM CONTACTS_TRANSFERRED_IN_FROM_QUEUE Unit: COUNT Statistic: SUM CONTACTS_TRANSFERRED_OUT Unit: COUNT Statistic: SUM CONTACTS_TRANSFERRED_OUT_FROM_QUEUE Unit: COUNT Statistic: SUM HANDLE_TIME Unit: SECONDS Statistic: AVG HOLD_TIME Unit: SECONDS Statistic: AVG INTERACTION_AND_HOLD_TIME Unit: SECONDS Statistic: AVG INTERACTION_TIME Unit: SECONDS Statistic: AVG OCCUPANCY Unit: PERCENT Statistic: AVG QUEUE_ANSWER_TIME Unit: SECONDS Statistic: AVG QUEUED_TIME Unit: SECONDS Statistic: MAX SERVICE_LEVEL Unit: PERCENT Statistic: AVG Threshold: Only \"Less than\" comparisons are supported, with the following service level thresholds: 15, 20, 25, 30, 45, 60, 90, 120, 180, 240, 300, 600
- `InstanceId`: The identifier of the Amazon Connect instance.
- `StartTime`: The timestamp, in UNIX Epoch time format, at which to start the reporting interval for the retrieval of historical metrics data. The time must be specified using a multiple of 5 minutes, such as 10:05, 10:10, 10:15. The start time cannot be earlier than 24 hours before the time of the request. Historical metrics are available only for 24 hours.
# Optional Parameters
- `Groupings`: The grouping applied to the metrics returned. For example, when results are grouped by queue, the metrics returned are grouped by queue. The values returned apply to the metrics for each queue rather than aggregated for all queues. The only supported grouping is QUEUE. If no grouping is specified, a summary of metrics for all queues is returned.
- `MaxResults`: The maximimum number of results to return per page.
- `NextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
get_metric_data(EndTime, Filters, HistoricalMetrics, InstanceId, StartTime; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/metrics/historical/$(InstanceId)", Dict{String, Any}("EndTime"=>EndTime, "Filters"=>Filters, "HistoricalMetrics"=>HistoricalMetrics, "StartTime"=>StartTime); aws_config=aws_config)
get_metric_data(EndTime, Filters, HistoricalMetrics, InstanceId, StartTime, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/metrics/historical/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("EndTime"=>EndTime, "Filters"=>Filters, "HistoricalMetrics"=>HistoricalMetrics, "StartTime"=>StartTime), args)); aws_config=aws_config)
"""
ListApprovedOrigins()
Returns a paginated list of all approved origins associated with the instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_approved_origins(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/approved-origins"; aws_config=aws_config)
list_approved_origins(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/approved-origins", args; aws_config=aws_config)
"""
ListContactFlows()
Provides information about the contact flows for the specified Amazon Connect instance. You can also create and update contact flows using the Amazon Connect Flow language. For more information about contact flows, see Contact Flows in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `contactFlowTypes`: The type of contact flow.
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_contact_flows(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact-flows-summary/$(InstanceId)"; aws_config=aws_config)
list_contact_flows(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/contact-flows-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListHoursOfOperations()
Provides information about the hours of operation for the specified Amazon Connect instance. For more information about hours of operation, see Set the Hours of Operation for a Queue in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_hours_of_operations(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/hours-of-operations-summary/$(InstanceId)"; aws_config=aws_config)
list_hours_of_operations(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/hours-of-operations-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListInstanceAttributes()
Returns a paginated list of all attribute types for the given instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_instance_attributes(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/attributes"; aws_config=aws_config)
list_instance_attributes(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/attributes", args; aws_config=aws_config)
"""
ListInstanceStorageConfigs()
Returns a paginated list of storage configs for the identified instance and resource type.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `resourceType`: A valid resource type.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_instance_storage_configs(InstanceId, resourceType; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/storage-configs", Dict{String, Any}("resourceType"=>resourceType); aws_config=aws_config)
list_instance_storage_configs(InstanceId, resourceType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/storage-configs", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("resourceType"=>resourceType), args)); aws_config=aws_config)
"""
ListInstances()
Return a list of instances which are in active state, creation-in-progress state, and failed state. Instances that aren't successfully created (they are in a failed state) are returned only for 24 hours after the CreateInstance API was invoked.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_instances(; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance"; aws_config=aws_config)
list_instances(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance", args; aws_config=aws_config)
"""
ListLambdaFunctions()
Returns a paginated list of all the Lambda functions that show up in the drop-down options in the relevant contact flow blocks.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_lambda_functions(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/lambda-functions"; aws_config=aws_config)
list_lambda_functions(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/lambda-functions", args; aws_config=aws_config)
"""
ListLexBots()
Returns a paginated list of all the Amazon Lex bots currently associated with the instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_lex_bots(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/lex-bots"; aws_config=aws_config)
list_lex_bots(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/lex-bots", args; aws_config=aws_config)
"""
ListPhoneNumbers()
Provides information about the phone numbers for the specified Amazon Connect instance. For more information about phone numbers, see Set Up Phone Numbers for Your Contact Center in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
- `phoneNumberCountryCodes`: The ISO country code.
- `phoneNumberTypes`: The type of phone number.
"""
list_phone_numbers(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/phone-numbers-summary/$(InstanceId)"; aws_config=aws_config)
list_phone_numbers(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/phone-numbers-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListPrompts()
Provides information about the prompts for the specified Amazon Connect instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_prompts(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/prompts-summary/$(InstanceId)"; aws_config=aws_config)
list_prompts(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/prompts-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListQueues()
Provides information about the queues for the specified Amazon Connect instance. For more information about queues, see Queues: Standard and Agent in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
- `queueTypes`: The type of queue.
"""
list_queues(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/queues-summary/$(InstanceId)"; aws_config=aws_config)
list_queues(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/queues-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListRoutingProfileQueues()
List the queues associated with a routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `RoutingProfileId`: The identifier of the routing profile.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_routing_profile_queues(InstanceId, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/queues"; aws_config=aws_config)
list_routing_profile_queues(InstanceId, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/queues", args; aws_config=aws_config)
"""
ListRoutingProfiles()
Provides summary information about the routing profiles for the specified Amazon Connect instance. For more information about routing profiles, see Routing Profiles and Create a Routing Profile in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_routing_profiles(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles-summary/$(InstanceId)"; aws_config=aws_config)
list_routing_profiles(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/routing-profiles-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListSecurityKeys()
Returns a paginated list of all security keys associated with the instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_security_keys(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/security-keys"; aws_config=aws_config)
list_security_keys(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/instance/$(InstanceId)/security-keys", args; aws_config=aws_config)
"""
ListSecurityProfiles()
Provides summary information about the security profiles for the specified Amazon Connect instance. For more information about security profiles, see Security Profiles in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_security_profiles(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/security-profiles-summary/$(InstanceId)"; aws_config=aws_config)
list_security_profiles(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/security-profiles-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListTagsForResource()
Lists the tags for the specified resource. For sample policies that use tags, see Amazon Connect Identity-Based Policy Examples in the Amazon Connect Administrator Guide.
# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource.
"""
list_tags_for_resource(resourceArn; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/tags/$(resourceArn)"; aws_config=aws_config)
list_tags_for_resource(resourceArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/tags/$(resourceArn)", args; aws_config=aws_config)
"""
ListUserHierarchyGroups()
Provides summary information about the hierarchy groups for the specified Amazon Connect instance. For more information about agent hierarchies, see Set Up Agent Hierarchies in the Amazon Connect Administrator Guide.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_user_hierarchy_groups(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-groups-summary/$(InstanceId)"; aws_config=aws_config)
list_user_hierarchy_groups(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/user-hierarchy-groups-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ListUsers()
Provides summary information about the users for the specified Amazon Connect instance.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `maxResults`: The maximimum number of results to return per page.
- `nextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_users(InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/users-summary/$(InstanceId)"; aws_config=aws_config)
list_users(InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("GET", "/users-summary/$(InstanceId)", args; aws_config=aws_config)
"""
ResumeContactRecording()
When a contact is being recorded, and the recording has been suspended using SuspendContactRecording, this API resumes recording the call. Only voice recordings are supported at this time.
# Required Parameters
- `ContactId`: The identifier of the contact.
- `InitialContactId`: The identifier of the contact. This is the identifier of the contact associated with the first interaction with the contact center.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
resume_contact_recording(ContactId, InitialContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/resume-recording", Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
resume_contact_recording(ContactId, InitialContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/resume-recording", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)
"""
StartChatContact()
Initiates a contact flow to start a new chat for the customer. Response of this API provides a token required to obtain credentials from the CreateParticipantConnection API in the Amazon Connect Participant Service. When a new chat contact is successfully created, clients need to subscribe to the participant’s connection for the created chat within 5 minutes. This is achieved by invoking CreateParticipantConnection with WEBSOCKET and CONNECTION_CREDENTIALS. A 429 error occurs in two situations: API rate limit is exceeded. API TPS throttling returns a TooManyRequests exception from the API Gateway. The quota for concurrent active chats is exceeded. Active chat throttling returns a LimitExceededException. For more information about how chat works, see Chat in the Amazon Connect Administrator Guide.
# Required Parameters
- `ContactFlowId`: The identifier of the contact flow for initiating the chat. To see the ContactFlowId in the Amazon Connect console user interface, on the navigation menu go to Routing, Contact Flows. Choose the contact flow. On the contact flow page, under the name of the contact flow, choose Show additional flow information. The ContactFlowId is the last part of the ARN, shown here in bold: arn:aws:connect:us-west-2:xxxxxxxxxxxx:instance/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/contact-flow/846ec553-a005-41c0-8341-xxxxxxxxxxxx
- `InstanceId`: The identifier of the Amazon Connect instance.
- `ParticipantDetails`: Information identifying the participant.
# Optional Parameters
- `Attributes`: A custom key-value pair using an attribute map. The attributes are standard Amazon Connect attributes, and can be accessed in contact flows just like any other contact attributes. There can be up to 32,768 UTF-8 bytes across all key-value pairs per contact. Attribute keys can include only alphanumeric, dash, and underscore characters.
- `ClientToken`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
- `InitialMessage`: The initial message to be sent to the newly created chat.
"""
start_chat_contact(ContactFlowId, InstanceId, ParticipantDetails; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact/chat", Dict{String, Any}("ContactFlowId"=>ContactFlowId, "InstanceId"=>InstanceId, "ParticipantDetails"=>ParticipantDetails, "ClientToken"=>string(uuid4())); aws_config=aws_config)
start_chat_contact(ContactFlowId, InstanceId, ParticipantDetails, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact/chat", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactFlowId"=>ContactFlowId, "InstanceId"=>InstanceId, "ParticipantDetails"=>ParticipantDetails, "ClientToken"=>string(uuid4())), args)); aws_config=aws_config)
"""
StartContactRecording()
This API starts recording the contact when the agent joins the call. StartContactRecording is a one-time action. For example, if you use StopContactRecording to stop recording an ongoing call, you can't use StartContactRecording to restart it. For scenarios where the recording has started and you want to suspend and resume it, such as when collecting sensitive information (for example, a credit card number), use SuspendContactRecording and ResumeContactRecording. You can use this API to override the recording behavior configured in the Set recording behavior block. Only voice recordings are supported at this time.
# Required Parameters
- `ContactId`: The identifier of the contact.
- `InitialContactId`: The identifier of the contact. This is the identifier of the contact associated with the first interaction with the contact center.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `VoiceRecordingConfiguration`: Who is being recorded.
"""
start_contact_recording(ContactId, InitialContactId, InstanceId, VoiceRecordingConfiguration; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/start-recording", Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId, "VoiceRecordingConfiguration"=>VoiceRecordingConfiguration); aws_config=aws_config)
start_contact_recording(ContactId, InitialContactId, InstanceId, VoiceRecordingConfiguration, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/start-recording", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId, "VoiceRecordingConfiguration"=>VoiceRecordingConfiguration), args)); aws_config=aws_config)
"""
StartOutboundVoiceContact()
This API places an outbound call to a contact, and then initiates the contact flow. It performs the actions in the contact flow that's specified (in ContactFlowId). Agents are not involved in initiating the outbound API (that is, dialing the contact). If the contact flow places an outbound call to a contact, and then puts the contact in queue, that's when the call is routed to the agent, like any other inbound case. There is a 60 second dialing timeout for this operation. If the call is not connected after 60 seconds, it fails. UK numbers with a 447 prefix are not allowed by default. Before you can dial these UK mobile numbers, you must submit a service quota increase request. For more information, see Amazon Connect Service Quotas in the Amazon Connect Administrator Guide.
# Required Parameters
- `ContactFlowId`: The identifier of the contact flow for the outbound call. To see the ContactFlowId in the Amazon Connect console user interface, on the navigation menu go to Routing, Contact Flows. Choose the contact flow. On the contact flow page, under the name of the contact flow, choose Show additional flow information. The ContactFlowId is the last part of the ARN, shown here in bold: arn:aws:connect:us-west-2:xxxxxxxxxxxx:instance/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/contact-flow/846ec553-a005-41c0-8341-xxxxxxxxxxxx
- `DestinationPhoneNumber`: The phone number of the customer, in E.164 format.
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `Attributes`: A custom key-value pair using an attribute map. The attributes are standard Amazon Connect attributes, and can be accessed in contact flows just like any other contact attributes. There can be up to 32,768 UTF-8 bytes across all key-value pairs per contact. Attribute keys can include only alphanumeric, dash, and underscore characters.
- `ClientToken`: A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. The token is valid for 7 days after creation. If a contact is already started, the contact ID is returned. If the contact is disconnected, a new contact is started.
- `QueueId`: The queue for the call. If you specify a queue, the phone displayed for caller ID is the phone number specified in the queue. If you do not specify a queue, the queue defined in the contact flow is used. If you do not specify a queue, you must specify a source phone number.
- `SourcePhoneNumber`: The phone number associated with the Amazon Connect instance, in E.164 format. If you do not specify a source phone number, you must specify a queue.
"""
start_outbound_voice_contact(ContactFlowId, DestinationPhoneNumber, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact/outbound-voice", Dict{String, Any}("ContactFlowId"=>ContactFlowId, "DestinationPhoneNumber"=>DestinationPhoneNumber, "InstanceId"=>InstanceId, "ClientToken"=>string(uuid4())); aws_config=aws_config)
start_outbound_voice_contact(ContactFlowId, DestinationPhoneNumber, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("PUT", "/contact/outbound-voice", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactFlowId"=>ContactFlowId, "DestinationPhoneNumber"=>DestinationPhoneNumber, "InstanceId"=>InstanceId, "ClientToken"=>string(uuid4())), args)); aws_config=aws_config)
"""
StopContact()
Ends the specified contact.
# Required Parameters
- `ContactId`: The ID of the contact.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
stop_contact(ContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/stop", Dict{String, Any}("ContactId"=>ContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
stop_contact(ContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/stop", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)
"""
StopContactRecording()
When a contact is being recorded, this API stops recording the call. StopContactRecording is a one-time action. If you use StopContactRecording to stop recording an ongoing call, you can't use StartContactRecording to restart it. For scenarios where the recording has started and you want to suspend it for sensitive information (for example, to collect a credit card number), and then restart it, use SuspendContactRecording and ResumeContactRecording. Only voice recordings are supported at this time.
# Required Parameters
- `ContactId`: The identifier of the contact.
- `InitialContactId`: The identifier of the contact. This is the identifier of the contact associated with the first interaction with the contact center.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
stop_contact_recording(ContactId, InitialContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/stop-recording", Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
stop_contact_recording(ContactId, InitialContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/stop-recording", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)
"""
SuspendContactRecording()
When a contact is being recorded, this API suspends recording the call. For example, you might suspend the call recording while collecting sensitive information, such as a credit card number. Then use ResumeContactRecording to restart recording. The period of time that the recording is suspended is filled with silence in the final recording. Only voice recordings are supported at this time.
# Required Parameters
- `ContactId`: The identifier of the contact.
- `InitialContactId`: The identifier of the contact. This is the identifier of the contact associated with the first interaction with the contact center.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
suspend_contact_recording(ContactId, InitialContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/suspend-recording", Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
suspend_contact_recording(ContactId, InitialContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/suspend-recording", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)
"""
TagResource()
Adds the specified tags to the specified resource. The supported resource types are users, routing profiles, and contact flows. For sample policies that use tags, see Amazon Connect Identity-Based Policy Examples in the Amazon Connect Administrator Guide.
# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource.
- `tags`: One or more tags. For example, { \"tags\": {\"key1\":\"value1\", \"key2\":\"value2\"} }.
"""
tag_resource(resourceArn, tags; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/tags/$(resourceArn)", Dict{String, Any}("tags"=>tags); aws_config=aws_config)
tag_resource(resourceArn, tags, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tags"=>tags), args)); aws_config=aws_config)
"""
UntagResource()
Removes the specified tags from the specified resource.
# Required Parameters
- `resourceArn`: The Amazon Resource Name (ARN) of the resource.
- `tagKeys`: The tag keys.
"""
untag_resource(resourceArn, tagKeys; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/tags/$(resourceArn)", Dict{String, Any}("tagKeys"=>tagKeys); aws_config=aws_config)
untag_resource(resourceArn, tagKeys, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("DELETE", "/tags/$(resourceArn)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("tagKeys"=>tagKeys), args)); aws_config=aws_config)
"""
UpdateContactAttributes()
Creates or updates the contact attributes associated with the specified contact. You can add or update attributes for both ongoing and completed contacts. For example, you can update the customer's name or the reason the customer called while the call is active, or add notes about steps that the agent took during the call that are displayed to the next agent that takes the call. You can also update attributes for a contact using data from your CRM application and save the data with the contact in Amazon Connect. You could also flag calls for additional analysis, such as legal review or identifying abusive callers. Contact attributes are available in Amazon Connect for 24 months, and are then deleted. Important: You cannot use the operation to update attributes for contacts that occurred prior to the release of the API, September 12, 2018. You can update attributes only for contacts that started after the release of the API. If you attempt to update attributes for a contact that occurred prior to the release of the API, a 400 error is returned. This applies also to queued callbacks that were initiated prior to the release of the API but are still active in your instance.
# Required Parameters
- `Attributes`: The Amazon Connect attributes. These attributes can be accessed in contact flows just like any other contact attributes. You can have up to 32,768 UTF-8 bytes across all attributes for a contact. Attribute keys can include only alphanumeric, dash, and underscore characters.
- `InitialContactId`: The identifier of the contact. This is the identifier of the contact associated with the first interaction with the contact center.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
update_contact_attributes(Attributes, InitialContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/attributes", Dict{String, Any}("Attributes"=>Attributes, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
update_contact_attributes(Attributes, InitialContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact/attributes", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Attributes"=>Attributes, "InitialContactId"=>InitialContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)
"""
UpdateContactFlowContent()
Updates the specified contact flow. You can also create and update contact flows using the Amazon Connect Flow language.
# Required Parameters
- `ContactFlowId`: The identifier of the contact flow.
- `Content`: The JSON string that represents contact flow’s content. For an example, see Example contact flow in Amazon Connect Flow language in the Amazon Connect Administrator Guide.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
update_contact_flow_content(ContactFlowId, Content, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact-flows/$(InstanceId)/$(ContactFlowId)/content", Dict{String, Any}("Content"=>Content); aws_config=aws_config)
update_contact_flow_content(ContactFlowId, Content, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact-flows/$(InstanceId)/$(ContactFlowId)/content", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Content"=>Content), args)); aws_config=aws_config)
"""
UpdateContactFlowName()
The name of the contact flow. You can also create and update contact flows using the Amazon Connect Flow language.
# Required Parameters
- `ContactFlowId`: The identifier of the contact flow.
- `InstanceId`: The identifier of the Amazon Connect instance.
# Optional Parameters
- `Description`: The description of the contact flow.
- `Name`: The name of the contact flow.
"""
update_contact_flow_name(ContactFlowId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact-flows/$(InstanceId)/$(ContactFlowId)/name"; aws_config=aws_config)
update_contact_flow_name(ContactFlowId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/contact-flows/$(InstanceId)/$(ContactFlowId)/name", args; aws_config=aws_config)
"""
UpdateInstanceAttribute()
Updates the value for the specified attribute type.
# Required Parameters
- `AttributeType`: The type of attribute.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Value`: The value for the attribute. Maximum character limit is 100.
"""
update_instance_attribute(AttributeType, InstanceId, Value; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/instance/$(InstanceId)/attribute/$(AttributeType)", Dict{String, Any}("Value"=>Value); aws_config=aws_config)
update_instance_attribute(AttributeType, InstanceId, Value, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/instance/$(InstanceId)/attribute/$(AttributeType)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Value"=>Value), args)); aws_config=aws_config)
"""
UpdateInstanceStorageConfig()
Updates an existing configuration for a resource type. This API is idempotent.
# Required Parameters
- `AssociationId`: The existing association identifier that uniquely identifies the resource type and storage config for the given instance ID.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `StorageConfig`:
- `resourceType`: A valid resource type.
"""
update_instance_storage_config(AssociationId, InstanceId, StorageConfig, resourceType; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}("StorageConfig"=>StorageConfig, "resourceType"=>resourceType); aws_config=aws_config)
update_instance_storage_config(AssociationId, InstanceId, StorageConfig, resourceType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/instance/$(InstanceId)/storage-config/$(AssociationId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("StorageConfig"=>StorageConfig, "resourceType"=>resourceType), args)); aws_config=aws_config)
"""
UpdateRoutingProfileConcurrency()
Updates the channels that agents can handle in the Contact Control Panel (CCP) for a routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `MediaConcurrencies`: The channels agents can handle in the Contact Control Panel (CCP).
- `RoutingProfileId`: The identifier of the routing profile.
"""
update_routing_profile_concurrency(InstanceId, MediaConcurrencies, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/concurrency", Dict{String, Any}("MediaConcurrencies"=>MediaConcurrencies); aws_config=aws_config)
update_routing_profile_concurrency(InstanceId, MediaConcurrencies, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/concurrency", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("MediaConcurrencies"=>MediaConcurrencies), args)); aws_config=aws_config)
"""
UpdateRoutingProfileDefaultOutboundQueue()
Updates the default outbound queue of a routing profile.
# Required Parameters
- `DefaultOutboundQueueId`: The identifier for the default outbound queue.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `RoutingProfileId`: The identifier of the routing profile.
"""
update_routing_profile_default_outbound_queue(DefaultOutboundQueueId, InstanceId, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/default-outbound-queue", Dict{String, Any}("DefaultOutboundQueueId"=>DefaultOutboundQueueId); aws_config=aws_config)
update_routing_profile_default_outbound_queue(DefaultOutboundQueueId, InstanceId, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/default-outbound-queue", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DefaultOutboundQueueId"=>DefaultOutboundQueueId), args)); aws_config=aws_config)
"""
UpdateRoutingProfileName()
Updates the name and description of a routing profile. The request accepts the following data in JSON format. At least Name or Description must be provided.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `RoutingProfileId`: The identifier of the routing profile.
# Optional Parameters
- `Description`: The description of the routing profile. Must not be more than 250 characters.
- `Name`: The name of the routing profile. Must not be more than 127 characters.
"""
update_routing_profile_name(InstanceId, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/name"; aws_config=aws_config)
update_routing_profile_name(InstanceId, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/name", args; aws_config=aws_config)
"""
UpdateRoutingProfileQueues()
Updates the properties associated with a set of queues for a routing profile.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `QueueConfigs`: The queues to be updated for this routing profile.
- `RoutingProfileId`: The identifier of the routing profile.
"""
update_routing_profile_queues(InstanceId, QueueConfigs, RoutingProfileId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/queues", Dict{String, Any}("QueueConfigs"=>QueueConfigs); aws_config=aws_config)
update_routing_profile_queues(InstanceId, QueueConfigs, RoutingProfileId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/routing-profiles/$(InstanceId)/$(RoutingProfileId)/queues", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("QueueConfigs"=>QueueConfigs), args)); aws_config=aws_config)
"""
UpdateUserHierarchy()
Assigns the specified hierarchy group to the specified user.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `UserId`: The identifier of the user account.
# Optional Parameters
- `HierarchyGroupId`: The identifier of the hierarchy group.
"""
update_user_hierarchy(InstanceId, UserId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/hierarchy"; aws_config=aws_config)
update_user_hierarchy(InstanceId, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/hierarchy", args; aws_config=aws_config)
"""
UpdateUserHierarchyGroupName()
Updates the name of the user hierarchy group.
# Required Parameters
- `HierarchyGroupId`: The identifier of the hierarchy group.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `Name`: The name of the hierarchy group. Must not be more than 100 characters.
"""
update_user_hierarchy_group_name(HierarchyGroupId, InstanceId, Name; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)/name", Dict{String, Any}("Name"=>Name); aws_config=aws_config)
update_user_hierarchy_group_name(HierarchyGroupId, InstanceId, Name, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/user-hierarchy-groups/$(InstanceId)/$(HierarchyGroupId)/name", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Name"=>Name), args)); aws_config=aws_config)
"""
UpdateUserHierarchyStructure()
Updates the user hierarchy structure: add, remove, and rename user hierarchy levels.
# Required Parameters
- `HierarchyStructure`: The hierarchy levels to update.
- `InstanceId`: The identifier of the Amazon Connect instance.
"""
update_user_hierarchy_structure(HierarchyStructure, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/user-hierarchy-structure/$(InstanceId)", Dict{String, Any}("HierarchyStructure"=>HierarchyStructure); aws_config=aws_config)
update_user_hierarchy_structure(HierarchyStructure, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/user-hierarchy-structure/$(InstanceId)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("HierarchyStructure"=>HierarchyStructure), args)); aws_config=aws_config)
"""
UpdateUserIdentityInfo()
Updates the identity information for the specified user. Someone with the ability to invoke UpdateUserIndentityInfo can change the login credentials of other users by changing their email address. This poses a security risk to your organization. They can change the email address of a user to the attacker's email address, and then reset the password through email. We strongly recommend limiting who has the ability to invoke UpdateUserIndentityInfo. For more information, see Best Practices for Security Profiles in the Amazon Connect Administrator Guide.
# Required Parameters
- `IdentityInfo`: The identity information for the user.
- `InstanceId`: The identifier of the Amazon Connect instance.
- `UserId`: The identifier of the user account.
"""
update_user_identity_info(IdentityInfo, InstanceId, UserId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/identity-info", Dict{String, Any}("IdentityInfo"=>IdentityInfo); aws_config=aws_config)
update_user_identity_info(IdentityInfo, InstanceId, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/identity-info", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("IdentityInfo"=>IdentityInfo), args)); aws_config=aws_config)
"""
UpdateUserPhoneConfig()
Updates the phone configuration settings for the specified user.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `PhoneConfig`: Information about phone configuration settings for the user.
- `UserId`: The identifier of the user account.
"""
update_user_phone_config(InstanceId, PhoneConfig, UserId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/phone-config", Dict{String, Any}("PhoneConfig"=>PhoneConfig); aws_config=aws_config)
update_user_phone_config(InstanceId, PhoneConfig, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/phone-config", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("PhoneConfig"=>PhoneConfig), args)); aws_config=aws_config)
"""
UpdateUserRoutingProfile()
Assigns the specified routing profile to the specified user.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `RoutingProfileId`: The identifier of the routing profile for the user.
- `UserId`: The identifier of the user account.
"""
update_user_routing_profile(InstanceId, RoutingProfileId, UserId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/routing-profile", Dict{String, Any}("RoutingProfileId"=>RoutingProfileId); aws_config=aws_config)
update_user_routing_profile(InstanceId, RoutingProfileId, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/routing-profile", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("RoutingProfileId"=>RoutingProfileId), args)); aws_config=aws_config)
"""
UpdateUserSecurityProfiles()
Assigns the specified security profiles to the specified user.
# Required Parameters
- `InstanceId`: The identifier of the Amazon Connect instance.
- `SecurityProfileIds`: The identifiers of the security profiles for the user.
- `UserId`: The identifier of the user account.
"""
update_user_security_profiles(InstanceId, SecurityProfileIds, UserId; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/security-profiles", Dict{String, Any}("SecurityProfileIds"=>SecurityProfileIds); aws_config=aws_config)
update_user_security_profiles(InstanceId, SecurityProfileIds, UserId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect("POST", "/users/$(InstanceId)/$(UserId)/security-profiles", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("SecurityProfileIds"=>SecurityProfileIds), args)); aws_config=aws_config)
|
# Miscellaneous items.
Maybe{T} = Union{T,Nothing} where {T}
function acos_(x::Float64)
if abs(x) > 1.0
if 1.0 < x < 1.0 + 1e-12
x = 1.0
elseif -1.0 - 1e-12 < x < -1.0
x = -1.0
else
error("Invalid cosine: $(x).")
end
end
acos(x)
end
"Index of oxygen atom."
const AO = 1
"Index of first hydrogen atom."
const AH1 = 2
"Index of second hydrogen atom."
const AH2 = 3
"Water atomic masses (g / mol)."
const MS = [15.999, 1.008, 1.008]
"Fractional masses of atoms in a single water molecule."
const MS_FRAC = MS ./ sum(MS)
"First molecule of constraint."
const CN1 = 1
"Second molecule of constraint."
const CN2 = 2
"Bead index for constraint."
const CJ = 1
bead_prev(P::Int, j::Int) = mod(j - 1, 1:P)
bead_next(P::Int, j::Int) = mod(j + 1, 1:P)
|
### BasicContParamIOStream
type BasicContParamIOStream <: ParameterIOStream{Continuous}
value::Union{IOStream, Void}
loglikelihood::Union{IOStream, Void}
logprior::Union{IOStream, Void}
logtarget::Union{IOStream, Void}
gradloglikelihood::Union{IOStream, Void}
gradlogprior::Union{IOStream, Void}
gradlogtarget::Union{IOStream, Void}
tensorloglikelihood::Union{IOStream, Void}
tensorlogprior::Union{IOStream, Void}
tensorlogtarget::Union{IOStream, Void}
dtensorloglikelihood::Union{IOStream, Void}
dtensorlogprior::Union{IOStream, Void}
dtensorlogtarget::Union{IOStream, Void}
diagnosticvalues::Union{IOStream, Void}
names::Vector{AbstractString}
size::Tuple
n::Integer
diagnostickeys::Vector{Symbol}
open::Function
close::Function
mark::Function
reset::Function
flush::Function
write::Function
function BasicContParamIOStream(
size::Tuple,
n::Integer,
streams::Vector{Union{IOStream, Void}},
diagnostickeys::Vector{Symbol}=Symbol[],
filenames::Vector{AbstractString}=[(streams[i] == nothing) ? "" : streams[i].name[7:end-1] for i in 1:14]
)
instance = new()
fnames = fieldnames(BasicContParamIOStream)
for i in 1:14
setfield!(instance, fnames[i], streams[i])
end
instance.names = filenames
instance.size = size
instance.n = n
instance.diagnostickeys = diagnostickeys
instance.open = eval(codegen(:open, instance, fnames))
instance.close = eval(codegen(:close, instance, fnames))
instance.mark = eval(codegen(:mark, instance, fnames))
instance.reset = eval(codegen(:reset, instance, fnames))
instance.flush = eval(codegen(:flush, instance, fnames))
instance.write = eval(codegen(:write, instance, fnames))
instance
end
end
function BasicContParamIOStream(
size::Tuple,
n::Integer,
filenames::Vector{AbstractString},
diagnostickeys::Vector{Symbol}=Symbol[],
mode::AbstractString="w"
)
fnames = fieldnames(BasicContParamIOStream)
BasicContParamIOStream(
size,
n,
Union{IOStream, Void}[isempty(filenames[i]) ? nothing : open(filenames[i], mode) for i in 1:14],
diagnostickeys,
filenames
)
end
function BasicContParamIOStream(
size::Tuple,
n::Integer;
monitor::Vector{Bool}=[true; fill(false, 12)],
filepath::AbstractString="",
filesuffix::AbstractString="csv",
diagnostickeys::Vector{Symbol}=Symbol[],
mode::AbstractString="w"
)
fnames = fieldnames(BasicContParamIOStream)
filenames = Array(AbstractString, 14)
for i in 1:13
filenames[i] = (monitor[i] == false ? "" : joinpath(filepath, string(fnames[i])*"."*filesuffix))
end
filenames[14] = (isempty(diagnostickeys) ? "" : joinpath(filepath, "diagnosticvalues."*filesuffix))
BasicContParamIOStream(size, n, filenames, diagnostickeys, mode)
end
function BasicContParamIOStream(
size::Tuple,
n::Integer,
monitor::Vector{Symbol};
filepath::AbstractString="",
filesuffix::AbstractString="csv",
diagnostickeys::Vector{Symbol}=Symbol[],
mode::AbstractString="w"
)
fnames = fieldnames(BasicContParamIOStream)
BasicContParamIOStream(
size,
n,
monitor=[fnames[i] in monitor ? true : false for i in 1:13],
filepath=filepath,
filesuffix=filesuffix,
diagnostickeys=diagnostickeys,
mode=mode
)
end
function codegen(::Type{Val{:open}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol
push!(body,:(_iostream.names = _names))
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(body, :(setfield!(_iostream, $(QuoteNode(f)), open(_names[$i], _mode))))
end
end
@gensym _open
quote
function $_open{S<:AbstractString}(_iostream::BasicContParamIOStream, _names::Vector{S}, _mode::AbstractString="w")
$(body...)
end
end
end
function codegen(::Type{Val{:close}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(body, :(close(getfield(_iostream, $(QuoteNode(f))))))
end
end
@gensym _close
quote
function $_close(_iostream::BasicContParamIOStream)
$(body...)
end
end
end
function codegen(::Type{Val{:mark}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(body, :(mark(getfield(_iostream, $(QuoteNode(f))))))
end
end
@gensym _mark
quote
function $_mark(_iostream::BasicContParamIOStream)
$(body...)
end
end
end
function codegen(::Type{Val{:reset}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(body, :(reset(getfield($(iostream), $(QuoteNode(f))))))
end
end
@gensym _reset
quote
function $_reset(_iostream::BasicContParamIOStream)
$(body...)
end
end
end
function codegen(::Type{Val{:flush}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(body, :(flush(getfield($(iostream), $(QuoteNode(f))))))
end
end
@gensym _flush
quote
function $_flush(_iostream::BasicContParamIOStream)
$(body...)
end
end
end
function codegen(::Type{Val{:write}}, iostream::BasicContParamIOStream, fnames::Vector{Symbol})
body = []
local f::Symbol # f must be local to avoid compiler errors. Alternatively, this variable declaration can be omitted
for i in 1:14
if iostream.(fnames[i]) != nothing
f = fnames[i]
push!(
body,
:(write(getfield($(iostream), $(QuoteNode(f))), join(getfield(_state, $(QuoteNode(f))), ','), "\n"))
)
end
end
@gensym _write
quote
function $_write{F<:VariateForm}(_iostream::BasicContParamIOStream, _state::ParameterState{Continuous, F})
$(body...)
end
end
end
function Base.write(iostream::BasicContParamIOStream, nstate::BasicContUnvParameterNState)
fnames = fieldnames(BasicContParamIOStream)
for i in 1:13
if iostream.(fnames[i]) != nothing
writedlm(iostream.(fnames[i]), nstate.(fnames[i]))
end
end
if iostream.diagnosticvalues != nothing
writedlm(iostream.diagnosticvalues, nstate.diagnosticvalues', ',')
end
end
function Base.write(iostream::BasicContParamIOStream, nstate::BasicContMuvParameterNState)
fnames = fieldnames(BasicContParamIOStream)
for i in 2:4
if iostream.(fnames[i]) != nothing
writedlm(iostream.(fnames[i]), nstate.(fnames[i]))
end
end
for i in (1, 5, 6, 7, 14)
if iostream.(fnames[i]) != nothing
writedlm(iostream.(fnames[i]), nstate.(fnames[i])', ',')
end
end
for i in 8:10
if iostream.(fnames[i]) != nothing
statelen = abs2(iostream.size)
for j in 1:nstate.n
write(iostream.stream, join(nstate.value[1+(j-1)*statelen:j*statelen], ','), "\n")
end
end
end
for i in 11:13
if iostream.(fnames[i]) != nothing
statelen = iostream.size^3
for j in 1:nstate.n
write(iostream.stream, join(nstate.value[1+(j-1)*statelen:j*statelen], ','), "\n")
end
end
end
end
function Base.read!{N<:Real}(iostream::BasicContParamIOStream, nstate::BasicContUnvParameterNState{N})
fnames = fieldnames(BasicContParamIOStream)
for i in 1:13
if iostream.(fnames[i]) != nothing
setfield!(nstate, fnames[i], vec(readdlm(iostream.(fnames[i]), ',', N)))
end
end
if iostream.diagnosticvalues != nothing
nstate.diagnosticvalues = readdlm(iostream.diagnosticvalues, ',', Any)'
end
end
function Base.read!{N<:Real}(iostream::BasicContParamIOStream, nstate::BasicContMuvParameterNState{N})
fnames = fieldnames(BasicContParamIOStream)
for i in 2:4
if iostream.(fnames[i]) != nothing
setfield!(nstate, fnames[i], vec(readdlm(iostream.(fnames[i]), ',', N)))
end
end
for i in (1, 5, 6, 7)
if iostream.(fnames[i]) != nothing
setfield!(nstate, fnames[i], readdlm(iostream.(fnames[i]), ',', N)')
end
end
for i in 8:10
if iostream.(fnames[i]) != nothing
statelen = abs2(iostream.size)
line = 1
while !eof(iostream.stream)
nstate.value[1+(line-1)*statelen:line*statelen] =
[parse(N, c) for c in split(chomp(readline(iostream.stream)), ',')]
line += 1
end
end
end
for i in 11:13
if iostream.(fnames[i]) != nothing
statelen = iostream.size^3
line = 1
while !eof(iostream.stream)
nstate.value[1+(line-1)*statelen:line*statelen] =
[parse(N, c) for c in split(chomp(readline(iostream.stream)), ',')]
line += 1
end
end
end
if iostream.diagnosticvalues != nothing
nstate.diagnosticvalues = readdlm(iostream.diagnosticvalues, ',', Any)'
end
end
function Base.read{N<:Real}(iostream::BasicContParamIOStream, T::Type{N})
nstate::ContinuousParameterNState
fnames = fieldnames(BasicContParamIOStream)
l = length(iostream.size)
if l == 0
nstate = BasicContUnvParameterNState(
iostream.n,
[iostream.(fnames[i]) != nothing ? true : false for i in 1:13],
iostream.diagnostickeys,
T
)
elseif l == 1
nstate = BasicContMuvParameterNState(
iostream.size[1],
iostream.n,
[iostream.(fnames[i]) != nothing ? true : false for i in 1:13],
iostream.diagnostickeys,
T
)
else
error("BasicContParamIOStream.size must be a tuple of length 0 or 1, got $(iostream.size) length")
end
read!(iostream, nstate)
nstate
end
function Base.show(io::IO, iostream::BasicContParamIOStream)
fnames = fieldnames(BasicContParamIOStream)
fbool = map(n -> getfield(iostream, n) != nothing, fnames[1:13])
indentation = " "
println(io, "BasicContParamIOStream:")
println(io, indentation*"state size = $(iostream.size)")
println(io, indentation*"number of states = $(iostream.n)")
print(io, indentation*"monitored components:")
if !any(fbool)
println(io, " none")
else
print(io, "\n")
for i in 1:13
if fbool[i]
println(io, string(indentation^2, fnames[i]))
end
end
end
print(io, indentation*"diagnostics:")
if isempty(iostream.diagnostickeys)
print(io, " none")
else
for k in iostream.diagnostickeys
print(io, "\n")
print(io, string(indentation^2, k))
end
end
end
|
@info("Testing conditioning of non-orth 3B SHIP Basis")
using Test
using SHIPs, JuLIP, JuLIP.Testing, QuadGK, LinearAlgebra, SHIPs.JacobiPolys
using SHIPs: TransformedJacobi, transform, transform_d, eval_basis!,
alloc_B, alloc_temp
##
get_IN(N) = collect((shpB.idx_Bll[N][1]+1):(shpB.idx_Bll[N][end]+shpB.len_Bll[N][end]))
# function barrier
gramian(N, shpB, Nsamples=100_000; normalise=false) =
gramian(N, get_IN(N), alloc_temp(shpB), alloc_B(shpB), shpB, Nsamples, normalise)
function gramian(N, IN, tmp, B, shpB, Nsamples = 100_000, normalise = false)
Zs = zeros(Int16, N)
lenB = length(IN)
G = zeros(Float64, lenB, lenB)
for n = 1:Nsamples
Rs = SHIPs.Utils.rand(shpB.J, N)
eval_basis!(B, tmp, shpB, Rs, Zs, 0)
for j = 1:lenB
Bj = B[IN[j]]'
@simd for i = 1:lenB
@inbounds G[i,j] += Bj * B[IN[i]]
end
end
end
if normalise
g = diag(G)
for i = 1:lenB, j = 1:lenB
G[i,j] /= sqrt(g[i]*g[j])
end
end
return G / Nsamples
end
##
Nmax = 4
Nsamples = 100_000
rl, ru = 0.5, 3.0
fcut = PolyCutoff2s(2, rl, ru)
trans = PolyTransform(2, 1.0)
shpB = SHIPBasis( SparseSHIP(Nmax, 10), trans, fcut )
@info("Conditions numbers of gramians")
for N = 1:Nmax
GN = gramian(N, shpB, Nsamples, normalise=false)
@show N, cond(GN)
end
@info("Conditions numbers of normalised gramians")
for N = 1:Nmax
GN = gramian(N, shpB, Nsamples, normalise=true)
@show N, cond(GN)
end
|
# parses color specifications of form "0xRRGGBB" or "#RRGGBB" into colors to form a gradient
Base.parse(::Type{Gradient},startstr::AbstractString, endstr::AbstractString, nilstr::AbstractString) =
Gradient(parse(RGB8bit,startstr),parse(RGB8bit,endstr),parse(RGB8bit,nilstr))
Base.parse(::Type{Gradient},str::AbstractString) =
parse(Gradient,split(str)...)
# example: 0x7fa656 0x8bfd32 0x5fe995 (0.379184,-0.312113) zoom2.99581e-07 pow0.474523 affine0
function Base.parse(::Type{CameraSpec},specstr::AbstractString)
spec=split(specstr)
return CameraSpec(parse(Gradient,join(spec[1:3]," ")),parse_complex(spec[4]),
parse_zoom(spec[5]),parse_pow(spec[6]),parse_affine(spec[7]))
end
# parses string "(re,im)" into a complex number Complex(re,im)
parse_complex(str::AbstractString)=Complex([parse(Float64,x) for x in split(str[2:end-1],",")]...)
# parses string "zoom1.2345" into a floating point number with everything after the 'zoom'
parse_zoom(str::AbstractString)=parse(Float64,str[5:end])
# parses string "pow1.2345" into a floating point number with everything after the 'pow'
parse_pow(str::AbstractString)=parse(Float64,str[4:end])
# parses string "affine0" into a boolean depending on whether the number after 'affine' is 0 or 1
parse_affine(str::AbstractString)=convert(Bool,parse(Int8,str[7]))
|
# Autogenerated wrapper script for pandoc_crossref_jll for x86_64-w64-mingw32
export pandoc_crossref
JLLWrappers.@generate_wrapper_header("pandoc_crossref")
JLLWrappers.@declare_executable_product(pandoc_crossref)
function __init__()
JLLWrappers.@generate_init_header()
JLLWrappers.@init_executable_product(
pandoc_crossref,
"bin\\pandoc-crossref.exe",
)
JLLWrappers.@generate_init_footer()
end # __init__()
|
using Documenter, AerostructuralDynamics
makedocs(;
modules = [AerostructuralDynamics],
pages = [
"Home" => "index.md",
"Getting Started" => "guide.md",
"Examples" => "examples.md",
"Model Documentation" => [
"Aerodynamic Models" => [
"Steady Thin Airfoil Theory" => joinpath("aerodynamics", "steady.md"),
"Quasi-Steady Thin Airfoil Theory" => joinpath("aerodynamics", "quasisteady.md"),
"Wagner's Function" => joinpath("aerodynamics", "wagner.md"),
"Peters' Finite State" => joinpath("aerodynamics", "peters.md"),
"Lifting Line" => joinpath("aerodynamics", "liftingline.md"),
],
"Structural Models" => [
"Typical Section" => joinpath("structures", "section.md"),
"Rigid Body" => joinpath("structures", "rigidbody.md"),
"Geometrically Exact Beam Theory" => joinpath("structures", "gxbeam.md"),
],
"Coupled Models" => [
"Steady Thin Airfoil Theory + Typical Section" => joinpath("couplings", "steady-section.md"),
"Quasi-Steady Thin Airfoil Theory + Typical Section" => joinpath("couplings", "quasisteady-section.md"),
"Wagner's Function + Typical Section" => joinpath("couplings", "wagner-section.md"),
"Peters' Finite State + Typical Section" => joinpath("couplings", "peters-section.md"),
"Lifting Line + Rigid Body" => joinpath("couplings", "liftingline-rigidbody.md"),
"Lifting Line + Geometrically Exact Beam Theory" => joinpath("couplings", "liftingline-gxbeam.md"),
"Lifting Line + Geometrically Exact Beam Theory + Rigid Body" => joinpath("couplings", "liftingline-gxbeam-rigidbody.md"),
],
],
"Library" => [
"Public" => joinpath("library", "public.md"),
"Internals" => joinpath("library", "internals.md"),
],
"Developer Guide" => "developer.md",
],
sitename = "AerostructuralDynamics.jl",
authors = "Taylor McDonnell <taylormcd@byu.edu>",
# format = LaTeX(), # uncomment for PDF output
)
deploydocs(
repo = "github.com/byuflowlab/AerostructuralDynamics.jl.git",
devbranch = "main",
)
|
# open-loop-bank-model.jl
# SimLynx Open Loop Processing Example
using SimLynx
SimLynx.greet()
using Distributions: Exponential, Uniform
using Random
const N_TELLERS = 2
const MEAN_INTERARRIVAL_TIME = 4.0
const MIN_SERVICE_TIME = 2.0
const MAX_SERVICE_TIME = 10.0
"Process to generate n customers arriving into the system."
@process generator(n::Integer) begin
dist = Exponential(MEAN_INTERARRIVAL_TIME)
for i = 1:n
@schedule now customer(i)
# We don't want to wait after the last customer, which could extend the
# simulation time past the last customer leaving.
if i < n
work(rand(dist))
end
end
end
"The ith customer into the system."
@process customer(i::Integer) begin
dist = Uniform(MIN_SERVICE_TIME, MAX_SERVICE_TIME)
@with_resource tellers begin
work(rand(dist))
end
end
"Run the simulation for n customers."
function run_simulation(n1::Integer, n2::Integer)
@assert n1 > 0 && n2 > 0
println("SimLynx Open Loop Processing Example")
println("Number of runs = $n1, number of customers = $n2")
println("Single Queue, $N_TELLERS Teller Bank Model")
@simulation begin
avg_wait = Variable{Float64}(data=:tally, history=true)
for i = 1:n1
@simulation begin
global tellers = Resource(N_TELLERS, "tellers")
@schedule at 0.0 generator(n2)
start_simulation()
avg_wait.value = tellers.wait.stats.mean
end
end
print_stats(avg_wait, title="Average Wait Statistics")
plot_history(avg_wait, title="Average Wait History")
end
end
run_simulation(10_000, 100)
|
module Aircrafts
include("aircrafts/C310.jl")
include("aircrafts/F16.jl")
include("trimmer.jl")
end
|
using DiffEqBayes, BenchmarkTools
using OrdinaryDiffEq, RecursiveArrayTools, Distributions, ParameterizedFunctions, Mamba, BenchmarkTools
using Plots
gr(fmt=:png)
fitz = @ode_def FitzhughNagumo begin
dv = v - v^3/3 -w + l
dw = τinv*(v + a - b*w)
end a b τinv l
prob_ode_fitzhughnagumo = ODEProblem(fitz,[1.0,1.0],(0.0,10.0),[0.7,0.8,1/12.5,0.5])
sol = solve(prob_ode_fitzhughnagumo, Tsit5())
t = collect(range(1,stop=10,length=10))
sig = 0.20
data = convert(Array, VectorOfArray([(sol(t[i]) + sig*randn(2)) for i in 1:length(t)]))
scatter(t, data[1,:])
scatter!(t, data[2,:])
plot!(sol)
priors = [Truncated(Normal(1.0,0.5),0,1.5),Truncated(Normal(1.0,0.5),0,1.5),Truncated(Normal(0.0,0.5),-0.5,0.5),Truncated(Normal(0.5,0.5),0,1)]
@time bayesian_result_stan = stan_inference(prob_ode_fitzhughnagumo,t,data,priors;reltol=1e-5,abstol=1e-5,vars =(StanODEData(),InverseGamma(3,2)))
plot_chain(bayesian_result_stan)
@time bayesian_result_turing = turing_inference(prob_ode_fitzhughnagumo,Tsit5(),t,data,priors)
plot_chain(bayesian_result_turing)
using DiffEqBenchmarks
DiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])
|
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg
name = "Pangomm"
version = v"2.49.1"
# Collection of sources required to complete build
sources = [
ArchiveSource("https://download.gnome.org/sources/pangomm/$(version.major).$(version.minor)/pangomm-$(version).tar.xz",
"a2272883152618fddea016a62f50eb23b9b056ab3c08f3b64422591e6a507bd5")
]
# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/pangomm*/
if [[ "${target}" == "${MACHTYPE}" ]]; then
# Delete host libexpat.so to avoid confusion
rm /usr/lib/libexpat*
fi
mkdir output && cd output
meson --cross-file=${MESON_TARGET_TOOLCHAIN} ..
ninja -j${nproc}
ninja install
"""
# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms(; experimental=true))
# We don't have armv6l Pango at the moment
filter!(p -> arch(p) != "armv6l", platforms)
# The products that we will ensure are always built
products = [
LibraryProduct(["libpangomm-$(version.major)", "libpangomm-$(version.major).48"], :libpangomm)
]
# Dependencies that must be installed before this package can be built
dependencies = [
Dependency(PackageSpec(name="Cairomm_jll", uuid="af74c99f-f0eb-54aa-aecc-a10e8fc65c17"); compat="~1.16.1")
Dependency(PackageSpec(name="Glibmm_jll", uuid="5d85a9da-21f7-5855-afec-cdc5039c46e8"); compat="~2.68.1")
Dependency(PackageSpec(name="Pango_jll", uuid="36c8627f-9965-5494-a995-c6b170f724f3"); compat="1.47.0")
BuildDependency(PackageSpec(name="Xorg_xorgproto_jll", uuid="c4d99508-4286-5418-9131-c86396af500b"))
]
# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6", preferred_gcc_version = v"7.1.0")
|
"""
The **pcl_surface** library deals with reconstructing the original surfaces
from 3D scans.
http://docs.pointclouds.org/trunk/group__surface.html
## Exports
$(EXPORTS)
"""
module PCLSurface
using DocStringExtensions
using LibPCL
using PCLCommon
using Cxx
const libpcl_surface = LibPCL.find_library_e("libpcl_surface")
try
Libdl.dlopen(libpcl_surface, Libdl.RTLD_GLOBAL)
catch e
warn("You might need to set DYLD_LIBRARY_PATH to load dependencies proeprty.")
rethrow(e)
end
end # module
|
function r2cf(n1::Integer, n2::Integer)
ret = Int[]
while n2 != 0
n1, (t1, n2) = n2, divrem(n1, n2)
push!(ret, t1)
end
ret
end
r2cf(r::Rational) = r2cf(numerator(r), denominator(r))
function r2cf(n1, n2, maxiter=20)
ret = Int[]
while n2 != 0 && maxiter > 0
n1, (t1, n2) = n2, divrem(n1, n2)
push!(ret, t1)
maxiter -= 1
end
ret
end
mutable struct NG
a1::Int
a::Int
b1::Int
b::Int
end
function ingress(ng, n)
ng.a, ng.a1= ng.a1, ng.a + ng.a1 * n
ng.b, ng.b1 = ng.b1, ng.b + ng.b1 * n
end
needterm(ng) = ng.b == 0 || ng.b1 == 0 || !(ng.a // ng.b == ng.a1 // ng.b1)
function egress(ng)
n = ng.a // ng.b
ng.a, ng.b = ng.b, ng.a - ng.b * n
ng.a1, ng.b1 = ng.b1, ng.a1 - ng.b1 * n
r2cf(n)
end
egress_done(ng) = (if needterm(ng) ng.a, ng.b = ng.a1, ng.b1 end; egress(ng))
done(ng) = ng.b == 0 && ng.b1 == 0
function testng()
data = [["[1;5,2] + 1/2", [2,1,0,2], [13,11]],
["[3;7] + 1/2", [2,1,0,2], [22, 7]],
["[3;7] divided by 4", [1,0,0,4], [22, 7]],
["[1;1] divided by sqrt(2)", [0,1,1,0], [1,sqrt(2)]]]
for d in data
str, ng, r = d[1], NG(d[2]...), d[3]
print(rpad(str, 25), "->")
for n in r2cf(r...)
if !needterm(ng)
print(" $(egress(ng))")
end
ingress(ng, n)
end
while true
print(" $(egress_done(ng))")
if done(ng)
println()
break
end
end
end
end
testng()
|
using PyPlot
using SpecialFunctions: erfcx
"""
ψ1(α, ϵ, N=100)
Approximates `(1+ϵ)^α - 1` by its Taylor expansion about `ϵ=0` using up to
`N` terms.
"""
function ψ1(α::T, ϵ::Complex{T}, N=100) where T <: AbstractFloat
s = Complex(α, zero(T))
term = s
for n = 1:N
term *= -( (n-α)/(n+1) ) * ϵ
s += term
if abs(term) < eps(T)
break
end
end
if abs(term) > 10*eps(T)
error("ψ1 expansion did not converge after $N terms")
end
return s
end
"""
ψ2(α, ϵ, N=100)
Approximates `(1+ϵ)^α - (1+αϵ)` by its Taylor expansion about `ϵ=0` using up
to `N` terms.
"""
function ψ2(α::T, ϵ::Complex{T}, N=100) where T <: AbstractFloat
s = Complex(-α * (1-α) / 2, zero(T))
term = s
for n = 1:N
term *= -( (n+1-α)/(n+2) ) * ϵ
s += term
if abs(term) < eps(T)
break
end
end
if abs(term) > 10*eps(T)
error("ψ1 expansion did not converge after $N terms")
end
return s
end
function H(α::T, β::T, w::Complex{T}, x::T, sep::T) where T <: AbstractFloat
xa = x^(1/α)
ϵ = ( w - xa ) / xa
if abs(ϵ) > sep
return w^(α-β) / (w^α-x) - 1 / (α*ϵ*x^(β/α))
else
return ( ψ1(α-β,ϵ) - (1+ϵ)^(α-β) * ψ2(α,ϵ)/ψ1(α,ϵ) ) / (α*x^(β/α))
end
end
a(ϕ) = acosh(2ϕ/((4ϕ-π)*sin(ϕ)))
b(ϕ) = ( (4π*ϕ-π^2) / a(ϕ) )
function Qpos(α::T, β::T, x::T, N::Integer, sep::T) where T <: AbstractFloat
ϕ = parse(T, "1.17210")
h = a(ϕ) / N
μ = b(ϕ) * N
w0r = μ * ( 1 - sin(ϕ) )
w0 = Complex(w0r, zero(T))
s = ( exp(w0r) * cos(ϕ) / 2 ) * real(H(α, β, w0, x, sep))
for n = 1:N
un = n * h
iunmϕ = Complex(-ϕ, un)
wn = μ * ( 1 + sin(iunmϕ) )
s += real( exp(wn) * H(α, β, wn, x, sep) * cos(iunmϕ) )
end
return ( x^((1-β)/α) * exp(x^(1/α)) / α ) + ( a(ϕ) * b(ϕ) / π ) * s
end
function Hplus(α::T, β::T, w::Complex{T}, x::T, sep::T) where T <: AbstractFloat
γp = x^(1/α) * exp(complex(zero(T), π/α))
ϵp = ( w - γp ) / γp
if abs(ϵp) > sep
return w^(α-β) / ( w^α + x ) - γp^(1-β) / ( α * ϵp * γp^β )
else
return ( ψ1(α-β,ϵp) - (1+ϵp)^(α-β)*ψ2(α,ϵp) / ψ1(α,ϵp) ) / (α*γp^β)
end
end
function Hminus(α::T, β::T, w::Complex{T}, x::T, sep::T
) where T <: AbstractFloat
γm= x^(1/α) * exp(complex(zero(T), -π/α))
ϵm = ( w - γm) / γm
if abs(ϵm) > sep
return w^(α-β) / ( w^α + x ) - γm^(1-β) / ( α * ϵm * γm^β )
else
return ( ψ1(α-β,ϵm) - (1+ϵm)^(α-β)*ψ2(α,ϵm) / ψ1(α,ϵm) ) / (α*γm^β)
end
end
function Qneg(α::T, β::T, x::T, N::Integer, sep::T) where T <: AbstractFloat
@assert 1 < α < 2
ϕ = parse(T, "1.17210")
h = a(ϕ) / N
μ = b(ϕ) * N
w0r = μ * ( 1 - sin(ϕ) )
w0 = Complex(w0r, zero(T))
s = ( exp(w0r) * cos(ϕ) / 2 ) * real(Hplus(α, β, w0, x, sep))
for n = 1:N
un = n * h
iunmϕ = Complex(-ϕ, un)
wn = μ * ( 1 + sin(iunmϕ) )
s += real( exp(wn) * ( Hplus(α, β, wn, x, sep)
+ Hminus(α, β, wn, x, sep) ) * cos(iunmϕ) ) / 2
end
sum_residues = ( ( x^((1-β)/α) / α ) * exp(x^(1/α)*cos(π/α))
*cos( π*(1-β)/α + x^(1/α)*sin(π/α) ) )
return sum_residues + ( a(ϕ)*b(ϕ)/π ) * s
end
α = 0.5
β = 1.0
sep = 0.2
N = 10
figure(1)
x = 2.0
t = range(-2.0, 2.0, length=201)
θ = π/4
w = x^(1/α) .+ t * exp(Complex(0.0, θ))
Hvals = H.(α, β, w, x, sep)
plot(t, real.(Hvals), t, imag.(Hvals))
grid(true)
figure(2)
x = range(0.0, 1.0, length=201)
plot(x, Qpos.(α, β, x, N, sep) - erfcx.(-x))
grid(true)
figure(3)
α = 3/2
x = 2.0
γplus = x^(1/α) * exp(Complex(0.0,π/α))
t = range(-2.0, 2.0, length=201)
θ = π/4
w = x^(1/α) .+ t * exp(Complex(0.0, θ))
Hvals = Hplus.(α, β, w, x, sep)
plot(t, real.(Hvals), t, imag.(Hvals))
grid(true)
figure(4)
x = range(0.0, 5.0, length=201)
plot(x, Qneg.(α, β, x, N, sep))
grid(true)
|
"""
Additional activity selector
returns a category of additional activity choosen by agent.
**Arguments**
* `feature_classes` : dictionary containing all possible types of features in the simulation
** Assumptions
- there is maximum one waypoint
-probability of driving directly to work is equal to 0.5
-otherwise waypoint type is chosen randomly from the features categories
"""
function additional_activity(agent_profile::DataFrames.DataFrame, before::Bool,
sim_data::OpenStreetMapXSim.SimData)
if rand() < 0.5
return nothing
else
return rand(keys(sim_data.feature_classes))
end
end
|
function POMDPs.transition(mdp::GenerativeMergingMDP, s::AugScene, a::Int64)
# Pr(sp |s, a)
rng = MersenneTwister(1)
spred = gen(DDNOut(:sp), mdp, s, a, rng)
s_vec = extract_features(mdp, spred)
sig_p = diagm(0 => [1.0 for i=1:length(s_vec)])
return d = MultivariateNormal(s_vec, sig_p)
end
function POMDPs.observation(mdp::GenerativeMergingMDP, a::Int64, s)
sig_o = diagm(0 => [0.5 for i=1:length(s)])
return MultivariateNormal(s, sig_o)
end
"""
MergingBelief
A type to represent belief state. It consists of the current observation `o` and the estimated driver types represented
by a dictionnary mapping ID to cooperation levels.
# fields
- `o::AugScene`
- `driver_types::Dict{Int64, Float64}`
"""
struct MergingBelief
o::AugScene
driver_types::Dict{Int64, Float64}
end
function POMDPs.convert_s(t::Type{V}, b::MergingBelief, mdp::GenerativeMergingMDP) where V<:AbstractArray
ovec = convert_s(t, b.o, mdp)
fore, merge, fore_main, rear_main = get_neighbors(mdp.env, b.o.scene, EGO_ID)
if fore.ind != nothing
fore_id = b.o.scene[fore.ind].id
ovec[6] = b.driver_types[fore_id] > 0.5
end
if merge.ind != nothing
merge_id = b.o.scene[merge.ind].id
ovec[9] = b.driver_types[merge_id] > 0.5
end
if fore_main.ind != nothing
fore_main_id = b.o.scene[fore_main.ind].id
ovec[12] = b.driver_types[fore_main_id] > 0.5
end
if rear_main.ind != nothing
rear_main_id = b.o.scene[rear_main.ind].id
ovec[15] = b.driver_types[rear_main_id] > 0.5
end
return ovec
end
function belief_weight(t::Type{V}, b::MergingBelief, mdp::GenerativeMergingMDP, state) where V <: AbstractArray
ovec = convert_s(t, b.o, mdp)
fore, merge, fore_main, rear_main = get_neighbors(mdp.env, b.o.scene, EGO_ID)
weight = 1.0
if fore.ind != nothing
fore_id = b.o.scene[fore.ind].id
ovec[6] = state[1] #b.driver_types[fore_id] > 0.5
weight *= b.driver_types[fore_id]*state[1] + (1 - b.driver_types[fore_id])*(1 - state[1])
end
if merge.ind != nothing
merge_id = b.o.scene[merge.ind].id
ovec[9] = state[2] #b.driver_types[merge_id] > 0.5
weight *= b.driver_types[merge_id]*state[2] + (1 - b.driver_types[merge_id])*(1 - state[2])
end
if fore_main.ind != nothing
fore_main_id = b.o.scene[fore_main.ind].id
ovec[12] = state[3] #b.driver_types[fore_main_id] > 0.5
weight *= b.driver_types[fore_main_id]*state[3] + (1 - b.driver_types[fore_main_id])*(1 - state[3])
end
if rear_main.ind != nothing
rear_main_id = b.o.scene[rear_main.ind].id
ovec[15] = state[4] #b.driver_types[rear_main_id] > 0.5
weight *= b.driver_types[rear_main_id]*state[4] + (1 - b.driver_types[rear_main_id])*(1 - state[4])
end
return ovec, weight
end
const driver_type_states = collect(Iterators.product([[0,1] for i=1:4]...))
"""
MergingUpdater <: Updater
A belief updater for `MergingBelief`. It sets `o` to the current observation and updates
the belief on the drivers cooperation level using Bayes' rule
"""
struct MergingUpdater <: Updater
# must set observe_cooperation to false
# must fill in all the driver models and make a deepcopy
mdp::GenerativeMergingMDP
function MergingUpdater(mdp::GenerativeMergingMDP)
mdp_ = deepcopy(mdp)
mdp_.observe_cooperation = false
for i=1:mdp.max_cars
mdp_.driver_models[i+1] = CooperativeIDM()
end
return new(mdp_)
end
end
function POMDPs.update(up::MergingUpdater, b_old::MergingBelief, a::Int64, o::AugScene)
# b_neigh = update_neighbors(up.mdp, b_old, o)
driver_types = deepcopy(b_old.driver_types)
for i=2:up.mdp.max_cars+1
update_proba!(up.mdp, b_old, driver_types, a, o, i)
end
return MergingBelief(o, driver_types)
end
function update_neighbors(mdp::GenerativeMergingMDP, b::MergingBelief, o::AugScene)
fore, merge, fore_main, rear_main = get_neighbors(mdp.env, o.scene, EGO_ID)
bfore = b.fore
bmerge = b.merge
bforemain = b.fore_main
brearmain = b.rear_main
current_neighbors = [bfore.id, bmerge.id, bforemain.id, brearmain.id]
if fore.ind == nothing
bfore = (id=nothing, prob=0.5)
elseif o.scene[fore.ind].id != b.fore.id
bfore = (id=o.scene[fore.ind].id, prob=0.5)
end
if merge.ind == nothing
bmerge = (id=nothing, prob=0.5)
elseif o.scene[merge.ind].id != b.merge.id
bmerge = (id=o.scene[merge.ind].id, prob=0.5)
end
if fore_main.ind == nothing
bforemain = (id=nothing, prob=0.5)
elseif o.scene[fore_main.ind].id != b.fore_main.id
bforemain = (id=o.scene[fore_main.ind].id, prob=0.5)
end
if rear_main.ind == nothing
bforerear = (id=nothing, prob=0.5)
elseif o.scene[rear_main.ind].id != b.rear_main.id
brearmain = (id=o.scene[rear_main.ind].id, prob=0.5)
end
return MergingBelief(b.o, bfore, bmerge, bforemain, brearmain)
end
function update_proba!(mdp::GenerativeMergingMDP, b::MergingBelief, driver_types::Dict, a::Int64, o::AugScene, id::Int64)
sp_vec = extract_features(mdp, o)
probs = zeros(2)
sp_vec = extract_features(mdp, o)
old_prob = driver_types[id]
if maximum(old_prob) ≈ 1.0
maximum(old_prob)
return driver_types
end
probs = zeros(2)
for c in [0, 1]
mdp.driver_models[id].c = c
v_des = 5.0
set_desired_speed!(mdp.driver_models[id], v_des)
d = transition(mdp, b.o, a)
probs[Int(c + 1)] += pdf(d, sp_vec)*(c*old_prob + (1 - c)*(1 - old_prob))
end
# @printf("probs = %s id=%d \n", probs, id)
if sum(probs) ≈ 0.0
probs = [0.5, 0.5]
end
normalize!(probs, 1)
driver_types[id] = probs[2]
return driver_types
end
function BeliefUpdaters.initialize_belief(up::MergingUpdater, s0::AugScene)
driver_types = Dict{Int64, Float64}()
for i=2:up.mdp.max_cars+1
driver_types[i] = 0.5
end
b0 = MergingBelief(s0, driver_types)
return b0
end |
# ---
# title: 480. Sliding Window Median
# id: problem480
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Sliding Window
# link: <https://leetcode.com/problems/sliding-window-median/description/>
# hidden: true
# ---
#
# Median is the middle value in an ordered integer list. If the size of the list
# is even, there is no middle value. So the median is the mean of the two middle
# value.
#
# Examples:
#
# `[2,3,4]` , the median is `3`
#
# `[2,3]`, the median is `(2 + 3) / 2 = 2.5`
#
# Given an array _nums_ , there is a sliding window of size _k_ which is moving
# from the very left of the array to the very right. You can only see the _k_
# numbers in the window. Each time the sliding window moves right by one
# position. Your job is to output the median array for each window in the
# original array.
#
# For example,
# Given _nums_ = `[1,3,-1,-3,5,3,6,7]`, and _k_ = 3.
#
#
#
# Window position Median
# --------------- -----
# [1 3 -1] -3 5 3 6 7 1
# 1 [3 -1 -3] 5 3 6 7 -1
# 1 3 [-1 -3 5] 3 6 7 -1
# 1 3 -1 [-3 5 3] 6 7 3
# 1 3 -1 -3 [5 3 6] 7 5
# 1 3 -1 -3 5 [3 6 7] 6
#
#
# Therefore, return the median sliding window as `[1,-1,-1,3,5,6]`.
#
# **Note:**
# You may assume `k` is always valid, ie: `k` is always smaller than input
# array's size for non-empty array.
# Answers within `10^-5` of the actual value will be accepted as correct.
#
#
## @lc code=start
using LeetCode
## add your code here:
## @lc code=end
|
# module for testing each common modules
module TestCommon
using Test
# target modules
include(joinpath(split(@__FILE__, "test")[1], "src/common/covariance_ellipse/covariance_ellipse.jl"))
include(joinpath(split(@__FILE__, "test")[1], "src/common/error_calculation/error_calculation.jl"))
include(joinpath(split(@__FILE__, "test")[1], "src/common/state_transition/state_transition.jl"))
include(joinpath(split(@__FILE__, "test")[1], "src/common/observation_function/observation_function.jl"))
function main()
@testset "Common" begin
@testset "CovarianceEllipse" begin
@test_nowarn draw_covariance_ellipse!([0.0, 0.0, 0.0],
[1.0 0.0 0.0;
0.0 1.0 0.0;
0.0 0.0 1.0], 3)
end
@testset "ErrorCalculation" begin
error = calc_lon_lat_error([5.0, 5.0, 5.0], [0.0, 0.0, 0.0])
@test error[1] == 5.00
@test error[2] == 5.00
@test error[3] == 5.00
end
@testset "StateTransition" begin
@test state_transition(0.1, 0.0, 1.0, [0, 0, 0]) == [0.1, 0.0, 0.0]
@test state_transition(0.1, 10.0/180*pi, 9.0, [0, 0, 0]) == [0.5729577951308232, 0.5729577951308231, 1.5707963267948966]
@test state_transition(0.1, 10.0/180*pi, 18.0, [0, 0, 0]) == [7.016709298534876e-17, 1.1459155902616465, 3.141592653589793]
end
@testset "ObservationFunction" begin
@test observation_function([-2, -1, pi/5*6], [2.0, -2.0]) == [4.123105625617661, 2.2682954597449703]
end
end
end
end |
using BayesianDataFusion
using Distributed
using SparseArrays
using Test
X = sprand(50, 100, 0.1)
Y1 = rand(50, 3)
Y2 = rand(100, 2)
Z1 = X' * Y1
Z2 = X * Y2
addprocs(2)
@everywhere using BayesianDataFusion
fp = psparse(X, workers())
Z1p = transpose(fp) * Y1
Z2p = fp * Y2
@test Z1 ≈ Z1p
@test Z2 ≈ Z2p
W = sprand(50, 10, 0.1)
rd = RelationData(W, class_cut = 0.5, feat1 = fp)
assignToTest!(rd.relations[1], 2)
result = macau(rd, burnin = 2, psamples = 2, num_latent=5, verbose=false)
@test size(rd.entities[1].model.beta) == (size(fp,2), 5)
########### parallel sparse with CSR ###########
fp2 = psparse(SparseMatrixCSC(X'), workers())
Z1r = transpose(fp2) * Y1
Z2r = fp2 * Y2
@test Z1 ≈ Z1r
@test Z2 ≈ Z2r
rd2 = RelationData(W, class_cut = 0.5, feat1 = fp2)
assignToTest!(rd2.relations[1], 2)
result = macau(rd2, burnin = 2, psamples = 2, num_latent=5, verbose=false)
rmprocs( workers() )
|
# Copyright (c) 2021 J.A. Duffek
# Copyright (c) 2000 D.M. Spink
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
using Plots;
"""
democurve()
Shows two simple test curves.
# Examples:
```julia
julia> democurve()
```
"""
function democurve()
crv = nrbtestcrv();
# plot the control points
plot(crv.coefs[1,:],crv.coefs[2,:],
title = "Arbitrary Test 2D Curves.",
m = (7, :transparent, stroke(1, :red)),
lw =1.0,
c = :red,
linestyle =:dash,
framestyle=:box,
legend = false);
# plot the nurbs curve
nrbplot!(crv,48);
# modify the curve
crv.knots[4] = 0.1;
# plot the nurbs curve
nrbplot!(crv,48);
end # democurve
|
using Test
using CLIMAParameters
using CLIMAParameters: AbstractEarthParameterSet
using CLIMAParameters.Planet
@testset "Planet (Earth)" begin
struct EarthParameterSet <: AbstractEarthParameterSet end
ps = EarthParameterSet()
# Planet
@test cp_d(ps) ≈ R_d(ps) / kappa_d(ps)
@test cv_d(ps) ≈ cp_d(ps) - R_d(ps)
@test molmass_ratio(ps) ≈ molmass_dryair(ps) / molmass_water(ps)
@test cv_v(ps) ≈ cp_v(ps) - R_v(ps)
@test cv_l(ps) ≈ cp_l(ps)
@test cv_i(ps) ≈ cp_i(ps)
@test T_0(ps) ≈ T_triple(ps)
@test LH_f0(ps) ≈ LH_s0(ps) - LH_v0(ps)
@test e_int_v0(ps) ≈ LH_v0(ps) - R_v(ps) * T_0(ps)
@test e_int_i0(ps) ≈ LH_f0(ps)
@test R_d(ps) ≈ gas_constant() / molmass_dryair(ps)
@test R_v(ps) ≈ gas_constant() / molmass_water(ps)
@test year_anom(ps) ≈ 365.26 * day(ps)
@test orbit_semimaj(ps) ≈ 1 * astro_unit()
@test !isnan(T_freeze(ps))
@test !isnan(T_min(ps))
@test !isnan(T_max(ps))
@test !isnan(T_icenuc(ps))
@test !isnan(pow_icenuc(ps))
@test !isnan(press_triple(ps))
@test !isnan(surface_tension_coeff(ps))
end
|
const AGGR2FUN = Dict(:add => sum, :sub => sum, :mul => prod, :div => prod,
:max => maximum, :min => minimum, :mean => mean)
abstract type GraphNet end
@inline update_edge(gn::T, e, vi, vj, u) where {T<:GraphNet} = e
@inline update_vertex(gn::T, ē, vi, u) where {T<:GraphNet} = vi
@inline update_global(gn::T, ē, v̄, u) where {T<:GraphNet} = u
@inline function update_batch_edge(gn::T, adj, E, V, u) where {T<:GraphNet}
edge_idx = edge_index_table(adj)
E_ = Vector[]
for (i, js) = enumerate(adj)
for j = js
k = edge_idx[(i,j)]
e = update_edge(gn, get_feature(E, k), get_feature(V, i), get_feature(V, j), u)
push!(E_, e)
end
end
hcat(E_...)
end
@inline function update_batch_vertex(gn::T, Ē, V, u) where {T<:GraphNet}
V_ = Vector[]
for i = 1:size(V,2)
v = update_vertex(gn, get_feature(Ē, i), get_feature(V, i), u)
push!(V_, v)
end
hcat(V_...)
end
@inline function aggregate_neighbors(gn::T, aggr::Symbol, E, accu_edge, num_V, num_E) where {T<:GraphNet}
@assert !iszero(accu_edge) "accumulated edge must not be zero."
cluster = generate_cluster(E, accu_edge, num_V, num_E)
pool(aggr, cluster, E)
end
@inline function aggregate_neighbors(gn::T, aggr::Nothing, E, accu_edge, num_V, num_E) where {T<:GraphNet}
@nospecialize E accu_edge num_V num_E
end
@inline function aggregate_edges(gn::T, aggr::Symbol, E) where {T<:GraphNet}
u = vec(AGGR2FUN[aggr](E, dims=2))
aggr == :sub && (u = -u)
aggr == :div && (u = 1 ./ u)
u
end
@inline function aggregate_edges(gn::T, aggr::Nothing, E) where {T<:GraphNet}
@nospecialize E
end
@inline function aggregate_vertices(gn::T, aggr::Symbol, V) where {T<:GraphNet}
u = vec(AGGR2FUN[aggr](V, dims=2))
aggr == :sub && (u = -u)
aggr == :div && (u = 1 ./ u)
u
end
@inline function aggregate_vertices(gn::T, aggr::Nothing, V) where {T<:GraphNet}
@nospecialize V
end
function propagate(gn::T, fg::FeaturedGraph, naggr=nothing, eaggr=nothing, vaggr=nothing) where {T<:GraphNet}
adj = adjacency_list(fg)
num_V = nv(fg)
accu_edge = accumulated_edges(adj)
num_E = accu_edge[end]
E = edge_feature(fg)
V = node_feature(fg)
u = global_feature(fg)
E = update_batch_edge(gn, adj, E, V, u)
Ē = aggregate_neighbors(gn, naggr, E, accu_edge, num_V, num_E)
V = update_batch_vertex(gn, Ē, V, u)
ē = aggregate_edges(gn, eaggr, E)
v̄ = aggregate_vertices(gn, vaggr, V)
u = update_global(gn, ē, v̄, u)
FeaturedGraph(graph(fg), V, E, u)
end
|
# Squared Exponential Covariance Function
include("se_iso.jl")
include("se_ard.jl")
"""
SE(ll::Union{Float64,Vector{Float64}}, lσ::Float64)
Create squared exponential kernel with length scale `exp.(ll)` and signal standard deviation
`exp(lσ)`.
See also [`SEIso`](@ref) and [`SEArd`](@ref).
"""
SE(ll::Float64, lσ::Float64) = SEIso(ll, lσ)
SE(ll::Vector{Float64}, lσ::Float64) = SEArd(ll, lσ)
|
# module Bukdu.Plug
struct Parsers <: AbstractPlug
end
"""
plug(::Type{Parsers}, parsers::Vector{Symbol} = ContentParsers.default_content_parsers; decoders...)
"""
function plug(::Type{Parsers}, parsers::Vector{Symbol} = ContentParsers.default_content_parsers; decoders...)
ContentParsers.env[:decoders] = merge(ContentParsers.default_content_decoders, Dict{Symbol,Type{<:ContentParsers.AbstractDecoder}}(decoders))
ContentParsers.env[:parsers] = union(parsers, first.(collect(decoders)))
end
# module Bukdu.Plug
|
"""
box_counting_dim(xg, yg, basin; kwargs...)
This function compute the box-counting dimension of the boundary. It is related to the uncertainty dimension.
[C. Grebogi, S. W. McDonald, E. Ott, J. A. Yorke, Final state sensitivity: An obstruction to predictability, Physics Letters A, 99, 9, 1983]
## Arguments
* `basin` : the matrix containing the information of the basin.
* `xg`, `yg` : 1-dim range vector that defines the grid of the initial conditions to test.
## Keyword arguments
* `kwargs...` these arguments are passed to `generalized_dim` see `ChaosTools.jl` for the docs.
"""
function box_counting_dim(xg, yg, basin; kwargs...)
# get points coordinates in the boudary
bnd = get_boundary_filt(basin)
I1 = findall(bnd .== 1);
v = Dataset{2,eltype(xg)}()
for ind in I1; push!(v, [xg[ind[1]] , yg[ind[2]]]); end;
return generalized_dim(v; q=0, kwargs...)
end
function box_counting_dim(xg, yg, bsn::BasinInfo; kwargs...)
ind = findall(iseven.(bsn.basin) .== true)
# Not sure it is necessary to deepcopy
basin_test = deepcopy(bsn.basin)
# Remove attractors from the picture
for k in ind; basin_test[k] = basin_test[k]+1; end
return box_counting_dim(xg, yg, basin_test; kwargs...)
end
"""
uncertainty_exponent(bsn::BasinInfo, integ; precision=1e-3) -> α,e,ε,f_ε
This function estimates the uncertainty exponent of the boundary. It is related to the uncertainty dimension.
[C. Grebogi, S. W. McDonald, E. Ott, J. A. Yorke, Final state sensitivity: An obstruction to predictability, Physics Letters A, 99, 9, 1983]
## Arguments
* `bsn` : structure that holds the information of the basin.
* `integ` : handle to the iterator of the dynamical system.
## Keyword arguments
* `precision` variance of the estimator of the uncertainty function.
"""
function uncertainty_exponent(bsn::BasinInfo, integ; precision=1e-3)
xg = bsn.xg; yg = bsn.yg;
nx=length(xg)
ny=length(yg)
xi = xg[1]; xf = xg[end];
grid_res_x=xg[2]-xg[1]
num_step=10
N_u = zeros(1,num_step) # number of uncertain box
N = zeros(1,num_step) # number of boxes
ε = zeros(1,num_step) # resolution
# First we compute a crude estimate to have an idea at which resolution
D,e,f = static_estimate(xg,yg,bsn);
println("First estimate: α=",D)
# resolution in log scale
# estimate the minimum resolution to estimate a f_ε ∼ 10^-3
min_ε = -3/D[1]
@show min_ε = max(min_ε,-7) # limit resolution to 10^-7 to avoid numerical inconsistencies.
max_ε = log10(grid_res_x*5) # max radius of the ball is roughly 5 pixels.
r_ε = 10 .^ range(min_ε,max_ε,length=num_step)
for (k,eps) in enumerate(r_ε)
Nb=0; Nu=0; μ=0; σ²=0; M₂=0;
completed = 0;
# Find uncertain boxes
while completed == 0
k1 = rand(1:nx)
k2 = rand(1:ny)
c1 = bsn.basin[k1,k2]
c2 = get_color_point!(bsn, integ, [xg[k1]+eps,yg[k2]])
c3 = get_color_point!(bsn, integ, [xg[k1]-eps,yg[k2]])
if length(unique([c1,Int(c2),Int(c3)]))>1
Nu = Nu + 1
end
Nb += 1
# Welford's online average estimation and variance of the estimator
M₂ = wel_var(M₂, μ, Nu/Nb, Nb)
μ = wel_mean(μ, Nu/Nb, Nb)
σ² = M₂/Nb
# If the process is binomial, the variance of the estimator is Nu/Nb·(1-Nu/Nb)/Nb (p·q/N)
# simulations matches
#push!(sig,Nu/Nb*(1-Nu/Nb)/Nb)
# Stopping criterion: variance of the estimator of the mean bellow 1e-3
if Nu > 50 && σ² < precision
completed = 1
@show Nu,Nb,σ²
end
if Nu < 10 && Nb>10000
# skip this value, we don't find the boundary
# corresponds to roughly f_ε ∼ 10^-4
@warn "Resolution may be too small for this basin, skip value"
completed = 1
Nu = 0
end
end
N_u[k]=Nu
N[k]=Nb
ε[k]=eps
end
# uncertain function
f_ε = N_u./N
# remove zeros in case there are:
ind = f_ε .> 0
f_ε = f_ε[ind]
ε = ε[ind]
# @show i1,D=linear_region(vec(log10.(ε)), vec(log10.(f_ε)))
# Dϵ=0.
# @show i1
# get exponent from a linear region
@. model(x, p) = p[1]*x+p[2]
fit = curve_fit(model, vec(log10.(ε)), vec(log10.(f_ε)), [2., 2.])
D = coef(fit)
Dϵ = estimate_errors(fit)
return D[1], Dϵ[1], vec(log10.(ε)),vec(log10.(f_ε))
end
function wel_var(M₂, μ, xₙ, n)
μ₂ = μ + (xₙ - μ)/n
M₂ = M₂ + (xₙ - μ)*(xₙ - μ₂)
return M₂
end
function wel_mean(μ, xₙ, n)
return μ + (xₙ - μ)/n
end
function static_estimate(xg,yg,bsn; precision=1e-4)
xg = bsn.xg; yg = bsn.yg;
y_grid_res=yg[2]-yg[1]
nx=length(xg)
ny=length(yg)
num_step=10
N_u = zeros(1,num_step) # number of uncertain box
N = zeros(1,num_step) # number of boxes
ε = zeros(1,num_step) # resolution
# resolution in pixels
min_ε = 1;
max_ε = 10;
r_ε = min_ε:max_ε
#@show r_ε = 10 .^ range(log10(min_ε),log10(max_ε),length=num_step)
for (k,eps) in enumerate(r_ε)
Nb=0; Nu=0; μ=0; σ²=0; M₂=0;
completed = 0;
# Find uncertain boxes
while completed == 0
kx = rand(1:nx)
ky = rand(ceil(Int64,eps+1):floor(Int64,ny-eps))
indy = range(ky-eps,ky+eps,step=1)
c = [bsn.basin[kx,ky] for ky in indy]
if length(unique(c))>1
Nu = Nu + 1
end
Nb += 1
# Welford's online average estimation and variance of the estimator
M₂ = wel_var(M₂, μ, Nu/Nb, Nb)
μ = wel_mean(μ, Nu/Nb, Nb)
σ² = M₂/Nb
# Stopping criterion: variance of the estimator of the mean bellow 1e-3
if Nu > 50 && σ² < precision
completed = 1
#@show Nu,Nb,σ²
end
end
N_u[k]=Nu
N[k]=Nb
ε[k]=eps*y_grid_res
end
# uncertain function
f_ε = N_u./N
# remove zeros in case there are:
ind = f_ε .> 0.
f_ε = f_ε[ind]
ε = ε[ind]
# get exponent
@. model(x, p) = p[1]*x+p[2]
fit = curve_fit(model, vec(log10.(ε)), vec(log10.(f_ε)), [2., 2.])
D = coef(fit)
@show estimate_errors(fit)
#D = linear_region(vec(log10.(ε)), vec(log10.(f_ε)))
return D[1],vec(log10.(ε)), vec(log10.(f_ε))
end
function ball_estimate(xg,yg,bsn; precision = 1e-4)
xg = bsn.xg; yg = bsn.yg;
xf=xg[end];xi=xg[1];yf=yg[end];yi=yg[1];
y_grid_res=yg[2]-yg[1]
nx=length(xg)
ny=length(yg)
num_step=10
N_u = zeros(1,num_step) # number of uncertain box
N = zeros(1,num_step) # number of boxes
ε = zeros(1,num_step) # resolution
# resolution in pixels
min_ε = 1;
max_ε = 10;
@show r_ε = 10 .^ range(log10(min_ε),log10(max_ε),length=num_step)
#r_ε = (min_ε:max_ε)*y_grid_res
for (k,eps) in enumerate(r_ε)
Nb=0; Nu=0; μ=0; σ²=0; M₂=0;
completed = 0;
c_ind = get_ind_in_circle(eps)
# Find uncertain boxes
while completed == 0
kx = rand()*((nx-eps)-(1+eps))+1+eps
ky = rand()*((ny-eps)-(1+eps))+1+eps
# I = get_indices_in_range(kx, ky, eps, c_ind)
# c = [ bsn.basin[n[1],n[2]] for n in eachrow(I)]
Ix,Iy = get_indices_in_range(kx, ky, eps, c_ind)
c = [ bsn.basin[n,m] for n in Ix, m in Iy]
if length(unique(c))>1
Nu = Nu + 1
end
Nb += 1
# Welford's online average estimation and variance of the estimator
M₂ = wel_var(M₂, μ, Nu/Nb, Nb)
μ = wel_mean(μ, Nu/Nb, Nb)
σ² = M₂/Nb
# Stopping criterion: variance of the estimator of the mean bellow 1e-3
if Nu > 50 && σ² < precision
completed = 1
@show Nu,Nb,σ²
end
end
N_u[k]=Nu
N[k]=Nb
ε[k]=eps*y_grid_res
end
# uncertain function
f_ε = N_u./N
# remove zeros in case there are:
ind = f_ε .> 0.
f_ε = f_ε[ind]
ε = ε[ind]
# get exponent
@. model(x, p) = p[1]*x+p[2]
fit = curve_fit(model, vec(log10.(ε)), vec(log10.(f_ε)), [2., 2.])
D = coef(fit)
@show estimate_errors(fit)
return D[1],vec(log10.(ε)), vec(log10.(f_ε))
end
function get_indices_in_range(kx, ky, eps,c_ind)
# center and scale
#indx = ceil.(Int64,(kx-eps):1.:(kx+eps))
#indy = ceil.(Int64,(ky-eps):1.:(ky+eps))
indx = range(ceil.(Int64,kx-eps),ceil(Int64,kx+eps)-1,step=1)
indy = range(ceil.(Int64,ky-eps),ceil(Int64,ky+eps)-1,step=1)
#I = deepcopy(c_ind)
#Find indices in a circle of radius eps
#I[:,1] .= I[:,1] .+ ceil(Int64,kx)
#I[:,2] .= I[:,2] .+ ceil(Int64,ky)
#@show [[n[1],n[2]] for n in I]
return indx,indy
#return I
end
function get_ind_in_circle(r)
#Find indices in a circle of radius eps
I = Array{Int64,1}[]
r_l = ceil(Int16,r)
for n in -r_l:r_l, m in -r_l:r_l
if n^2+m^2 ≤ r^2
push!(I, [n; m])
end
end
v= hcat(I...)'
return v
end
|
let
roadway = gen_straight_roadway(3, 1000.0, lane_width=1.0)
rec = SceneRecord(1, 0.1, 5)
update!(rec, Scene([
Vehicle(VehicleState(VecSE2( 0.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Vehicle(VehicleState(VecSE2(10.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
]))
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 1)) == 0.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 2)) == 0.0
@test isapprox(convert(Float64, get(MARKERDIST_LEFT, rec, roadway, 1)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_LEFT, rec, roadway, 2)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_RIGHT, rec, roadway, 1)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_RIGHT, rec, roadway, 2)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_LEFT_LEFT, rec, roadway, 1)), 1.5)
@test isapprox(convert(Float64, get(MARKERDIST_LEFT_LEFT, rec, roadway, 2)), 1.5)
@test isnan(convert(Float64, get(MARKERDIST_RIGHT_RIGHT, rec, roadway, 1)))
@test isnan(convert(Float64, get(MARKERDIST_RIGHT_RIGHT, rec, roadway, 2)))
@test isapprox(convert(Float64, get(DIST_FRONT, rec, roadway, 1)), 10.0 - 5.0)
@test convert(Float64, get(DIST_FRONT, rec, roadway, 2, censor_hi=100.0)) == 100.0
update!(rec, Scene([
Vehicle(VehicleState(VecSE2( 1.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Vehicle(VehicleState(VecSE2(10.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
Vehicle(VehicleState(VecSE2(12.0,1.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 3),
Vehicle(VehicleState(VecSE2( 0.0,1.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 4),
]))
@test isapprox(convert(Float64, get(MARKERDIST_LEFT, rec, roadway, 3)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_RIGHT, rec, roadway, 3)), 0.5)
@test isapprox(convert(Float64, get(MARKERDIST_LEFT_LEFT, rec, roadway, 3)), 1.5)
@test isapprox(convert(Float64, get(MARKERDIST_RIGHT_RIGHT, rec, roadway, 3)), 1.5)
@test isapprox(convert(Float64, get(DIST_FRONT, rec, roadway, 1)), 9.0 - 5.0)
@test isapprox(convert(Float64, get(DIST_FRONT_LEFT, rec, roadway, 1)), 11.0 - 5.0)
@test convert(Float64, get(DIST_FRONT_RIGHT, rec, roadway, 1)) == 100.0
@test isapprox(convert(Float64, get(DIST_FRONT, rec, roadway, 4)), 12.0 - 5.0)
@test convert(Float64, get(DIST_FRONT_LEFT, rec, roadway, 4)) == 100.0
@test isapprox(convert(Float64, get(DIST_FRONT_RIGHT, rec, roadway, 4)), 1.0 - 5.0)
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 1)) == 1.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 2)) == 1.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 3)) == 1.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 4)) == 1.0
update!(rec, Scene([
Vehicle(VehicleState(VecSE2( 0.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Vehicle(VehicleState(VecSE2(-10.0,1.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
Vehicle(VehicleState(VecSE2( 0.0,1.0,0.5), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 3),
]))
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 1)) == 1.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 2)) == 0.0
@test convert(Float64, get(IS_COLLIDING, rec, roadway, 3)) == 1.0
# super-simple test
for f in allfeatures()
get(f, rec, roadway, 3)
end
end |
using MatrixAlgebra
using BandedMatrices
using MiscUtilities
using DoubleFloats
using Plots
n = 10000
function sband(n::Integer, a::Vector{T}) where T
k = length(a)
SH = T<:Complex ? Hermitian : Symmetric
SH(BandedMatrix([-i => fill(a[i+1], n-i) for i = 0:min(k,n)-1]...), :L)
end
#A, B = sband(n, [6.0, -4, 1, 0.1]), sband(n, [2.0, 1, 0, 0])
#ws = MatrixAlgebra.make_workspace(A, B)
cws(T, A=A, B=B) = MatrixAlgebra.make_workspace(copy_elementtype(T, A), copy_elementtype(T, B))
eig(k) = MatrixAlgebra.eigval!(ws, k, lb[k], ub[k], 1)
function pl(a::T, b::T, v::AbstractVector = T[]) where T
pf(x) = clamp(x - f(x), a, b)
ph1(x) = clamp(x - h(x, 1), a, b)
phh0(x) = clamp(x - hh(x, 1, (1.0, 0.0, 0.0, 1.0)), a, b)
phh1(x) = clamp(x - hh(x, 1, (-1.0, 1.0, 1.0, 1.0)), a, b)
ph2(x) = clamp(x - h(x, 2), a, b)
ph3(x) = clamp(x - h(x, 3), a, b)
ph10(x) = clamp(x - h(x, 10), a, b)
ph100(x) = clamp(x - h(x, 100), a, b)
ph1000(x) = clamp(x - h(x, 1000), a, b)
pg1(x) = clamp(x - g(x, v), a, b)
p = plot(legend=nothing)
plot!(p, [a; b], [a; b])
plot!(p, range(a,stop=b,length=2001), [pf; phh0; phh1])
#display(p)
end
function pl(a::Integer,b::Integer = a + 1)
d = (eve[b] - eve[a] ) * 0.5
pl(eve[a] - d, eve[b] + d)
end
function plfh(a, b)
p = plot(legend=nothing)
plot!(p, [a; b], [0; 0])
plot!(p, range(a,stop=b,length=1001), [f; h])
#display(p)
end
function h(x::AbstractFloat, r=1)
κ, η, ζ = detderivates(A, B, x)
n = size(A, 1)
MatrixAlgebra.laguerre1(η, ζ, n, r)
end
function g(x::AbstractFloat, v::AbstractVector)
n = size(A, 1)
p = length(v)
y = sum(inv.(x .- v))
z = sum(inv.(x .- v) .^ 2)
κ, η, ζ = detderivates(A, B, x)
r1 = float(1)
r2 = clamp(η^2 / ζ, 1, n)
w = 0 # η^2 / ( ζ + η^2 )
r = r1 + ( r2 - r1 ) * w^n
r = clamp(rest(x), 1, n)
MatrixAlgebra.laguerre1(η - y, ζ - z, n - p, r)
end
function hh(x::AbstractFloat, r = 1, (a,b,c,d) = (1.0, 0.0, 0.0, 1.0), A=A, B=B)
AA = A * a + B * c
BB = B * d + A * b
ws = cws(typeof(x), AA, BB)
t = (a * x + c) / (d + b * x)
κ, η, ζ = MatrixAlgebra.detderivates!(ws, t)
n = size(A, 1)
α = ζ / η^2
dt = n / η / ( 1 + sqrt((n-r)/r*max(n * α - 1, 0.0)))
tt = t - dt
xx = (d * tt - c) / (a - b * tt)
dx = x - xx
dx
end
function f(x)
κ, η, ζ = detderivates(A, B, x)
1 / η
end
function kappa(x, A=A, B=B)
κ, η, ζ = detderivates(A, B, x)
κ
end
function rest(x, A=A, B=B)
κ, η, ζ = detderivates(A, B, x)
η ^ 2 / ζ
end
nothing
|
@testset "393.utf-8-validation.jl" begin
@test valid_utf8([197, 130, 1]) == true
@test valid_utf8([235, 140, 4]) == false
@test valid_utf8([255]) == false
@test valid_utf8([237]) == false
@test valid_utf8([0]) == true
end
|
"""
drawmandelbrotR2(f [, x0, y0; hasescaped, maxiterations])
Return the drawing of the Mandelbrot set of a family of functions
\$f_{a,b}:\\mathbb{R}^2\\rightarrow\\mathbb{R}^2\$ with \$a,b\\in\\mathbb{R}\$,
in a rectangular region in \$\\mathbb{R}^2\$,
using the escape time of iterations algorithm,
over a given "critical" point \$(x_0,y_0)\$.
The Mandelbrot set of \$f_{a,b}\$ over \$(x_0,y_0)\$ is defined as
\$\\mathcal{M}(f_{a,b},(x_0,y_0))=\\{(a,b)\\in\\mathbb{R}^2\\,|\\,|f_{a,b}^n(x_0,y_0)|\\nrightarrow\\infty\\,n\\rightarrow\\infty\\}\$
#### Arguments
- `f::Function`: A function \$f:\\mathbb{R}^2\\times\\mathbb{R}^2\\rightarrow\\mathbb{R}^2\$.
- `x0::Real`: X coordinate of the "critical" point.
- `y0::Real`: Y coordinate of the "critical" point.
- `hasescaped::Function`: A boolean function to check if the iterations has escaped.
- `maxiterations::Integer`: Maximum number of iterations to check.
"""
function drawmandelbrotR2(f::Function, x0::Real=0, y0::Real=0;
hasescaped::Function=(x::Real,y::Real) -> x*x+y*y > 4, maxiterations::Int=100)
# Veryfying if graphics backend supports functions
SDDGraphics.supported(:drawpixel)
# Verifying functions
@assert typeof(f(0., 0., 1., 1.)) <: Tuple{Real,Real}
@assert typeof(hasescaped(1., 1.)) <: Bool
SDDGraphics.newdrawing()
SDDGraphics.updatecolorarray(maxiterations)
@sweeprectregion SDDGraphics.xlims() SDDGraphics.ylims() SDDGraphics.canvassize() begin
xn,yn = x0,y0
escapetime = maxiterations
for n in 0:maxiterations
if hasescaped(xn,yn)
escapetime = n
break
end # if hasescaped
xn,yn = f(x,y,xn,yn)
end # for n maxiterations
SDDGraphics.color(escapetime)
SDDGraphics.drawpixel(i,j)
end # Implemented algorithm
SDDGraphics.drawing()
end # function drawtrappedpointsR2
"""
drawmandelbrotC(f [, z0; hasescaped, maxiterations])
Return the drawing of the Mandelbrot set of a family of functions
\$f_{\\lambda}:\\mathbb{C}\\rightarrow\\mathbb{C}\$,
in a rectangular region in \$\\mathbb{C}\$,
using the escape time of iterations algorithm,
over a given "critical" point \$z_0\$.
The Mandelbrot set of \$f_{\\lambda}\$ over \$z_0\$ is defined as
\$\\mathcal{M}(f_{\\lambda},z_0)=\\{\\lambda\\in\\mathbb{C}\\,|\\,|f_{\\lambda}^n(z_0)|\\nrightarrow\\infty\\,n\\rightarrow\\infty\\}\$
#### Arguments
- `f::Function`: A function \$f:\\mathbb{C}\\times\\mathbb{C}\\rightarrow\\mathbb{C}\$.
- `z0::Number`: A "critical" point.
- `hasescaped::Function`: A boolean function to check if the iterations has escaped.
- `maxiterations::Integer`: Maximum number of iterations to check.
"""
function drawmandelbrotC(f::Function, z0::Number=0;
hasescaped::Function=z::Number -> abs2(z) > 4, maxiterations::Int=100)
# Veryfying if graphics backend supports functions
SDDGraphics.supported(:drawpixel)
# Verifying functions
@assert typeof(f(0, 1.0im)) <: Number
@assert typeof(hasescaped(1.0im)) <: Bool
SDDGraphics.newdrawing()
SDDGraphics.updatecolorarray(maxiterations)
@sweeprectregion SDDGraphics.xlims() SDDGraphics.ylims() SDDGraphics.canvassize() begin
λ = complex(x,y)
zn = z0
escapetime = maxiterations
for n in 0:maxiterations
if hasescaped(zn)
escapetime = n
break
end # if hasescaped
zn = f(λ, zn)
end # for n maxiterations
SDDGraphics.color(escapetime)
SDDGraphics.drawpixel(i,j)
end # Implemented algorithm
SDDGraphics.drawing()
end # function drawtrappedpointsC
|
#handle scope
N = 3
f1(a, b) = a+b
g1(a, b) = (a*b, a-b)
h1(a, b) = a^b
k(a, b, c) = (a + b) / c
@testset "NNTopo" begin
using Transformers.Stacks: print_topo
f(x) = x+1
g(x) = x+2
h(x) = x+3
topo1 = @nntopo x => a => b => y
@test topo1((f,g,h), 10) == h(g(f(10)))
topo2 = @nntopo x => 4 => y
@test topo2((f,f,f,f, g), 10) == g(f(f(f(f(10)))))
(x1, x2, x3, x4) = [2, 3, 7, 5]
t = f1(x1, x2)
z1, z2 = g1(t, x3)
w = h1(x4, z1)
y = k(x2, z2, w)
topo3 = @nntopo (x1, x2, x3, x4):(x1, x2) => t:(t, x3) => (z1, z2):(x4, z1) => w:(x2, z2, w) => y
@test topo3((f1, g1, h1, k), x1, x2, x3, x4) ≈ y
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
print_topo(outWrite, topo3; models=(f1, g1, h1, k))
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
@test topo_string == """topo_func(model, x1, x2, x3, x4)
t = f1(x1, x2)
(z1, z2) = g1(t, x3)
w = h1(x4, z1)
y = k(x2, z2, w)
y
end
"""
end
topo = @nntopo((e, m, mask):e → pe:(e, pe) → t → (t:(t, m, mask) → t:(t, m, mask)) → $N:t → c)
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
print_topo(outWrite, topo)
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
@test topo_string == """topo_func(model, e, m, mask)
pe = model[1](e)
t = model[2](e, pe)
t = model[3](t)
t = model[4](t, m, mask)
t = model[5](t, m, mask)
t = model[6](t, m, mask)
c = model[7](t)
c
end
"""
end
localn = 3
topo = @nntopo_str "(e, m, mask):e → pe:(e, pe) → t → (t:(t, m, mask) → t:(t, m, mask)) → $localn:t → c"
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
print_topo(outWrite, topo)
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
@test topo_string == """topo_func(model, e, m, mask)
pe = model[1](e)
t = model[2](e, pe)
t = model[3](t)
t = model[4](t, m, mask)
t = model[5](t, m, mask)
t = model[6](t, m, mask)
c = model[7](t)
c
end
"""
end
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
topo = @nntopo x => ((y => z => t) => 3 => w) => 2
print_topo(outWrite, topo)
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
@test topo_string == """topo_func(model, x)
y = model[1](x)
z = model[2](y)
t = model[3](z)
z = model[4](t)
t = model[5](z)
z = model[6](t)
t = model[7](z)
w = model[8](t)
z = model[9](w)
t = model[10](z)
z = model[11](t)
t = model[12](z)
z = model[13](t)
t = model[14](z)
w = model[15](t)
w
end
"""
end
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
topo = @nntopo x => y' => 3 => z
print_topo(outWrite, topo)
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
if v"1.0.0" <= VERSION <= v"1.2.0"
@test topo_string == """topo_func(model, x)
y = model[1](x)
%1 = y
y = model[2](y)
%2 = y
y = model[3](y)
%3 = y
y = model[4](y)
%4 = y
z = model[5](y)
(z, (%1, %2, %3, %4))
end
"""
else
@test topo_string == """topo_func(model, x)
y = model[1](x)
%1 = y
y = model[2](y)
%2 = y
y = model[3](y)
%3 = y
y = model[4](y)
%4 = y
z = model[5](y)
(z, (var"%1", var"%2", var"%3", var"%4"))
end
"""
end
end
let STDOUT = stdout
(outRead, outWrite) = redirect_stdout()
topo = @nntopo (x,y) => (a,b,c,d') => (w',r',y) => (m,n)' => z
print_topo(outWrite, topo)
close(outWrite)
topo_string = String(readavailable(outRead))
close(outRead)
redirect_stdout(STDOUT)
if v"1.0.0" <= VERSION <= v"1.2.0"
@test topo_string == """topo_func(model, x, y)
(a, b, c, d) = model[1](x, y)
%1 = d
(w, r, y) = model[2](a, b, c, d)
%2 = (w, r)
(m, n) = model[3](w, r, y)
%3 = (m, n)
z = model[4](m, n)
(z, (%1, %2, %3))
end
"""
else
@test topo_string == """topo_func(model, x, y)
(a, b, c, d) = model[1](x, y)
%1 = d
(w, r, y) = model[2](a, b, c, d)
%2 = (w, r)
(m, n) = model[3](w, r, y)
%3 = (m, n)
z = model[4](m, n)
(z, (var"%1", var"%2", var"%3"))
end
"""
end
end
end
|
module BayesOpt
export bayesopt
if isfile(joinpath(dirname(@__FILE__), "..", "deps", "deps.jl"))
include("../deps/deps.jl")
else
error("BayesOpt was not properly installed. Please run Pkg.build(\"BayesOpt\")")
end
include("params.jl")
include("opt.jl")
# This doesn't work on v0.4 since closures aren't c-callable functions.
function bayesopt(
f::Function,
x0::Vector{Float64},
lb::Vector{Float64},
ub::Vector{Float64};
n_iterations::Integer=190,
verbose_level::Integer=1)
# wrap the function f (assumed to take an argument of Vector{Float64}) with a closure
function f′(n, x, grad, fdata)
return f(unsafe_wrap(Array, x, n))
end
params = initialize_parameters_to_default()
params.n_iterations = n_iterations
params.verbose_level = verbose_level
minf = Ref{Float64}(0)
x = copy(x0)
r = bayes_optimization(length(x), f′, C_NULL, lb, ub, x, minf, params)
if r != 0
error("optimization failed")
end
return minf[], x
end
end # module
|
code = ARGS[1]
code = replace(code, "⏎" => "\n")
highlighter = nothing
highlighter_str = get(ENV, "_INTERACTIVECODESEARCH_JL_HIGHLIGHTER", nothing)
if highlighter_str !== nothing
highlighter = @eval @cmd $highlighter_str
end
file = line = nothing
if (m = match(r"(.*) in \w+ at (.*):([0-9]+)$", code)) !== nothing
# code = String(m[1])
file = m[2]
line = parse(Int, m[3])
if isabspath(file)
print(basename(file), " (")
printstyled(file; color = :light_black)
println(")")
else
print(file, " ")
end
println("at line ", line)
if isfile(file)
open(pipeline(highlighter, stdin = IOBuffer(read(file)), stderr = stderr)) do io
width, height = displaysize(stdout)
for (i, str) in enumerate(eachline(io))
if i > line + height * 2
close(io)
break
elseif i > line - 2
if i == line
printstyled(lpad(i, 5), " "; color = :magenta, bold = true)
printstyled(">"; color = :red)
else
print(lpad(i, 5), " ")
printstyled(":"; color = :light_black)
end
print(str)
printstyled("\u200b") # zero-width space
println()
end
end
end
exit()
end
end
if highlighter === nothing
print(code)
else
run(pipeline(highlighter, stdin = IOBuffer(code), stdout = stdout, stderr = stderr))
end
|
mutable struct Config
train::Bool
end
const CONFIGS = [Config(true) for i=1:nthreads()]
getconfig() = CONFIGS[threadid()]
setconfig(config::Config) = CONFIGS[threadid()] = config
istrain() = getconfig().train
settrain(b::Bool) = getconfig().train = b
|
using YaoCompiler
using YaoCompiler.Intrinsics
target = YaoTargetQASM.OpenQASMTarget()
interp = YaoInterpreter(;target)
code_typed(Intrinsics.apply, Tuple{AnyReg, typeof(Adder3.adder3())}; interp)
ast = code_qasm(typeof(Adder3.adder3()))
Adder3.t()
qelib = joinpath(pkgdir(YaoTargetQASM), "test", "qelib1.inc")
@macroexpand qasm"""
OPENQASM 2.0;
include "$qelib";
gate majority a,b,c
{
cx c,b;
cx c,a;
ccx a,b,c;
}
"""
using OpenQASM
using YaoTargetQASM
using YaoCompiler
using YaoCompiler.Intrinsics
using CompilerPluginTools
qasm"""
OPENQASM 2.0;
gate cx c,t { CX c,t; }
gate u1(lambda) q { U(0,0,lambda) q; }
gate t a { u1(pi/4) a; }
gate h a { u2(0,pi) a; }
gate tdg a { u1(-pi/4) a; }
gate ccx a,b,c
{
h c;
cx b,c; tdg c;
cx a,c; t c;
cx b,c; tdg c;
cx a,c; t b; t c; h c;
cx a,b; t a; tdg b;
cx a,b;
}
gate majority a,b,c
{
cx c,b;
cx c,a;
ccx a,b,c;
}
"""
ast = code_qasm(typeof(majority()))
@device function test_inline()
1:3 => ccx()
end
ast = code_qasm(typeof(test_inline()))
code_qasm(typeof(ccx()))
code_typed(Intrinsics.apply, (AnyReg, typeof(majority())); interp=YaoInterpreter())
interp = YaoInterpreter()
mi = method_instance(Intrinsics.apply, (AnyReg, typeof(test_inline())))
result = Core.Compiler.InferenceResult(mi)
frame = Core.Compiler.InferenceState(result, false, interp)
Core.Compiler.typeinf(interp, frame)
opt_params = Core.Compiler.OptimizationParams(interp)
opt = Core.Compiler.OptimizationState(frame, opt_params, interp)
preserve_coverage = Core.Compiler.coverage_enabled(opt.mod)
ci = opt.src; nargs = opt.nargs - 1;
ir = Core.Compiler.convert_to_ircode(ci, Core.Compiler.copy_exprargs(ci.code), preserve_coverage, nargs, opt)
ir = Core.Compiler.slot2reg(ir, ci, nargs, opt)
ir = compact!(ir)
sv = opt
todo = Core.Compiler.assemble_inline_todo!(ir, sv.inlining)
state = sv.inlining
todo = Core.Compiler.Pair{Int, Any}[]
et = state.et
method_table = state.method_table
ir
r = Core.Compiler.process_simple!(ir, todo, 6, state)
ir = Core.Compiler.ssa_inlining_pass!(ir, ir.linetable, sv.inlining, sv.src.propagate_inbounds)
# ir = compact!(ir)
# ir = Core.Compiler.getfield_elim_pass!(ir)
# ir = Core.Compiler.adce_pass!(ir)
# ir = Core.Compiler.type_lift_pass!(ir)
# ir = compact!(ir)
# ir = inline_const!(ir)
# ir = YaoCompiler.elim_location_mapping!(ir)
# code_typed(Intrinsics.apply, (AnyReg, typeof(ccx()), typeof(Locations(1:3))); interp)
# op = tdg()
# todo = assemble_inline_todo!(ir, state)
# ir |
# julia1_2.6.jl String Operations and Pattern matching
#
# String character addressing 1 to end
# The first byte of a UTF-8 multibyte character
# will yield the character, the other bytes cause exceptions
s="Abcπ∑z\u2200\n" # or s=string("Abcπ∑z∀")
# ∀ for each operator (eg. ∀x∊S for each x belonging to set S)
println(sizeof(s)) # total number of bytes in string
println(length(s)) # length in characters
# best way to deal with each character
for c in s
print(c)
end
# and this can become a one liner using ";"
for c in s; print(c); end
println(s[5]) # this will cause an exception since continuation byte
name="Mike"
n=76
s=string("Hi ",name,n,30," ",π,",\n") # Converts and concatenates
# julia uses * for concatenation
# rather than + (+ implies communtative)
s="Hi "*name*",/n"
s="hi $name,\n" # so using String is not necessary
# The $ operator can also be used to evaluate expressions
n=63
s="Hi $(sqrt(n+1)),\n"
# triple quote used for embedded quotes and indentation
lem="""
The lead lemming said, "Jump!"
and they all did.
"""
println(lem)
for i=0x2200:0x2240; print(Char(i)); end # interesting symbols
###
t='a'*'z'
u='z'-'a'
v='a'+1
w='a'+'b' # meaningless so error
# character comparisons
'A'<='X'<='Z' # true comparison
'A'<='a'<='Z' #false comparison
# lexicographic ordering using < > <= >= == !=
"abacus"<"zoo" # true
"Zoo"<"abacus" # true because 'Z'<'a'Char'
"Zoo"<"Abacus" # false
"α"<"𝛂" # true because first alpha from lower greek alphabet.
s="πAbc∑z\u2200\n"
t=chomp(s)
chop(t)
lowercase(t)
uppercase(t)
t[end]
first(t) # all strings start at 1.
Last(t)
split(t,'∑')
strip(" "*t*" ")
textwidth(s)
i=1 # all strings start at 1.
t[i]
i=nextind(t,i)
t[i]
textwidth(s)
###
# regular expressions (type Regex)- Perl compatible
# see www.pcre.org
# Regex common escape sequences - table
# \a An alarm bell
# \c? The control character you specify for ?
# \d A digit between 0 and 9
# \D A non digit character
# \e The character generated by pressing escape
# \E The end of an \L or \U sequence
# \f A form feed
# \l The next lower case character
# \L The next lower case characters until \E
# \n A new line of data
# \Q The next metacharacter until \E is found
# \r a carriage return
# \s A whitespace character
# \S A non-white space character
# \t A tab
# \u The next Uppercase character
# \U The next uppercase characters until \E
# \w A word character (alphanumeric characters or underscores)
# \W A non-word characters
# \O? The octal character you specify for ?
# \x? The hexadecimal character you specify for ?
Other metacharacters
# ^ Match at beginning of String
# $ Match at end of String
# + 1 or more of preceding type
# * 0 or more of preceding type
# [?-?] match range, eg. [A-G], [1-5] and [A-Za-z]
# Test to make sure password not all alpha
i=0
while(i==0)
global i
passwd=readline()
if match(r"^[A-Za-zα-ω]*$",passwd) === nothing
println("password good")
i=1
else
println("all alpha, try again")
end
end
# pick time out of text
linewithtime="a good holiday weekend, its 15:45 and sunny."
m=match(r"(?<hour>\d+):(?<minute>\d+)",linewithtime)
println(m[:hour]*":"*m[:minute])
# For more read Redex Cheat Sheet at:
# www.rexegg.com/regex-quickstart.html
|
export MaximalIndependentSet
struct MaximalIndependentSet end
"""
independent_set(g, MaximalIndependentSet(); seed=-1)
Find a random set of vertices that are independent (no two vertices are adjacent to each other) and
it is not possible to insert a vertex into the set without sacrificing the independence property.
### Implementation Notes
Performs [Approximate Maximum Independent Set](https://en.wikipedia.org/wiki/Maximal_independent_set#Sequential_algorithm) once.
Returns a vector of vertices representing the vertices in the independent set.
### Performance
Runtime: O(|V|+|E|)
Memory: O(|V|)
Approximation Factor: maximum(degree(g))+1
### Optional Arguments
- If `seed >= 0`, a random generator is seeded with this value.
"""
function independent_set(
g::AbstractGraph{T},
alg::MaximalIndependentSet;
seed::Int=-1
) where T <: Integer
nvg = nv(g)
ind_set = Vector{T}()
sizehint!(ind_set, nvg)
deleted = falses(nvg)
for v in randperm(getRNG(seed), nvg)
(deleted[v] || has_edge(g, v, v)) && continue
deleted[v] = true
push!(ind_set, v)
deleted[neighbors(g, v)] .= true
end
return ind_set
end
|
## Graph layouts ##
"""
layout_random(g::Graph)
Place nodes at random positions. They are uniformly distributed along each axis.
"""
layout_random(g::Graph) = (rand(nodecount(g)), rand(nodecount(g)))
"""
layout_line(g::Graph)
Place nodes on a horisontal line.
Combining this layout with `edge_curve=1` when plotting yields an
[arc diagram](https://en.wikipedia.org/wiki/Arc_diagram).
"""
layout_line(g::Graph) = (
[Float64(i) for i = nodes(g)], ones(Float64, nodecount(g)))
"""
layout_circle(g::Graph[, clockwise=true])
Place nodes on a circle, a.k.a. [circular layout](https://en.wikipedia.org/wiki/Circular_layout).
Set `clockwise` to change node ordering.
"""
function layout_circle(g::Graph, clockwise=true)
Δα = 2 * pi / nodecount(g) * (clockwise ? 1 : -1)
α0 = -pi / 2 - Δα
return (
Float64[cos(α0 + Δα * i) for i = nodes(g)],
Float64[sin(α0 + Δα * i) for i = nodes(g)])
end
"""
layout_fruchterman_reingold(g::Graph[; maxiter, scale...)
Layout network with Fruchterman-Reingold force-directed algorithm.
# References
Fruchterman, Thomas MJ, and Edward M Reingold. 1991.
“Graph Drawing by Force-Directed Placement.” Software: Practice and Experience 21 (11):1129–64.
"""
function layout_fruchterman_reingold(g::Graph; maxiter=250, scale=sqrt(nodecount(g)), init_temp=sqrt(nodecount(g)))
n = nodecount(g)
x = scale / 2 .* (rand(n) .- 0.5)
y = scale / 2 .* (rand(n) .- 0.5)
@inbounds for iter = 1:maxiter
force_x, force_y = zeros(n), zeros(n)
for i = 1:n
@inbounds for j = 1:i-1
d_x, d_y = x[j] - x[i], y[j] - y[i]
f = - 1 / (d_x^2 + d_y^2) # repulsive force
force_x[i] += d_x * f
force_y[i] += d_y * f
force_x[j] -= d_x * f
force_y[j] -= d_y * f
end
@inbounds for j = map(x->x.node, g.nodes[i].forward) # TODO: create generic way to handle this
d_x, d_y = x[j] - x[i], y[j] - y[i]
f = n * sqrt(d_x ^ 2 + d_y ^ 2) # attractive force
force_x[i] += d_x * f
force_y[i] += d_y * f
force_x[j] -= d_x * f
force_y[j] -= d_y * f
end
end
t = init_temp / iter
@inbounds for i = 1:n
force_mag = sqrt(force_x[i] ^ 2 + force_y[i] ^ 2) # apply forces
if force_mag > t
coef = t / force_mag
x[i] += force_x[i] * coef
y[i] += force_y[i] * coef
end
mag = sqrt(x[i] ^ 2 + y[i] ^ 2) # don't let points run away
if mag > scale
x[i] *= scale / mag
y[i] *= scale / mag
end
end
end
return x, y
end
"""
rescale(v, newmax, margin)
Rescale elements of `v` to fill range `margin:newmax - margin`.
"""
function rescale(v, newmax::Real, margin::Real) :: Vector{Int}
if length(v) == 0
return Int[]
end
oldmin, oldmax = extrema(v)
if oldmax > oldmin
k = (newmax - 2margin) / (oldmax - oldmin)
return Int[round(Int, margin + (x - oldmin) * k) for x = v]
else
return Int[round(Int, newmax / 2) for x = v]
end
end
|
"""
read_scalar(f::JLDFile, rr, header_offset::RelOffset)
Read raw data representing a scalar with read representation `rr` from the current position
of JLDFile `f`. `header_offset` is the RelOffset of the object header, used to resolve
cycles.
"""
function read_scalar end
"""
read_array!(v::Array, f::JLDFile, rr)
Fill the array `v` with the contents of JLDFile `f` at the current position, assuming a
ReadRepresentation `rr`.
"""
function read_array! end
"""
read_compressed_array!(v::Array, f::JLDFile, rr, data_length::Int)
Fill the array `v` with the compressed contents of JLDFile `f` at the current position,
assuming a ReadRepresentation `rr` and that the compressed data has length `data_length`.
"""
function read_compressed_array! end
#
# MmapIO
#
# Cutoff for using ordinary IO instead of copying into mmapped region
const MMAP_CUTOFF = 1048576
@inline function read_scalar(f::JLDFile{MmapIO}, rr, header_offset::RelOffset)
io = f.io
inptr = io.curptr
obj = jlconvert(rr, f, inptr, header_offset)
io.curptr = inptr + odr_sizeof(rr)
obj
end
@inline function read_array!(v::Array{T}, f::JLDFile{MmapIO},
rr::ReadRepresentation{T,T}) where T
io = f.io
inptr = io.curptr
n = length(v)
nb = odr_sizeof(T)*n
if nb > MMAP_CUTOFF && (!Sys.iswindows() || !f.written)
# It turns out that regular IO is faster here (at least on OS X), but on Windows,
# we shouldn't use ordinary IO to read, since coherency with the memory map is not
# guaranteed
mmapio = f.io
regulario = mmapio.f
seek(regulario, inptr - io.startptr)
unsafe_read(regulario, pointer(v), nb)
else
unsafe_copyto!(pointer(v), convert(Ptr{T}, inptr), n)
end
io.curptr = inptr + odr_sizeof(T) * n
v
end
@inline function read_array!(v::Array{T}, f::JLDFile{MmapIO},
rr::ReadRepresentation{T,RR}) where {T,RR}
io = f.io
inptr = io.curptr
n = length(v)
@simd for i = 1:n
if !jlconvert_canbeuninitialized(rr) || jlconvert_isinitialized(rr, inptr)
@inbounds v[i] = jlconvert(rr, f, inptr, NULL_REFERENCE)
end
inptr += odr_sizeof(RR)
end
io.curptr = inptr + odr_sizeof(RR) * n
v
end
@inline function read_compressed_array!(v::Array{T}, f::JLDFile{MmapIO},
rr::ReadRepresentation{T,RR},
data_length::Int) where {T,RR}
io = f.io
inptr = io.curptr
data = transcode(ZlibDecompressor, unsafe_wrap(Array, Ptr{UInt8}(inptr), data_length))
@simd for i = 1:length(v)
dataptr = Ptr{Cvoid}(pointer(data, odr_sizeof(RR)*(i-1)+1))
if !jlconvert_canbeuninitialized(rr) || jlconvert_isinitialized(rr, dataptr)
@inbounds v[i] = jlconvert(rr, f, dataptr, NULL_REFERENCE)
end
end
io.curptr = inptr + data_length
v
end
function write_data(io::MmapIO, f::JLDFile, data, odr::S, ::ReferenceFree,
wsession::JLDWriteSession) where S
io = f.io
ensureroom(io, odr_sizeof(odr))
cp = io.curptr
h5convert!(cp, odr, f, data, wsession)
io.curptr == cp || throw(InternalError())
io.curptr = cp + odr_sizeof(odr)
nothing
end
function write_data(io::MmapIO, f::JLDFile, data, odr::S, ::HasReferences,
wsession::JLDWriteSession) where S
io = f.io
ensureroom(io, odr_sizeof(odr))
p = position(io)
cp = IndirectPointer(io, p)
h5convert!(cp, odr, f, data, wsession)
seek(io, p + odr_sizeof(odr))
nothing
end
@static if Sys.isunix()
function raw_write(io::MmapIO, ptr::Ptr{UInt8}, nb::Int)
if nb > MMAP_CUTOFF
pos = position(io)
# Ensure that the current page has been flushed to disk
msync(io, pos, min(io.endptr - io.curptr, nb))
# Write to the underlying IOStream
regulario = io.f
seek(regulario, pos)
unsafe_write(regulario, ptr, nb)
# Invalidate cache of any pages that were just written to
msync(io, pos, min(io.n - pos, nb), true)
# Make sure the mapping is encompasses the written data
ensureroom(io, nb + 1)
# Seek to the place we just wrote
seek(io, pos + nb)
else
unsafe_write(io, ptr, nb)
end
nothing
end
else
# Don't use ordinary IO to write files on Windows, since coherency with memory map is
# not guaranteed
function raw_write(io::MmapIO, ptr::Ptr{UInt8}, nb::Int)
unsafe_write(io, ptr, nb)
nothing
end
end
write_data(io::MmapIO, f::JLDFile, data::Array{T}, odr::Type{T}, ::ReferenceFree,
wsession::JLDWriteSession) where {T} =
raw_write(io, Ptr{UInt8}(pointer(data)), odr_sizeof(odr) * length(data))
function write_data(io::MmapIO, f::JLDFile, data::Array{T}, odr::S, ::ReferenceFree,
wsession::JLDWriteSession) where {T,S}
io = f.io
ensureroom(io, odr_sizeof(odr) * length(data))
cp = cporig = io.curptr
@simd for i = 1:length(data)
@inbounds h5convert!(cp, odr, f, data[i], wsession)
cp += odr_sizeof(odr)
end
io.curptr == cporig || throw(InternalError())
io.curptr = cp
nothing
end
function write_data(io::MmapIO, f::JLDFile, data::Array{T}, odr::S, ::HasReferences,
wsession::JLDWriteSession) where {T,S}
io = f.io
ensureroom(io, odr_sizeof(odr) * length(data))
p = position(io)
cp = IndirectPointer(io, p)
for i = 1:length(data)
if isassigned(data, i)
@inbounds h5convert!(cp, odr, f, data[i], wsession)
else
@inbounds h5convert_uninitialized!(cp, odr)
end
cp += odr_sizeof(odr)
end
seek(io, cp.offset)
nothing
end
#
# IOStream/BufferedWriter
#
@inline function read_scalar(f::JLDFile{IOStream}, rr, header_offset::RelOffset)
r = Vector{UInt8}(undef, odr_sizeof(rr))
@GC.preserve r begin
unsafe_read(f.io, pointer(r), odr_sizeof(rr))
jlconvert(rr, f, pointer(r), header_offset)
end
end
@inline function read_compressed_array!(v::Array{T}, f::JLDFile{IOStream},
rr::ReadRepresentation{T,RR},
data_length::Int) where {T,RR}
io = f.io
data_offset = position(io)
n = length(v)
data = read!(ZlibDecompressorStream(io), Vector{UInt8}(undef, odr_sizeof(RR)*n))
@simd for i = 1:n
dataptr = Ptr{Cvoid}(pointer(data, odr_sizeof(RR)*(i-1)+1))
if !jlconvert_canbeuninitialized(rr) || jlconvert_isinitialized(rr, dataptr)
@inbounds v[i] = jlconvert(rr, f, dataptr, NULL_REFERENCE)
end
end
seek(io, data_offset + data_length)
v
end
@inline function read_array!(v::Array{T}, f::JLDFile{IOStream},
rr::ReadRepresentation{T,T}) where T
unsafe_read(f.io, pointer(v), odr_sizeof(T)*length(v))
v
end
@inline function read_array!(v::Array{T}, f::JLDFile{IOStream},
rr::ReadRepresentation{T,RR}) where {T,RR}
n = length(v)
nb = odr_sizeof(RR)*n
io = f.io
data = read!(io, Vector{UInt8}(undef, nb))
@simd for i = 1:n
dataptr = Ptr{Cvoid}(pointer(data, odr_sizeof(RR)*(i-1)+1))
if !jlconvert_canbeuninitialized(rr) || jlconvert_isinitialized(rr, dataptr)
@inbounds v[i] = jlconvert(rr, f, dataptr, NULL_REFERENCE)
end
end
v
end
function write_data(io::BufferedWriter, f::JLDFile, data, odr::S, ::DataMode,
wsession::JLDWriteSession) where S
position = io.position[]
h5convert!(Ptr{Cvoid}(pointer(io.buffer, position+1)), odr, f, data, wsession)
io.position[] = position + odr_sizeof(odr)
nothing
end
function write_data(io::BufferedWriter, f::JLDFile, data::Array{T}, odr::Type{T}, ::ReferenceFree,
wsession::JLDWriteSession) where T
unsafe_write(io, Ptr{UInt8}(pointer(data)), odr_sizeof(odr) * length(data))
nothing
end
function write_data(io::IOStream, f::JLDFile, data::Array{T}, odr::Type{T}, ::ReferenceFree,
wsession::JLDWriteSession) where T
unsafe_write(io, Ptr{UInt8}(pointer(data)), odr_sizeof(odr) * length(data))
nothing
end
function write_data(io::BufferedWriter, f::JLDFile, data::Array{T}, odr::S,
::DataMode, wsession::JLDWriteSession) where {T,S}
position = io.position[]
cp = Ptr{Cvoid}(pointer(io.buffer, position+1))
@simd for i = 1:length(data)
if isassigned(data, i)
@inbounds h5convert!(cp, odr, f, data[i], wsession)
else
@inbounds h5convert_uninitialized!(cp, odr)
end
cp += odr_sizeof(odr)
end
io.position[] = position + odr_sizeof(odr) * length(data)
nothing
end
function write_data(io::IOStream, f::JLDFile, data::Array{T}, odr::S, wm::DataMode,
wsession::JLDWriteSession) where {T,S}
nb = odr_sizeof(odr) * length(data)
buf = Vector{UInt8}(undef, nb)
pos = position(io)
cp = Ptr{Cvoid}(pointer(buf))
@simd for i = 1:length(data)
if isassigned(data, i)
@inbounds h5convert!(cp, odr, f, data[i], wsession)
else
@inbounds h5convert_uninitialized!(cp, odr)
end
cp += odr_sizeof(odr)
end
# We might seek around in the file as a consequence of writing stuff, so seek back. We
# don't need to worry about this for a BufferedWriter, since it will seek back before
# writing.
!isa(wm, ReferenceFree) && seek(io, pos)
write(io, buf)
nothing
end
|
"""
## module ASE
### Summary
Provides Julia wrappers for some of ASE's functionality. Currently:
* `ase.Atoms` becomes `type ASEAtoms`
* `ase.calculators.neighborlist.NeighborList`
should become `ASENeighborList`, but it is ignored to use
the `matscipy` neighbourlist instead.
TODO: implement ASENeighbourList as backup in case `matscipy` is
not available
* `Atoms.get_array` becomes `get_data`
* `Atoms.set_array` becomes `set_data!`
"""
module ASE
# the functions to be implemented
import JuLIP:
positions, set_positions!, unsafe_positions, # ✓
cell, set_cell!, # ✓
pbc, set_pbc!, # ✓
set_data!, get_data, # ✓
calculator, set_calculator!, # ✓
constraint, set_constraint!, # ✓
neighbourlist, # ✓
energy, forces
import Base.length, Base.deleteat! # ✓
# from arrayconversions:
using JuLIP: mat, vecs, JVecF, JVecs, JVecsF, pyarrayref,
AbstractAtoms, AbstractConstraint, NullConstraint,
AbstractCalculator, NullCalculator
# extra ASE functionality:
import Base.repeat # ✓
export ASEAtoms, # ✓
repeat, rnn, chemical_symbols, ASECalculator, extend!
using PyCall
@pyimport ase.io as ase_io
@pyimport ase.atoms as ase_atoms
@pyimport ase.build as ase_build
#################################################################
### Wrapper for ASE Atoms object and its basic functionality
################################################################
"""
`type ASEAtoms <: AbstractAtoms`
Julia wrapper for the ASE `Atoms` class.
## Constructors
The default constructor is
```
at = ASEAtoms("Al"; repeat=(2,3,4), cubic=true, pbc = (true, false, true))
```
For internal usage there is also a constructor `ASEAtoms(po::PyObject)`
"""
type ASEAtoms <: AbstractAtoms
po::PyObject # ase.Atoms instance
calc::AbstractCalculator
cons::AbstractConstraint
end
ASEAtoms(po::PyObject) = ASEAtoms(po, NullCalculator(), NullConstraint())
function set_calculator!(at::ASEAtoms, calc::AbstractCalculator)
at.calc = calc
return at
end
calculator(at::ASEAtoms) = at.calc
function set_constraint!(at::ASEAtoms, cons::AbstractConstraint)
at.cons = cons
return at
end
constraint(at::ASEAtoms) = at.cons
function ASEAtoms( s::AbstractString;
repeatcell=nothing, cubic=false, pbc=(true,true,true) )
at = bulk(s, cubic=cubic)
repeatcell != nothing ? at = repeat(at, repeatcell) : nothing
set_pbc!(at, pbc)
return at
end
ASEAtoms(s::AbstractString, X::JVecsF) = ASEAtoms( ase_atoms.Atoms(s, mat(X)') )
"Return the PyObject associated with `a`"
pyobject(a::ASEAtoms) = a.po
get_array(a::ASEAtoms, name) = a.po[:get_array(name)]
set_array!(a::ASEAtoms, name, value) = a.po[:set_array(name, value)]
#
# TODO: write an explanation about storage layout here
#
positions(at::ASEAtoms) = copy( pyarrayref(at.po["positions"]) ) |> vecs
unsafe_positions(at::ASEAtoms) = pyarrayref(at.po["positions"]) |> vecs
function set_positions!(a::ASEAtoms, p::JVecsF)
p_py = PyReverseDims(mat(p))
a.po[:set_positions](p_py)
return a
end
length(at::ASEAtoms) = length( unsafe_positions(at::ASEAtoms) )
set_pbc!(at::ASEAtoms, val::Bool) = set_pbc!(at, (val,val,val))
function set_pbc!(a::ASEAtoms, val::NTuple{3,Bool})
a.po[:pbc] = val
return a
end
pbc(a::ASEAtoms) = a.po[:pbc]
cell(at::ASEAtoms) = at.po[:get_cell]()
set_cell!(a::ASEAtoms, p::Matrix) = (a.po[:set_cell](p); a)
function deleteat!(at::ASEAtoms, n::Integer)
at.po[:__delitem__](n-1) # delete in the actual array
return at
end
"""
`repeat(a::ASEAtoms, n::(Int64, Int64, Int64)) -> ASEAtoms`
Takes an `ASEAtoms` configuration / cell and repeats is n_j times
into the j-th dimension. For example,
```
atm = repeat( bulk("C"), (3,3,3) )
```
creates 3 x 3 x 3 unit cells of carbon.
"""
repeat(a::ASEAtoms, n::NTuple{3, Int64}) = ASEAtoms(a.po[:repeat](n))
import Base.*
*(at::ASEAtoms, n::NTuple{3, Int64}) = repeat(at, n)
*(n::NTuple{3, Int64}, at::ASEAtoms) = repeat(at, n)
*(at::ASEAtoms, n::Integer) = repeat(at, (n,n,n))
*(n::Integer, at::ASEAtoms) = repeat(at, (n,n,n))
export bulk, graphene_nanoribbon, nanotube, molecule
@doc ase_build.bulk[:__doc__] ->
bulk(args...; kwargs...) = ASEAtoms(ase_build.bulk(args...; kwargs...))
@doc ase_build.graphene_nanoribbon[:__doc__] ->
graphene_nanoribbon(args...; kwargs...) =
ASEAtoms(ase_build.graphene_nanoribbon(args...; kwargs...))
"nanotube(n, m, length=1, bond=1.42, symbol=\"C\", verbose=False)"
nanotube(args...; kwargs...) =
ASEAtoms(ase_build.nanotube(args...; kwargs...))
@doc ase_build.molecule[:__doc__] ->
molecule(args...; kwargs...) =
ASEAtoms(ase_build.molecule(args...; kwargs...))
############################################################
# matscipy neighbourlist functionality
############################################################
include("MatSciPy.jl")
neighbourlist(at::ASEAtoms, cutoff::Float64) = MatSciPy.NeighbourList(at, cutoff)
######################################################
# Attaching an ASE-style calculator
# ASE-style aliases
######################################################
type ASECalculator <: AbstractCalculator
po::PyObject
end
function set_calculator!(at::ASEAtoms, calc::ASECalculator)
at.po[:set_calculator](calc.po)
at.calc = calc
return at
end
set_calculator!(at::ASEAtoms, po::PyObject) =
set_calculator!(at, ASECalculator(po))
forces(calc::ASECalculator, at::ASEAtoms) = at.po[:get_forces]()' |> vecs
energy(calc::ASECalculator, at::ASEAtoms) = at.po[:get_potential_energy]()
"""
Creates an `ASECalculator` that uses `ase.calculators.emt` to compute
energy and forces. This is very slow and is only included for
demonstration purposes.
"""
function EMTCalculator()
@pyimport ase.calculators.emt as emt
return ASECalculator(emt.EMT())
end
################### extra ASE functionality ###################
# TODO: we probably want more of this
# and a more structured way to translate
#
"""
`extend!(at::ASEAtoms, atadd::ASEAtoms)`
add `atadd` atoms to `at` and returns `at`; only `at` is modified
A short variant is
```julia
extend!(at, (s, x))
```
where `s` is a string, `x::JVecF` a position
"""
function extend!(at::ASEAtoms, atadd::ASEAtoms)
at.po[:extend](atadd.po)
return at
end
extend!{S <: AbstractString}(at::ASEAtoms, atnew::Tuple{S,JVecF}) =
extend!(at, ASEAtoms(atnew[1], atnew[2]))
"return vector of chemical symbols as strings"
chemical_symbols(at::ASEAtoms) = pyobject(at)[:get_chemical_symbols]()
write(filename::AbstractString, at::ASEAtoms) = ase_io.write(filename, at.po)
# TODO: trajectory; see
# https://wiki.fysik.dtu.dk/ase/ase/io/trajectory.html
# TODO: rnn should be generalised to compute a reasonable rnn estimate for
# an arbitrary set of positions
"""
`rnn(species)` : returns the nearest-neighbour distance for a given species
"""
function rnn(species::AbstractString)
X = unsafe_positions(bulk(species) * 2)
return minimum( norm(X[n]-X[m]) for n = 1:length(X) for m = n+1:length(X) )
end
end # module
|
### A Pluto.jl notebook ###
# v0.15.1
using Markdown
using InteractiveUtils
# ╔═╡ 89495294-10ed-11ec-04a9-db58dba9f3d1
begin
using MixedModels # run mixed models
using MixedModelsSim # simulation functions for mixed models
using DataFrames, Tables # work with data tables
using StableRNGs # random number generator
using CSV # write CSV files
using Statistics # basic math funcions
using DataFramesMeta # dplyr-like operations
using Gadfly # plotting package
using PlutoUI
end
# ╔═╡ c071c03f-6ddb-415e-8445-b4fd8d45abc1
md"""
Power Analysis and Simulation Tutorial
======================================
This tutorial demonstrates how to conduct power analyses and data simulation using Julia and the MixedModelsSim package.
Power analysis is an important tool for planning an experimental design. Here we show how to
1. Take existing data and calculate power by simulating new data.
2. Adapt parameters in a given Linear Mixed Model to analyze power without changing the existing data set.
3. Create a (simple) balanced fully crossed dataset from scratch and analyze power.
4. Recreate a more complex dataset from scratch and analyze power for specific model parameter but various sample sizes.
### Load the packages we'll be using in Julia
First, here are the packages needed in this example.
"""
# ╔═╡ 14ae0269-ea23-4c73-a04f-40eece7a5bc5
TableOfContents()
# ╔═╡ 76df9a69-7ee6-4876-9dcc-e6178f59d3ad
md"
### Define number of iterations
Here we define how many model simulations we want to do. A large number will give more reliable results, but will take longer to compute. It is useful to set it to a low number for testing, and increase it for your final analysis.
"
# ╔═╡ 16822577-6f44-4330-9181-678bb2c7cce2
nsims = 500
# ╔═╡ d4e9bb7e-3f70-48fb-a73c-9606cfb39f39
md"""
## Take existing data and calculate power by simulate new data with bootstrapping.
### Build a Linear Mixed Model from existing data.
For the first example we are going to simulate bootstrapped data from an existing data set:
*Experiment 2 from Kronmüller, E., & Barr, D. J. (2007). Perspective-free pragmatics: Broken precedents and the recovery-from-preemption hypothesis. Journal of Memory and Language, 56(3), 436-455.*
The data we will be using through out this tutorial is a study about how in a conversation the change of a speaker or the change of precedents (which are patterns of word usage to discribe an object, e.g. one can refer to the same object "white shoes", "runners", "sneakers") affects the understanding.
Objects are presented on a screen while participants listen to instructions to move the objects around. Participants eye movements are tracked.
The dependent variable is response time, defined as the latency between the onset of the test description and the moment at which the target was selected.
The independent variables are speaker (old vs. new), precedents (maintain vs. break) and cognitive load (a secondary memory task).
We have to load the data and define some characteristics like the contrasts and the underlying model.
Load existing data:
"""
# ╔═╡ 4c00bf63-1d33-4f16-9776-e2f3915850f9
kb07 = MixedModels.dataset(:kb07);
# ╔═╡ 87af988a-2d55-4c24-a132-3c76f1ae562b
md"""
Set contrasts:
"""
# ╔═╡ 8caad72c-a8d7-4e23-8eb6-b9096141b471
contrasts = Dict(:spkr => HelmertCoding(),
:prec => HelmertCoding(),
:load => HelmertCoding());
# ╔═╡ 29b32ea9-0018-4ec3-9095-1e527e11fc4f
md"""
The chosen LMM for this dataset is defined by the following model formula:
"""
# ╔═╡ 3763460c-046d-46ce-b9ef-4faf1fbd0428
kb07_f = @formula( rt_trunc ~ 1 + spkr+prec+load + (1|subj) + (1+prec|item) );
# ╔═╡ f05a1f73-503a-4ed7-8879-1da242b2b224
md"""
Fit the model:
"""
# ╔═╡ a75ad071-0789-41ab-9253-27c8bca615ad
kb07_m = fit(MixedModel, kb07_f, kb07; contrasts=contrasts)
# ╔═╡ 8e4629aa-58b7-4ab8-8954-74ee579a3f9b
md"""
### Simulate from existing data with same model parameters
We will first look at the power of the dataset with the same parameters as in the original data set. This means that each dataset will have the exact number of observations as the original data. Here, we use the model `kb07_m` we fitted above to our dataset `kb07`.
You can use the `parameparametricbootstrap()` function to run `nsims` iterations of data sampled using the parameters from `kb07_m`.
Set up a random seed to make the simulation reproducible. You can use your favourite number.
To use multithreading, you need to set the number of cores you want to use.
E.g. in Visual Studio Code, open the settings (gear icon in the lower left corner or cmd-,) and search for "thread".
Set `julia.NumThreads` to the number of cores you want to use (at least 1 less than your total number).
Set random seed for reproducibility:
"""
# ╔═╡ 3e0e9908-002c-4def-a2eb-c8f7d775f205
rng = StableRNG(42);
# ╔═╡ 33d9ecae-ac5c-4fdf-bd1a-4d68f785084a
md"""
Run nsims iterations:
"""
# ╔═╡ b3e2dea0-bfb0-4d5d-bd9c-8ed0e0272cc0
kb07_sim = parametricbootstrap(rng, nsims, kb07_m; use_threads = false);
# ╔═╡ 1b814e14-136e-45ad-83e9-c783e30dc4b1
md"""
**Try**: Run the code above with or without `use_threads = true`.
The output DataFrame `kb07_sim` contains the results of the bootstrapping procedure.
"""
# ╔═╡ fc141d66-3252-4989-b6e4-98bbfe82385a
df = DataFrame(kb07_sim.allpars);
# ╔═╡ 5d7c1822-453c-4483-a1a1-32e149145afb
first(df, 9)
# ╔═╡ ef3c9d81-38cf-45d6-9258-926ad209e36f
nrow(df)
# ╔═╡ 146c6a52-a512-4601-9b58-bc56575bfb2e
md"""
The dataframe df has 4500 rows: 9 parameters, each from 500 iterations.
Plot some bootstrapped parameter:"""
# ╔═╡ 4598ae9a-8d39-4280-a74a-4d7145d64920
begin
σres = @where(df, :type .== "σ", :group .== "residual").value
plot(x = σres, Geom.density, Guide.xlabel("Parametric bootstrap estimates of σ"), Guide.ylabel("Density"))
βInt = @where(df, :type .== "β", :names .== "(Intercept)").value
plot(x = βInt, Geom.density, Guide.xlabel("Parametric bootstrap estimates of β (Intercept)"), Guide.ylabel("Density"))
βSpeaker = @where(df, :type .== "β", :names .== "spkr: old").value
plot(x = βSpeaker, Geom.density, Guide.xlabel("Parametric bootstrap estimates of β Speaker"), Guide.ylabel("Density"))
βPrecedents = @where(df, :type .== "β", :names .== "prec: maintain").value
plot(x = βPrecedents, Geom.density, Guide.xlabel("Parametric bootstrap estimates of β Precedents"), Guide.ylabel("Density"))
βLoad = @where(df, :type .== "β", :names .== "load: yes").value
plot(x = βLoad, Geom.density, Guide.xlabel("Parametric bootstrap estimates of β Load"), Guide.ylabel("Density"))
end
# ╔═╡ fa91a0f8-675e-4155-9ff4-58090689c397
md"""
Convert p-values of your fixed-effects parameters to dataframe
"""
# ╔═╡ 811a81ac-50d9-4d07-98d1-3fc8e1586685
kb07_sim_df = DataFrame(kb07_sim.coefpvalues);
# ╔═╡ d8257d21-8dad-4533-ba93-78ba7c3202b3
md"""
Have a look at your simulated data:
"""
# ╔═╡ ac2f3b62-e86c-43b2-8109-558db79e5773
first(kb07_sim_df, 8)
# ╔═╡ 67493854-920e-477e-805b-21d58cd19ade
md"""
Now that we have a bootstrapped data, we can start our power calculation.
### Power calculation
The function `power_table()` from `MixedModelsSim` takes the output of `parametricbootstrap()` and calculates the proportion of simulations where the p-value is less than alpha for each coefficient.
You can set the `alpha` argument to change the default value of 0.05 (justify your alpha).
"""
# ╔═╡ 8c06724f-a947-44c2-8541-7aa50c915356
ptbl = power_table(kb07_sim,0.05)
# ╔═╡ fc239c6e-ca35-4df6-81b2-115be160437b
md"""
An estimated power of 1 means that in every iteration the specific parameter we are looking at was below our alpha.
An estimated power of 0.5 means that in half of our iterations the specific parameter we are looking at was below our alpha.
An estimated power of 0 means that for none of our iterations the specific parameter we are looking at was below our alpha.
You can also do it manually:
"""
# ╔═╡ 97907ccc-e4b8-43a3-9e5a-ae1da59a203a
kb07_sim_df[kb07_sim_df.coefname .== Symbol("prec: maintain"),:]
# ╔═╡ a383994a-e4f4-4c9e-9f17-32ec11e32e87
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("(Intercept)"),:p] .< 0.05)
# ╔═╡ 523c1c21-43d2-469e-b138-3dd5cab1e6b9
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("spkr: old"),:p] .< 0.05)
# ╔═╡ 3419a020-7333-4cb5-981b-84e7fa788280
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("prec: maintain"),:p] .< 0.05)
# ╔═╡ 231ce20d-ea0c-4314-a7b0-0e296bc2160b
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("load: yes"),:p] .< 0.05)
# ╔═╡ b66ab7be-0547-4535-9d33-cfae62441c61
md"""
For nicely displaying, you can use `pretty_table`:
"""
# ╔═╡ 356751b1-73cc-4dae-ad5a-b1cd0b45ede0
pretty_table(ptbl)
# ╔═╡ 910ca4be-d4bf-4231-95d6-de8b3e97d4d5
md"""
## Adapt parameters in a given Linear Mixed Model to analyze power without changing the existing data set.
Let's say we want to check our power to detect effects of spkr, prec, and load
that are only half the size as in our pilot data. We can set a new vector of beta values
with the `β` argument to `parametricbootstrap()`.
Set random seed for reproducibility:
"""
# ╔═╡ 11eacaa9-f309-4c72-a659-3fc262f3111f
md"""
Specify β:
"""
# ╔═╡ bc6ace0a-2776-409c-892c-6892df79f0e7
new_beta = kb07_m.β
# ╔═╡ bbe93bad-4d41-4300-910a-ec16a660def3
new_beta[2:4] = kb07_m.β[2:4]/2;
# ╔═╡ 9510ce0a-6ba7-4903-8e2a-84f6fc69492c
new_beta
# ╔═╡ f5436bb7-9087-437f-bc43-1b113c907695
md"""Run nsims iterations:"""
# ╔═╡ 9fbfff0f-289c-4c92-9ffa-615ad1b69ff2
kb07_sim_half = parametricbootstrap(rng, nsims, kb07_m; β = new_beta, use_threads = false);
# ╔═╡ 7aa2cea2-9136-42ad-bc62-9966aa93b84c
md"""### Power calculation
"""
# ╔═╡ f7a5cffe-2819-4a9f-a56e-45fefb2c4201
power_table(kb07_sim_half)
# ╔═╡ c3c9ab9c-c81d-44d2-bd45-fb72a7c5da8a
md"""
Convert p-values of your fixed-effects parameters to dataframe
"""
# ╔═╡ 9e9c337e-556f-44a8-ad5f-0476be1458b0
kb07_sim_half_df = DataFrame(kb07_sim_half.coefpvalues);
# ╔═╡ 6b7fdacd-1343-42a2-8e7e-d06bd559765d
mean(kb07_sim_half_df[kb07_sim_half_df.coefname .== Symbol("(Intercept)"),:p] .< 0.05)
# ╔═╡ f232988a-c3cf-404f-9f0d-fe0ef591e8bb
mean(kb07_sim_half_df[kb07_sim_half_df.coefname .== Symbol("spkr: old"),:p] .< 0.05)
# ╔═╡ ed309fad-0058-4069-8e8e-e526b2b36370
mean(kb07_sim_half_df[kb07_sim_half_df.coefname .== Symbol("prec: maintain"),:p] .< 0.05)
# ╔═╡ 2fc97a13-abc5-42ff-a1eb-28e24271fae0
mean(kb07_sim_half_df[kb07_sim_half_df.coefname .== Symbol("load: yes"),:p] .< 0.05)
# ╔═╡ 42f4e755-c7b1-46e2-91fd-31a19ccd5685
md"""## Create a (simple) balanced fully crossed dataset from scratch and analyze power.
"""
# ╔═╡ fcd25a28-cb0d-4077-8b20-f5837c4e99f8
md"""
In some situations, instead of using an existing dataset it may be useful to simulate the data from scratch. This could be the case when the original data is not available but the effect sizes are known. That means that we have to:
a) specify the effect sizes manually
b) manually create an experimental design, according to which data can be simulated
If we simulate data from scratch, aside from subject and item number, we can manipulate the arguments `β`, `σ` and `θ`.
Lets have a closer look at them, define their meaning and we will see where the corresponding values in the model output are.
"""
# ╔═╡ ae7efbb0-aa35-4128-aebf-10a1deab5fee
md"""
### Fixed Effects (βs)
`β` are our effect sizes. If we look again on our LMM summary from the `kb07`-dataset `kb07_m`
we see our four `β` under fixed-effects parameters in the `Est.`-column.
"""
# ╔═╡ 21567edd-0593-4823-b538-15dcb0de48f0
kb07_m
# ╔═╡ 5eb6074a-a695-4404-841e-21b7b82f1150
kb07_m.β
# ╔═╡ a02e6191-239f-4b0b-996d-f73bfc54ea28
md"""
### Residual Variance (σ)
`σ` is the `residual`-standard deviation also listed in the `Est.`-column.
"""
# ╔═╡ ce275097-63e5-410e-a23b-9fdd4250e35c
kb07_m
# ╔═╡ c5f9f6ad-0b18-434b-a368-42afd8cb398e
kb07_m.σ
# ╔═╡ 9adf46f1-d84c-4ae3-af1b-2087adbf0315
md"""
### Random Effects (θ)
The meaning of `θ` is a bit less intuitive. In a less complex model (one that only has intercepts for the random effects) or if we suppress the correlations in the formula with `zerocorr()` then `θ` describes the relationship between the random effects standard deviation and the standard deviation of the residual term.
In our `kb07_m` example:
The `residual` standard deviation is `680.032`.
The standard deviation of our first variance component *`item - (Intercept)`* is `364.713`.
Thus our first `θ` is the relationship: variance component devided by `residual` standard deviation
364.713 / 680.032 = `0.53631`
"""
# ╔═╡ 077b22ae-814f-4b18-8297-2124317cbff6
kb07_m.θ
# ╔═╡ f33d0b96-3b3c-4651-8b39-46461445cd09
md"""
We also can calculate the `θ` for variance component *`subj - (Intercept)`*.
The `residual` standard deviation is `680.032`.
The standard deviation of our variance component *`subj - (Intercept)`* is `298.026`.
Thus, the related θ is the relationship: variance component devided by `residual` standard deviation
298.026 / 680.032 = `0.438252`
"""
# ╔═╡ 8103cf6e-18a2-40a1-8043-c87ed92e1c11
kb07_m.θ
# ╔═╡ cdee3c0c-6c85-4515-8ffd-1b1c71018e09
md"""
We can not calculate the `θ`s for variance component *`item - prec: maintain`* this way, because it includes the correlation of
*`item - prec: maintain`* and *`item - (Intercept)`*. But keep in mind that the relation of *`item - prec: maintain`*-variability (`252.521`)
and the `residual`-variability (`680.032`) is 252.521 / 680.032 = `0.3713369`.
The `θ` vector is the flattened version of the variance-covariance matrix - a lowertrinangular matrix.
The on-diagonal elements are just the standard deviations (the `σ`'s). If all off-diagonal elements are zero, we can use our
calculation above. The off-diagonal elements are covariances and correspond to the correlations (the `ρ`'s).
If they are unequal to zero, as it is in our `kb07`-dataset, one way to get the two missing `θ`-values is to take the values directly from the model we have already fitted.
See the two inner values:
"""
# ╔═╡ f5535f46-e919-4dad-9f0e-337d68ab669b
kb07_m.θ
# ╔═╡ 6f2c0659-3f5d-45d8-8a40-b3124ce49fa3
md"""
Another way is to make use of the `create_re()` function.
Here you have to define the relation of all random effects variabilities to the variability of the residuals, as shown above,
and the correlation-matrices.
Let's start by defining the correlation matrix for the `item`-part.
The diagonal is always `1.0` because everything is perfectly correlated with itself.
The elements below the diagonal follow the same form as the `Corr.` entries in the output of `VarCorr()`.
In our example the correlation of
*`item - prec: maintain`* and *`item - (Intercept)`* is `-0.7`.
The elements above the diagonal are just a mirror image.
"""
# ╔═╡ 9b5601c0-613e-426f-9318-c87ba9108f42
re_item_corr = [1.0 -0.7; -0.7 1.0]
# ╔═╡ d0493428-916e-4bfe-8f5a-586e21af0f5c
md"""
Now we put together all relations of standard deviations and the correlation-matrix for the `item`-group.
This calculates the covariance factorization which is the theta matrix.
"""
# ╔═╡ ca0b404c-50da-43eb-8bb6-d6037e09ba64
re_item = create_re(0.536, 0.371; corrmat = re_item_corr)
# ╔═╡ 2a04994e-bb88-455b-a732-bae9ef1c5422
md" ![](https://github.com/lschwetlick/MixedModelsSim.jl/blob/new_tutorial/docs/src/ThetaExplanation.png?raw=true)"
# ╔═╡ 5e364a80-e5d9-458b-be1e-d00dafa04033
md"""
Note: Don't be too specific with your values in create_re(). If there are rounding errors, you will get the error-message:
`PosDefException: matrix is not Hermitian; Cholesky factorization failed.`
But you can extract the exact values like shown below:
"""
# ╔═╡ 026c051d-bcfa-4b1d-8648-bdd0d8cdf894
corr_exact = VarCorr(kb07_m).σρ.item.ρ[1]
# ╔═╡ 2951d7fe-0373-4f52-86e3-c11bd7a57f1a
σ_residuals_exact = VarCorr(kb07_m).s
# ╔═╡ 1ddbde42-6dcc-425d-b906-92880bb15e89
σ_1_exact = VarCorr(kb07_m).σρ.item.σ[1] / σ_residuals_exact
# ╔═╡ 29ef3cab-e774-4cf8-a392-92eec8acc98b
σ_2_exact = VarCorr(kb07_m).σρ.item.σ[2] / σ_residuals_exact
# ╔═╡ 37f07a78-3616-41c4-90ad-6fc52d9223b3
re_item_corr_exact = [1.0 corr_exact; corr_exact 1.0]
# ╔═╡ f4929a81-71db-4a78-86f9-22c7ed89f04d
re_item_exact = create_re(σ_1_exact, σ_2_exact; corrmat = re_item_corr_exact)
# ╔═╡ dd8aa406-ef50-4036-9d6f-f499934a84c3
md"""
Let's continue with the `subj`-part.
Since there the by-subject random effects have only one entry (the intercept), there are no correlations to specify and we can omit the `corrmat` argument.
Now we put together all relations of standard deviations and the correlation-matrix for the `subj`-group:
This calculates the covariance factorization which is the theta matrix.
"""
# ╔═╡ f8432a72-da18-4540-9a26-2c4091bd43ac
re_subj = create_re(0.438)
# ╔═╡ 1fb0fa62-9757-4a0c-ac67-89a6f4b68caf
md"""
If you want the exact value you can use
"""
# ╔═╡ 47ddae23-9cfd-4db1-bbe7-446c456a2fb5
md"""
We already extracted
"""
# ╔═╡ ce10d865-0edf-4f34-9142-48297fb79810
σ_residuals_exact
# ╔═╡ c1055a38-1f1a-4ef2-9fda-fe14670821b9
md"""
Following the above logic, but of course you can only do the first step:"""
# ╔═╡ 651a7d74-715a-4562-85b1-97a8bdaf27a2
σ_3_exact = VarCorr(kb07_m).σρ.subj.σ[1] / σ_residuals_exact
# ╔═╡ 3e182015-b555-4b9a-91b9-5e6a58e020b3
re_subj_exact = create_re(σ_3_exact)
# ╔═╡ 4ca9d39a-c061-4f99-b240-bd8fdd773530
md"""
As mentioned above `θ` is the compact form of these covariance matrices:
"""
# ╔═╡ 4d5abbf8-5c04-41e6-a49d-8798c985f953
kb07_m.θ = vcat( flatlowertri(re_item), flatlowertri(re_subj) )
# ╔═╡ b6d4353c-c4bf-421e-abd6-e1c4e427f1fe
md"""
We can install these parameter in the `parametricbootstrap()`-function or in the model like this:
"""
# ╔═╡ 223f7d34-e433-49f4-bae7-818ec91985df
update!(kb07_m, re_item, re_subj)
# ╔═╡ 82f87d91-963a-4fb9-96c1-162db2cd9c58
md"""
## A simple example from scratch
"""
# ╔═╡ d9eb46c8-c37a-4037-aca6-addf66690a10
md"""
Having this knowledge about the parameters we can now **simulate data from scratch**
The `simdat_crossed()` function from `MixedModelsSim` lets you set up a data frame with a specified experimental design.
For now, it only makes fully balanced crossed designs!, but you can generate an unbalanced design by simulating data for the largest cell and deleting extra rows.
Firstly we will set an easy design where `subj_n` subjects per `age` group (O or Y) respond to `item_n` items in each of two `condition`s (A or B).
Your factors need to be specified separately for between-subject, between-item, and within-subject/item factors using `Dict` with the name of each factor as the keys and vectors with the names of the levels as values.
We start with the between subject factors:
"""
# ╔═╡ 2a6a4bf8-93f6-4185-8510-bb0c0cb979c8
subj_btwn_smpl = Dict("age" => ["O", "Y"])
# ╔═╡ cd479f01-7b04-46c7-9f23-8615dee536de
md"""
There are no between-item factors in this design so you can omit it or set it to nothing.
Note that if you have factors which are between subject and between item, you need to put them in both dicts.
"""
# ╔═╡ 356b2ee9-aecc-4819-b535-eb11e46d2e52
item_btwn_smpl = nothing
# ╔═╡ ec41b5cf-461f-4655-a3c0-dc7db29e3ac6
md"""
Next, we put within-subject/item factors in a dict:
"""
# ╔═╡ 811669c1-ea76-4db2-a09a-de3480cb428b
both_win_smpl = Dict("condition" => ["A", "B"])
# ╔═╡ 20b38246-966b-4cc3-82ce-4cdb76be058e
md"""
Define subject and item number:
"""
# ╔═╡ 2a3411a4-42df-4f6c-bf38-cc7114c5ec87
begin
subj_n_smpl = 10
item_n_smpl = 30
end
# ╔═╡ 48f404de-f654-4021-ba98-edeaabec6e5b
md"""
Simulate data:
"""
# ╔═╡ 2164a837-b0e9-4207-90fd-4db090021963
dat_smpl = simdat_crossed(subj_n_smpl,
item_n_smpl,
subj_btwn = subj_btwn_smpl,
item_btwn = item_btwn_smpl,
both_win = both_win_smpl);
# ╔═╡ 873d708d-3f3a-4510-877d-25f73710a35b
md"Have a look:
"
# ╔═╡ d5b7f38f-2e72-44b6-9d37-131a14e47658
first(DataFrame(dat_smpl),8)
# ╔═╡ f3465ca6-8838-4f71-9f8a-df727c0f3780
first(sort(DataFrame(dat_smpl),[:subj,:item]),18)
# ╔═╡ 6155d5d8-cf14-4c73-8f41-b0ac5f40244a
md"""
The values we see in the column `dv` is just random noise.
Set contrasts:
"""
# ╔═╡ 91120f25-068e-402c-9b13-2eb8d3833b0c
contrasts_smpl = Dict(:age => HelmertCoding(),
:condition => HelmertCoding());
# ╔═╡ 0f627b49-72c6-4235-a7f2-bd3bd758704a
md"""Define formula:
"""
# ╔═╡ 7a9c7cd3-851b-4d2b-be12-cea014e834e5
f1 = @formula dv ~ 1 + age * condition + (1|item) + (1|subj);
# ╔═╡ b4f9eff5-3626-47ed-ab8a-8d70f926c831
md"""Note that we did not include condition as random slopes for item and subject.
This is mainly to keep the example simple and to keep the parameter `θ` easier to understand (see Section 3 for the explanation of theta).
Fit the model:"""
# ╔═╡ 5caa14d8-73b8-46d7-b0e1-bc58522f24eb
m1 = fit(MixedModel, f1, dat_smpl, contrasts=contrasts_smpl)
# ╔═╡ 97af5c8a-ab21-45c1-8fbc-39f749c4d0c7
md"""
Because the `dv` is just random noise from N(0,1), there will be basically no subject or item random variance, residual variance will be near 1.0, and the estimates for all effects should be small.
Don't worry, we'll specify fixed and random effects directly in `parametricbootstrap()`.
Set random seed for reproducibility:
"""
# ╔═╡ 7dfc2f19-bcb8-4669-a119-5238e248ac5c
rng_smpl = StableRNG(42);
# ╔═╡ c88f5177-1a24-4ffc-9228-3f8bd873eb07
md"""
Specify `β`, `σ`, and `θ`, we just made up this parameter:
"""
# ╔═╡ 72304a3d-6a3a-40a5-933f-4cc88852db11
new_beta_smpl = [0.0, 0.25, 0.25, 0.]
# ╔═╡ 99f81384-06c3-45a4-8ccf-305ab7622fe3
new_sigma_smpl = 2.0
# ╔═╡ a171e0d3-a406-42cf-9567-4d33d7be3159
new_theta_smpl = [1.0, 1.0]
# ╔═╡ e7740a25-15c2-4997-b838-22f4e8b9bf78
md"""
Run nsims iterations:
"""
# ╔═╡ 08d1781d-dad4-47c8-861f-d745d0f406bf
sim_smpl = parametricbootstrap(rng_smpl, nsims, m1,
β = new_beta_smpl,
σ = new_sigma_smpl,
θ = new_theta_smpl,
use_threads = false);
# ╔═╡ 7b7423be-dbbf-4e13-8c98-2eea4df0d02f
md"""
### Power calculation
"""
# ╔═╡ 97130e8f-f155-4c4f-a061-696bdbb3c588
ptbl_smpl= power_table(sim_smpl)
# ╔═╡ 55096ce7-b7f2-4884-a853-a87316cd171a
DataFrame(shortestcovint(sim_smpl))
# ╔═╡ 7dd1cd44-ee63-4c14-9e82-d2b7c7cef7f8
md"""
For nicely displaying it, you can use pretty_table:
"""
# ╔═╡ 63f69580-c5bc-463e-a42b-757b3d897be1
pretty_table(ptbl_smpl)
# ╔═╡ d57de97c-c21f-4e74-b093-5d3a552609e7
md"""
Convert p-values of your fixed-effects parameters to dataframe
"""
# ╔═╡ ac8ba024-a466-419d-9c80-ef9212228361
sim_smpl_df = DataFrame(sim_smpl.coefpvalues);
# ╔═╡ 0cff3191-cdd7-43dc-8761-7ad8bfc64b8c
[mean(sim_smpl_df[sim_smpl_df.coefname .== Symbol("(Intercept)"),:p] .< 0.05),
mean(sim_smpl_df[sim_smpl_df.coefname .== Symbol("age: Y"),:p] .< 0.05),
mean(sim_smpl_df[sim_smpl_df.coefname .== Symbol("condition: B"),:p] .< 0.05),
mean(sim_smpl_df[sim_smpl_df.coefname .== Symbol("age: Y & condition: B"),:p] .< 0.05)]
# ╔═╡ fc75435a-3cce-42ab-9e7d-3b9126d634b6
md"""
## Recreate a more complex dataset from scratch and analyze power for specific model parameter but various sample sizes.
### Recreate the `kb07`-dataset from scratch
For full control over all parameters in our `kb07` data set we will recreate the design using the method shown above.
Define subject and item number:
"""
# ╔═╡ a48b29ef-94da-4917-b1fe-e9101e56f319
begin
subj_n_cmpl = 56
item_n_cmpl = 32
end
# ╔═╡ 9dcbb3f7-c2d2-4b05-aa25-5adb4ca72d7f
md"""
Define factors in a dict:
"""
# ╔═╡ 8d13df4c-8468-482b-92f7-62f28a1bf995
begin
subj_btwn_cmpl = nothing
item_btwn_cmpl = nothing
both_win_cmpl = Dict("spkr" => ["old", "new"],
"prec" => ["maintain", "break"],
"load" => ["yes", "no"]);
end
# ╔═╡ d63c51d1-1ef8-4aa9-b0f1-288c387f6d72
md"### **Try**: Play with `simdat_crossed`.
"
# ╔═╡ 7bbe248a-6ff5-44f6-9cd4-4fdbd48b81ec
begin
subj_btwn_play = nothing
item_btwn_play = nothing
both_win_play = Dict("spkr" => ["old", "new"],
"prec" => ["maintain", "break"],
"load" => ["yes", "no"]);
subj_n_play = 56
item_n_play = 32
fake_kb07_play = simdat_crossed(subj_n_play, item_n_play,
subj_btwn = subj_btwn_play,
item_btwn = item_btwn_play,
both_win = both_win_play);
fake_kb07_df_play = DataFrame(fake_kb07_play);
end
# ╔═╡ 462c5d9d-e579-4cc4-8f99-af7486ee9714
md"""
Simulate data:
"""
# ╔═╡ f5d79038-e98a-472b-b82c-699ee90112bf
fake_kb07 = simdat_crossed(subj_n_cmpl, item_n_cmpl,
subj_btwn = subj_btwn_cmpl,
item_btwn = item_btwn_cmpl,
both_win = both_win_cmpl);
# ╔═╡ 4ce55c9a-f91b-4724-a3af-349289599d45
md"""
Make a dataframe:
"""
# ╔═╡ 1346fd99-6cec-43b7-bca3-c8dfcf3bb207
fake_kb07_df = DataFrame(fake_kb07);
# ╔═╡ 18dc8d6d-7200-424a-b715-5ae14f4f178f
md"""
Have a look:
"""
# ╔═╡ 410e4de9-a672-4774-b281-562e444299a3
first(fake_kb07_df,8)
# ╔═╡ b93bcbd0-3bd1-45fc-b7f8-27319b05b290
md"""
The function `simdat_crossed` generates a balanced fully crossed design.
Unfortunately, our original design is not balanced fully crossed. Every subject saw an image only once, thus in one of eight possible conditions. To simulate that we only keep one of every eight lines.
We sort the dataframe to enable easier selection
"""
# ╔═╡ 26b5c5b4-6ae2-4bc6-83c9-1f1b0a485d5d
fake_kb07_df_sort = sort(fake_kb07_df, [:subj, :item, :load, :prec, :spkr])
# ╔═╡ 8d487d48-e80c-4ad0-8977-eaea7a6ed1e9
md"""
In order to select only the relevant rows of the data set we define an index which represents a random choice of one of every eight rows. First we generate a vector `idx` which represents which row to keep in each set of 8.
"""
# ╔═╡ d223b588-e380-458c-a546-f552f51fdda5
len = convert(Int64,(length(fake_kb07)/8));
# ╔═╡ 7d6ef8df-3230-4b90-8756-1f41b73670d4
idx_0 = rand(rng, collect(1:8) , len);
# ╔═╡ 8a04a59a-5ddd-4783-83ae-d73008673aa1
md"""
Then we create an array `A`, of the same length that is populated multiples of the number 8. Added together `A` and `idx` give the indexes of one row from each set of 8s.
"""
# ╔═╡ 0d24be79-1d59-4d44-bf08-6fa3826847ac
begin
A_0 = repeat([8], inner=len-1)
A_1 = append!( [0], A_0 )
A_2 = cumsum(A_1)
idx_1 = idx_0 + A_2
end
# ╔═╡ 7e993ae9-7a84-42f8-98e8-9195e987d942
md"""
Reduce the balanced fully crossed design to the original experimental design:
"""
# ╔═╡ f6ae17ef-3ab3-469f-970b-8aee0e3adfcd
fake_kb07_df_final= fake_kb07_df_sort[idx_1, :];
# ╔═╡ 5916d763-658b-44f6-baea-6cd11898954f
rename!(fake_kb07_df_final, :dv => :rt_trunc)
# ╔═╡ fa219b9c-52e9-45b1-9bf4-6daf1f7983c7
md"""
Now we can use the simulated data in the same way as above.
Set contrasts:
"""
# ╔═╡ cbe91c03-352c-42fe-a410-3371e023a2c8
contrasts_cmpl = Dict(:spkr => HelmertCoding(),
:prec => HelmertCoding(),
:load => HelmertCoding());
# ╔═╡ 35938e63-7b16-40b9-a321-fce1f3f933f7
md"""
Use formula, same as above `kb07_f`
"""
# ╔═╡ 35fe77d9-81bd-4a8e-9b5a-fe5baf28b2f6
fake_kb07_m = fit(MixedModel, kb07_f, fake_kb07_df_final, contrasts=contrasts_cmpl)
# ╔═╡ a1640dce-dd08-427e-bb9d-7d3ef8495617
md"""
Use random seed for reproducibility `rng`
"""
# ╔═╡ 63220c73-f12a-4ec5-aa73-5efe9b6e2fcf
md"""
Then, again, we specify `β`, `σ`, and `θ`.
Here we use the values that we found in the model of the existing dataset:
"""
# ╔═╡ edb5e147-0fed-41d0-b48e-24537e2463f9
kb07_m
# ╔═╡ 69fc8f6b-8862-44d0-aca2-20def7028487
md"`β`"
# ╔═╡ 9ba9c512-ba39-4260-a4f3-1eebc3678afa
new_beta_cmpl = [2181.85, 67.879, -333.791, 78.5904]; #manual
# ╔═╡ c4a252b5-58df-428c-81e1-0e22353e41fc
new_beta_cmpl_exact = kb07_m.β; #grab from existing model
# ╔═╡ b350df8d-e351-43c3-870e-bae8ee3916b1
md"`σ`"
# ╔═╡ 721140a5-4986-46df-bc18-9834506e1e2e
new_sigma_cmpl = 680.032; #manual
# ╔═╡ 62dc7c9c-8fdf-42e2-a6a3-ec954e538bdc
new_sigma_cmpl_exact = kb07_m.σ; #grab from existing model
# ╔═╡ df24c706-2455-4324-8941-e66ffc084890
md"""
Have a look on original model again:
"""
# ╔═╡ adc5f8fa-cdf6-4b19-843d-a0cddd26b9ae
VarCorr(kb07_m)
# ╔═╡ 526dab6b-3409-4ffd-b1af-56eb73f5b7cb
md"`θ`"
# ╔═╡ 57efe6d8-16dc-4f60-9b78-f840f1d44fed
re_item_corr_cmpl = [1.0 -0.7; -0.7 1.0];
# ╔═╡ 71ab4138-bb3a-47a3-9d12-9a7004624dea
re_item_cmpl = create_re(0.536, 0.371; corrmat = re_item_corr_cmpl);
# ╔═╡ fd90e01d-9e14-4bac-9e1f-3f2d36cf1507
re_subj_cmpl = create_re(0.438);
# ╔═╡ fea3d964-4190-4413-aff1-5aa9ae4df0c0
new_theta_cmpl = vcat( flatlowertri(re_item_cmpl), flatlowertri(re_subj_cmpl) ) #manual
# ╔═╡ 845a4983-74ce-4cfa-84d9-ed1f043ce9f1
new_theta_cmpl_exact = kb07_m.θ; #grab from existing model
# ╔═╡ 9120bd5f-f6b3-417e-8b81-286c1c9a7a4e
md"""
Run nsims iterations:
"""
# ╔═╡ 5ab9112e-328c-44c2-bf1d-527576aedb38
fake_kb07_sim = parametricbootstrap(rng, nsims, fake_kb07_m,
β = new_beta_cmpl,
σ = new_sigma_cmpl,
θ = new_theta_cmpl,
use_threads = false)
# ╔═╡ e9e851c1-e74f-4b8a-9a8f-c817a6c751fc
md"""
### Power calculation
"""
# ╔═╡ 5070c540-4d53-4107-8748-5e3f56fea37f
power_table(fake_kb07_sim)
# ╔═╡ 0ae98b2b-0e3f-4974-aa67-39a0882469fa
fake_kb07_sim_df = DataFrame(fake_kb07_sim.coefpvalues);
# ╔═╡ 6cb151cf-2f03-44f2-8a7a-5c8ef0236079
[mean(fake_kb07_sim_df[fake_kb07_sim_df.coefname .== Symbol("(Intercept)"),:p] .< 0.05),
mean(fake_kb07_sim_df[fake_kb07_sim_df.coefname .== Symbol("spkr: old"),:p] .< 0.05),
mean(fake_kb07_sim_df[fake_kb07_sim_df.coefname .== Symbol("prec: maintain"),:p] .< 0.05),
mean(fake_kb07_sim_df[fake_kb07_sim_df.coefname .== Symbol("load: yes"),:p] .< 0.05)]
# ╔═╡ 2bc411ac-e4b8-4e85-9243-4a222935290d
md"""
Compare to the powertable from the existing data:
"""
# ╔═╡ 4ccc0b79-7f26-4994-8126-88955460e43a
[mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("(Intercept)"),:p] .< 0.05),
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("spkr: old"),:p] .< 0.05),
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("prec: maintain"),:p] .< 0.05),
mean(kb07_sim_df[kb07_sim_df.coefname .== Symbol("load: yes"),:p] .< 0.05)]
# ╔═╡ ea53f15b-db89-444c-bdde-25747751d505
md"""
We have successfully recreated the power simulation of an existing dataset from scratch. This has the advantage, that we now can iterate over different numbers of subjects and items.
"""
# ╔═╡ de802935-40fe-4010-b361-5ce1d1a6e19e
md"""
Compare to the powertable from the existing data:
"""
# ╔═╡ f273f990-f5b3-4f7e-a066-4da7bf71c165
power_table(kb07_sim)
# ╔═╡ f4b1e8af-7a3a-43ae-a189-080fa9886c44
md"""
We have successfully recreated the power simulation of an existing dataset from scratch. This has the advantage, that we now can iterate over different numbers of subjects and items.
## Loop over subject and item sizes
When designing a study, you may be interested in trying various numbers of subjects and items to see how that affects the power of your study.
To do this you can use a loop to run simulations over a range of values for any parameter.
### We first define every fixed things outside the loop (same as above):
Define factors in a dict:
"""
# ╔═╡ eca8b9d0-3c9b-4be4-bb2b-bbbaed248bfc
md"""
`subj_btwn_cmpl`, `item_btwn_cmpl`, `both_win_cmpl`
"""
# ╔═╡ b53158c1-80f6-4286-ae89-6273e47d4b95
md"""
`contrasts_cmpl`
"""
# ╔═╡ a0df1382-68d2-4b29-be29-3b3ebb94cb1e
md"`rng`"
# ╔═╡ 98244829-7c17-42f0-a10b-1d86408a4fb7
md"""
`kb07_f`
"""
# ╔═╡ 02d09aac-70ac-48ed-829a-3be9b2fa605c
md"""
`new_beta_cmpl`, `new_sigma_cmpl`, `new_theta_cmpl`
"""
# ╔═╡ 806491f8-e739-4537-8768-125d9124d157
md"""
### Then we define the variables that out loop will iterate over
Define subject and item numbers as arrays:
"""
# ╔═╡ 1f026d1a-9d5c-4732-9a42-bb85be9cff0b
sub_ns = [20, 30, 40];
# ╔═╡ 1ec45e86-fce4-43a6-b6dd-74972b316113
item_ns = [16, 24, 32];
# ╔═╡ 34b70baa-46f2-42cc-98bb-06b6d2c38ee3
md"""
Make an empty dataframe:
"""
# ╔═╡ 77aa8869-176d-4bf4-a021-b588b769e44f
d = DataFrame();
# ╔═╡ 2f8f5fa3-892a-4641-84e9-b0dfa59d2b27
md"""
### Run the loop:
"""
# ╔═╡ 789c6ecd-9933-49a5-b3fa-5c3ff86488b3
for subj_n in sub_ns
for item_n in item_ns
# Make balanced fully crossed data:
fake_kb07 = simdat_crossed(subj_n, item_n,
subj_btwn = subj_btwn,
item_btwn = item_btwn,
both_win = both_win);
fake_kb07_df = DataFrame(fake_kb07)
# Reduce the balanced fully crossed design to the original experimental design:
fake_kb07_df = sort(fake_kb07_df, [:subj, :item, :load, :prec, :spkr])
len = convert(Int64,(length(fake_kb07)/8))
idx = rand(rng, collect(1:8) , len)
A = repeat([8], inner=len-1)
A = append!( [0], A )
A = cumsum(A)
idx = idx+A
fake_kb07_df= fake_kb07_df[idx, :]
rename!(fake_kb07_df, :dv => :rt_trunc)
# Fit the model:
fake_kb07_m = fit(MixedModel, kb07_f, fake_kb07_df, contrasts=contrasts);
# Run nsims iterations:
fake_kb07_sim = parametricbootstrap(rng, nsims, fake_kb07_m,
β = new_beta,
σ = new_sigma,
θ = new_theta,
use_threads = false);
# Power calculation
ptbl = power_table(fake_kb07_sim)
ptdf = DataFrame(ptbl)
ptdf[!, :item_n] .= item_n
ptdf[!, :subj_n] .= subj_n
append!(d, ptdf)
end
end
# ╔═╡ f117902c-7a84-4a6c-ab6a-0dd11cddee16
md"""
Our dataframe `d` now contains the power information for each combination of subjects and items.
"""
# ╔═╡ dbc5569b-cb73-44c0-970c-16f713349163
print(d)
# ╔═╡ a562900c-93af-4562-8f92-445e59bc9481
md"""
Lastly we plot our results:
"""
# ╔═╡ 9165b8ac-4962-432f-9643-525f441d9615
begin
categorical!(d, :item_n)
plot(d, x="subj_n", y="power",xgroup= "coefname",color="item_n", Geom.subplot_grid(Geom.point, Geom.line), Guide.xlabel("Number of subjects by parameter"), Guide.ylabel("Power"))
end
# ╔═╡ e54b4939-f389-49f0-90c0-1a0b2ff87774
md"""
# Credit
This tutorial was conceived for ZiF research and tutorial workshop by Lisa DeBruine (Feb. 2020) presented again by Phillip Alday during the SMLP Summer School (Sep. 2020).
Updated and extended by Lisa Schwetlick & Daniel Backhaus, with the kind help of Phillip Alday, after changes to the package.
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataFramesMeta = "1313f7d8-7da2-5740-9ea0-a2ca25f37964"
Gadfly = "c91e804a-d5a3-530f-b6f0-dfbca275c004"
MixedModels = "ff71e718-51f3-5ec2-a782-8ffcbfa3c316"
MixedModelsSim = "d5ae56c5-23ca-4a1f-b505-9fc4796fc1fe"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
StableRNGs = "860ef19b-820b-49d6-a774-d7a799459cd3"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
Tables = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
[compat]
CSV = "~0.9.1"
DataFrames = "~1.2.2"
DataFramesMeta = "~0.9.1"
Gadfly = "~1.3.3"
MixedModels = "~4.1.1"
MixedModelsSim = "~0.2.3"
PlutoUI = "~0.7.9"
StableRNGs = "~1.0.0"
Tables = "~1.5.1"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
[[AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "485ee0867925449198280d4af84bdb46a2a404d0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.0.1"
[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"
[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
[[Arrow]]
deps = ["ArrowTypes", "BitIntegers", "CodecLz4", "CodecZstd", "DataAPI", "Dates", "Mmap", "PooledArrays", "SentinelArrays", "Tables", "TimeZones", "UUIDs"]
git-tree-sha1 = "b00e6eaba895683867728e73af78a00218f0db10"
uuid = "69666777-d1a9-59fb-9406-91d4454c9d45"
version = "1.6.2"
[[ArrowTypes]]
deps = ["UUIDs"]
git-tree-sha1 = "a0633b6d6efabf3f76dacd6eb1b3ec6c42ab0552"
uuid = "31f734f8-188a-4ce0-8406-c8a06bd891cd"
version = "1.2.1"
[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[AxisAlgorithms]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"]
git-tree-sha1 = "a4d07a1c313392a77042855df46c5f534076fab9"
uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950"
version = "1.0.0"
[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Statistics", "UUIDs"]
git-tree-sha1 = "42ac5e523869a84eac9669eaceed9e4aa0e1587b"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.1.4"
[[BitIntegers]]
deps = ["Random"]
git-tree-sha1 = "f50b5a99aa6ff9db7bf51255b5c21c8bc871ad54"
uuid = "c3b6d118-76ef-56ca-8cc7-ebb389d030a1"
version = "0.2.5"
[[Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[CSV]]
deps = ["CodecZlib", "Dates", "FilePathsBase", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings"]
git-tree-sha1 = "c907e91e253751f5840135f4c9deb1308273338d"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.9.1"
[[CategoricalArrays]]
deps = ["DataAPI", "Future", "JSON", "Missings", "Printf", "RecipesBase", "Statistics", "StructTypes", "Unicode"]
git-tree-sha1 = "1562002780515d2573a4fb0c3715e4e57481075e"
uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597"
version = "0.10.0"
[[Chain]]
git-tree-sha1 = "cac464e71767e8a04ceee82a889ca56502795705"
uuid = "8be319e6-bccf-4806-a6f7-6fae938471bc"
version = "0.4.8"
[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "30ee06de5ff870b45c78f529a6b093b3323256a3"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.3.1"
[[CodecBzip2]]
deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"]
git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7"
uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd"
version = "0.7.2"
[[CodecLz4]]
deps = ["Lz4_jll", "TranscodingStreams"]
git-tree-sha1 = "59fe0cb37784288d6b9f1baebddbf75457395d40"
uuid = "5ba52731-8f18-5e0d-9241-30f10d1ec561"
version = "0.4.0"
[[CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"
[[CodecZstd]]
deps = ["TranscodingStreams", "Zstd_jll"]
git-tree-sha1 = "d19cd9ae79ef31774151637492291d75194fc5fa"
uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2"
version = "0.7.0"
[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"
[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "6071cb87be6a444ac75fdbf51b8e7273808ce62f"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.35.0"
[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
[[Compose]]
deps = ["Base64", "Colors", "DataStructures", "Dates", "IterTools", "JSON", "LinearAlgebra", "Measures", "Printf", "Random", "Requires", "Statistics", "UUIDs"]
git-tree-sha1 = "c6461fc7c35a4bb8d00905df7adafcff1fe3a6bc"
uuid = "a81c6b42-2e10-5240-aca2-a61377ecd94b"
version = "0.9.2"
[[Contour]]
deps = ["StaticArrays"]
git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.5.7"
[[CoupledFields]]
deps = ["LinearAlgebra", "Statistics", "StatsBase"]
git-tree-sha1 = "6c9671364c68c1158ac2524ac881536195b7e7bc"
uuid = "7ad07ef1-bdf2-5661-9d2b-286fd4296dac"
version = "0.2.0"
[[Crayons]]
git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.0.4"
[[DataAPI]]
git-tree-sha1 = "bec2532f8adb82005476c141ec23e921fc20971b"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.8.0"
[[DataFrames]]
deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "d785f42445b63fc86caa08bb9a9351008be9b765"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.2.2"
[[DataFramesMeta]]
deps = ["Chain", "DataFrames", "MacroTools", "Reexport"]
git-tree-sha1 = "29e71b438935977f8905c0cb3a8a84475fc70101"
uuid = "1313f7d8-7da2-5740-9ea0-a2ca25f37964"
version = "0.9.1"
[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"
[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "9f46deb4d4ee4494ffb5a40a27a2aced67bdd838"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.4"
[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[Distributions]]
deps = ["FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns"]
git-tree-sha1 = "a837fdf80f333415b69684ba8e8ae6ba76de6aaa"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.24.18"
[[DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "a32185f5428d3986f47c2ab78b1f216d5e6cc96f"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.8.5"
[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"
[[FFTW]]
deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"]
git-tree-sha1 = "f985af3b9f4e278b1d24434cbb546d6092fca661"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "1.4.3"
[[FFTW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3676abafff7e4ff07bbd2c42b3d8201f31653dcc"
uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a"
version = "3.3.9+8"
[[FilePathsBase]]
deps = ["Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "0f5e8d0cb91a6386ba47bd1527b240bd5725fbae"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.10"
[[FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays"]
git-tree-sha1 = "693210145367e7685d8604aee33d9bfb85db8b31"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.11.9"
[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[GLM]]
deps = ["Distributions", "LinearAlgebra", "Printf", "Reexport", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "StatsModels"]
git-tree-sha1 = "f564ce4af5e79bb88ff1f4488e64363487674278"
uuid = "38e38edf-8417-5370-95a0-9cbb8c7f171a"
version = "1.5.1"
[[Gadfly]]
deps = ["Base64", "CategoricalArrays", "Colors", "Compose", "Contour", "CoupledFields", "DataAPI", "DataStructures", "Dates", "Distributions", "DocStringExtensions", "Hexagons", "IndirectArrays", "IterTools", "JSON", "Juno", "KernelDensity", "LinearAlgebra", "Loess", "Measures", "Printf", "REPL", "Random", "Requires", "Showoff", "Statistics"]
git-tree-sha1 = "96da4818e4d481a29aa7d66aac1eb778432fb89a"
uuid = "c91e804a-d5a3-530f-b6f0-dfbca275c004"
version = "1.3.3"
[[Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[Hexagons]]
deps = ["Test"]
git-tree-sha1 = "de4a6f9e7c4710ced6838ca906f81905f7385fd6"
uuid = "a1b4810d-1bce-5fbd-ac56-80944d57a21f"
version = "0.2.0"
[[IndirectArrays]]
git-tree-sha1 = "c2a145a145dc03a7620af1444e0264ef907bd44f"
uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959"
version = "0.5.1"
[[IntelOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c"
uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0"
version = "2018.0.3+2"
[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[Interpolations]]
deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"]
git-tree-sha1 = "61aa005707ea2cebf47c8d780da8dc9bc4e0c512"
uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
version = "0.13.4"
[[InvertedIndices]]
git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f"
uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f"
version = "1.1.0"
[[IrrationalConstants]]
git-tree-sha1 = "f76424439413893a832026ca355fe273e93bce94"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.0"
[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"
[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"
[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"
[[JSON3]]
deps = ["Dates", "Mmap", "Parsers", "StructTypes", "UUIDs"]
git-tree-sha1 = "b3e5984da3c6c95bcf6931760387ff2e64f508f3"
uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
version = "1.9.1"
[[Juno]]
deps = ["Base64", "Logging", "Media", "Profile"]
git-tree-sha1 = "07cb43290a840908a771552911a6274bc6c072c7"
uuid = "e5e0dc1b-0480-54bc-9374-aad01c23163d"
version = "0.8.4"
[[KernelDensity]]
deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"]
git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707"
uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b"
version = "0.6.3"
[[LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"
[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[Loess]]
deps = ["Distances", "LinearAlgebra", "Statistics"]
git-tree-sha1 = "b5254a86cf65944c68ed938e575f5c81d5dfe4cb"
uuid = "4345ca2d-374a-55d4-8d30-97f9976e7612"
version = "0.5.3"
[[LogExpFunctions]]
deps = ["ChainRulesCore", "DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "86197a8ecb06e222d66797b0c2d2f0cc7b69e42b"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.2"
[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[Lz4_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "5d494bc6e85c4c9b626ee0cab05daa4085486ab1"
uuid = "5ced341a-0733-55b8-9ab6-a4889d929147"
version = "1.9.3+0"
[[MKL_jll]]
deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"]
git-tree-sha1 = "c253236b0ed414624b083e6b72bfe891fbd2c7af"
uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7"
version = "2021.1.1+1"
[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "0fb723cd8c45858c22169b2e42269e53271a6df7"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.7"
[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[MathOptInterface]]
deps = ["BenchmarkTools", "CodecBzip2", "CodecZlib", "JSON", "LinearAlgebra", "MutableArithmetics", "OrderedCollections", "Printf", "SparseArrays", "Test", "Unicode"]
git-tree-sha1 = "a1f9933fa00624d8c97301253d14710b80fa08ee"
uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
version = "0.10.1"
[[MathProgBase]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "9abbe463a1e9fc507f12a69e7f29346c2cdc472c"
uuid = "fdba3010-5040-5b88-9595-932c9decdf73"
version = "0.7.8"
[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
[[Measures]]
git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.1"
[[Media]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "75a54abd10709c01f1b86b84ec225d26e840ed58"
uuid = "e89f7d12-3494-54d1-8411-f7d8b9ae1f27"
version = "0.5.0"
[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "2ca267b08821e86c5ef4376cffed98a46c2cb205"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.1"
[[MixedModels]]
deps = ["Arrow", "DataAPI", "Distributions", "GLM", "JSON3", "LazyArtifacts", "LinearAlgebra", "Markdown", "NLopt", "PooledArrays", "ProgressMeter", "Random", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StatsModels", "StructTypes", "Tables"]
git-tree-sha1 = "f318e42a48ec0a856292bafeec6b07aed3f6d600"
uuid = "ff71e718-51f3-5ec2-a782-8ffcbfa3c316"
version = "4.1.1"
[[MixedModelsSim]]
deps = ["LinearAlgebra", "MixedModels", "PooledArrays", "PrettyTables", "Random", "Statistics", "Tables"]
git-tree-sha1 = "ad4eaa164a5ab5fd22effcb86e7c991192ed3488"
uuid = "d5ae56c5-23ca-4a1f-b505-9fc4796fc1fe"
version = "0.2.3"
[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[Mocking]]
deps = ["ExprTools"]
git-tree-sha1 = "748f6e1e4de814b101911e64cc12d83a6af66782"
uuid = "78c3b35d-d492-501b-9361-3d52fe80e533"
version = "0.7.2"
[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
[[MutableArithmetics]]
deps = ["LinearAlgebra", "SparseArrays", "Test"]
git-tree-sha1 = "3927848ccebcc165952dc0d9ac9aa274a87bfe01"
uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0"
version = "0.2.20"
[[NLopt]]
deps = ["MathOptInterface", "MathProgBase", "NLopt_jll"]
git-tree-sha1 = "f115030b9325ca09ef1619ba0617b2a64101ce84"
uuid = "76087f3c-5699-56af-9a33-bf431cd00edd"
version = "0.6.4"
[[NLopt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "2b597c46900f5f811bec31f0dcc88b45744a2a09"
uuid = "079eb43e-fd8e-5478-9966-2cf3e3edb778"
version = "2.7.0+0"
[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
[[OffsetArrays]]
deps = ["Adapt"]
git-tree-sha1 = "c870a0d713b51e4b49be6432eff0e26a4325afee"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.10.6"
[[OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[PDMats]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "4dd403333bcf0909341cfe57ec115152f937d7d8"
uuid = "90014a1f-27ba-587c-ab20-58faa44d9150"
version = "0.11.1"
[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "438d35d2d95ae2c5e8780b330592b6de8494e779"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.0.3"
[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[PlutoUI]]
deps = ["Base64", "Dates", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "Suppressor"]
git-tree-sha1 = "44e225d5837e2a2345e69a1d1e01ac2443ff9fcb"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.9"
[[PooledArrays]]
deps = ["DataAPI", "Future"]
git-tree-sha1 = "a193d6ad9c45ada72c14b731a318bedd3c2f00cf"
uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720"
version = "1.3.0"
[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"
[[PrettyTables]]
deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"]
git-tree-sha1 = "0d1245a357cc61c8cd61934c07447aa569ff22e6"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "1.1.0"
[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[Profile]]
deps = ["Printf"]
uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79"
[[ProgressMeter]]
deps = ["Distributed", "Printf"]
git-tree-sha1 = "afadeba63d90ff223a6a48d2009434ecee2ec9e8"
uuid = "92933f4c-e287-5a05-a399-4b506db050ca"
version = "1.7.1"
[[QuadGK]]
deps = ["DataStructures", "LinearAlgebra"]
git-tree-sha1 = "12fbe86da16df6679be7521dfb39fbc861e1dc7b"
uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
version = "2.4.1"
[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[Ratios]]
deps = ["Requires"]
git-tree-sha1 = "7dff99fbc740e2f8228c6878e2aad6d7c2678098"
uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439"
version = "0.4.1"
[[RecipesBase]]
git-tree-sha1 = "44a75aa7a527910ee3d1751d1f0e4148698add9e"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.1.2"
[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"
[[Rmath]]
deps = ["Random", "Rmath_jll"]
git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f"
uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa"
version = "0.7.0"
[[Rmath_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7"
uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f"
version = "0.3.0+0"
[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[SentinelArrays]]
deps = ["Dates", "Random"]
git-tree-sha1 = "54f37736d8934a12a200edea2f9206b03bdf3159"
uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c"
version = "1.3.7"
[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[ShiftedArrays]]
git-tree-sha1 = "22395afdcf37d6709a5a0766cc4a5ca52cb85ea0"
uuid = "1277b4bf-5013-50f5-be3d-901d8477a67a"
version = "1.0.0"
[[Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"
[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"
[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[SpecialFunctions]]
deps = ["ChainRulesCore", "LogExpFunctions", "OpenSpecFun_jll"]
git-tree-sha1 = "a322a9493e49c5f3a10b50df3aedaf1cdb3244b7"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.6.1"
[[StableRNGs]]
deps = ["Random", "Test"]
git-tree-sha1 = "3be7d49667040add7ee151fefaf1f8c04c8c8276"
uuid = "860ef19b-820b-49d6-a774-d7a799459cd3"
version = "1.0.0"
[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3240808c6d463ac46f1c1cd7638375cd22abbccb"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.12"
[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[StatsAPI]]
git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.0.0"
[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "8cbbc098554648c84f79a463c9ff0fd277144b6c"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.10"
[[StatsFuns]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
git-tree-sha1 = "46d7ccc7104860c38b11966dd1f72ff042f382e4"
uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
version = "0.9.10"
[[StatsModels]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Printf", "ShiftedArrays", "SparseArrays", "StatsBase", "StatsFuns", "Tables"]
git-tree-sha1 = "3fa15c1f8be168e76d59097f66970adc86bfeb95"
uuid = "3eaba693-59b7-5ba5-a881-562e759f1c8d"
version = "0.6.25"
[[StructTypes]]
deps = ["Dates", "UUIDs"]
git-tree-sha1 = "8445bf99a36d703a09c601f9a57e2f83000ef2ae"
uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4"
version = "1.7.3"
[[SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[Suppressor]]
git-tree-sha1 = "a819d77f31f83e5792a76081eee1ea6342ab8787"
uuid = "fd094767-a336-5f1f-9728-57cf17d0bbfb"
version = "0.2.0"
[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "368d04a820fe069f9080ff1b432147a6203c3c89"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.5.1"
[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[TimeZones]]
deps = ["Dates", "Future", "LazyArtifacts", "Mocking", "Pkg", "Printf", "RecipesBase", "Serialization", "Unicode"]
git-tree-sha1 = "6c9040665b2da00d30143261aea22c7427aada1c"
uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53"
version = "1.5.7"
[[TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.6"
[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[WeakRefStrings]]
deps = ["DataAPI", "Parsers"]
git-tree-sha1 = "4a4cfb1ae5f26202db4f0320ac9344b3372136b0"
uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5"
version = "1.3.0"
[[WoodburyMatrices]]
deps = ["LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "59e2ad8fd1591ea019a5259bd012d7aee15f995c"
uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6"
version = "0.5.3"
[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
[[Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"
[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""
# ╔═╡ Cell order:
# ╟─c071c03f-6ddb-415e-8445-b4fd8d45abc1
# ╠═89495294-10ed-11ec-04a9-db58dba9f3d1
# ╠═14ae0269-ea23-4c73-a04f-40eece7a5bc5
# ╟─76df9a69-7ee6-4876-9dcc-e6178f59d3ad
# ╠═16822577-6f44-4330-9181-678bb2c7cce2
# ╟─d4e9bb7e-3f70-48fb-a73c-9606cfb39f39
# ╠═4c00bf63-1d33-4f16-9776-e2f3915850f9
# ╟─87af988a-2d55-4c24-a132-3c76f1ae562b
# ╠═8caad72c-a8d7-4e23-8eb6-b9096141b471
# ╟─29b32ea9-0018-4ec3-9095-1e527e11fc4f
# ╠═3763460c-046d-46ce-b9ef-4faf1fbd0428
# ╟─f05a1f73-503a-4ed7-8879-1da242b2b224
# ╠═a75ad071-0789-41ab-9253-27c8bca615ad
# ╟─8e4629aa-58b7-4ab8-8954-74ee579a3f9b
# ╠═3e0e9908-002c-4def-a2eb-c8f7d775f205
# ╟─33d9ecae-ac5c-4fdf-bd1a-4d68f785084a
# ╠═b3e2dea0-bfb0-4d5d-bd9c-8ed0e0272cc0
# ╟─1b814e14-136e-45ad-83e9-c783e30dc4b1
# ╠═fc141d66-3252-4989-b6e4-98bbfe82385a
# ╠═5d7c1822-453c-4483-a1a1-32e149145afb
# ╠═ef3c9d81-38cf-45d6-9258-926ad209e36f
# ╟─146c6a52-a512-4601-9b58-bc56575bfb2e
# ╠═4598ae9a-8d39-4280-a74a-4d7145d64920
# ╟─fa91a0f8-675e-4155-9ff4-58090689c397
# ╠═811a81ac-50d9-4d07-98d1-3fc8e1586685
# ╟─d8257d21-8dad-4533-ba93-78ba7c3202b3
# ╠═ac2f3b62-e86c-43b2-8109-558db79e5773
# ╟─67493854-920e-477e-805b-21d58cd19ade
# ╠═8c06724f-a947-44c2-8541-7aa50c915356
# ╟─fc239c6e-ca35-4df6-81b2-115be160437b
# ╠═97907ccc-e4b8-43a3-9e5a-ae1da59a203a
# ╠═a383994a-e4f4-4c9e-9f17-32ec11e32e87
# ╠═523c1c21-43d2-469e-b138-3dd5cab1e6b9
# ╠═3419a020-7333-4cb5-981b-84e7fa788280
# ╠═231ce20d-ea0c-4314-a7b0-0e296bc2160b
# ╟─b66ab7be-0547-4535-9d33-cfae62441c61
# ╠═356751b1-73cc-4dae-ad5a-b1cd0b45ede0
# ╟─910ca4be-d4bf-4231-95d6-de8b3e97d4d5
# ╟─11eacaa9-f309-4c72-a659-3fc262f3111f
# ╠═bc6ace0a-2776-409c-892c-6892df79f0e7
# ╠═bbe93bad-4d41-4300-910a-ec16a660def3
# ╠═9510ce0a-6ba7-4903-8e2a-84f6fc69492c
# ╟─f5436bb7-9087-437f-bc43-1b113c907695
# ╠═9fbfff0f-289c-4c92-9ffa-615ad1b69ff2
# ╟─7aa2cea2-9136-42ad-bc62-9966aa93b84c
# ╠═f7a5cffe-2819-4a9f-a56e-45fefb2c4201
# ╠═c3c9ab9c-c81d-44d2-bd45-fb72a7c5da8a
# ╠═9e9c337e-556f-44a8-ad5f-0476be1458b0
# ╠═6b7fdacd-1343-42a2-8e7e-d06bd559765d
# ╠═f232988a-c3cf-404f-9f0d-fe0ef591e8bb
# ╠═ed309fad-0058-4069-8e8e-e526b2b36370
# ╠═2fc97a13-abc5-42ff-a1eb-28e24271fae0
# ╟─42f4e755-c7b1-46e2-91fd-31a19ccd5685
# ╟─fcd25a28-cb0d-4077-8b20-f5837c4e99f8
# ╟─ae7efbb0-aa35-4128-aebf-10a1deab5fee
# ╠═21567edd-0593-4823-b538-15dcb0de48f0
# ╠═5eb6074a-a695-4404-841e-21b7b82f1150
# ╟─a02e6191-239f-4b0b-996d-f73bfc54ea28
# ╠═ce275097-63e5-410e-a23b-9fdd4250e35c
# ╠═c5f9f6ad-0b18-434b-a368-42afd8cb398e
# ╟─9adf46f1-d84c-4ae3-af1b-2087adbf0315
# ╠═077b22ae-814f-4b18-8297-2124317cbff6
# ╟─f33d0b96-3b3c-4651-8b39-46461445cd09
# ╠═8103cf6e-18a2-40a1-8043-c87ed92e1c11
# ╟─cdee3c0c-6c85-4515-8ffd-1b1c71018e09
# ╠═f5535f46-e919-4dad-9f0e-337d68ab669b
# ╟─6f2c0659-3f5d-45d8-8a40-b3124ce49fa3
# ╠═9b5601c0-613e-426f-9318-c87ba9108f42
# ╟─d0493428-916e-4bfe-8f5a-586e21af0f5c
# ╠═ca0b404c-50da-43eb-8bb6-d6037e09ba64
# ╟─2a04994e-bb88-455b-a732-bae9ef1c5422
# ╟─5e364a80-e5d9-458b-be1e-d00dafa04033
# ╠═026c051d-bcfa-4b1d-8648-bdd0d8cdf894
# ╠═2951d7fe-0373-4f52-86e3-c11bd7a57f1a
# ╠═1ddbde42-6dcc-425d-b906-92880bb15e89
# ╠═29ef3cab-e774-4cf8-a392-92eec8acc98b
# ╠═37f07a78-3616-41c4-90ad-6fc52d9223b3
# ╠═f4929a81-71db-4a78-86f9-22c7ed89f04d
# ╟─dd8aa406-ef50-4036-9d6f-f499934a84c3
# ╠═f8432a72-da18-4540-9a26-2c4091bd43ac
# ╟─1fb0fa62-9757-4a0c-ac67-89a6f4b68caf
# ╟─47ddae23-9cfd-4db1-bbe7-446c456a2fb5
# ╠═ce10d865-0edf-4f34-9142-48297fb79810
# ╟─c1055a38-1f1a-4ef2-9fda-fe14670821b9
# ╠═651a7d74-715a-4562-85b1-97a8bdaf27a2
# ╠═3e182015-b555-4b9a-91b9-5e6a58e020b3
# ╟─4ca9d39a-c061-4f99-b240-bd8fdd773530
# ╠═4d5abbf8-5c04-41e6-a49d-8798c985f953
# ╟─b6d4353c-c4bf-421e-abd6-e1c4e427f1fe
# ╠═223f7d34-e433-49f4-bae7-818ec91985df
# ╟─82f87d91-963a-4fb9-96c1-162db2cd9c58
# ╟─d9eb46c8-c37a-4037-aca6-addf66690a10
# ╠═2a6a4bf8-93f6-4185-8510-bb0c0cb979c8
# ╟─cd479f01-7b04-46c7-9f23-8615dee536de
# ╠═356b2ee9-aecc-4819-b535-eb11e46d2e52
# ╟─ec41b5cf-461f-4655-a3c0-dc7db29e3ac6
# ╠═811669c1-ea76-4db2-a09a-de3480cb428b
# ╟─20b38246-966b-4cc3-82ce-4cdb76be058e
# ╠═2a3411a4-42df-4f6c-bf38-cc7114c5ec87
# ╟─48f404de-f654-4021-ba98-edeaabec6e5b
# ╠═2164a837-b0e9-4207-90fd-4db090021963
# ╟─873d708d-3f3a-4510-877d-25f73710a35b
# ╠═d5b7f38f-2e72-44b6-9d37-131a14e47658
# ╠═f3465ca6-8838-4f71-9f8a-df727c0f3780
# ╟─6155d5d8-cf14-4c73-8f41-b0ac5f40244a
# ╠═91120f25-068e-402c-9b13-2eb8d3833b0c
# ╟─0f627b49-72c6-4235-a7f2-bd3bd758704a
# ╠═7a9c7cd3-851b-4d2b-be12-cea014e834e5
# ╟─b4f9eff5-3626-47ed-ab8a-8d70f926c831
# ╠═5caa14d8-73b8-46d7-b0e1-bc58522f24eb
# ╟─97af5c8a-ab21-45c1-8fbc-39f749c4d0c7
# ╠═7dfc2f19-bcb8-4669-a119-5238e248ac5c
# ╟─c88f5177-1a24-4ffc-9228-3f8bd873eb07
# ╠═72304a3d-6a3a-40a5-933f-4cc88852db11
# ╠═99f81384-06c3-45a4-8ccf-305ab7622fe3
# ╠═a171e0d3-a406-42cf-9567-4d33d7be3159
# ╟─e7740a25-15c2-4997-b838-22f4e8b9bf78
# ╠═08d1781d-dad4-47c8-861f-d745d0f406bf
# ╟─7b7423be-dbbf-4e13-8c98-2eea4df0d02f
# ╠═97130e8f-f155-4c4f-a061-696bdbb3c588
# ╠═55096ce7-b7f2-4884-a853-a87316cd171a
# ╟─7dd1cd44-ee63-4c14-9e82-d2b7c7cef7f8
# ╠═63f69580-c5bc-463e-a42b-757b3d897be1
# ╟─d57de97c-c21f-4e74-b093-5d3a552609e7
# ╠═ac8ba024-a466-419d-9c80-ef9212228361
# ╠═0cff3191-cdd7-43dc-8761-7ad8bfc64b8c
# ╟─fc75435a-3cce-42ab-9e7d-3b9126d634b6
# ╠═a48b29ef-94da-4917-b1fe-e9101e56f319
# ╟─9dcbb3f7-c2d2-4b05-aa25-5adb4ca72d7f
# ╠═8d13df4c-8468-482b-92f7-62f28a1bf995
# ╟─d63c51d1-1ef8-4aa9-b0f1-288c387f6d72
# ╠═7bbe248a-6ff5-44f6-9cd4-4fdbd48b81ec
# ╟─462c5d9d-e579-4cc4-8f99-af7486ee9714
# ╠═f5d79038-e98a-472b-b82c-699ee90112bf
# ╟─4ce55c9a-f91b-4724-a3af-349289599d45
# ╠═1346fd99-6cec-43b7-bca3-c8dfcf3bb207
# ╟─18dc8d6d-7200-424a-b715-5ae14f4f178f
# ╠═410e4de9-a672-4774-b281-562e444299a3
# ╟─b93bcbd0-3bd1-45fc-b7f8-27319b05b290
# ╠═26b5c5b4-6ae2-4bc6-83c9-1f1b0a485d5d
# ╟─8d487d48-e80c-4ad0-8977-eaea7a6ed1e9
# ╠═d223b588-e380-458c-a546-f552f51fdda5
# ╠═7d6ef8df-3230-4b90-8756-1f41b73670d4
# ╟─8a04a59a-5ddd-4783-83ae-d73008673aa1
# ╠═0d24be79-1d59-4d44-bf08-6fa3826847ac
# ╟─7e993ae9-7a84-42f8-98e8-9195e987d942
# ╠═f6ae17ef-3ab3-469f-970b-8aee0e3adfcd
# ╠═5916d763-658b-44f6-baea-6cd11898954f
# ╟─fa219b9c-52e9-45b1-9bf4-6daf1f7983c7
# ╠═cbe91c03-352c-42fe-a410-3371e023a2c8
# ╟─35938e63-7b16-40b9-a321-fce1f3f933f7
# ╠═35fe77d9-81bd-4a8e-9b5a-fe5baf28b2f6
# ╟─a1640dce-dd08-427e-bb9d-7d3ef8495617
# ╟─63220c73-f12a-4ec5-aa73-5efe9b6e2fcf
# ╠═edb5e147-0fed-41d0-b48e-24537e2463f9
# ╟─69fc8f6b-8862-44d0-aca2-20def7028487
# ╠═9ba9c512-ba39-4260-a4f3-1eebc3678afa
# ╠═c4a252b5-58df-428c-81e1-0e22353e41fc
# ╟─b350df8d-e351-43c3-870e-bae8ee3916b1
# ╠═721140a5-4986-46df-bc18-9834506e1e2e
# ╠═62dc7c9c-8fdf-42e2-a6a3-ec954e538bdc
# ╟─df24c706-2455-4324-8941-e66ffc084890
# ╠═adc5f8fa-cdf6-4b19-843d-a0cddd26b9ae
# ╟─526dab6b-3409-4ffd-b1af-56eb73f5b7cb
# ╠═57efe6d8-16dc-4f60-9b78-f840f1d44fed
# ╠═71ab4138-bb3a-47a3-9d12-9a7004624dea
# ╠═fd90e01d-9e14-4bac-9e1f-3f2d36cf1507
# ╠═fea3d964-4190-4413-aff1-5aa9ae4df0c0
# ╠═845a4983-74ce-4cfa-84d9-ed1f043ce9f1
# ╟─9120bd5f-f6b3-417e-8b81-286c1c9a7a4e
# ╠═5ab9112e-328c-44c2-bf1d-527576aedb38
# ╟─e9e851c1-e74f-4b8a-9a8f-c817a6c751fc
# ╠═5070c540-4d53-4107-8748-5e3f56fea37f
# ╠═0ae98b2b-0e3f-4974-aa67-39a0882469fa
# ╠═6cb151cf-2f03-44f2-8a7a-5c8ef0236079
# ╟─2bc411ac-e4b8-4e85-9243-4a222935290d
# ╠═4ccc0b79-7f26-4994-8126-88955460e43a
# ╠═ea53f15b-db89-444c-bdde-25747751d505
# ╟─de802935-40fe-4010-b361-5ce1d1a6e19e
# ╠═f273f990-f5b3-4f7e-a066-4da7bf71c165
# ╟─f4b1e8af-7a3a-43ae-a189-080fa9886c44
# ╟─eca8b9d0-3c9b-4be4-bb2b-bbbaed248bfc
# ╟─b53158c1-80f6-4286-ae89-6273e47d4b95
# ╟─a0df1382-68d2-4b29-be29-3b3ebb94cb1e
# ╟─98244829-7c17-42f0-a10b-1d86408a4fb7
# ╟─02d09aac-70ac-48ed-829a-3be9b2fa605c
# ╟─806491f8-e739-4537-8768-125d9124d157
# ╠═1f026d1a-9d5c-4732-9a42-bb85be9cff0b
# ╠═1ec45e86-fce4-43a6-b6dd-74972b316113
# ╟─34b70baa-46f2-42cc-98bb-06b6d2c38ee3
# ╠═77aa8869-176d-4bf4-a021-b588b769e44f
# ╟─2f8f5fa3-892a-4641-84e9-b0dfa59d2b27
# ╠═789c6ecd-9933-49a5-b3fa-5c3ff86488b3
# ╟─f117902c-7a84-4a6c-ab6a-0dd11cddee16
# ╠═dbc5569b-cb73-44c0-970c-16f713349163
# ╠═a562900c-93af-4562-8f92-445e59bc9481
# ╠═9165b8ac-4962-432f-9643-525f441d9615
# ╟─e54b4939-f389-49f0-90c0-1a0b2ff87774
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
|
#####
##### AlphaZero.jl
##### Jonathan Laurent, Carnegie Mellon University (2019)
#####
module AlphaZero
export MCTS, MinMax, GameInterface, GI, Report, Network, Benchmark
export Params, SelfPlayParams, LearningParams, ArenaParams
export MctsParams, MemAnalysisParams
export Env, train!, learning!, self_play!, get_experience
export AbstractGame, AbstractPlayer, interactive!
export MctsPlayer, RandomPlayer, EpsilonGreedyPlayer, NetworkPlayer, Human
export SamplesWeighingPolicy, CONSTANT_WEIGHT, LOG_WEIGHT, LINEAR_WEIGHT
export ColorPolicy, ALTERNATE_COLORS, BASELINE_WHITE, CONTENDER_WHITE
export AbstractNetwork, OptimiserSpec, Nesterov, CyclicNesterov, Adam
export SimpleNet, SimpleNetHP, ResNet, ResNetHP
export AbstractSchedule, PLSchedule, StepSchedule
export Session, resume!, save, play_game, run_new_benchmark
export Explorer, explore
include("util.jl")
import .Util
using .Util: Option, @unimplemented
include("game.jl")
using .GameInterface
const GI = GameInterface
include("mcts.jl")
import .MCTS
include("networks/network.jl")
using .Network
include("ui/log.jl")
using .Log
import Plots
import Colors
import JSON2
import JSON3
using Formatting
using Crayons
using Colors: @colorant_str
using ProgressMeter
using Base: @kwdef
using Serialization: serialize, deserialize
using DataStructures: Stack, CircularBuffer
using Distributions: Categorical, Dirichlet
using Statistics: mean
include("schedule.jl")
include("params.jl")
include("report.jl")
include("memory.jl")
include("learning.jl")
include("play.jl")
include("training.jl")
include("minmax.jl")
import .MinMax
include("benchmark.jl")
using .Benchmark
# We support Flux and Knet
const USE_KNET = true
if USE_KNET
@eval begin
include("networks/knet.jl")
using .KNets
end
else
@eval begin
include("networks/flux.jl")
using .FluxNets
end
end
include("ui/explorer.jl")
include("ui/plots.jl")
include("ui/json.jl")
include("ui/session.jl")
end
|
module ITCC
using Distances
include("utils.jl")
export itcc, ITCC_Result, readtsv
type ITCC_Result<:Any
cX::Array{Int,2}
cY::Array{Int,2}
q::Matrix{Float64}
p_clust::Matrix{Float64}
kl::Float64
converged::Bool
num_iters::Int
end
# itcc with option to specify vectors of initial partions
function itcc(p::AbstractArray{Float64,2}, k::Int, l::Int, n_iters::Int, convergeThresh::Float64, cX::Array{Int,2}, cY::Array{Int,2})
m = size(p,1)
n = size(p,2)
converged = false
kl_curr = 0.0
kl_prev = 0.0
num_iters = 0
q = calc_q(p, 1:m, cX, 1:n, cY)
kl_curr = kl_divergence(vec(p), vec(q))
for i in 1:n_iters
kl_prev = kl_curr
num_iters = i
# Update cX, q
cX = next_cX(p,q, cX, k)
q = calc_q(p, 1:m, cX, 1:n, cY)
# Update cY, q
cY = next_cY(p,q, cY, l)
q = calc_q(p, 1:m, cX, 1:n, cY)
kl_curr = kl_divergence(vec(p), vec(q))
if (kl_prev - kl_curr) < convergeThresh
converged = true
break
end
end
return ITCC_Result(cX, cY, q, prob_clust(p, 1:k,cX, 1:l,cY), kl_curr, converged, num_iters)
end
"""
# If no cX, cY are specified, default to random assignments
function itcc(p::Array{Float64,2}, k::Int, l::Int, n_iters::Int, convergeThresh::Float64)
cX = rand(1:k, size(p,1))
cY = rand(1:l, size(p,2))
itcc(p, k, l, n_iters, convergeThresh, cX, cY)
end
"""
function readtsv(filepath)
data = readdlm(filepath, '\t')
n = maximum(data[:,2])+1
m = maximum(data[:,4])+1
joint_prob = zeros(n,m)
numData = size(data,1)
for i in 1:numData
joint_prob[data[i,2]+1, data[i,4]+1] = data[i,5]/numData
end
return joint_prob
end
end # module
|
function readinput(filename)
ingredients = Vector()
allergens = Vector()
for line in readlines(filename)
ingredients_str, contains_str = split(line, "(contains ")
push!(ingredients, Set(String(m.match) for m in eachmatch(r"[a-z]+", ingredients_str)))
push!(allergens, Set(String(m.match) for m in eachmatch(r"[a-z]+", contains_str)))
end
return (ingredients, allergens)
end
function getpotentialingredients(ingredients, allergens)
allingredients = union(ingredients...)
allallergens = union(allergens...)
potentialingredients = Dict()
for allergen in allallergens
potentialingredients[allergen] = copy(allingredients)
for (ilist, alist) in zip(ingredients, allergens)
if allergen in alist
intersect!(potentialingredients[allergen], ilist)
end
end
end
return potentialingredients
end
function part1(potentialingredients, ingredients)
allingredients = union(ingredients...)
unsafe = union(values(potentialingredients)...)
return sum(count(ilist -> s in ilist, ingredients) for s in setdiff(allingredients, unsafe))
end
function part2(potentialingredients, ingredients, allergens)
matched = Vector()
while !isempty(potentialingredients)
for (allergen, ingredients) in potentialingredients
if length(ingredients) == 1
ingredient = pop!(ingredients)
push!(matched, (allergen, ingredient))
delete!(potentialingredients, allergen)
for ilist in values(potentialingredients)
delete!(ilist, ingredient)
end
break;
end
end
end
sort!(matched, by=((a,i),)->a)
return join([i for (_,i) in matched], ",")
end
(ingredients, allergens) = readinput("d21.in")
potentialingredients = getpotentialingredients(ingredients, allergens)
println("P1: ", part1(potentialingredients, ingredients))
println("P2: ", part2(potentialingredients, ingredients, allergens))
|
include("DataTypes.jl")
include("ParserFunctions.jl")
include("Config.jl")
using HTTP
using CSV
using DataFrames
using Suppressor
availablemodels = [
"mix",
"ecmwf-ifs",
"ecmwf-ens",
"ecmwf-ens-cluster",
"ecmwf-ens-tc",
"ecmwf-vareps",
"ecmwf-mmsf",
"cmc-gem",
"ncep-gfs",
"mm-tides",
"mm-swiss1k",
"ukmo-euro4",
"mf-arome",
"dwd-icon-eu",
"ecmwf-cams",
"fmi-silam",
"ecmwf-wam",
"ecmwf-cmems",
"noaa-hycom",
"ecmwf-era5",
"chc-chirps2",
"mix-radar",
"mm-heliosat",
"mm-lightning",
"noaa-swpc",
"mix-satellite",
"eumetsat-h03b",
"dlr-corine",
"mix-obs",
"mm-mos",
"mri-esm2-ssp126",
"mri-esm2-ssp245",
"mri-esm2-ssp370",
"mri-esm2-ssp460",
"mri-esm2-ssp585"
]
ensemblemodels = Dict(
"ecmwf-ens" => [string(x) for x in 0:1:50],
"ecmwf-vareps" => [string(x) for x in 0:1:32],
"ecmwf-mmsf" => [string(x) for x in 0:1:31],
"ncep-gfs-ens" => [string(x) for x in 0:1:31]
)
clustermodels = Dict(
"as above" => "so below"
)
"""
Optional arguments should be checked to ensure that they correspond to valid API calls.
Some of these have not been implemented yet: valid ens_select and cluster_select depend on the chosen model,
and I don't have complete information on this to hand as of the time of first draft.
"""
function checkopts(model, calibrated, mask, ens_select, cluster_select, timeout)
if model === nothing
else
@assert in(model, availablemodels)
end
calibrated::Union{Bool, Nothing}
if mask === nothing
else
mask = lowercase(mask)
@assert mask == "land" || mask == "sea"
end
# @assert ens_select belongs to some group of valid values (dependent on model) or is nothing
# @assert cluster_select as above
timeout::Union{Integer, Nothing}
end
"""
Returns a DataFrame containing a time-series for each of the pairs of coordinates provided and each of the parameters requested.
The first two columns describe the location (latitude and longitude) of the time-series; the third column contains the date and
time as a string. The remaining columns contain the data for the requested variables at these locations and dates/times.
The user may provide a username and password; otherwise those contained in Config.jl are used. Change these to your own credentials
to avoid having to provide the information for every request. Optional arguments are also available, see
https://www.meteomatics.com/en/api/request/optional-parameters/ for more details and default behaviour.
"""
function querytimeseries(coordinate_list, startdate, enddate, interval, parameters; username=username, password=password,
model=nothing, calibrated=nothing, mask=nothing, ens_select=nothing, cluster_select=nothing, timeout=nothing)
checkopts(model, calibrated, mask, ens_select, cluster_select, timeout)
url = parse_url(
username,
password,
data_url(
validdatetime = parse_datetimes(startdate, enddate, interval),
parameters = parse_parameters(parameters),
location = parse_locations(coordinate_list),
opts = Dict(
"model" => model,
"calibrated" => calibrated,
"mask" => mask,
"ens_select" => ens_select,
"cluster_select" => cluster_select,
"timeout" => timeout
)
)
)
return handlerequest(url)
end
"""
Returns a DataFrame containing longitudes in the first row and latitudes in the first column. The rest of the DataFrame is populated
with the requested data at the coordinates subtended by row/column #1. The date and time of the request is not contained within the
DataFrame: users should keep track of this separately.
The user may provide a username and password; otherwise those contained in Config.jl are used. Change these to your own credentials
to avoid having to provide the information for every request. Optional arguments are also available, see
https://www.meteomatics.com/en/api/request/optional-parameters/ for more details and default behaviour.
"""
function querygrid(startdate, parameter::String, north, west, south, east, reslat, reslon; username=username, password=password,
model=nothing, calibrated=nothing, mask=nothing, ens_select=nothing, cluster_select=nothing, timeout=nothing)
checkopts(model, calibrated, mask, ens_select, cluster_select, timeout)
url = parse_url(
username,
password,
data_url(
validdatetime = parse_datetime(startdate),
parameters = parse_parameters(parameter),
location = parse_locations(north, west, south, east, reslon, reslat),
opts = Dict(
"model" => model,
"calibrated" => calibrated,
"mask" => mask,
"ens_select" => ens_select,
"cluster_select" => cluster_select,
"timeout" => timeout
)
)
)
@suppress_err df = handlerequest(url) # warning (regarding badly shaped .csv) suppressed
# post-process the DataFrame:
df = df[2:end, :] # remove header
rename!(df, names(df)[1] => "Column1", names(df)[2] => "Column2") # change column names (back to defaults; hardcoded)
col1 = [missing, parse.(Float64, df[2:end, 1])...] # now that string values have been removed, convert cols to float...
col2 = [parse.(Float64, df[1:end, 2])...] # ...achieved by making substitute columns with strings replaced by missing...
df = df[:, 3:end] # ...removing the original columns from the DataFrame...
insertcols!(df, 1, :Column1 => col1) # ...and inserting the prepared columns at the requisite indexes
insertcols!(df, 2, :Column2 => col2)
allowmissing!(df)
return df
end
"""
Returns one DataFrame per requested parameter, containing longitudes in the first row and latitudes in the first column. The rest of the DataFrame is populated
with the requested data at the coordinates subtended by row/column #1. The date and time of the request is not contained within the
DataFrame: users should keep track of this separately.
The user may provide a username and password; otherwise those contained in Config.jl are used. Change these to your own credentials
to avoid having to provide the information for every request. Optional arguments are also available, see
https://www.meteomatics.com/en/api/request/optional-parameters/ for more details and default behaviour.
"""
function querygrid(startdate, parameters::Vector{String}, north, west, south, east, reslat, reslon; username=username, password=password,
model=nothing, calibrated=nothing, mask=nothing, ens_select=nothing, cluster_select=nothing, timeout=nothing)
if length(parameters) == 1
return querygrid(startdate, parameters[1], north, west, south, east, reslat, reslon; username=username, password=password,
model=model, calibrated=calibrated, mask=mask, ens_select=ens_select, cluster_select, timeout=timeout)
else
checkopts(model, calibrated, mask, ens_select, cluster_select, timeout)
url = parse_url(
username,
password,
data_url(
validdatetime = parse_datetime(startdate),
parameters = parse_parameters(parameters),
location = parse_locations(north, west, south, east, reslon, reslat),
opts = Dict(
"model" => model,
"calibrated" => calibrated,
"mask" => mask,
"ens_select" => ens_select,
"cluster_select" => cluster_select,
"timeout" => timeout
)
)
)
df = handlerequest(url)
dfs = Array{DataFrame}(undef, length(names(df)) - 3)
i = 1
for column in names(df)[4:end]
dfs[i] = reshape(select(df, 1, 2, column))
i += 1
end
return dfs
end
end
"""
Takes a DataFrame as returned by a grid request of multiple parameters. Reshapes- and processes the DataFrame and returns it.
"""
function reshape(df::DataFrames.DataFrame)
unstacked = unstack(df, 1, 2, 3)
allowmissing!(unstacked)
firstrow = DataFrame(Dict((names(unstacked)[i], [0.0, parse.(Float64, names(unstacked[:, 2:end]))...][i]) for i in 1:length(names(unstacked))))[:, names(unstacked)]
allowmissing!(firstrow)
firstrow[1,1] = missing
[push!(firstrow, unstacked[i, :]) for i in 1:length(unstacked[:, 1])]
rename!(firstrow, [names(firstrow)[i] => "Column$i" for i in 1:length(names(firstrow))]...)
return firstrow
end
"""
Returns a DataFrame whose first column is the names of the parameters requested and whose second- and third columns are,
respectively, the minimum date from which that variable is available in the queried model and the maximum available date
for that parameter. This is a meta-request - no optional parameters exist. The user may still optionally provide a
username and password; otherwise these are obtained from Config.jl.
"""
function querytimeranges(parameters, model; username=username, password=password)
url = parse_url(username, password, meta_url(metaquery="get_time_range", model=model, parameters=parse_parameters(parameters)))
return handlerequest(url)
end
"""
Returns a DataFrame whose first column is the date & time of some variable requested from a model, and whose subsequent columns
describe the date and time at which the model was run to produce the results which would currently be obtained by querying the model
for each of the parameters queried. This is a meta-request - no optional parameters exist. The user may still optionally provide a
username and password; otherwise these are obtained from Config.jl.
"""
function queryinitdatetime(startdate, enddate, interval, parameters, model; username=username, password=password)
url = parse_url(
username, password, meta_url(metaquery="get_init_date", model=model,
parameters=parse_parameters(parameters), validdatetime=parse_datetimes(startdate, enddate, interval))
)
return handlerequest(url)
end
"""
Takes a URL, parsed from a url data type, from a query function. Obtains a response from the API for this URL,
parses the response as a CSV, and parses the CSV data as a DataFrame.
"""
function handlerequest(url)
response = HTTP.request("GET", url)
csv_data = CSV.File(response.body)
return DataFrames.DataFrame(csv_data)
end
|
@testset "CompressedWordVectors" begin
n = 50
D = 20
k = 2
m = 5
vocab = [randstring(10) for _ in 1:n]
vectors = rand(D, n)
distance = Distances.SqEuclidean()
wv = WordVectors(vocab, vectors)
compressed_type = CompressedWordVectors{QuantizedArrays.OrthogonalQuantization,
UInt8, Distances.SqEuclidean, Float64, String, Int}
cwv = compress(wv, sampling_ratio = 0.5, k=k, m=m,
method=:pq, distance=distance)
@test cwv isa compressed_type
@test EmbeddingsAnalysis.vocabulary(cwv) == cwv.vocab
@test EmbeddingsAnalysis.in_vocabulary(cwv, vocab[1])
@test EmbeddingsAnalysis.size(cwv) == size(cwv.vectors)
idx = rand(1:n); word = vocab[idx]
@test EmbeddingsAnalysis.index(cwv, word) == cwv.vocab_hash[word]
@test EmbeddingsAnalysis.get_vector(cwv, word) == cwv.vectors[:, idx]
@test EmbeddingsAnalysis.similarity(cwv, word, word) ==
cwv.vectors[:,idx]' * cwv.vectors[:,idx]
n=3
csw = EmbeddingsAnalysis.cosine_similar_words(cwv, vocab[1], n)
@test csw isa Vector{String}
@test length(csw) == n
aw = EmbeddingsAnalysis.analogy_words(cwv, [vocab[1]], [], n)
@test aw isa Vector{String}
@test length(aw) == n
end
|
#Crawler model, for the module, should work
using Requests
using HTTP
using Gumbo
using AbstractTrees
using ArgParse
using JLD
#define our crawler
type Crawler
startUrl::AbstractString
urlsVisited::Array{AbstractString}
urlsToCrawl::Array{AbstractString}
content::Dict{AbstractString, AbstractString}
#the content is dictoianry{url: html content}
breadthFirst::Bool
#constructors
function Crawler(starturl::AbstractString)
return new(starturl, AbstractString[], AbstractString[],Dict{AbstractString, AbstractString}(), true)
end
function Crawler(starturl::AbstractString, breadthfirst::Bool)
return new(starturl, AbstractString[],AbstractString[],Dict{AbstractString, AbstractString}(), breadthfirst)
end
function Crawler(starturl::AbstractString, urlstocrawl::Array{AbstractString},breadthfirst::Bool)
return new(starturl, AbstractString[], urlstocrawl, Dict{AbstractString, AbstractString}(), breadthfirst)
end
function Crawler(starturl::AbstractString, urlstocrawl::Array{AbstractString})
return new(starturl, AbstractString[], urlstocrawl, Dict{AbstractString, AbstractString}(), true)
end
#remove this, just a test
function Crawler(urlstocrawl::Array{AbstractString}, breadthfirst::Bool)
return new("", AbstractString[], urlstocrawl, Dict{AbstractString, AbstractString}(), breadthfirst)
end
function Crawler(urlstocrawl::Array{AbstractString})
return new("", AbstractString[], urlstocrawl, Dict{AbstractString, AbstractString}(), true)
end
end
function crawl(crawler::Crawler, num_iterations::Integer=10, verbose=true, save=true)
#first we check if it's the first thing we see. so we should just check this
#shall we just define variables from the crawler? nah, let's not. we should just access them consistently
#as it's meant t be updated in place, I assume
#we should dump this in thefucntoin so it doesn't slow down
const successCode = 200
#our immediate return if correct
if isempty(crawler.urlsToCrawl) && crawler.startUrl==""
return crawler.content, crawler.urlsVisited
end
if isempty(crawler.urlsToCrawl) && crawler.startUrl!=""
#so we are at the beginning so we visit our first piece
#we set the starturl to urls to crawl
push!(crawler.urlsToCrawl,crawler.startUrl)
crawler.startUrl=""
end
#okay, now we begin the loop
for i in 0:num_iterations
#we check if empty we probably shouldn't do this on each iteratino, but oh well!
if isempty(crawler.urlsToCrawl) && crawler.startUrl==""
return crawler.content, crawler.urlsVisited
end
url = pop!(crawler.urlsToCrawl)
#we get the content
#we make the request with http
#we first check this works... idk
#println(crawler.urlsVisited)
#println(crawler.urlsToCrawl)
if !(url in crawler.urlsVisited)
if verbose==true
println("requesting $url")
end
#we do our processing
#we should really check for failure conditions here, and make the fucntions
#suitably type stable for decent performance
response = pingUrl(url)
doc = parseResponse(response)
links = extractLinks(doc)
#add the stuff to the crawler
push!(crawler.urlsVisited, url)
append!(crawler.urlsToCrawl, links)
crawler.content[url] = doc
if url in crawler.urlsToCrawl
println("repeat url")
num_iterations +=1
end
end
end
#now once we're finished our loop
#we return stuff and save
if save==true
#we just have a default here
filename = "JuliaCrawler"
saveCrawler(crawler, filename)
end
return crawler.content, crawler.urlsVisited
end
#let's split this huge death function up into smaller ones so it makes sense
function pingUrl(url::AbstractString)
#this is where we do our try catch logic, to make it simple
try
response = HTTP.get(url)
return response
catch
return nothing
end
end
#this function is terrible and not type stable. we should deal with this somehow!
function parseResponse(response::Response)
res = String(response.body)
#do anything else we need here
doc = parsehtml(res)
return doc
end
function extractLinks(doc::Gumbo.HTMLDocument)
#get links array
links = AbstractString[]
const link_key = "href"
const fail_key = "#"
for elem in PostOrderDFC(doc.root)
if typeof(elem)==Gumbo.HTMLElement(:a}
link=get(elem.attributes, link_key, fail_key)
if link != "#"
push!(links, link)
end
end
end
return links
end
function reset_crawler(crawler::Crawler)
#this function just resets all the stuff and clears it
empty!(crawler.urlsVisited)
empty!(crawler.urlsToCrawl)
crawler.content = Dict()
return crawler
end
# dagnabbi we don't have wifi and we have no idea how to actually save thi sstuff. I guess we got to look it up via phone?
#okay, now our big function with the logic
#okay, we sorted out that, which is great to be honest. but now we'regoing to have to figure out how to do files and the like, which is just going to be annoying I think
#let's try this - we're using JLD
function saveCrawler(crawler::Crawler, filename::String, startUrl=true, urlsVisited=true, urlsToCrawl=false, content=true)
#I think that's all the thing, so we can decide what to add
crawlerDict = Dict()
if startUrl==true
crawlerDict["starting_url"] = crawler.startUrl
end
if urlsVisited==true
crawlerDict["urls_visited"]= crawler.urlsVisited
end
if urlsToCrawl==true
crawlerDIct["urls_to_crawl"] = crawler.urlsToCrawl
end
if content==true
crawlerDict["content"] = crawler.content
end
fname = filename + ".jld"
save(fname, crawlerDict)
end
# what else do we need to do. we need to integrate this. somehow into the main crawl function. we can do that pretty soon I think/hope
# at some point I could implement threading and stuff, but not for now. this isj ust a fairly straightforward image crawler. hopefully. I dno't even know really
# not sure how we're going to implement that
#maybe we'll have markov chains somewhere?
# this is our arg parse settings so we can see if it works and write it up properly
function parse_commandline()
s = ArgParseSettings(prog="Julia Web Crawler",
description="A webcrawler written in Julia",
commands_are_required=false,
version="0.0.1",
add_version=true)
@add_arg_table s begin
"--urls"
help="either a url to start at or a set of urls to start visiting"
required=true
"--breadth-first", "--b"
help="a flag or whether the crawler should search depth or breadth first"
action=:store_true
default = true
"--num_iterations", "--i"
help="the number of iteratinos to run the crawler for"
default=10
end
return parse_args(s)
end
function setupCrawler(urls, b=true)
return Crawler(urls, b)
end
function begin_crawl(urls, b=true, num_iterations::Integer=10)
crawler = setupCrawler(urls, b)
crawl(crawler, num_iterations, b)
end
|
using Distributed
# addprocs(8);
# addprocs(4);
# addprocs(16);
addprocs((Sys.CPU_THREADS >> 1) + (1 - nprocs()) # master, and 1 slave for every 2 threads
# @everywhere begin
#
# # using Pkg
# # include(joinpath(dir("AsymptoticPosteriors"), "examples/NGSCov.jl"));
# end
@everywhere begin
# include("/home/chris/.julia/dev/AsymptoticPosteriors/examples/NGSCov.jl")
includet("/home/chriselrod/.julia/dev/AsymptoticPosteriors/examples/NGSCov.jl")
# include("/home/celrod/.julia/dev/AsymptoticPosteriors/examples/NGSCov.jl")
# using DifferentiableObjects
const truth = CorrErrors((0.15, 0.4), (0.9, 0.95), (0.85,0.97), (0.6, 0.2));
const data = NoGoldDataCorr(truth,160,320,52);
const datacorr = NoGoldData(truth,160,320,52);
x = randnsimd(6);
end
@everywhere begin
@time const ap = AsymptoticPosterior(data, x);
end
@everywhere begin
@time quantile(ap, 0.025)
# @time apc = AsymptoticPosterior(data, randn(6), Val(6));
summary(ap)
end
@everywhere begin
function set_up_sim(truth, n_common=100, n1=1000, n2=30)
S₁, S₂, C₁, C₂, π₁, π₂ = truth.S[1], truth.S[2], truth.C[1], truth.C[2], truth.π[1], truth.π[2]
init = SizedSIMDVector{6,Float64}(undef)
for i ∈ 1:4
init[i] = truth.Θ[i]
end
for i ∈ 7:length(truth.Θ)
init[i-2] = truth.Θ[i]
end
data = NoGoldData(truth, n_common, n1, n2)
# resample!(data, truth, n_common, n1, n2)
ap = AsymptoticPosterior(undef, data, init)
data, ap, init
end
function simulation(truth, k, iter, n_common, n1, n2)
data, ap, init = set_up_sim(truth, n_common, n1, n2)
simulation_core!(data, ap, init, truth, k, iter, n_common, n1, n2)
end
function simulation_core!(data, ap, init, truth, k, iter, n_common = 100, n1 = 1000, n2 = 30)
sim_results = Array{Float64}(undef,3,6,k)
S₁, S₂, C₁, C₂, π₁, π₂ = truth.S[1], truth.S[2], truth.C[1], truth.C[2], truth.π[1], truth.π[2]
AsymptoticPosteriors.fit!(ap.map, init)
set_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, 1)
set_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, 1)
set_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, 1)
set_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, 1)
set_buffer!(sim_results, inv_logit, π₁, ap, 5, 1)
set_buffer!(sim_results, inv_logit, π₂, ap, 6, 1)
@inbounds for j ∈ 2:iter
resample!(data, truth, n_common, n1, n2)
AsymptoticPosteriors.fit!(ap.map, init)
update_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, 1)
update_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, 1)
update_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, 1)
update_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, 1)
update_buffer!(sim_results, inv_logit, π₁, ap, 5, 1)
update_buffer!(sim_results, inv_logit, π₂, ap, 6, 1)
end
for i ∈ 2:k
n_common *= 2
n1 *= 2
n2 *= 2
resample!(data, truth, n_common, n1, n2)
AsymptoticPosteriors.fit!(ap.map, init)
set_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, i)
set_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, i)
set_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, i)
set_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, i)
set_buffer!(sim_results, inv_logit, π₁, ap, 5, i)
set_buffer!(sim_results, inv_logit, π₂, ap, 6, i)
@inbounds for j ∈ 2:iter
resample!(data, truth, n_common, n1, n2)
AsymptoticPosteriors.fit!(ap.map, init)
update_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, i)
update_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, i)
update_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, i)
update_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, i)
update_buffer!(sim_results, inv_logit, π₁, ap, 5, i)
update_buffer!(sim_results, inv_logit, π₂, ap, 6, i)
end
end
sim_results
end
function simulation(truth, K1,K2,K3, iter, n_common, n1, n2)
data, ap, init, sim_results = set_up_sim(truth, n_common, n1, n2)
simulation_core!(data, ap, init, sim_results, truth, K1,K2,K3, iter, n_common, n1, n2)
end
function simulation_core!(data, ap, init, truth, K1,K2,K3, iter, n_common_base, n1_base, n2_base)
sim_results = Array{Float64}(undef,3,6,K1,K2,K3)
S₁, S₂, C₁, C₂, π₁, π₂ = truth.S[1], truth.S[2], truth.C[1], truth.C[2], truth.π[1], truth.π[2]
for k3 ∈ 1:K3, k2 ∈ 1:K2, k1 ∈ 1:K1
n_common = round(Int, n_common_base * 2^((k1-1)//8))
n1 = round(Int, n1_base * 2^((k2-1)//8))
n2 = round(Int, n2_base * 2^((k3-1)//8))
resample!(data, truth, n_common, n1, n2)
# try
AsymptoticPosteriors.fit!(ap.map, init)
set_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, k1,k2,k3)
set_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, k1,k2,k3)
set_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, k1,k2,k3)
set_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, k1,k2,k3)
set_buffer!(sim_results, inv_logit, π₁, ap, 5, k1,k2,k3)
set_buffer!(sim_results, inv_logit, π₂, ap, 6, k1,k2,k3)
# catch err
# @show data
# @show n_common, n1, n2
# rethrow(err)
# end
@inbounds for j ∈ 2:iter
resample!(data, truth, n_common, n1, n2)
# try
AsymptoticPosteriors.fit!(ap.map, init)
update_buffer!(sim_results, inv_uhalf_logit, S₁, ap, 1, k1,k2,k3)
update_buffer!(sim_results, inv_uhalf_logit, S₂, ap, 2, k1,k2,k3)
update_buffer!(sim_results, inv_uhalf_logit, C₁, ap, 3, k1,k2,k3)
update_buffer!(sim_results, inv_uhalf_logit, C₂, ap, 4, k1,k2,k3)
update_buffer!(sim_results, inv_logit, π₁, ap, 5, k1,k2,k3)
update_buffer!(sim_results, inv_logit, π₂, ap, 6, k1,k2,k3)
# catch err
# @show data
# @show n_common, n1, n2
# rethrow(err)
# end
end
end
sim_results
end
function update_buffer!(buffer::AbstractArray{T}, f, true_val, ap, j, k...) where T
l = f(quantile(ap, 0.025, j))
isfinite(l) || throw("$l not finite, j = $j")
u = f(quantile(ap, 0.975, j))
isfinite(u) || throw("$u not finite, j = $j")
if (l < true_val) && (u > true_val)
buffer[1,j,k...] += one(T)
end
buffer[2,j,k...] += u - l
buffer[3,j,k...] += abs(true_val- f(ap.map.θhat[j]))
end
function set_buffer!(buffer::AbstractArray{T}, f, true_val, ap, j, k...) where T
l = f(quantile(ap, 0.025, j))
isfinite(l) || throw("$l not finite, j = $j")
u = f(quantile(ap, 0.975, j))
isfinite(u) || throw("$u not finite, j = $j")
buffer[1,j,k...] = ifelse((l < true_val) && (u > true_val), one(T), zero(T)) # need to set it to zero.
buffer[2,j,k...] = u - l
buffer[3,j,k...] = abs(true_val- f(ap.map.θhat[j]))
end
@inline inv_uhalf_logit(x) = 0.5+0.5/(1+exp(-x ))
const increments = (
((4,0), (-4,0), (0, 0) ),
((4,0), (0,0), (-4, 0)),
((-4,0), (8,0), (0, 0) ),
((-4,0), (0,0), (8, 0) ),
((0,0), (4,0), (0, 0) ),
((0,0), (0,0), (10, 0)),
((2,0), (0,0), (0, 0) ),
((0,4), (0,-4), (0, 0) ),
((0,4), (0,0), (0,-4) ),
((0,-4), (0,8), (0, 0) ),
((0,-4), (0,0), (0,8) ),
((0,0), (0,4), (0, 0) ),
((0,0), (0,0), (0, 4) ),
((0,2), (0,0), (0, 0) )
)
function increment_n(n_common, n1, n2, i)
increment = increments[i]
nctemp = n_common .+ increment[1]
n1temp = n1 .+ increment[2]
n2temp = n2 .+ increment[3]
nctemp, n1temp, n2temp
end
function cost((n1cost,n2cost), n_common, n1, n2)
n1cost * sum(n_common .+ n1) + n2cost * sum(n_common .+ n2)
end
function increment_cost((n1cost,n2cost), i)
n_common, n1, n2 = increments[i]
n1cost * sum(n_common .+ n1) + n2cost * sum(n_common .+ n2)
end
function average_loss(costs, iter, n_common, n1, n2)
sim_results = Array{Float64}(undef,length(increments))
S₁, S₂, C₁, C₂, π₁, π₂ = truth.S[1], truth.S[2], truth.C[1], truth.C[2], truth.π[1], truth.π[2]
init = SizedSIMDVector{6,Float64}(undef)
for i ∈ 1:4
init[i] = truth.Θ[i]
end
for i ∈ 7:length(truth.Θ)
init[i-2] = truth.Θ[i]
end
# uses global data and ap
for i ∈ 1:length(increments)
nctemp, n1temp, n2temp = increment_n(n_common, n1, n2, i)
if any(nctemp .< 0) || any(n1temp .< 0) || any(n2temp .< 0)
sim_results[i] = Inf
continue
end
sim_results[i] = increment_cost(costs, i)*iter
@inbounds for k ∈ 1:iter
resample!(data, truth, nctemp, n1temp, n2temp)
AsymptoticPosteriors.fit!(ap.map, init)
sim_results[i] += loss(ap, init)
end
end
sim_results# ./ iter
end
# @inline lossv2(v, truth, p) = v > truth ? p*(v-truth) : (1-p)*(truth-v)
@inline loss(v, truth, p) = (p - (v < truth))*(v-truth)
loss((l, u)::Tuple{<:Number,<:Number}, truth, pl = 0.025, pu = 0.975) = loss(l, truth, pl) + loss(u, truth, pu)
function loss(ap::AsymptoticPosteriors.AsymptoticPosterior, truth)
l = 0.0
@inbounds for i ∈ eachindex(truth)
l += loss((quantile(ap, 0.025, i),quantile(ap, 0.975, i)), truth[i])
end
l
end
end #everywhere
function run_simulation(truth, k = 5, iter = 25, n_common = 200, n1 = 100, n2 = 30)
@distributed (+) for i ∈ 2:nprocs()
simulation(truth, k, iter, n_common, n1, n2)
end
end
function run_simulation2(truth, k = 10, iter = 50, n_common = 100, n1 = 500, n2 = 30)
@distributed (+) for i ∈ 2:nprocs()
simulation(truth, k,k,k, iter, n_common, n1, n2)
end
end
function run_simulation(truth, N=10, k = 5, iter = 25, n_common = 200, n1 = 100, n2 = 30)
out = simulation_core(truth, k, iter, n_common, n1, n2)
for i ∈ 2:N
out += simulation(truth, k, iter, n_common, n1, n2)
end
out
end
# @time @everywhere begin
# const data = NoGoldData(truth)
# const ap = AsymptoticPosterior(undef, data, x)
# end #everywhere
function simulation_search( costs, num_iter, n_common = (100,100), n1 = (200,200), n2 = (30,30) )
nproc = nprocs()
current_loss = Inf
losses = @distributed (+) for i ∈ 2:nproc
average_loss(costs, num_iter, n_common, n1, n2)
end
last_loss, minind = findmin(losses)
iteration = 1
while last_loss < current_loss
@show iteration, losses
@show n_common, n1, n2
iteration += 1
current_loss = last_loss
n_common, n1, n2 = increment_n(n_common, n1, n2, minind)
losses = @distributed (+) for i ∈ 2:nproc
average_loss(costs, num_iter, n_common, n1, n2)
end
last_loss, minind = findmin(losses)
if last_loss > current_loss # We'll try again.
println("Failed to find best argument. Searching broadly.")
for n ∈ 1:length(increments)
n_common_temp, n1_temp, n2_temp = increment_n(n_common, n1, n2, n)
(any(n_common_temp .< 0) || any(n1_temp .< 0) || any(n2_temp .< 0)) && continue
losses_temp = @distributed (+) for i ∈ 2:nproc
average_loss(costs, num_iter, n_common_temp, n1_temp, n2_temp)
end
@show n_common_temp, n1_temp, n2_temp
@show losses_temp
last_loss_temp, minind_temp = findmin(losses_temp)
last_loss_temp += increment_cost(costs, n) * num_iter * (nproc-1)
if last_loss_temp < current_loss
last_loss = last_loss_temp
n_common, n1, n2 = n_common_temp, n1_temp, n2_temp
minind = minind_temp
break
end
end
end
end
@show iteration, losses
n_common, n1, n2, current_loss
end
# @time simulation_search((0.0000005,0.005), 1000, (150,150), (5,5), (5,5))
# 4869.788621 seconds (380.42 k allocations: 35.323 MiB, 0.00% gc time)
# ((350, 320), (75, 15), (5, 5), 441712.07542121154)
# 138 137
# 274 235
# 898 275
# 942 283
# 964* 900
# 968* 944
# 971* 966*
# 973* 970*
# 1012 973*
# 1014* 975*
# 1159 1014
# 1295 1016*
# 1335 1161
# 1297
# 1337
#
|
using Documenter, PowerSystems
using InfrastructureSystems
const PSYPATH = dirname(pathof(PowerSystems))
# This is commented out because the output is not user-friendly. Deliberation on how to best
# communicate this information to users is ongoing.
#include(joinpath(@__DIR__, "src", "generate_validation_table.jl"))
makedocs(
modules = [PowerSystems],
format = Documenter.HTML(mathengine = Documenter.MathJax()),
sitename = "PowerSystems.jl",
authors = "Jose Daniel Lara, Daniel Thom and Clayton Barrows",
pages = Any[ # Compat: `Any` for 0.4 compat
"Introduction" => "index.md",
"User Guide" => Any[
"man/parsing.md",
"man/data.md",
],
"Developer" => Any[
"Tests" => "developer/tests.md",
"Logging" => "developer/logging.md",
"Style Guide" => "developer/style.md",
"Extending Parsing" => "developer/extending_parsing.md",
],
"API" => Any[
"PowerSystems" => "api/PowerSystems.md"
]
]
)
deploydocs(
repo = "github.com/NREL/PowerSystems.jl.git",
branch = "gh-pages",
target = "build",
make = nothing,
)
|
using QueryOperators
using DataValues
using Test
@testset "QueryOperators" begin
@testset "Core" begin
source_1 = [1,2,2,3,4]
enum = QueryOperators.query(source_1)
@test collect(QueryOperators.@filter(QueryOperators.query(source_1), i->i>2)) == [3,4]
@test collect(QueryOperators.@map(QueryOperators.query(source_1), i->i^2)) == [1,4,4,9,16]
@test collect(QueryOperators.@take(enum, 2)) == [1,2]
@test collect(QueryOperators.@drop(enum, 2)) == [2,3,4]
@test QueryOperators.@count(enum) == 5
@test QueryOperators.@count(enum, x->x%2==0) == 3
dropped_str = ""
for i in QueryOperators.drop(enum, 2)
dropped_str *= string(i)
end
@test dropped_str == "234"
dropped_str = ""
for i in QueryOperators.drop(enum, 80)
dropped_str *= string(i)
end
@test dropped_str == ""
taken_str = ""
for i in QueryOperators.take(enum, 2)
taken_str *= string(i)
end
@test taken_str == "12"
filtered_str = ""
for i in QueryOperators.@filter(enum, x->x%2==0)
filtered_str *= string(i)
end
@test filtered_str == "224"
filtered_str = ""
for i in QueryOperators.@filter(enum, x->x>100)
filtered_str *= string(i)
end
@test filtered_str == ""
@test collect(QueryOperators.@filter(enum, x->x<3)) == [1,2,2]
grouped = []
for i in QueryOperators.@groupby(QueryOperators.query(source_1), i->i, i->i^2)
push!(grouped, i)
end
@test grouped == [[1],[4,4],[9],[16]]
mapped = []
for i in collect(QueryOperators.@map(enum, i->i*3))
push!(mapped, i)
end
@test mapped == [3,6,6,9,12]
# ensure that the default value must be of the same type
errored = false
try
QueryOperators.@default_if_empty(source_1, "string")
catch
errored = true
end
@test errored == true
# default_if_empty for regular array
d = []
for i in QueryOperators.@default_if_empty(source_1, 0)
push!(d, i)
end
@test d == [1, 2, 2, 3, 4]
@test collect(QueryOperators.default_if_empty(DataValue{Int}[]))[1] == DataValue{Int}()
@test collect(QueryOperators.default_if_empty(DataValue{Int}[], DataValue{Int}()))[1] == DataValue{Int}()
# passing in a NamedTuple of DataValues
nt = (a=DataValue(2), b=DataValue("test"), c=DataValue(3))
def = QueryOperators.default_if_empty(typeof(nt)[])
@test typeof(collect(def)[1]) == typeof(nt)
ordered = QueryOperators.@orderby(enum, x -> -x)
@test collect(ordered) == [4, 3, 2, 2, 1]
filtered = QueryOperators.@orderby(QueryOperators.@filter(enum, x->x%2 == 0), x->x)
@test collect(filtered) == [2, 2, 4]
ordered = QueryOperators.@orderby_descending(enum, x -> -x)
@test collect(ordered) == [1, 2, 2, 3, 4]
desired = [[1], [2, 2, 3], [4]]
grouped = QueryOperators.@groupby(enum, x -> floor(x/2), x->x)
@test collect(grouped) == desired
group_no_macro = QueryOperators.groupby(enum, x -> floor(x/2), quote x->floor(x/2) end)
@test collect(group_no_macro) == desired
outer = QueryOperators.query([1,2,3,4,5,6])
inner = QueryOperators.query([2,3,4,5])
join_desired = [[3,2], [4,3], [5,4], [6,5]]
@test collect(QueryOperators.@join(outer, inner, x->x, x->x+1, (i,j)->[i,j])) == join_desired
group_desired = [[1, Int64[]], [2, Int64[]], [3, [2]], [4, [3]], [5, [4]], [6, [5]]]
@test collect(QueryOperators.@groupjoin(outer, inner, x->x, x->x+1, (i,j)->[i,j])) == group_desired
many_map_desired = [[1, 2], [2, 4], [2, 4], [3, 6], [4, 8]]
success = collect(QueryOperators.@mapmany(enum, x->[x*2], (x,y)->[x,y])) == many_map_desired
@test success # for some reason, this is required to avoid a BoundsError
first = QueryOperators.query([1, 2])
second = [3, 4]
many_map_desired = [(1,3), (1,4), (2,3), (2,4)]
success = collect(QueryOperators.@mapmany(first, i->second, (x,y)->(x,y))) == many_map_desired
@test success
ntups = QueryOperators.query([(a=1, b=2, c=3), (a=4, b=5, c=6)])
@test sprint(show, ntups) == """
2x3 query result
a │ b │ c
──┼───┼──
1 │ 2 │ 3
4 │ 5 │ 6"""
@test sprint(show, enum) == """
5-element query result
1
2
2
3
4"""
@test sprint((stream,data)->show(stream, "text/html", data), ntups) ==
"<table><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tbody><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></tbody></table>"
gather_result1 = QueryOperators.gather(QueryOperators.query([(US=1, EU=1, CN=1), (US=2, EU=2, CN=2), (US=3, EU=3, CN=3)]))
@test sprint(show, gather_result1) == """9x2 query result\nkey │ value\n────┼──────\n:US │ 1 \n:EU │ 1 \n:CN │ 1 \n:US │ 2 \n:EU │ 2 \n:CN │ 2 \n:US │ 3 \n:EU │ 3 \n:CN │ 3 """
gather_result2 = QueryOperators.gather(QueryOperators.query([(Year=2017, US=1, EU=1, CN=1), (Year=2018, US=2, EU=2, CN=2), (Year=2019, US=3, EU=3, CN=3)]), :US, :EU, :CN)
@test sprint(show, gather_result2) == "9x3 query result\nYear │ key │ value\n─────┼─────┼──────\n2017 │ :US │ 1 \n2017 │ :EU │ 1 \n2017 │ :CN │ 1 \n2018 │ :US │ 2 \n2018 │ :EU │ 2 \n2018 │ :CN │ 2 \n2019 │ :US │ 3 \n2019 │ :EU │ 3 \n2019 │ :CN │ 3 "
@test sprint((stream,data)->show(stream, "application/vnd.dataresource+json", data), ntups) ==
"{\"schema\":{\"fields\":[{\"name\":\"a\",\"type\":\"integer\"},{\"name\":\"b\",\"type\":\"integer\"},{\"name\":\"c\",\"type\":\"integer\"}]},\"data\":[{\"a\":1,\"b\":2,\"c\":3},{\"a\":4,\"b\":5,\"c\":6}]}"
end
include("test_enumerable_unique.jl")
include("test_namedtupleutilities.jl")
end
|
"""
# Refs
[1] F. L. Lewis, D. Vrabie, and K. Vamvoudakis, "Reinforcement Learning and Feedback Control: Using Natural Decision Mehods to Design Optimal Adaptive Controllers," IEEE Control Systems, vol. 32, no. 6, pp.76-105, 2012.
# Variables
V̂ ∈ R: the estimate of (state) value function
- V̂.basis: Φ
- V̂.param: w
d: polynomial degree
"""
mutable struct CTLinearValueIterationIRL
Q
R
V̂::LinearApproximator
T::Real
N::Int
function CTLinearValueIterationIRL(Q, R,
T=0.04, N=3, d_value::Int=2, d_controller::Int=4;
V̂=LinearApproximator(2, 2; with_bias=false),
)
@assert T > 0
new(Q, R, V̂, T, N)
end
end
function RunningCost(irl::CTLinearValueIterationIRL)
@unpack Q, R = irl
return QuadraticCost(Q, R)
end
"""
Infer he approximate optimal input.
"""
function ApproximateOptimalInput(irl::CTLinearValueIterationIRL, B)
@unpack R = irl
return function (x, p, t)
P = ARE_solution(irl)
K = inv(R) * B' * P
û = -K * x
end
end
function ARE_solution(irl::CTLinearValueIterationIRL)
ŵ = irl.V̂.param
P = [ ŵ[1] ŵ[2]/2;
ŵ[2]/2 ŵ[3]]
P
end
function update_params_callback(irl::CTLinearValueIterationIRL, w_tol)
stop_conds = function(w, w_prev)
stop_conds_dict = Dict(
:w_tol => norm(w - w_prev) < w_tol,
)
end
i = 0
w_prev = nothing
∫rs = []
V̂_nexts = []
Φs = []
V̂_nexts = []
is_terminated = false
affect! = function (integrator)
@unpack t = integrator
X = integrator.u
@unpack x, ∫r = X
∫r = length(∫r) == 1 ? ∫r[1] : error("Invalid ∫r") # for both Number and Array
push!(∫rs, ∫r)
push!(Φs, irl.V̂.basis(x))
if length(∫rs) > 1
push!(V̂_nexts, diff(∫rs[end-1:end])[1] + irl.V̂(x)[1]) # initial_affect=true
end
if is_terminated == false
if length(V̂_nexts) >= irl.N
i += 1
irl.V̂.param = pinv(hcat(Φs[end-irl.N:end-1]...)') * hcat(V̂_nexts...)'
if w_prev != nothing
stop_conds_dict = stop_conds(irl.V̂.param, w_prev)
is_terminated = stop_conds_dict |> values |> any
end
w_prev = deepcopy(irl.V̂.param)
V̂_nexts = []
@show t, i, irl.V̂.param
end
end
end
cb_train = PeriodicCallback(affect!, irl.T; initial_affect=true)
end
|
module Types
abstract type AbstractSpec end
abstract type SpecModifier <: AbstractSpec end
struct SingleComponent <: AbstractSpec end
struct OneMol <: AbstractSpec end
abstract type MassBasisModifier <: SpecModifier end
struct MOLAR <: MassBasisModifier end
struct MASS <: MassBasisModifier end
struct TOTAL <: MassBasisModifier end
abstract type CompoundModifier <: SpecModifier end
struct FRACTION <: CompoundModifier end
struct TOTAL_AMOUNT <: CompoundModifier end
abstract type VolumeModifier <: SpecModifier end
struct DENSITY <: VolumeModifier end
struct VOLUME <: VolumeModifier end
abstract type AbstractIntensiveSpec{T1<:MassBasisModifier} <: AbstractSpec end
abstract type AbstractTotalSpec <: AbstractSpec end
abstract type AbstractFractionSpec <: AbstractSpec end
abstract type CategoricalSpec <: AbstractSpec end
abstract type AbstractEnergySpec{T1} <: AbstractIntensiveSpec{T1} end
struct Enthalpy{T} <: AbstractEnergySpec{T} end
struct InternalEnergy{T} <: AbstractEnergySpec{T} end
struct Gibbs{T} <: AbstractEnergySpec{T} end
struct Helmholtz{T} <: AbstractEnergySpec{T} end
struct Entropy{T} <: AbstractIntensiveSpec{T} end
struct VolumeAmount{T1,T2<:VolumeModifier} <: AbstractIntensiveSpec{T1} end
struct Pressure <: AbstractSpec end
struct Temperature <: AbstractSpec end
# those are vectors,
struct MaterialCompounds{T1<:MassBasisModifier,T2<:CompoundModifier} <: AbstractTotalSpec end
struct MaterialAmount{T1<:MassBasisModifier} <: AbstractTotalSpec end
#humidity, to support wet gas
abstract type HumidityModifier <: AbstractSpec end
struct WetBulbTemperature <:HumidityModifier end
struct RelativeHumidity <:HumidityModifier end
struct HumidityRatio <:HumidityModifier end
struct MassHumidity <:HumidityModifier end
struct MolarHumidity <:HumidityModifier end
struct HumidityDewPoint <:HumidityModifier end
struct HumiditySpec{T<:HumidityModifier} <: AbstractSpec end
struct PhaseFractions <: AbstractFractionSpec end
struct VolumeFraction <: AbstractFractionSpec end
struct VaporFraction{T<:MassBasisModifier} <: AbstractFractionSpec end
struct PhaseTag <: CategoricalSpec end
struct TwoPhaseEquilibrium <: CategoricalSpec end
struct Options <: CategoricalSpec end
#not defined for now
struct MolecularWeight <: AbstractSpec end
#variable spec, signal to make a variable specs
struct VariableSpec end
#base type to define models
abstract type ThermoModel end
export AbstractSpec
export SpecModifier
export AbstractIntensiveSpec
export AbstractTotalSpec
export AbstractFractionSpec
export CategoricalSpec
export SingleComponent
export OneMol
export MOLAR
export MASS
export TOTAL
export FRACTION
export TOTAL_AMOUNT
export DENSITY
export VOLUME
export AbstractEnergySpec
export Enthalpy
export InternalEnergy
export Gibbs
export Helmholtz
export Entropy
export VolumeAmount
export Pressure
export Temperature
export MaterialCompounds
export MaterialAmount
export PhaseFractions
export VaporFraction
export PhaseTag
export TwoPhaseEquilibrium
export Options
export MolecularWeight
export VariableSpec
export ThermoModel
export HumidityModifier
export WetBulbTemperature
export RelativeHumidity
export HumidityRatio
export MassHumidity
export MolarHumidity
export HumidityDewPoint
export HumiditySpec
end
using .Types
const KW_TO_SPEC = Dict{Symbol,Any}(
:h => Enthalpy{MOLAR}()
,:g => Gibbs{MOLAR}()
,:a => Helmholtz{MOLAR}()
,:u => InternalEnergy{MOLAR}()
,:mol_h => Enthalpy{MOLAR}()
,:mol_g => Gibbs{MOLAR}()
,:mol_a => Helmholtz{MOLAR}()
,:mol_u => InternalEnergy{MOLAR}()
,:mass_h => Enthalpy{MASS}()
,:mass_g => Gibbs{MASS}()
,:mass_a => Helmholtz{MASS}()
,:mass_u => InternalEnergy{MASS}()
,:total_h => Enthalpy{TOTAL}()
,:total_g => Gibbs{TOTAL}()
,:total_a => Helmholtz{TOTAL}()
,:total_u => InternalEnergy{TOTAL}()
,:s => Entropy{MOLAR}()
,:mol_s => Entropy{MOLAR}()
,:mass_s => Entropy{MASS}()
,:total_s => Entropy{TOTAL}()
,:p => Pressure()
,:P => Pressure()
,:t => Temperature()
,:T => Temperature()
,:v => VolumeAmount{MOLAR,VOLUME}()
,:mol_v => VolumeAmount{MOLAR,VOLUME}()
,:mass_v => VolumeAmount{MASS,VOLUME}()
,:total_v => VolumeAmount{TOTAL,VOLUME}()
,:V => VolumeAmount{TOTAL,VOLUME}()
,:rho => VolumeAmount{MOLAR,DENSITY}()
,:mol_rho => VolumeAmount{MOLAR,DENSITY}()
,:mass_rho => VolumeAmount{MASS,DENSITY}()
,:ρ => VolumeAmount{MOLAR,DENSITY}()
,:mol_ρ => VolumeAmount{MOLAR,DENSITY}()
,:mass_ρ => VolumeAmount{MASS,DENSITY}()
,:mass => MaterialAmount{MASS}()
,:moles => MaterialAmount{MOLAR}()
,:xn => MaterialCompounds{MOLAR,FRACTION}()
,:xm => MaterialCompounds{MASS,FRACTION}()
,:n => MaterialCompounds{MOLAR,TOTAL_AMOUNT}()
,:m => MaterialCompounds{MASS,TOTAL_AMOUNT}()
,:mw => MolecularWeight()
,:quality => VaporFraction{MASS}() #looking for better name
,:vfrac => VaporFraction{MOLAR}() #looking for better name
,:phase_fracs => PhaseFractions() #looking for better name
,:phase =>PhaseTag()
,:sat => TwoPhaseEquilibrium()
,:single_component => SingleComponent()
,:one_mol => OneMol()
,:options => Options()
,:hum_wetbulb => HumiditySpec{WetBulbTemperature}()
,:hum_ratio => HumiditySpec{HumidityRatio}()
,:hum_molfrac => HumiditySpec{MolarHumidity}()
,:hum_massfrac => HumiditySpec{MassHumidity}()
,:rel_hum => HumiditySpec{RelativeHumidity}()
,:hum_dewpoint => HumiditySpec{HumidityDewPoint}()
)
const SPEC_TO_KW = Dict{Any,Symbol}(
Enthalpy{MOLAR}() => :mol_h
,Gibbs{MOLAR}() => :mol_g
,Helmholtz{MOLAR}() => :mol_a
,InternalEnergy{MOLAR}() => :mol_u
,Enthalpy{MASS}() => :mass_h
,Gibbs{MASS}() => :mass_g
,Helmholtz{MASS}() => :mass_a
,InternalEnergy{MASS}() => :mass_u
,Enthalpy{TOTAL}() => :total_h
,Gibbs{TOTAL}() => :total_g
,Helmholtz{TOTAL}() => :total_a
,InternalEnergy{TOTAL}() => :total_u
,Entropy{MOLAR}() => :mol_s
,Entropy{MASS}() => :mass_s
,Entropy{TOTAL}() => :total_s
,Pressure() => :p
,Temperature() => :t
,VolumeAmount{MOLAR,VOLUME}() => :mol_v
,VolumeAmount{MASS,VOLUME}() => :mass_v
,VolumeAmount{TOTAL,VOLUME}() => :total_v
,VolumeAmount{MOLAR,DENSITY}() => :rho
,VolumeAmount{MOLAR,DENSITY}() => :mol_rho
,VolumeAmount{MASS,DENSITY}() => :mass_rho
,MaterialAmount{MASS}() => :mass
,MaterialAmount{MOLAR}() => :moles
,MaterialCompounds{MOLAR,FRACTION}() => :xn
,MaterialCompounds{MASS,FRACTION}() => :xm
,MaterialCompounds{MOLAR,TOTAL_AMOUNT}() => :n
,MaterialCompounds{MASS,TOTAL_AMOUNT}() => :n
,MolecularWeight() => :mw
,VaporFraction{MASS}() => :quality#looking for better name
,VaporFraction{MOLAR}() => :vfrac#looking for better name
,PhaseFractions() => :phase_fracs #looking for better name
,PhaseTag() => :phase
,TwoPhaseEquilibrium() => :sat
,SingleComponent() => :single_component
,OneMol() => :one_mol
,Options() => :options
,HumiditySpec{WetBulbTemperature}() => :hum_wetbulb
,HumiditySpec{HumidityRatio}() => :hum_ratio
,HumiditySpec{MolarHumidity}() => :hum_molfrac
,HumiditySpec{MassHumidity}() => :hum_massfrac
,HumiditySpec{RelativeHumidity}() => :rel_hum
,HumiditySpec{HumidityDewPoint}() => :hum_dewpoint
)
module QuickStates
using ..Types
const SinglePT = Tuple{Pressure,Temperature,SingleComponent}
const MultiPT = Tuple{Pressure,Temperature,MaterialCompounds}
pt() = (Pressure(),Temperature(),SingleComponent())
ptx() = (Pressure(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
ptn() = (Pressure(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SinglePV = Tuple{Pressure,VolumeAmount,SingleComponent}
const MultiPV = Tuple{Pressure,VolumeAmount,MaterialCompounds}
pv() = (Pressure(),VolumeAmount{MOLAR,VOLUME}(),SingleComponent())
pvx() = (Pressure(),VolumeAmount{MOLAR,VOLUME}(),MaterialCompounds{MOLAR,FRACTION}())
pvn() = (Pressure(),VolumeAmount{MOLAR,VOLUME}(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SingleVT = Tuple{VolumeAmount,Temperature,SingleComponent}
const MultiVT = Tuple{VolumeAmount,Temperature,MaterialCompounds}
vt() = (VolumeAmount{MOLAR,VOLUME}(),Temperature(),SingleComponent())
vtx() = (VolumeAmount{MOLAR,VOLUME}(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
vtn() = (VolumeAmount{MOLAR,VOLUME}(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
ρt() = (VolumeAmount{MOLAR,DENSITY}(),Temperature(),SingleComponent())
ρtx() = (VolumeAmount{MOLAR,DENSITY}(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
ρtn() = (VolumeAmount{MOLAR,VOLUME}(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SinglePS = Tuple{Pressure,Entropy,SingleComponent}
const MultiPS = Tuple{Pressure,Entropy,MaterialCompounds}
st() = (Pressure(),Entropy{MOLAR}(),SingleComponent())
stx() = (Pressure(),Entropy{MOLAR}(),MaterialCompounds{MOLAR,FRACTION}())
stn() = (Pressure(),Entropy{MOLAR}(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SinglePH = Tuple{Pressure,Enthalpy,SingleComponent}
const MultiPH = Tuple{Pressure,Enthalpy,MaterialCompounds}
ph() = (Pressure(),Enthalpy{MOLAR}(),SingleComponent())
phx() = (Pressure(),Enthalpy{MOLAR}(),MaterialCompounds{MOLAR,FRACTION}())
phn() = (Pressure(),Enthalpy{MOLAR}(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SingleSatT = Tuple{TwoPhaseEquilibrium,Temperature,SingleComponent}
const MultiSatT = Tuple{TwoPhaseEquilibrium,Temperature,MaterialCompounds}
sat_t() = (TwoPhaseEquilibrium(),Temperature(),SingleComponent())
sat_tx() = (TwoPhaseEquilibrium(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
sat_tn() = (TwoPhaseEquilibrium(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SingleSatP = Tuple{TwoPhaseEquilibrium,Pressure,SingleComponent}
const MultiSatP = Tuple{TwoPhaseEquilibrium,Pressure,MaterialCompounds}
sat_p() = (TwoPhaseEquilibrium(),Pressure(),SingleComponent())
sat_px() = (TwoPhaseEquilibrium(),Pressure(),MaterialCompounds{MOLAR,FRACTION}())
sat_pn() = (TwoPhaseEquilibrium(),Pressure(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
molar_ϕt() = (VaporFraction{MOLAR}(),Temperature(),SingleComponent())
molar_ϕntx() = (VaporFraction{MOLAR}(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
molar_ϕtn() = (VaporFraction{MOLAR}(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
mass_ϕt() = (VaporFraction{MASS}(),Temperature(),SingleComponent())
mass_ϕntx() = (VaporFraction{MASS}(),Temperature(),MaterialCompounds{MOLAR,FRACTION}())
mass_ϕtn() = (VaporFraction{MASS}(),Temperature(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const SingleΦP = Tuple{VaporFraction,Pressure,SingleComponent}
const MultiΦP = Tuple{VaporFraction,Pressure,MaterialCompounds}
const SingleΦT = Tuple{VaporFraction,Temperature,SingleComponent}
const MultiΦT = Tuple{VaporFraction,Temperature,MaterialCompounds}
const SingleΦnP = Tuple{VaporFraction{MOLAR},Pressure,SingleComponent}
const MultiΦnP = Tuple{VaporFraction{MOLAR},Pressure,MaterialCompounds}
const SingleΦnT = Tuple{VaporFraction{MOLAR},Temperature,SingleComponent}
const MultiΦnT = Tuple{VaporFraction{MOLAR},Temperature,MaterialCompounds}
const SingleΦmP = Tuple{VaporFraction{MASS},Pressure,SingleComponent}
const MultiΦmP = Tuple{VaporFraction{MASS},Pressure,MaterialCompounds}
const SingleΦmT = Tuple{VaporFraction{MASS},Temperature,SingleComponent}
const MultiΦmT = Tuple{VaporFraction{MASS},Temperature,MaterialCompounds}
ϕp() = (VaporQuality(),Pressure(),SingleComponent())
ϕpx() = (VaporQuality(),Pressure(),MaterialCompounds{MOLAR,FRACTION}())
ϕpn() = (VaporQuality(),Pressure(),MaterialCompounds{MOLAR,TOTAL_AMOUNT}())
const MultiT = Union{Tuple{Temperature,AbstractSpec,MaterialCompounds},Tuple{AbstractSpec,Temperature,MaterialCompounds}}
const SingleT = Union{Tuple{Temperature,AbstractSpec,SingleComponent},Tuple{AbstractSpec,Temperature,SingleComponent}}
export SinglePT,MultiPT
export SingleVT,MultiVT
export SinglePS,MultiPS
export SinglePH,MultiPH
export SingleSatT,MultiSatT
export SingleSatP,MultiSatP
export SingleΦT,MultiΦT
export SingleΦP,MultiΦP
export SingleΦmT,MultiΦmT
export SingleΦmP,MultiΦmP
export SingleΦnT,MultiΦnT
export SingleΦnP,MultiΦnP
export SinglePV,MultiPV
export SingleT,MultiT
end
|