licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1115 | using BEAST
using CompScienceMeshes
using Test
@hilbertspace j[1:3]
@hilbertspace k[1:3]
n = BEAST.n
SL = BEAST.diag(BEAST.Maxwell3D.singlelayer(wavenumber=1.0))
EF = BEAST.Maxwell3D.planewave(polarization=point(1,0,0), direction=point(0,0,1), wavenumber=1.0)
ef = (n × EF) × n
bf = SL[j,k]
lf = ef[j]
@test length(bf.terms) == 3
for term in bf.terms
@test term.test_id == term.trial_id
end
mesh1 = Mesh(
[
point(0,0,0),
point(1,0,0),
point(1,1,0),
point(0,1,0),
],
[
index(1,2,3),
index(1,3,4)
]
)
mesh2 = CompScienceMeshes.translate(mesh1, point(0,0,1))
mesh3 = CompScienceMeshes.translate(mesh1, point(0,0,2))
X1 = raviartthomas(mesh1)
X2 = raviartthomas(mesh2)
X3 = raviartthomas(mesh3)
X = X1 × X2 × X3
dbf = BEAST.discretise(bf, j=>X, k=>X)
dlf = BEAST.discretise(lf, j=>X)
space_mappings = (j=>X, k=>X,)
for sm in space_mappings
@show sm
end
M = assemble(dbf)
A = Matrix(M)
@test A[1,2] == A[1,3] == A[2,1] == A[2,3] == A[3,1] == A[3,2] == 0
@test A[1,1] ≈ A[2,2] ≈ A[3,3]
N = assemble(SL, X, X)
B = Matrix(N)
@test A == B | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1404 | using Test
using CompScienceMeshes
using BEAST
using StaticArrays
T = Float64
P = SVector{3,T}
omega = 1.0;
id = Identity()
nc = NCross()
#fn = Pkg.dir("BEAST","test","sphere2.in")
fn = joinpath(dirname(@__FILE__),"assets","sphere316.in")
m = readmesh(fn)
rt = raviartthomas(m)
bc = buffachristiansen(m)
G1 = zeros(ComplexF64, numfunctions(rt), numfunctions(rt))
BEAST.assemble_local_matched!(id, rt, rt, (v,m,n)->(G1[m,n]+=v))
G2 = zeros(ComplexF64, numfunctions(rt), numfunctions(rt))
BEAST.assemble_local_mixed!(id, rt, rt, (v,m,n)->(G2[m,n]+=v))
# G1 = BEAST.assemble_local_matched(id, rt, rt)
# G2 = BEAST.assemble_local_mixed(id, rt, rt)
@test norm(G1-G2, Inf) ≈ 0 atol = sqrt(eps())
@test norm(G1-G1', Inf) ≈ 0 atol = sqrt(eps())
@test norm(G2-G2', Inf) ≈ 0 atol = sqrt(eps())
G = zeros(ComplexF64, numfunctions(rt), numfunctions(bc))
BEAST.assemble_local_mixed!(nc, rt, bc, (v,m,n)->(G[m,n]+=v))
@test cond(G) ≈ 2.919026332637947
G = zeros(ComplexF64, numfunctions(rt), numfunctions(rt))
BEAST.assemble_local_mixed!(nc, rt, rt, (v,m,n)->(G[m,n]+=v))
@test norm(G+G', Inf) ≈ 0 atol = sqrt(eps())
v = [
point(0.0, 0.0, 0.0),
point(1.0, 0.0, 0.0),
point(1.0, 1.0, 0.0),
point(0.0, 1.0, 0.0),]
f = [
index(1,2,3),
index(1,3,4)
]
Γ = Mesh(v,f)
X = raviartthomas(Γ)
I = Identity()
G = assemble(I,X,X)
@test size(G) == (1,1)
@test norm(G[1,1] - 1/3) < sqrt(eps())
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 9930 | import BEAST; BE = BEAST;
using CompScienceMeshes
using StaticArrays
using Test
T = Float64
P = SVector{3,T}
tol = eps(T)*10^3
struct IntegrationDomain{T,P}
signed_height::T
dist_to_plane::T
center::P
plane_center::P
unit_normal::P
segments::Vector{SVector{2,P}}
end
function IntegrationDomain(p1, p2, p3, center)
t1 = p2 - p1
t2 = p3 - p1
unit_normal = t1 × t2
unit_normal /= norm(unit_normal)
signed_height = dot(center-p1, unit_normal)
dist_to_plane = abs(signed_height)
plane_center = center - signed_height * unit_normal
s1 = SVector((p1, p2,))
s2 = SVector((p2, p3,))
s3 = SVector((p3, p1,))
segments = [s1, s2, s3]
#T = eltype(p1)
IntegrationDomain(
signed_height,
dist_to_plane,
center,
plane_center,
unit_normal,
segments)
end
wiltonints(a,b,c,center) = wiltonints(IntegrationDomain(a,b,c,center))
# type WiltonIntsWS{T}
# segments_through_c::Vector{T}
# end
# type WiltonIntsRV{T,N,M}
# scalars::SVector{N,T}
# gradients::SVector{M,T}
# end
# This function implements the Wilton algorithm for Integration of
# linear potentials on triangular domains
function wiltonints(domain::IntegrationDomain{T,Q}, tol=eps(T)*10^3) where {T,Q}
dim = 3
d = domain.signed_height
D = domain.dist_to_plane
c = domain.plane_center
n = domain.unit_normal
num_segments = length(domain.segments)
# outside the domain of integration, or whether it is on the boundary.
# keep track of whether the projected singularity is inside or
# If it is on the boundary, make a note of on which part of the boundary
# it is located.
c_inside = true
num_segments_through_c = 0
segments_through_c = zeros(Int, num_segments)
s = zeros(T,6) # TODO alloc
v = zeros(Q, 6) # TODO alloc
for i in 1 : num_segments
a = domain.segments[i][1]
b = domain.segments[i][2]
ab = b - a # segment tangent
l = norm(ab) # segment length
t = ab / l # unit tangent
m = cross(t,n) # unit binormal
ca = a - c
cb = b - c
# coordinates of a and b w.r.t. the projection
# of c on the line [a,b]
xa = dot(ca,t)
xb = dot(cb,t)
# signed and absolute distance of plane center to line
p = dot(ca,m)
P = abs(p)
if p < 0
c_inside = false
end
w2 = p^2 + d^2
ra = sqrt(xa^2 + w2)
rb = sqrt(xb^2 + w2)
w = sqrt(w2)
# if the plane center is NOT on the line through this segment
# use the general formula; no singularities are encountered in
# the computation
if P > tol
lg = log((xb+rb) / (xa+ra))
at = atan(d*xb/(p*rb)) - atan(d*xa/(p*ra))
s[1] += -at
s[2] += p*lg + d*at
s[3] += 1/2 * p * (xb-xa)
pt1 = 1/6*p*(xb*rb-xa*ra)
pt2 = (1/2*d*d+1/6*p*p)*p*lg
pt3 = 1/3*d*d*d*at
s[4] += pt1 + pt2 + pt3
pt1 = 1/2*xb*p*(1/6*xb*xb+1/2*p*p+d*d)
pt2 = 1/2*xa*p*(1/6*xa*xa+1/2*p*p+d*d)
s[5] += pt1 - pt2
pt1b = 1/20*p*xb*rb*(xb*xb+1/2*(9*d*d+5*p*p))
pt1a = 1/20*p*xa*ra*(xa*xa+1/2*(9*d*d+5*p*p))
pt2 = 1/40*p*(15*d*d*d*d+10*d*d*p*p+3*p*p*p*p)*lg + 0.2*d*d*d*d*d*at;
s[6] += (pt1b - pt1a) + pt2
v[1] += -lg * m
v[2] += 0.5 *((xb*rb-xa*ra) + w*w*lg) * m
pt1b = 0.5 * xb * (1/3*xb*xb + p*p)
pt1a = 0.5 * xa * (1/3*xa*xa + p*p)
v[3] += (pt1b - pt1a) * m
pt1 = 1/12*(xb*rb*rb*rb-xa*ra*ra*ra) + 1/8*w*w*(xb*rb-xa*ra)
pt2 = 1/8*w*w*w*w*lg
v[4] += (pt1 + pt2) * m
pt1b = 1/20*xb*xb*xb*xb*xb + 1/6*p*p*xb*xb*xb + 0.25*p*p*p*p*xb + 0.5*d*d*(1/3*xb*xb*xb + p*p*xb)
pt1a = 1/20*xa*xa*xa*xa*xa + 1/6*p*p*xa*xa*xa + 0.25*p*p*p*p*xa + 0.5*d*d*(1/3*xa*xa*xa + p*p*xa)
v[5] += (pt1b - pt1a) * m
else # plane center lies on the line ab
if xa*xb < tol^2
# projection c on ab lies in between a and b
num_segments_through_c += 1
segments_through_c[num_segments_through_c] = i
end
if D > tol
# singularity not in the plane of the triangle and thus not on ab
lg = log((xb+rb)/(xa+ra))
v[1] += -lg * m
pt1 = 0.5*(xb*rb-xa*ra)
pt2 = 0.5*w*w*lg
v[2] += (pt1 + pt2) * m
pt1b = 1/6*xb*xb*xb
pt1a = 1/6*xa*xa*xa
v[3] += (pt1b - pt1a) * m
pt1 = 1/12*(xb*rb*rb*rb-xa*ra*ra*ra) + 1/8*w*w*(xb*rb-xa*ra)
pt2 = 1/8*w*w*w*w*lg
v[4] += (pt1 + pt2) * m
pt1b = 1/20*xb*xb*xb*xb*xb + 1/6*p*p*xb*xb*xb + 0.25*p*p*p*p*xb + 0.5*d*d*(1/3*xb*xb*xb + p*p*xb)
pt1a = 1/20*xa*xa*xa*xa*xa + 1/6*p*p*xa*xa*xa + 0.25*p*p*p*p*xa + 0.5*d*d*(1/3*xa*xa*xa + p*p*xa)
v[5] += (pt1b - pt1a) * m
else # D <= tol
# the projected singularity lies on ab. It is assumed the singularity
# itself does not lie on [a,b] however, since this would lead to some
# of the integrals to become infinite.
lg = (xb > 0) ? log(xb/xa) : log(xa/xb)
v[1] += -lg * m
v[2] += 0.5*(xb*rb-xa*ra) * m
pt1b = 1/6*xb*xb*xb
pt1a = 1/6*xa*xa*xa
v[3] += (pt1b - pt1a) * m
pt1 = 1/12*(xb*rb*rb*rb-xa*ra*ra*ra) + 1/8*w*w*(xb*rb-xa*ra)
pt2 = 1/8*w*w*w*w*lg
v[4] += (pt1 + pt2) * m
pt1b = 1/20*xb*xb*xb*xb*xb + 1/6*p*p*xb*xb*xb + 0.25*p*p*p*p*xb + 0.5*d*d*(1/3*xb*xb*xb + p*p*xb)
pt1a = 1/20*xa*xa*xa*xa*xa + 1/6*p*p*xa*xa*xa + 0.25*p*p*p*p*xa + 0.5*d*d*(1/3*xa*xa*xa + p*p*xa)
v[5] += (pt1b - pt1a) * m
end # if D < tol
end # if p < tol
end # next segment
# contributions from intersection of epsilon cirlce around c with triangle
sgn = D < tol ? zero(d) : sign(d)
alpha = zero(d)
if num_segments_through_c == 0 && c_inside
alpha = 2pi
elseif num_segments_through_c == 1
alpha = pi
elseif num_segments_through_c == 2
i = segments_through_c[1]
t1 = domain.segments[i][2] - domain.segments[i][1]
i = segments_through_c[2]
t2 = domain.segments[i][2] - domain.segments[i][1]
cosalpha = dot(-t1,t2)/(norm(t1)*norm(t2))
alpha = acos(clamp(cosalpha,-1,+1))
elseif num_segments_through_c > 2
error("num_intersections must be either 0, 1, or 2.")
end
s[1] += alpha * sgn
s[2] += -alpha * D
s[4] += -1/3 * alpha * D*D*D
s[6] += -1/5 * alpha * D*D*D*D*D
# build gradients
g = Vector{Q}(undef,4)
g[1] = -1( v[1] - s[1] * n )
g[2] = +1( v[2] - d*s[2]*n )
g[3] = +2( v[3] - d*s[3]*n )
g[4] = +3( v[4] - d*s[4]*n )
return s, v, g
end
# s1 = int d/R^3
# s2 = int 1/R
# s3 = int 1
# s4 = int R
# s5 = int R^2
# s6 = int R^3
# v1 = int (rho'-rho)/R^3
# v2 = int (rho'-rho)/R
# v3 = int (rho'-rho)
# v4 = int (rho'-rho)*R
# v5 = int (rho'-rho)*R
# g1 = int grad' (1/R)
# g2 = int grad' R
# g3 = int grad' R^2
# g4 = int grad' R^3
function withquadrules(triangle, r, n)
u, w = BE.trgauss(n)
n = (triangle[1] - triangle[3]) × (triangle[2] - triangle[3])
n /= norm(n)
d = (r - triangle[1]) ⋅ n
ρ = r - d*n
scalar = zeros(T,6)
vector = zeros(P,6)
gradgr = zeros(P,4)
m = simplex(triangle[1], triangle[2], triangle[3])
for i in 1 : length(w)
q = neighborhood(m, u[:,i])
s = cartesian(q)
dq = w[i] * jacobian(q)
R = norm(s - r)
scalar[1] += d / R^3 * dq
scalar[2] += 1 / R * dq
scalar[3] += 1 * dq
scalar[4] += R * dq
scalar[5] += R^2 * dq
scalar[6] += R^3 * dq
vector[1] += (s - ρ) / R^3 * dq
vector[2] += (s - ρ) / R * dq
vector[3] += (s - ρ) * dq
vector[4] += (s - ρ) * R * dq
vector[5] += (s - ρ) * R^2 * dq
end
gradgr[1] = -1( vector[1] - scalar[1] * n )
gradgr[2] = +1( vector[2] - d*scalar[2]*n )
gradgr[3] = +2( vector[3] - d*scalar[3]*n )
gradgr[4] = +3( vector[4] - d*scalar[4]*n )
return scalar, vector, gradgr
end
tr = [
point(0.0, 0.0, 0.0),
point(2.0, 0.0, 0.0),
point(0.0, 3.0, 0.0)]
pts = [
(tr[1]+2*tr[2]-1*tr[3]),
(tr[1]+tr[2])/2 + point(0.0, 0.0, 0.3),
point(3.0, 0.0, 0.0),
(tr[1]+tr[2]+tr[3])/3 + point(0.0, 0.0, 0.3),
tr[2] + point(0.0, 0.0, 0.3),
(tr[1]+tr[2]+tr[3])/3 + point(0.0, 0.0, 100.0)
]
for _p in pts
s1, v1, g1 = wiltonints(tr[1],tr[2],tr[3],_p)
s2, v2, g2 = withquadrules(tr,_p,13)
for i in length(s1)
@test norm(s1[i]-s2[i]) < 1.0e-5
end
for i in length(v1)
@test norm(v1[i]-v2[i]) < 1.0e-5
end
for i in 1:length(g1)
for _j in 1:3
@test norm(g1[i][_j]-g2[i][_j]) < 1.0e-5
end
end
end
Γ = readmesh(joinpath(dirname(@__FILE__),"assets","sphere2.in"))
nc = numcells(Γ)
t = chart(Γ, first(Γ))
s = chart(Γ, nc)
X = BEAST.raviartthomas(Γ)
x = BEAST.refspace(X)
κ = 1.0
op = BEAST.MWSingleLayer3D(κ)
n = BE.numfunctions(x)
z1 = zeros(ComplexF64, n, n)
z2 = zeros(ComplexF64, n, n)
BE = BEAST
tqd = BE.quadpoints(x, [t], (12,))
bqd = BE.quadpoints(x, [s], (13,))
DQ_strategy = BE.DoubleQuadRule(tqd[1,1], bqd[1,1])
BEAST.momintegrals!(op, x, x, t, s, z1, DQ_strategy)
SE_strategy = BE.WiltonSERule(
tqd[1,1],
BE.DoubleQuadRule(
tqd[1,1],
bqd[1,1],
),
)
BEAST.momintegrals!(op, x, x, t, s, z2, SE_strategy)
@test norm(z1-z2) < 1.0e-7
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 777 | using BEAST
using CompScienceMeshes
Γ = readmesh(Pkg.dir("BEAST", "test","assets","flatplate.in"))
#Γ = readmesh(Pkg.dir("BEAST", "test","assets","smallflatplate.in"))
RT = raviartthomas(Γ)
X = RT
Y = RT
κ = 1.0
t = BEAST.MWDoubleLayer3D(κ*im)
BEAST.quadrule(op::BEAST.MaxwellOperator3D, g::BEAST.RTRefSpace, f::BEAST.RTRefSpace, i, τ, j, σ, qd) = BEAST.q(op, g, f, i, τ, j, σ, qd)
Zss = assemble(t,X,Y)
BEAST.quadrule(op::BEAST.MaxwellOperator3D, g::BEAST.RTRefSpace, f::BEAST.RTRefSpace, i, τ, j, σ, qd) = BEAST.qrdf(op, g, f, i, τ, j, σ, qd)
Zqrdf = assemble(t,X,Y)
BEAST.quadrule(op::BEAST.MaxwellOperator3D, g::BEAST.RTRefSpace, f::BEAST.RTRefSpace, i, τ, j, σ, qd) = BEAST.qrib(op, g, f, i, τ, j, σ, qd)
Zbogaert = assemble(t,X,Y)
println(abs(Zss)./abs(Zbogaert))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 549 | using BEAST
using CompScienceMeshes
Γ = readmesh(Pkg.dir("BEAST", "test", "assets","flatplate.in"))
RT = raviartthomas(Γ)
X = RT
Y = RT
κ = 1.0
t = Maxwell3D.singlelayer(gamma=im*κ)
BEAST.quadrule(op::BEAST.MaxwellOperator3D, g::BEAST.RTRefSpace, f::BEAST.RTRefSpace, i, τ, j, σ, qd) = BEAST.qrib(op, g, f, i, τ, j, σ, qd)
Zbogaert = assemble(t,X,Y)
BEAST.quadrule(op::BEAST.MaxwellOperator3D, g::BEAST.RTRefSpace, f::BEAST.RTRefSpace, i, τ, j, σ, qd) = BEAST.q(op, g, f, i, τ, j, σ, qd)
Zss = assemble(t,X,Y)
println(abs(Zbogaert)./abs(Zss))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1437 | using LinearAlgebra
using Test
using CompScienceMeshes
using BEAST
import CompScienceMeshes.SComplex2D
fn = joinpath(@__DIR__, "assets", "thick_cladding.msh")
G01 = SComplex2D(CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma01"))
G02 = SComplex2D(CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma02"))
G12 = SComplex2D(CompScienceMeshes.read_gmsh_mesh(fn, physical="Gamma12"))
G = SComplex2D(CompScienceMeshes.read_gmsh_mesh(fn))
b = boundary(G02)
G = weld(G01,G02,seam=b)
@test numcells(G01) + numcells(G02) == numcells(G)
@test numcells(skeleton(G01,1)) + numcells(skeleton(G02,1)) == numcells(skeleton(G,1)) + numcells(b)
G = weld(G,G12,seam=b)
@test numcells(G01) + numcells(G02) + numcells(G12) == numcells(G)
@test numcells(skeleton(G01,1)) + numcells(skeleton(G02,1)) + numcells(skeleton(G12,1)) == numcells(skeleton(G,1)) + 2*numcells(b)
G1 = weld(-G01, -G12, seam=b)
@test CompScienceMeshes.isoriented(G1)
G2 = weld(-G02, G12, seam=b)
@test CompScienceMeshes.isoriented(G2)
isclosed(m) = (length(boundary(m)) == 0)
@test isclosed(G1)
@test isclosed(G2)
E = skeleton(G,1)
E1 = skeleton(G1,1)
A1 = CompScienceMeshes.embedding(E1,E)
nd = BEAST.nedelec(G,E)
@test numfunctions(nd) == numcells(E)
nd1 = BEAST.nedelec(G1,E1)
@test numfunctions(nd1) == numcells(E1)
Z_direct = assemble(BEAST.Identity(), nd1, nd)
Z_expand = assemble(BEAST.Identity(), nd1, nd1) * A1
@test norm(Z_direct - Z_expand, Inf) ≤ √(eps(1.0))
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 317 | using BEAST
using Test
Id = ones(1,1)
Δt = 0.05
Z = zeros(1,1,2)
Z[:,:,1] = Id
Z[:,:,2] = Δt - Id
#Z = [Id; (Δt-Id)]
Nt = 100
B = zeros(1,Nt)
B[:,1] = ones(1)
Z0 = Z[:,:,1]
W0 = inv(Z0)
x = BEAST.mot(W0,Z,B,Nt)
n = 20
@show x[n]
@show exp(-n*Δt)
@show norm(x[n]-exp(-n*Δt))
@test norm(x[n]-exp(-n*Δt)) < 1.0e-2
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1377 | using CompScienceMeshes
using BEAST
using Test
############################################################################################
#
# Test the sign of the double layer potential
#
############################################################################################
γ = 0.0
K = MWDoubleLayer3D(γ)
τ = Mesh(
[
point(-4,0,0),
point(-6,0,0),
point(-5,-1,0)
],
[
index(1,2,3)])
σ = Mesh(
[
point(4,0,0),
point(6,0,0),
point(5,0,-1)
],
[
index(1,2,3)
]
)
@test numcells(τ) == 1
@test numcells(σ) == 1
T = raviartthomas(τ, boundary(τ))
S = raviartthomas(σ, boundary(σ))
@test numfunctions(T) == 3
@test numfunctions(S) == 3
t = chart(τ, first(cells(τ)))
s = chart(σ, first(cells(σ)))
p = neighborhood(t, [1,1]/2)
q = neighborhood(s, [1,1]/2)
R = norm(cartesian(p)-cartesian(q))
rt = refspace(T)
f = (refspace(T))(p)[3][1]
g = (refspace(S))(q)[3][1]
@test dot(f, point(0,1,0)) > 0
@test dot(g, point(0,0,1)) > 0
@show 1/R^2
z = assemble(K, T, S)
qd = quaddata(K, rt, rt, elements(τ), elements(σ))
zlocal = zeros(promote_type(scalartype(K), scalartype(S), scalartype(T)), 3, 3)
strat = BEAST.quadrule(K, rt, rt, 1, t, 1, s, qd)
strat = BEAST.DoubleQuadRule(qd.tpoints[1,1], qd.bpoints[1,1])
BEAST.momintegrals!(K, rt, rt, t, s, zlocal, strat)
z = zlocal[3,3]
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 482 | using BEAST
using CompScienceMeshes
using Test
x = Vec(1.0,0.0,0.0)
y = Vec(0.0,1.0,0.0)
z = Vec(0.0,0.0,1.0)
g = BEAST.creategaussian(1.0, 3.0)
pw = BEAST.planewave(x, z, g)
t = linspace(0.0, 6.0, 100);
y = [pw([0.0,0.0,0.0],x)[1] for x in t];
Δx = 1.0
Γ = meshrectangle(10.0, Δx, Δx)
X = raviartthomas(Γ)
Δt = 1.0
Nt = 20
U = timebasisc0d1(Float64, Δt, Nt)
b = zeros(Float64, numfunctions(X), numfunctions(U))
store(v, m, k) = (b[m,k] += v)
BEAST.assemble!(pw, X, U, store)
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | code | 1391 | using BEAST
using CompScienceMeshes
using WiltonInts84
using Test
p1 = point(0,0,0)
p2 = point(1,0,0)
p3 = point(0,1,0)
q1 = point(2,2,0)
q2 = point(2,1,0)
q3 = point(1,2,0)
τ = [p1,p2,p3]
σ = [q1,q2,q3]
m, M = BEAST.minmaxdist(τ, σ)
@show m, sqrt(2.0)
@show M, sqrt(8.0)
@test m ≈ sqrt(2.0)
@test M ≈ sqrt(8.0)
ΔR = sqrt(2)/2
r = BEAST.rings(τ,σ,ΔR)
@show r
cm = point(0.5,0.5,0.0)
cM = point(0.0,0.0,0.0)
S,V,G = WiltonInts84.wiltonints(q1,q2,q3,cm,(r[1]-2)*ΔR,(r[1]-1)*ΔR,Val{0})
@show S[3]
S,V,G = WiltonInts84.wiltonints(q1,q2,q3,cM,(r[end]-1)*ΔR,(r[end])*ΔR,Val{0})
@show S[3]
h = 0.05
Γ = meshrectangle(10.0, h, h, 3)
X = raviartthomas(Γ)
timestep = 1.0
numsteps = 10
S = timebasisc0d1(timestep, numsteps)
S = BEAST.timebasisspline2(timestep, numsteps)
c = 1.0
Ts = MWSingleLayerTDIO(c,1.0,0.0,0,0)
Th = MWSingleLayerTDIO(c,0.0,1.0,0,0)
Zs = BEAST.assemble(Ts,X,X,S)
Zh = BEAST.assemble(Th,X,X,S)
## Test the allcatestorage routine and in particular its type stability
h = 0.05
Γ = meshrectangle(10.0, h, h, 3)
X = raviartthomas(Γ)
timestep = 1.0
numsteps = 10
S = timebasisc0d1(timestep, numsteps)
S = BEAST.timebasisspline2(timestep, numsteps)
c = 1.0
Ts = MWSingleLayerTDIO(c,1.0,0.0,0,0)
Th = MWSingleLayerTDIO(c,0.0,1.0,0,0)
U = timebasiscxd0(Δt, Nt)
T = timebasisc0d1(Δt, Nt)
W = X ⊗ U
V = X ⊗ T
@code_warntype BEAST.allocatestorage(Ts,W,V,Val{:densestorage})
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 2737 | # BEAST
Boundary Element Analysis and Simulation Toolkit
[](https://github.com/krcools/BEAST.jl/actions/workflows/CI.yml)
[](http://codecov.io/github/krcools/BEAST.jl?branch=master)
[](https://krcools.github.io/BEAST.jl/latest/)
[](https://zenodo.org/badge/latestdoi/87720391)
## Introduction
This package contains common basis functions and assembly routines for the implementation of
boundary element methods. Examples are included for the 2D and 3D Helmholtz equations and for
the 3D Maxwell equations.
Support for the space-time Galerkin based solution of time domain integral equations is in
place for the 3D Helmholtz and Maxwell equations.
## Installation
Installing `BEAST` is done by entering the package manager (enter `]` at the julia REPL) and issuing:
```
pkg>add BEAST
```
To run the examples, the following steps are required in addition:
```
pkg> add CompScienceMeshes # For the creation of scatterer geometries
pkg> add Plots # For visualising the results
pkg> add GR # Other Plots compatible back-ends can be chosen
```
Examples can be run by:
```
julia>using BEAST
julia>d = dirname(pathof(BEAST))
julia>include(joinpath(d,"../examples/efie.jl"))
```
## Hello World
To solve scattering of a time harmonic electromagnetic plane wave by a perfectly conducting
sphere:
```julia
using CompScienceMeshes, BEAST
Γ = readmesh(joinpath(dirname(pathof(BEAST)),"../examples/sphere2.in"))
X = raviartthomas(Γ)
t = Maxwell3D.singlelayer(wavenumber=1.0)
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=1.0)
e = (n × E) × n
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
u = gmres(efie)
```

## Features
- General framework allowing to easily add support for more kernels, finite element spaces, and excitations.
- Assembly routines that take in symbolic representations of the defining bilinear form. Support for block systems and finite element spaces defined in terms of direct products or tensor products of atomic spaces.
- LU and iterative solution of the resulting system.
- Computation of secondary quantities of interest such as the near field and the limiting far field.
- Support for space-time Galerkin and convolution quadrature approaches to the solution of time domain boundary integral equations.
- Implementation of Lagrange zeroth and first order space, Raviart-Thomas, Brezzi-Douglas-Marini, and Buffa-Christianssen vector elemenents.
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 12852 | # The Matrix Assemble Routine
A lot of the design of this package derives from the need to express boundary element and finite element matrix assembly in a concise but general manner that is compatible with a wide range of linear and bilinear forms as encountered in the solution of variational problems.
In this section the matrix assembly routine at the center of this package will be discussed. As a case study we will go over the steps required to extend support for new kernels and new finite element spaces.
The matrix assemble routine is surprisingly short:
```julia
function assemblechunk!(biop::IntegralOperator, tfs::Space, bfs::Space, store)
test_elements, tad = assemblydata(tfs)
bsis_elements, bad = assemblydata(bfs)
tshapes = refspace(tfs); num_tshapes = numfunctions(tshapes)
bshapes = refspace(bfs); num_bshapes = numfunctions(bshapes)
T = promote_type(scalartype(biop), scalartype(tfs), scalartype(bfs))
zlocal = zeros(T, num_tshapes, num_bshapes)
qd = quaddata(biop, tshapes, bshapes, test_elements, bsis_elements)
for (p,tcell) in enumerate(test_elements), (q,bcell) in enumerate(bsis_elements)
fill!(zlocal, 0)
strat = quadrule(biop, tshapes, bshapes, p, tcell, q, bcell, qd)
momintegrals!(biop, tshapes, bshapes, tcell, bcell, zlocal, strat)
for j in 1 : num_bshapes, i in 1 : num_tshapes
z = zlocal[i,j]
for (m,a) in tad[p,i], (n,b) in bad[q,j]
store(a*z*b, m, n)
end end end end
```
Support for direct product spaces, linear combinations of kernels, non-standard storage of matrix elements, and parallel execution is provided by layers on top of this assembly routine. In this section we will focus on discussing the design and implementation of this inner building block that lies at the basis of more general functionality.
Finite element spaces are usually stored as a collection of functions that in turn each comprise contributions from a limited number of geometric elements that make up the support of the function. In FEM and BEM matrix assembly, however, we need the *tranposed* information: given a geometric cell, and a local shape function, we need the ability to efficiently retrieve the list of basis functions whose definition contains the given local shape function on the given cell and the weight (aka coefficient) by which it contributes. The data structure that contains this information is referred to as the assembly data `ad`. In particular, `ad[e,s]`, where `e` is the index of a geometric cell and `s` is the index of a local shape function, returns an iterable collection of pairs `(m,w)` where `m` is an index into the iterable collection of basis functions making up the finite element space and `w` is a weight, such that shape function `s` on geometric element `e` contributes with weight `w` to basis function `n`.
```julia
test_elements, tad = assemblydata(tfs)
bsis_elements, bad = assemblydata(bfs)
```
One final note on the `assemblydata` function: as you can see from the above snippet, the function returns, in addition to the actual assembly data, an iterable collection of geometric elements. This collection is a subset of the collection of elements making up the geometry on which the finite element space is defined. The elements returned are those that actually appear in the domain of one or more of the functions that span the finite element space. The double for loop that iterates over pairs of trial and testing functions will only visit those used elements. Elements that are part of the geometry but do not appear as part of the support of a function are skipped. This behaviour is required to guarantee scalability when using multiple threads in assembling the matrix: each thread is assigned a subset of the basis functions; visiting unused elements in all threads is harmful for the overall efficiency.
With this assembly data in hand, matrix assembly can be done by iterating over geometric cells, rather than over basis functions. Doing this avoids visiting a given geometric cell more than once. When computing matrices resulting from discretisation with e.g. Raviart-Thomas elements, this can speed up assembly time with a factor 9.
The problem of matrix assembly is now reduced to the computation of interactions between local shape functions defined on all possible pairs of geometric cells. The space of local shape functions can be retrieved by calling
```julia
tshapes = refspace(tfs); num_tshapes = numfunctions(tshapes)
bshapes = refspace(bfs); num_bshapes = numfunctions(bshapes)
```
Here, `num_tshapes` and `num_bshapes` are the number of local shape functions. For example, when using Raviart-Thomas elements, the number of local shape functions equals three (one for every edge of the reference triangle).
Based on this dimension, and based on the types used to represent numbers in the fields over which the spaces and the kernel are defined, the storage for local shape function interaction is pre-allocated:
```julia
T = promote_type(scalartype(biop), scalartype(tfs), scalartype(bfs))
zlocal = zeros(T, num_tshapes, num_bshapes)
```
Note that the computation of the storage type ensures that high precision or complex data types are only used when required. At all times the minimal storage type is selected. Not only does this keep memory use down, it also results in faster linear algebra computations such as matrix-vector multiplication.
Before entering the double for loop that is responsible for the enumeration of all pairs of geometric cells (a trial cell pairs with a test cell), the implementer is given the opportunity to precompute data for use in the integration kernels. For example when using numerical quadrature rules to compute the double integral in the expression of the matrix entries, it is likely that a set of quadrature points for any given trial cells will be reused in interactions with a large number of test cells. To avoid computing these points and weights over and over, the client developer is given the opportunity to compute and store them by providing an appropriate method for `quaddata` . If memory use is more important the runtime, the client programmer is perfectly allowed to compute points and weights on the fly without storing them.
```julia
fill!(zlocal, 0)
strat = quadrule(biop, tshapes, bshapes, p, tcell, q, bcell, qd)
momintegrals!(biop, tshapes, bshapes, tcell, bcell, zlocal, strat)
```
For a given pair `(tcell,bcell)` of test cell and trial cell (with respective indices `p` and `q` in collections `test_elements` and `bsis_elements`), all possible interactions between local shape functions are computed. After resetting the buffer used to store these interactions, the quadrature strategy is determined. The quadrature strategy in general could depend on:
- the kernel `biop` defining the integral operator,
- the local test and trial shape functions `tshapes` and `bshapes` (functions of high polynomial degree and functions that are highly oscillatory typically require bespoke integration methods),
- and the geometric test and trial cells `tcell` and `bcell` (cells that touch or are near to each other lead to quickly varying or even singular integrands requiring dedicated integration rules).
The method returns an object `strat` that: (i) describes (by its type and its data fields) the integration strategy that is appropriate to compute the current set of local interactions, (ii) contains all data precomputed and stored in `qd` that is relevant to this particular integration (for example a set of quadrature points and weights). This explains why the indices `p` and `q` where passed too `quadrule`: they allow for the quick retrieval of relevant pre-stored data from `qd`.
The routing that is responsible for the actual computation of the interactions between the local shape functions takes the quadrule object `strat` as one of its arguments. The idea is that `momintegrals!` has many methods, not only for different types of kernel and shape functions, but also for different types of `strat`. For example, there are implementations of `momintegrals!` for the computation of the Maxwellian single layer operator w.r.t. spaces of Raviart-Thomas elements that employ double numerical quadrature, singularity extraction, and even more advanced integration routines.
*Note*: the type of `strat` depends on the orientation of the two interacting geometric cells. This information is only available at runtime. In other words, there will be a slight type instability at this point in the code. This is by design however, and not different from the use of virtual functions in an c++ implementation. Numerical experiments show that this form of runtime polymorphism results in negligible runtime overhead.
When all possible interactions between local shape functions have been computed, they need to be stored in the global system matrix. This is done in the matrix assembly loop:
```julia
for j in 1 : num_bshapes
for i in 1 : num_tshapes
z = zlocal[i,j]
for (m,a) in tad[p,i]
for (n,b) in bad[q,j]
store(a*z*b, m, n)
end
end
end
end
```
For both the test and trial local shape functions, the global indices at which they appear in the finite element space (and the corresponding weights) are retrieved from the assembly data objects. The contributing value `v = a*z*b` is constructed and its storage is delegated to the `store` method, which we received as one of the arguments passed to `assemble_chunk!`. In the simplest case, `assemble_chunk!` can be used like this:
```julia
Z = zeros(ComplexF64, numfunctions(tfs), numfunctions(bfs))
store(v, m, n) = (Z[m,n] += v)
assemble_chunk!(kernel, tfs, bfs, store)
```
In other words `store` will simply add the computed value to the specified entry in the global system matrix. Allowing the caller to specify `store` as an argument allows for more flexibility than hardcoding this behaviour in the assembly routine. Indeed, when computing blocks of a larger system, or when e.g. the transposed or a multiple of a given operator is desired, a fairly simple redefinition of `store` can provide this functionality. This is also the reason why `assemble_chunk!` ends in an exclamation mark: even though strictly speaking none of the arguments are modified, the function clearly has an effect on variables defined outside of its scope!
## Case Study: Implementation of the Nitsche Operator Assembly
In the Nitsche method for the Maxwell system, penalty terms are added to the classic discretisation of the EFIE. When discretized using a non-conforming finite elements space (typically because the underlying geometric mesh is not conforming), the penalty term will force the solution to be divergence conforming in some weak sense. The penalty term derives from the following bilinear form:
```math
p(v,u) = \int_{\gamma} v(x) \int_{Γ} \frac{e^{-ik|x-y|}}{4π|x-y|} u(y) dy dx
```
Note that ``u(x)`` is supported by a 2D surface ``Γ`` whereas ``v(y)`` is supported by a 1D curve ``γ``. The complete implementation of this operator could look like
```julia
mutable struct SingleLayerTrace{T} <: MaxwellOperator3D
gamma::T
end
function quaddata(operator::SingleLayerTrace,
localtestbasis::LagrangeRefSpace, localtrialbasis::LagrangeRefSpace,
testelements, trialelements)
tqd = quadpoints(localtestbasis, testelements, (10,))
bqd = quadpoints(localtrialbasis, trialelements, (8,))
return (tpoints=tqd, bpoints=bqd)
end
function quadrule(op::SingleLayerTrace, g::LagrangeRefSpace, f::LagrangeRefSpace, i, τ, j, σ, qd)
DoubleQuadRule(
qd.tpoints[1,i],
qd.bpoints[1,j]
)
end
integrand(op::SingleLayerTrace, kernel, g, τ, f, σ) = f[1]*g[1]*kernel.green
```
Every kernel corresponds with a type. Kernels can potentially depend on a set of parameters; these appear as fields in the type. Here our Nitsche kernel depends on the wavenumber. In quaddata we precompute quadrature points for all geometric cells in the supports of test and trial elements. This is fairly sloppy: only one rule for test and trial integration is considered. A high accuracy implementation would typically compute points for both low quality and high quality quadrature rules.
Also `quadrule` is sloppy: we always select a `DoubleQuadRule` to perform the computation of interactions between local shape functions. No singularity extraction or other advanced technique is considered for nearby interactions. Clearly amateurs at work here!
`BEAST` provides a default implementation of an integration routine using double numerical quadrature. All that is required to tap into that implementation is a method overloading `integrand`. From the above formula it is clear what this method should look like.
That's it!
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 5774 | ```@meta
CurrentModule = BEAST
```
# BEAST.jl documentation
BEAST provides a number of types modelling concepts and a number of algorithms for the efficient and simple implementation of boundary and finite element solvers. It provides full implementations of these concepts for the LU based solution of boundary integral equations for the Maxwell and Helmholtz systems.
Because Julia only compiles code at execution time, users of this library can hook into the code provided in this package at any level. In the extreme case it suffices to provide overwrites of the `assemble` functions. In that case, only the LU solution will be performed by the code here.
At the other end it suffices that users only supply integration kernels that act on the element-element interaction level. This package will manage all required steps for matrix assembly.
For the Helmholtz 2D and Maxwell 3D systems, complete implementations are supplied. These models will be discussed in detail to give a more concrete idea of the APIs provides and how to extend them.
Central to the solution of boundary integral equations is the assembly of the system matrix. The system matrix is fully determined by specifying a kernel G, a set of trial functions, and a set of test functions.
## Basis
Sets of both trial and testing functions are implemented by models following the basis concept. The term basis is somewhat misleading as it is nowhere required nor enforced that these functions are linearly independent. Models implementing the Basis concept need to comply to the following semantics.
- [`numfunctions(basis)`](@ref): number of functions in the Basis.
- [`coordtype(basis)`](@ref): type of (the components of) the values taken on by the functions in the Basis.
- [`scalartype(d)`](@ref): the scalar field underlying the vector space the basis functions take value in.
- [`refspace(basis)`](@ref): returns the ReferenceSpace of local shape functions on which the Basis is built.
- [`assemblydata(basis)`](@ref): `assemblydata` returns an iterable collection `elements` of geometric elements and a look table `ad` for use in assembly of interaction matrices. In particular, for an index `element_idx` into `elements` and an index `local_shape_idx` in basis of local shape functions `refspace(basis)`, `ad[element_idx, local_shape_idx]` returns the iterable collection of `(global_idx, weight)` tuples such that the local shape function at `local_shape_idx` defined on the element at `element_idx` contributes to the basis function at `global_idx` with a weight of `weight`.
- [`geometry(basis)`](@ref): returns an iterable collection of Elements. The order in which these Elements are encountered corresponds to the indices used in the assembly data structure.
## Reference Space
The *reference space* concept defines an API for working with spaces of local shape functions. The main role of objects implementing this concept is to allow specialization of the functions that depend on the precise reference space used.
The functions that depend on the type and value of arguments modeling *reference space* are:
- [`numfunctions(refspace)`](@ref): returns the number of shape functions on each element.
## Kernel
A kernel is a fairly simple concept that mainly exists as part of the definition of a Discrete Operator. A kernel should obey the following semantics:
In many function definitions the kernel object is referenced by `operator` or something similar. This is a misleading name as an operator definition should always be accompanied by the domain and range space.
## Discrete Operator
Informally speaking, a Discrete Operator is a concept that allows for the computation of an interaction matrix. It is a kernel together with a test and trial basis. A Discrete Operator can be passed to `assemble` and friends to compute its matrix representation.
A discrete operator is a triple `(kernel, test_basis, trial_basis)`, where `kernel` is a Kernel, and `test_basis` and `trial_basis` are Bases. In addition, the following expressions should be implemented and behave according to the correct semantics:
- [`quaddata(operator,test_refspace,trial_refspace,test_elements,trial_elements)`](@ref): create the data required for the computation of element-element interactions during assembly of discrete operator matrices.
- [`quadrule(operator,test_refspace,trial_refspace,p,test_element,q_trial_element,qd)`](@ref): returns an integration strategy object that will be passed to `momintegrals!` to select an integration strategy. This rule can depend on the test/trial reference spaces and interacting elements. The indices `p` and `q` refer to the position of the interacting elements in the enumeration defined by `geometry(basis)` and allow for fast retrieval of any element specific data stored in the quadrature data object `qd`.
- [`momintegrals!(operator,test_refspace,trial_refspace,test_element,trial_element,zlocal,qr)`](@ref): this function computes the local interaction matrix between the set of local test and trial shape functions and a specific pair of elements. The target matrix `zlocal` is provided as an argument to minimise memory allocations over subsequent calls. `qr` is an object returned by `quadrule` and contains all static and dynamic data defining the integration strategy used.
In the context of fast methods such as the Fast Multipole Method other algorithms on Discrete Operators will typically be defined to compute matrix vector products. These algorithms do not explicitly compute and store the interaction matrix (this would lead to unacceptable computational and memory complexity).
```@docs
elements
```
```@docs
numfunctions
coordtype
scalartype
assemblydata
geometry
refspace
```
```@docs
quaddata
quadrule
momintegrals!
```
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 3809 | # Quadrature strategies
## Introduction
There are many ways to approximately compute the singular integrals that appear in boundary element discretisations of surface and volume integral euqations.
BEAST.jl is configured to select reasonable defaults, but advanced users may want to select their own quadrature rules. This section provides information on how to do this.
## quaddata and quadrule
Numerical quadrature is governed by a pair of functions that need to be designed to work together:
- `quaddata`: this function is executed before the assembly loop is entered. It's job is to compute all data needed for quadrature that the developer wants to be cached. Typically this is all geometric information such as the parametric and cartesian coordinates of all quadratures rules for all elemenents. It makes sense to cache this data as it will be used many times over in the double for loop that governs assembly. Typically, near singular interactions require more careful treatment than far interactions. This means that multiple quadrature rules per elements can be required. In such cases, the developer may want to opt to sture quadrature points and weights for all these rules. The function returns a quaddata object that holds all the cached data.
- `quadrule`: quadrule is executed inside the assembly hotloop. It receives a pair of elements and the quaddata object as its arguments. Based on this, the relevant cached data is extracted and stored in a quadrule object. The type of this object will determine the actual quadrature routined that will be called upon to do the numerical quadrature.
## quadstrat
The pair of quaddata and quadrule methods that is used is determined by the type of the operator and finite elements, and a `quadstrat` object. This object is passed to the assembly routine and passed on to `quaddata` and `quadstrat`, so it can be considered during dispatch.
Parameters, such as those that determine the accuracy of the numerical quadrature, are part of the runtime payload of the quadstrat object. This is usefull when the user is interested on the impact of these parameters on the performance and the accuracy of the solver without having to supply a new pair of `quadstrat`/`quaddata` methods for each possible value of these parameters.
Roughly this leads to the following (simplified) assembly routine:
```julia
function assemble(op, tfs, bfs, store; quadstrat=QS)
tad, tels = assemblydata(op, tfs)
bad, bels = assemblydata(op, bfs)
qd = quadata(op,tels,bels,quadstrat)
for tel in tels
for bel in bels
qr = quadrule(op,tel,bel,qd,quadstrat)
zlocal = momintegrals(op,tel,bel,qr)
for i in axes(zlocal,1)
for j in axes(zlocal,2)
m, a = tad[tel,i]
n, b = bad[bel,j]
store(a*zlocal[i,j]*b,m,n)
end end end end end
```
It is conceivable that the types and functions described above look like this:
```julia
struct DoubleNumQS
test_precision
trial_precision
end
function quaddata(op, tels, bels, quadstrat::DoubleNumQS)
tqps = [quadpoints(tel,precision=quadstrat.test_precision) for tel in tels]
bqps = [quadpoints(bel,precision=quadstrat.basis_precision) for bel in bels]
return (test_quadpoints=tqps, basis_quadpoints=bqps)
end
struct DoubleNumQR
test_quadpoints
trial_quadpoints
end
struct HighPrecisionQR end
function quadrule(op, tel, bel, qd, quadstrat::DoubleNumQs)
if wellseparated(tel, bel)
return DoubleNumQR(qd.test_quadpoints[tel], qd.basis_quadpoints[bel])
else
return HighPrecisionQR(tel, bel)
end
end
function momintegrals(op, tel, bel, qr::DoubleNumQR)
...
end
function momintegrals(op, tel, bel, qr::HighPrecisionQR)
...
end
``` | BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 3580 | # Solving the Time Domain EFIE using Marching-on-in-Time
If broadband information is required or if the system under study will be coupled to non-linear components, the scattering problem should be solved directly in the time domain, i.e. as a hyperbolic evolution problem.
## Building the geometry
Building the geometry and defining the spatial finite elements happens in completely the same manner as for frequency domain simulations:
```julia
using CompScienceMeshes
using BEAST
D, dx = 1.0, 0.3
Γ = meshsphere(1.0, dx)
X = raviartthomas(Γ)
nothing # hide
```
Time domain currents are approximated in the tensor product of a spatial and temporal finite element space:
$j(x) \approx \sum_{i=1}^{N_T} \sum_{m=1}^{N_S} u_{i,m} T_i(t) f_m(x)$
This package only supports translation invariant temopral basis functions, i.e.
$T_i(t) = T(t - i \Delta t),$
where $\Delta t$ is the time step used to solve the problem. This time step depends on the bandwidth of the incident field and the desired accuracy. Space-Time Galerkin solvers of the type used here are not subject to stability conditions linking spatial and temporal discretisation resolutions.
We need a temporal trial space and test space. Common examples of temporal trial spaces are the shifted quadratic spline and shifted lagrange basis functions. In this example, a shifted quadratic spline `S` is used for the trial space, while a delta function `U` is used as the temporal test space to obtain a time-stepping solution.
```julia
Δt, Nt = 0.25, 300
S = BEAST.timebasisspline2(Δt, Nt)
U = BEAST.timebasisdelta(Δt, Nt)
nothing # hide
```
We want to solve the EFIE, i.e. we want to find the current $j$ such that
$Tj = -e^i,$
where the incident electric field can be any Maxwell solution in the background medium. To describe this problem in Julia we create a retarded potential operator objects and a functional representing the incident field:
```julia
x = point(1.0,0.0,0.0)
y = point(0.0,1.0,0.0)
z = point(0.0,0.0,1.0)
gaussian = BEAST.creategaussian(30Δt, 60Δt)
E = BEAST.planewave(x, z, BEAST.derive(gaussian), 1.0)
T = BEAST.MWSingleLayerTDIO(1.0,-1.0,-1.0,2,0)
nothing; # hide
```
Using the finite element spaces defined above this retarded potential equation can be discretized.
```julia
V = X ⊗ S #Space and time trial basis
W = X ⊗ U #Space and time test basis
B = assemble(E, W)
Z = assemble(T, W, V)
nothing # hide
```
The variable `Z` can efficiently store the matrices corresponding to different delays (`assemble` knows about the specific sparsity pattern of such matrices and returns a sparse array of rank three fit for purpose).
The algorithm below solves the discrete convolution problem by marching on in time:
```julia
Z0 = Z[:,:,1]
W0 = inv(Z0)
x = BEAST.marchonintime(W0,Z,-B,Nt)
nothing # hide
```
Computing the values of the induced current is now possible in the same manner as for frequency domain simulations by first converting our MOT solution back to the frequency domain using the fourier transform, along with some adjustments.
```julia
Xefie, Δω, ω0 = fouriertransform(x, Δt, 0.0, 2)
ω = collect(ω0 + (0:Nt-1)*Δω)
_, i1 = findmin(abs(ω-1.0))
ω1 = ω[i1]
ue = Xefie[:,i1]
ue /= fouriertransform(gaussian)(ω1)
fcr, geo = facecurrents(ue, X)
nothing # hide
```
For now the package still relies upon Matlab for some of its visualisation. This dependency will be removed in the near future:
```julia
include(Pkg.dir("CompScienceMeshes","examples","matlab_patches.jl"))
mat"clf"
patch(geo, real.(norm.(fcr)))
mat"cd($(pwd()))"
mat"print('current.png', '-dpng')"
```
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 2498 | # Tutorial
```math
\newcommand{\vt}[1]{\boldsymbol{#1}}
\newcommand{\uv}[1]{\hat{\boldsymbol{#1}}}
\newcommand{\arr}[1]{\mathsf{#1}}
\newcommand{\mat}[1]{\boldsymbol{\mathsf{#1}}}
```
In this tutorial we will go through the steps required for the formulation and the solution of the scattering of a time harmonic electromagnetic wave by a rectangular plate by means of the solution of the electric field integral equation.
## Building the geometry
The sibling package `CompScienceMeshes` provides data structures and algorithms for working with simplical meshes in computational science. We will use it to create the geometry:
```@example 1
using CompScienceMeshes, BEAST
o, x, y, z = euclidianbasis(3)
h = 0.2
Γ = meshrectangle(1.0, 1.0, h)
@show numvertices(Γ)
@show numcells(Γ)
nothing # hide
```
Next, we create the finite element space of Raviart-Thomas aka Rao-Wilton-Glisson functions subordinate to the triangulation `Γ` constructed above:
```@example 1
X = raviartthomas(Γ)
nothing # hide
```
The scattering problem is defined by specifying the single layer operator and the functional acting as excitation. Here, the plate is illuminated by a plane wave. The actual excitation is the tangential trace of this electric field. This trace be constructed easily by using the symbolic normal vector field `n` defined as part of the `BEAST` package.
```@example 1
κ = 1.0
E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ)
e = (n × E) × n
nothing # hide
```
The single layer potential is also predefined by the `BEAST` package:
```@example 1
t = Maxwell3D.singlelayer(wavenumber=κ)
nothing # hide
```
It corresponds to the bilinear form
```math
t(\vt{k},\vt{j}) = \frac{1}{ik} \int_{\Gamma} \int_{\Gamma'} \nabla \cdot \vt{k}(x) \nabla \cdot \vt{j}(y) \frac{e^{-ik|x-y|}}{4\pi|x-y|} dy dx - ik \int_{\Gamma} \int_{\Gamma'} \vt{k}(x) \cdot \vt{j}(y) \frac{e^{-ik|x-y|}}{4\pi|x-y|} dy dx
```
Using the `LinearForms` package, which implements a simple form compiler for Julia (`@varform`), the EFIE can be defined and discretised by
```@example 1
@hilbertspace j
@hilbertspace k
efie = @discretise t[k,j]==e[k] j∈X k∈X
nothing # hide
```
Solving and computing the values of the induced current in the centers of the triangles of the mesh is now straightforward:
```@example 1
u = solve(efie)
fcr, geo = facecurrents(u,X)
nothing # hide
```
The resulting current distribution can be visualised by e.g. Matlab, Paraview, Plotly,...

| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 2.5.0 | 757efc563022d39e95f751b7e5a29d020a57e049 | docs | 931 | # Post-processing and Visualisation
## Field computation
The main API for the computation of fields in a vector of points is the potential function. This function is capable of computing
```math
F(x) = \int_{\Gamma} K(x,y) u(y) dy
```
with ``u(y) = \Sigma_{i=1}^N u_i f_i(y)`` and ``K(x,y)`` the integation kernel defining the type of potential. For example, the far field for a vector valued surface density is
```math
F(x) = \int_{\Gamma} e^{ik \frac{x \cdot y}{|x|}} u(y) dy
```
For a far field potential such as this, the value only depends on the direction, not the magnitude, of ``x``, as can be read off from the normalisation in the exponent.
The following script computes the far field along a semi-circle in the xz-plane.
```julia
Θ, Φ = range(0.0,stop=2π,length=100), 0.0
dirs = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for θ in Θ for ϕ in Φ]
farfield = potential(MWFarField3D(wavenumber=κ), dirs, u, X)
```
| BEAST | https://github.com/krcools/BEAST.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1444 | using Documenter, DocumenterMarkdown, Literate
using CEEDesigns
# Literate for tutorials
const literate_dir = joinpath(@__DIR__, "..", "tutorials")
const tutorials_src = [
"SimpleStatic.jl",
"SimpleGenerative.jl",
"StaticDesigns.jl",
"StaticDesignsFiltration.jl",
"GenerativeDesigns.jl",
"ActiveSampling.jl",
]
const generated_dir = joinpath(@__DIR__, "src", "tutorials/")
# copy tutorials src
for file in tutorials_src
println(joinpath(literate_dir, file), generated_dir)
cp(joinpath(literate_dir, file), joinpath(generated_dir, file); force = true)
end
for dir in ["assets", "data"]
cp(joinpath(literate_dir, dir), joinpath(generated_dir, dir); force = true)
end
for file in tutorials_src
Literate.markdown(
joinpath(generated_dir, file),
generated_dir;
documenter = true,
credit = false,
)
end
pages = [
"index.md",
"Tutorials" => [
"tutorials/SimpleStatic.md",
"tutorials/SimpleGenerative.md",
"tutorials/StaticDesigns.md",
"tutorials/StaticDesignsFiltration.md",
"tutorials/GenerativeDesigns.md",
"tutorials/ActiveSampling.md",
],
"api.md",
]
makedocs(;
sitename = "CEEDesigns.jl",
format = Documenter.HTML(;
prettyurls = false,
edit_link = "main",
assets = ["assets/favicon.ico"],
),
pages,
)
deploydocs(; repo = "github.com/Merck/CEEDesigns.jl.git")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 10124 | # # Active Sampling for Generative Designs
# ## Background on Active Sampling
# In multi-objective optimization (MOO), particularly in the context of active learning and reinforcement learning (RL),
# conditional sampling plays a critical role in achieving optimized outcomes that align with specific desirable criteria.
# The essence of conditional sampling is to direct the generative process not only towards the global objectives but also to adhere to additional, domain-specific constraints or features. This approach is crucial for several reasons:
# MOO often involves balancing several competing objectives, such as minimizing cost while maximizing performance.
# Conditional sampling allows for the integration of additional constraints or preferences,
# ensuring that the optimization does not overly favor one objective at the expense of others.
# On a related note, many optimization problems have domain-specific constraints or desirable features that are not explicitly part of the primary objectives.
# For example, in drug design, beyond just optimizing for efficacy and safety, one might need to consider factors like solubility or synthesizability.
# Conditional sampling ensures that solutions not only meet the primary objectives but also align with these additional practical considerations.
# ## Application to Generative Designs
# In the context of CEEDesigns.jl, active sampling can be used to selectively prioritize historical observations.
# For example, if the goal is to understand a current trend or pattern,
# active sampling can be used to assign more weight to recent data points or deprioritize those that may not be relevant to the current context.
# This way, the sampled data will offer a more precise representation of the current state or trend.
# For details on the theoretical background of generative designs and notation, please see our [introductory tutorial](SimpleGenerative.md) and an [applied tutorial](GenerativeDesigns.jl).
# Here we will again assume that the generative process is based on sampling from a historical dataset, which gives measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
# (with entities and features representing rows and columns, respectively).
# Each experiment $e$ may yield measurements on some
# subset of features $(X_{e}\subseteq X)$.
# Given the current state, i.e., experimental evidence acquired thus far for the new entity, we assign probabilistic weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
# weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
# $q(e_{S^{\prime}}|e_{S})$.
# In the context of active sampling, we aim to further adjust the weights, $w_{j}$, calculated by the algorithm.
# This adjustment can be accomplished by introducing a "prior", which is essentially a vector of weights that will multiply the computed weights, $w_{j}$, in an element-wise manner.
# If we denote the "prior" weights as $p_{j}$, then the final weights assigned to the $j$-th row are computed as $w'_{j} = p_{j} * w_{j}$.
# Alternatively, we can use "feature-wise" priors, which are considered when a readout for the specific feature is available for the new entity. # It is important to note here that the distance, which forms the basis of the probabilistic weights, is inherently computed only over the observed features.
# To be more precise, for each experiment $e\in E$, we let $p^e_j$ denote the "prior" associated with that specific experiment.
# If $S$ represents the set of experiments that have been performed for the new compound so far, we compute the reweighted probabilistic weight as $w'_{j} = \product_{e\in S} p^e_j \cdot w_j$.
# We remark that this method can be used to filter out certain rows by setting their weight to zero.
# Considering feature-wise priors can offer a more detailed and nuanced understanding of the data. These priors can be used to dynamically adjust the weight of historical observations, based on the specific readouts considered for the observation across different features.
# For more information about active sampling, refer to the following articles.
# - [Evolutionary Multiobjective Optimization via Efficient Sampling-Based Strategies](https://link.springer.com/article/10.1007/s40747-023-00990-z).
# - [Sample-Efficient Multi-Objective Learning via Generalized Policy Improvement Prioritization](https://arxiv.org/abs/2301.07784).
# - [Conditional gradient method for multiobjective optimization](https://link.springer.com/article/10.1007/s10589-020-00260-5)
# - [A practical guide to multi-objective reinforcement learning and planning](https://link.springer.com/article/10.1007/s10458-022-09552-y)
# ## Synthetic Data Example
using CEEDesigns, CEEDesigns.GenerativeDesigns
# We create a synthetic dataset with continuous variables, `x1`, `x2`, and `y`. Both `x1` and `x2` are modeled as independent random variables that follow a normal distribution.
# The target variable, `y`, is given as a weighted sum of `x1` and `x2`, with an additional noise component. The corrected version of your sentence should be: Consequently, if the value of `x2`, for example,
# falls into a "sparse" region, we want the algorithm to avoid overfitting and focus its attention more on the other variable.
using Random
using DataFrames
## Define the size of the dataset.
n = 1000;
## Generate `x1` and `x2` as independent random variables with normal distribution.
x1 = randn(n)
x2 = randn(n);
## Compute `y` as the sum of `x1`, `x2`, and the noise.
y = x1 .+ 0.2 * x2 .+ 0.1 * randn(n);
## Create a data frame.
data = DataFrame(; x1 = x1, x2 = x2, y = y);
data[1:10, :]
# ### Active Sampling
# We again use the default method `DistanceBased` to assign the probabilistic weights across historical observations.
# In addition, we will demonstrate the use of two additional keyword arguments of `DistanceBased`, related to active sampling:
# - `importance_weights`: this is a dictionary of pairs `colname` with either `weights` or a function `x -> weight`, which will be applied to each element of the column to obtain the vector of weights. If data for a given column is available in the current state, the product of the corresponding weights is used to adjust the similarity vector.
#
# For filtering out certain rows where the readouts fall outside a selected range, we can use the following keyword:
# - `filter_range`: this is a dictionary of pairs `colname => (lower bound, upper bound)`. If there's data in the current state for a specific column specified in this list, only historical observations within the defined range for that column are considered.
# In the current setup, we aim to adaptively filter out the values `x1` or `x2` that lie outside of one standard deviation from the mean.
filter_range = Dict()
filter_range = Dict("x1" => (-1, 1), "x2" => (-1, 1))
# We then call `DistanceBased` as follows:
(sampler_active, uncertainty_active, weights_active) = DistanceBased(
data;
target = "y",
similarity = Exponential(; λ = 1),
filter_range = filter_range,
);
# To compare behavior with and without active sampling, we call `DistanceBased` again:
(; sampler, uncertainty, weights) =
DistanceBased(data; target = "y", similarity = Exponential(; λ = 1));
# We plot the weights $w_j$ assigned to historical observations for both cases - with active sampling and without. The actual observation is shown in orange.
evidence = Evidence("x1" => 5.0, "x2" => 0.5)
#
using Plots
colors_active = max.(0.1, weights_active(evidence) ./ maximum(weights_active(evidence)))
p1 = scatter(
data[!, "x1"],
data[!, "x2"];
color = RGBA.(colorant"rgb(0,128,128)", colors_active),
title = "weights\n(active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p1,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p1
#
colors = max.(0.1, weights(evidence) ./ maximum(weights(evidence)))
p2 = scatter(
data[!, "x1"],
data[!, "x2"];
color = RGBA.(colorant"rgb(0,128,128)", colors),
title = "weights\n(no active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p2,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p2
#
# As it turns out, when active sampling was not used, the algorithm tended to overfit to the closest yet sparse points, which did not represent the true distribution accurately.
# We can also compare the estimated uncertainty, which is computed as the variance of the posterior.
#
# Without using active sampling, we obtain:
round(uncertainty_active(evidence); digits = 1)
#
# While for active sampling, we get:
round(uncertainty(evidence); digits = 1)
# #### Experimental Designs for Uncertainty Reduction
# We compare the set of cost-efficient designs in cases where active sampling is used and where it is not.
#
# We specify the experiments along with the associated features:
experiments = Dict("x1" => 1.0, "x2" => 1.0, "y" => 6.0)
# We specify the initial state.
evidence = Evidence("x2" => 5.0)
# Next we compute the set of efficient designs.
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
designs_active = efficient_designs(
experiments;
sampler = sampler_active,
uncertainty = uncertainty_active,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
# We can compare the fronts.
p = scatter(
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
ylabel = "% uncertainty",
label = "efficient designs (no active sampling)",
title = "efficient front",
color = :blue,
mscolor = nothing,
)
scatter!(
p,
map(x -> x[1][1], designs_active),
map(x -> x[1][2], designs_active);
label = "efficient designs (active sampling)",
color = :teal,
mscolor = nothing,
)
p
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 10515 | # # Heart Disease Triage Meets Generative Modeling
# Consider again a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer; instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# For details on the theoretical background and notation, please see our tutorial on [generative experimental designs](SimpleGenerative.md). This tutorial
# is a concrete application of the tools described in that document.
# Importantly, we aim to design personalized adaptive policies for each patient. At the beginning of the triage process, we use a patient's prior data, such as sex, age, or type of chest pain, to project a range of cost-efficient experimental designs. Internally, while constructing these designs, we incorporate multiple-step-ahead lookups to model probable experimental outcomes and consider the subsequent decisions for each outcome. Then after choosing a specific decision policy from this set and acquiring additional experimental readouts, we adjust the continuation based on this evidence.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# We provide appropriate scientific types of the features.
using ScientificTypes
types = Dict(
:MaxHR => Continuous,
:Cholesterol => Continuous,
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
# ## Generative Model for Outcomes Sampling
using CEEDesigns, CEEDesigns.GenerativeDesigns
# As previously discussed, we provide a dataset of historical records, the target variable, along with an information-theoretic measure to quantify the uncertainty about the target variable.
# In what follows, we obtain three functions:
# - `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator,
# - `uncertainty`: this is a function of `evidence`,
# - `weights`: this represents a function of `evidence` that distributes probabilistic weights across the rows in the dataset.
# Note that internally, a state of the decision process is represented as a tuple `(evidence, costs)`.
# You can specify the method for computing the distance using the `distance` keyword. By default, the Kronecker delta and quadratic distance will be utilised for categorical and continuous features, respectively.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
# Alternatively, you can provide a dictionary of `feature => distance` pairs. The implemented distance functionals are `DiscreteDistance(; λ)` and `QuadraticDistance(; λ, standardize=true)`. In that case, the specified distance will be applied to the respective feature, after which the distances will be collated across the range of features.
# The above call is therefore equivalent to:
numeric_feats = filter(c -> c <: Real, eltype.(eachcol(data)))
categorical_feats = setdiff(names(data), numeric_feats)
DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = merge(
Dict(c => DiscreteDistance() for c in categorical_feats),
Dict(c => QuadraticDistance() for c in numeric_feats),
),
);
# You can also use the squared Mahalanobis distance (`SquaredMahalanobisDistance(; diagonal)`). As the squared Mahalanobis distance only works with numeric features, we have to select a few, along with the target variable. For example, we could write:
DistanceBased(
data[!, ["RestingBP", "MaxHR", "Cholesterol", "FastingBS", "HeartDisease"]];
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 1),
);
# The package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20.0 => ["FastingBS"],
"HeartDisease" => 100.0,
)
# Let us inspect the distribution of belief for the following experimental evidence:
evidence = Evidence("Age" => 55, "Sex" => "M")
#
using StatsBase: countmap
using Plots
#
target_belief = countmap(data[!, "HeartDisease"], weights(evidence))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
# Let us next add an outcome of blood pressure measurement:
evidence_with_bp = merge(evidence, Dict("RestingBP" => 190))
target_belief = countmap(data[!, "HeartDisease"], weights(evidence_with_bp))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence_with_bp), digits=2))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
# ## Cost-Efficient Experimental Designs for Uncertainty Reduction
# In this experimental setup, our objective is to minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs for various levels of uncertainty threshold. In the following example, we generate 6 thresholds spaces evenly between 0 and 1, inclusive.
# Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl) is created, and the `POMDPs.solve` is called on the problem. Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
## set seed for reproducibility
using Random: seed!
seed!(1)
#
evidence = Evidence("Age" => 35, "Sex" => "M")
#
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 20_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
# We plot the Pareto-efficient actions:
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# We render the search tree for the second design, sorted in descending order based on the uncertainty threshold:
using D3Trees
d3tree = D3Tree(designs[2][2].tree; init_expand = 2)
# ### Parallel Experiments
# We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
"HeartDisease" => (100.0, 100.0),
)
# We have to provide the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
## minimize time, two concurrent experiments at maximum
seed!(1)
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 2_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 2, costs_tradeoff = (0, 1.0)),
repetitions = 5,
);
# We plot the Pareto-efficient actions:
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# ## Efficient Value Experimental Designs
# In this experimental setup, we aim to maximize the value of experimental evidence, adjusted for the incurred experimental costs.
# For this purpose, we need to specify a function that quantifies the "value" of decision-process making state, modeled as a tuple of experimental evidence and costs.
value = function (evidence, (monetary_cost, execution_time))
return (1 - uncertainty(evidence)) - (0.005 * sum(monetary_cost))
end
# Considering a discount factor $\lambda$, the total reward associated with the experimental state in an $n$-step decision process is given by $r = r_1 + \sum_{i=2}^n \lambda^{i-1} (r_i - r_{i-1})$, where $r_i$ is the value associated with the $i$-th state.
# In the following example, we also limit the maximum rollout horizon to 4.
#
seed!(1)
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(; n_iterations = 2_000, depth = 4, tree_in_info = true)
design = efficient_value(
experiments;
sampler,
value,
evidence,
solver,
repetitions = 5,
mdp_options = (; discount = 0.8),
);
#
design[1] # optimized cost-adjusted value
#
d3tree = D3Tree(design[2].tree; init_expand = 2)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 26316 | # # Generative Experimental Designs
# This document describes the theoretical background behind tools in CEEDesigns.jl for generative experimental designs
# and demonstrates uses on synthetic data examples.
# ## Setting
# Generative experimental designs differ from static designs in that the experimental design is specific for (or "personalized") to an incoming entity.
# Personalized cost-efficient experimental designs for the new entity are made based on existing information (if any) about the new entity,
# and from posterior distributions of unobserved features of that entity conditional on its observed features and historical data.
# The entities may be patients, molecular compounds, or any other objects where one has a store of historical data
# and seeks to find efficient experimental designs to learn more about a new arrival.
#
# The personalized experimental designs are motivated by the fact that the value of information collected from an experiment
# often differs across subsets of the population of entities.
# 
# In the context of static designs, we do not aspire to capture variation in information gain across different entities. Instead, we assume all entities come from a "Population" with a uniform information gain, in which case "Experiment C" would provide the maximum information value.
# On the other hand, if we have the ability to discern if the entity belong to subpopulations "Population 1" or "Population 2," then we can tailor our
# design to suggest either "Experiment A" or "Experiment B." Clearly, in the limit of a maximally heterogenous population, each
# entity has its own "row." Our tools are able to handle the entire spectrum of such scenarios though distance based similarity,
# described below.
# ## Theoretical Framework
# ### Historical Data
# Like static designs, we consider a set $E$ of $n$ experiments, each with an associated tuple $(m_{e},t_{e})$ of monetary and
# time costs (for more details on experiments and arrangements, see the tutorial on [static experimental designs](SimpleStatic.md)).
#
# Additionally, consider a historical dataset giving measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
# (with entities and features representing rows and columns, respectively). Each experiment $e$ may yield measurements on some
# subset of features $(X_{e}\subseteq X)$.
#
# Furthermore there is an additional column $y$ which is a target variable we want to predict (CEEDesigns.jl may allow $y$
# to be a vector, but we assume it is scalar here for ease of presentation).
#
# Letting $m=3$, then the historical dataset may be visualized as the following table:
# 
# ### New Entity
# When a new entity arrives, it will have an unknown outcome $y$ and unknown values of some or all features $x_{i} \in X$.
# We call the _state_ of the new entity the set of experiments conducted upon it so far (if any), along with the
# measurements on any features produced by those experiments (if any), called _evidence_.
#
# Consider the case where there are $n=3$ experiments, each of which yields a measurement on a single feature. Then
# the state of a new entity arriving for which $e_{1}$ has already been performed will look like:
# 
# Letting $S$ denote the set of experiments which have been performed so far, then $S^{\prime}=E\S$ are unperformed experiments.
# Then, _actions_ one can perform to learn more about the new entity are subsets of $S^{\prime}$. The size of subsets
# is limited by the maximum number of parallel experiments.
#
# In our running example, if the maximum number of parallel experiments is at least 2, then the available actions are:
# 
# ### Posterior Distributions
# Let $e_{S}$ be a random variable denoting the outcome of some experiments $S$ on the new entity. Then, there exists a
# posterior distribution $q(e_{S^{\prime}}|e_{S})$ over outcomes of unperformed experiments $S^{\prime}$, conditioned on the current
# state.
#
# Furthermore, there also exists a posterior distribution over the unobserved target variable $q(y|e_{S})$. The information
# value of the current state, derived from experimental evidence, can be defined as any statistical or information-theoretic
# measure applied to $q(y|e_{S})$. This can include variance or entropy (among others). The information value
# of the set of experiments performed in $S$ is analogous to $v_{S}$ defined in [static experimental designs](SimpleStatic.md).
# ### Similarity Weighting
# There may be many ways to define these posterior distributions, but our approach uses distance-based similarity
# scores to construct weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
# weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
# $q(e_{S^{\prime}}|e_{S})$.
#
# If there is no evidence associated with a new entity, we assign $w_{j}$ according to some prior distribution (uniform by default).
# Otherwise we use some particular distance and similarity metrics.
#
# For each feature $x\in X$, we consider a function $\rho_x$, which measures the distance between two outputs. Please be aware that the "distances" discussed here do not conform to the mathematical definition of "metrics", even though they are functions derived from underlying metrics (i.e., a square of a metric). This is justified when considering how these "distances" are subsequently converted into probabilistic weights.
#
# By default, we consider the following distances:
# - Rescaled Kronecker delta (i.e., $\rho(x, y)=0$ only when $x=y$, and $\rho(x, y)= \lambda$ under any other circumstances, with $\lambda > 0$) for discrete features (i.e., features whose types are modeled as `MultiClass` type in [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl));
# - Rescaled ("standardized", by default) squared distance $\rho(x, y) = λ \frac{(x - y)^2}{\sigma^2}$, where $\sigma^2$ is the variance of the feature column, estimated with respect to the prior for continuous features.
# - Squared Mahalanobis distance $\rho(x,y) = (x-y)^{⊤}\Sigma^{-1}(x-y)$, where $\Sigma$ is the empirical covariance matrix of the historical data.
#
# For distance metrics assuming independence of features (Kronecker delta and squared distance), given the new entity's experimental state with readouts over the feature set $F = \bigcup X_{e}$, where $e \in S$, we can calculate
# the distance from the $j$-th historical entity as $d_j = \sum_{x\in F} \rho_x (\hat x, x_j)$, where $\hat x$ and $x_j$ denote the readout
# for feature $x$ for the entity being tested and the entity recorded in $j$-th column.
# The squared Mahalanobis distance directly takes in "rows", $\rho(\hat{x},x_{j})$.
#
# Next, we convert distances $d_j$ into probabilistic weights $w_j$. By default, we use a rescaled exponential function, i.e.,
# we put $w_j = \exp(-\lambda d_j)$ with $\lambda=0.5$. Notably, $\lambda$'s value determines how belief is distributed across the historical entities.
# Larger values of $\lambda$ concentrate the belief tightly around the "closest" historical entities, while smaller values distribute more belief to more distant entities.
#
# Note that by choosing the squared Mahalanobis distance and the exponential function with a factor of $\lambda=0.5$, the resulting weight effectively equals the density of a [multivariate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function) fitted to the historical data. A similar assertion applies when we use the sum of "standardized" squared distances instead. However, in this latter case, we "enforce" the independence of the features.
#
# The proper choice of distance and similarity metrics depends on insight into the dataset at hand. Weights can then be used to construct
# weighted histograms or density estimators for the posterior distributions of interest, or to directly resample historical rows.
# 
# ### Policy Search
# Given these parts, searching for optimal experimental designs (actions arranged in an efficient way) depends on what our objective sense is.
#
# - The search may continue until the uncertainty about the posterior distribution of the target variable falls below a certain level. Our aim is to minimize the anticipated combined monetary cost and execution time of the search (considered as a "negative" reward). If all experiments are conducted without reaching below the required uncertainty level, or if the maximum number of experiments is exceeded, we penalize this scenario with an "infinitely negative" reward.
# - We may aim to minimize the expected uncertainty while being constrained by the combined costs of the experiment.
# - Alternatively, we could maximize the value of experimental evidence, adjusted for the incurred experimental costs.
# Standard Markov decision process (MDP) algorithms can be used to solve this problem (offline learning) or construct the policy (online learning) for the sequential decision-making.
# Our MDP's state space is finite-dimensional but generally continuous due to the allowance of continuous features, which complicates the problem and few algorithms specialize in this area.
# We used the Double Progressive Widening Algorithm for this task as detailed in [A Comparison of Monte Carlo Tree Search and Mathematical Optimization for Large Scale Dynamic Resource Allocation](https://arxiv.org/abs/1405.5498).
# In a nutshell, the Double Progressive Widening (DPW) algorithm is designed for online learning in complex environments, particularly those known as Continuous Finite-dimensional Markov Decision Processes where the state space is continuous. The key idea behind DPW is to progressively expand the search tree during the Monte Carlo Tree Search (MCTS) process. The algorithm does so by dynamically and selectively adding states and actions to the tree based on defined heuristics.
# In the context of online learning, this algorithm addresses the complexity and challenges of real-time decision-making in domains with a large or infinite number of potential actions. As information is gathered in actual runtime, the algorithm explores and exploits this information to make optimal or near-optimal decisions. In other words, DPW permits the learning process to adapt on-the-fly as more data is made available, making it an effective tool for the dynamic and uncertain nature of online environments.
# In particular, at the core of the Double Progressive Widening (DPW) algorithm are several key components, including expansion, search, and rollout.
# The search component is where the algorithm sifts through the search tree to determine the most promising actions or states to explore next. By using exploration-exploitation strategies, it can effectively balance its efforts between investigating previously successful actions and venturing into unexplored territories.
# The expansion phase is where the algorithm grows the search tree by adding new nodes, representing new state-action pairs, to the tree. This is done based on a predefined rule that dictates when and how much the tree should be expanded. This allows the algorithm to methodically discover and consider new potential actions without becoming overwhelmed with choices.
# Lastly, the rollout stage, also known as a simulation stage, is where the algorithm plays out a series of actions to the end of a game or scenario using a specific policy (like a random policy). The results of these rollouts are then used to update the estimates of the values of state-action pairs, increasing the accuracy of future decisions.
# 
# In the above figure, nodes represent states of the decision process, while edges correspond to actions connecting these states.
# A graphical summary of a single step of the overall search process to find the next best action, using our running example where a new entity
# has had $e_{1}$ performed out of 3 possible experiments is below:
# 
# ## Synthetic Data Example with Continuous $y$
# We now present an example of finding cost-efficient generative designs on synthetic data using the CEEDesigns.jl package.
#
# First we load necessary packages.
using CEEDesigns, CEEDesigns.GenerativeDesigns
using DataFrames
using ScientificTypes
import Distributions
using Copulas
using POMDPs, POMDPTools, MCTS
using Plots, StatsPlots, StatsBase
# ### Synthetic Data
# We use the "Friedman #3" method to make synthetic data for a regression problem from [scikit-learn](https://scikit-learn.org/stable/datasets/sample_generators.html#generators-for-regression).
# It considers $m=4$ features which predict a continuous $y$ via some nonlinear transformations. The marginal
# distributions of each feature are given by the scikit-learn documentation. We additionally use a Gaussian copula
# to induce a specified correlation structure on the features to illustrate the difference between Euclidean and Mahalanobis
# distance metrics. We sample $l=1000$ rows of the historical data.
make_friedman3 = function (U, noise = 0, friedman3 = true)
size(U, 2) == 4 || error("input U must have 4 columns, has $(size(U,2))")
n = size(U, 1)
X = DataFrame(zeros(Float64, n, 4), :auto)
for i = 1:4
X[:, i] .= U[:, i]
end
ϵ = noise > 0 ? rand(Distributions.Normal(0, noise), size(X, 1)) : 0
if friedman3
X.y = @. atan((X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4])) / X[:, 1]) + ϵ
else
## Friedman #2
X.y = @. (X[:, 1]^2 + (X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4]))^2)^0.5 + ϵ
end
return X
end
ρ12, ρ13, ρ14, ρ23, ρ24, ρ34 = 0.8, 0.5, 0.3, 0.5, 0.25, 0.4
Σ = [
1 ρ12 ρ13 ρ14
ρ12 1 ρ23 ρ24
ρ13 ρ23 1 ρ34
ρ14 ρ24 ρ34 1
]
X1 = Distributions.Uniform(0, 100)
X2 = Distributions.Uniform(40 * π, 560 * π)
X3 = Distributions.Uniform(0, 1)
X4 = Distributions.Uniform(1, 11)
C = GaussianCopula(Σ)
D = SklarDist(C, (X1, X2, X3, X4))
X = rand(D, 1000)
data = make_friedman3(transpose(X), 0.01)
data[1:10, :]
# We can check that the empirical correlation is roughly the same as the specified theoretical values:
cor(Matrix(data[:, Not(:y)]))
# We ensure that our algorithms know that we have provided data of specified types.
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Continuous,
)
data = coerce(data, types);
# We may plot each feature $x_{i} \in X = {x_{1},x_{2},x_{3},x_{4}}$ against $y$.
p1 = scatter(data.x1, data.y; legend = false, xlab = "x1")
p2 = scatter(data.x2, data.y; legend = false, xlab = "x2")
p3 = scatter(data.x3, data.y; legend = false, xlab = "x3")
p4 = scatter(data.x4, data.y; legend = false, xlab = "x4")
plot(p1, p2, p3, p4; layout = (2, 2), legend = false)
# ### Distance-based Similarity
# Given historical data, a target variable $y$, and metric to quantify uncertainty around
# the posterior distribution on the target $q(y|e_{S})$, the function `DistanceBased`
# returns three functions needed by CEEDesigns.jl:
# - `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator;
# - `uncertainty`: this is a function of `evidence`,
# - `weights`: this represents a function of `evidence` that generates probability weights $w_j$ to each row in the historical data.
#
# By default, Euclidean distance is used as the distance metric. In the second
# call to `DistanceBased`, we instead use the squared Mahalanobis distance.
# It is possible to specify different distance metrics for each feature, see our
# [heart disease generative modeling](GenerativeDesigns.md) tutorial for more information.
# In both cases, the squared exponential function is used to convert distances
# to weights.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
(sampler_mh, uncertainty_mh, weights_mh) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 0),
);
# We can look at the uncertainty in $y$ for a state where a single
# feature is "observed" at its mean value.
# As we consider only a single non-missing entry, note that the probabilistic weights assigned by the squared Mahalanobis distance
# are generally less "spread out." This is because the variant of the squared Mahalanobis distance, which we implemented for handling missing values,
# effectively multiplies the other quadratic distance by a factor greater than one.
# For more details, refer to page 285 of
# [Multivariate outlier detection in incomplete survey data: The epidemic algorithm and transformed rank correlations](https://www.jstor.org/stable/3559861).
# The interaction with uncertainties is more complex as the uncertainty depends on the values of the target variable that correspond to the rows in the historical data.
data_uncertainties =
[i => uncertainty(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
data_uncertainties_mh =
[i => uncertainty_mh(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties_mh; by = x -> x[2], rev = true)
p1 = sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
title = "Uncertainty\n(Euclidean distance)",
)
p2 = sticks(
eachindex(data_uncertainties_mh),
[i[2] for i in data_uncertainties_mh];
xformatter = i -> data_uncertainties_mh[Int(i)][1],
label = false,
title = "Uncertainty\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
# We can view the posterior distribution $q(y|e_{S})$ conditioned on a state (here arbitrarily set to $S = e_{3}$, giving evidence for $x_{3}$).
evidence = Evidence("x3" => mean(data.x3))
plot_weights = StatsBase.weights(weights(evidence))
plot_weights_mh = StatsBase.weights(weights_mh(evidence))
p1 = Plots.histogram(
data.y;
weights = plot_weights,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Euclidean distance)",
)
p2 = Plots.histogram(
data.y;
weights = plot_weights_mh,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
# Like static designs, generative designs need to be provided a `DataFrame` assigning to each experiment
# a tuple of monetary and time costs $(m_{e},t_{e})$, and what features each experiment provides observations of.
# We'll set up the experimental costs such that experiments which have less marginal uncertainty are more costly
# We finally add a very expensive "final" experiment which can directly observe the target variable.
observables_experiments = Dict(["x$i" => "e$i" for i = 1:4])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(data_uncertainties_mh)
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
# ### Find Cost-efficient Experimental Designs
# We can now find cost-efficient experimental designs for a new entity that has no measurements (`Evidence()`).
# Our objective sense is to minimize expected experimental combined cost while trying to reduce uncertainty to
# a threshold value. We examine 7 different threshold levels of uncertainty, evenly spaced between 0 and 1, inclusive.
# Additionally we set the `costs_tradeoff` such that equal weight is given to time and monetary cost when
# constructing the combined costs of experiments.
#
# Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl)
# is created, and the `POMDPs.solve` is called on the problem.
# Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
#
# Note that we use the Euclidean distance, due to somewhat faster runtime.
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
# We plot the Pareto-efficient actions.
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# ## Synthetic Data Example with Discrete $y$
# ### Synthetic Data
# We use n-class classification problem generator from [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html#sklearn.datasets.make_classification)
# We used parameters given below, for a total of $m=5$ features, with 4 of those informative and 1 redundant (linear combination of the other 4) feature.
# The $y$ has 2 classes, with some added noise. We again sample $l=1000$ rows of historical entities.
#
# The dataset can be approximately reproduced as below:
## using PyCall
## sklearn = PyCall.pyimport_conda("sklearn", "scikit-learn")
## py"""
## import sklearn as sk
## from sklearn.datasets import make_classification
## """
## X, y = py"make_classification(n_samples=1000,n_features=5,n_informative=4,n_redundant=1,n_repeated=0,n_classes=2,n_clusters_per_class=2,flip_y=0.1)"
## using DataFrames, CSV
## dat = DataFrame(X, :auto)
## dat.y = y
## CSV.write("./class.csv",dat)
using CSV
data = CSV.read("./data/class.csv", DataFrame)
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Multiclass,
)
data = coerce(data, types);
# ### Distance-based Similarity
# We now set up the distance based similarity functions. We use `Entropy` as our metric of uncertainty this time,
# which is more suitable for discrete $y$.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Entropy(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
# We may also look at the uncertainty from each marginal distribution of features.
# This is a bit nonsensical as the data generating function will create multimodal clusters
# so it will look artifically as if nothing is informative, but that is not the case.
data_uncertainties =
[i => uncertainty(Evidence(i => mode(data[:, i]))) for i in names(data)[1:end-1]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
ylab = "Uncertainty",
)
# We can view the posterior distribution $q(y|e_{S})$ when we consider the state as evidence a single measurement
# of the first feature, set to the mean of that distribution.
evidence = Evidence("x1" => mean(data.x1))
plot_weights = StatsBase.weights(weights(evidence))
target_belief = countmap(data[!, "y"], plot_weights)
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["0", "1"]);
p
# Like previous examples, we'll set up the experimental costs such that experiments which have less marginal uncertainty
# are more costly, add a final very expensive experiment directly on the target variable.
observables_experiments = Dict(["x$i" => "e$i" for i = 1:5])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(sort(data_uncertainties; by = x -> x[2], rev = true))
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
# ### Find Cost-efficient Experimental Designs
# We can now find sets of cost-efficient experimental designs for a new entity with no measurements (`Evidence()`).
# We use the same solver parameters as for the exaple with continuous $y$, and plot the resulting
# Pareto front.
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 9309 | # # Static Experimental Designs
# In this document we describe the theoretical background behind the tools in CEEDesigns.jl for producing optimal "static experimental designs," i.e.,
# arrangements of experiments that exist along a Pareto-optimal tradeoff between cost and information gain.
# We also show an example with synthetic data.
# ## Setting
# Consider the following scenario. There exists a set of experiments, each of which, when performed, yields
# measurements on one or more observables (features). Each subset of observables (and therefore each subset of experiments)
# has some "information value," which is intentionally vaguely defined for generality, but for example, may be
# a loss function if that subset is used to train some machine learning model. It is generally the value of acquiring that information.
# Finally, each experiment has some monetary cost and execution time to perform the experiment, and
# the user has some known tradeoff between overall execution time and cost.
#
# CEEDesigns.jl provides tools to take these inputs and produce a set of optimal "arrangements" of experiments for each
# subset of experiments that form a Pareto front along the tradeoff between information gain and total combined cost
# (monetary and time). This allows informed decisions to be made, for example, regarding how to allocate scarce
# resources to a set of experiments that attain some acceptable level of information (or, conversely, reduce
# uncertainty below some level).
#
# The arrangements produced by the tools introduced in this tutorial are called "static" because they inherently
# assume that for each experiment, future data will deterministically yield the same information gain as the "historical" data did.
# This information gain from the "historical" data is quantified based on certain aggregate statistics.
#
# We can also consider "generative experimental designs," where the information gain is modeled as a random variable. This concept is detailed in another [tutorial](./SimpleGenerative.jl).
#
# This tutorial introduces the theoretical framework behind static experimental designs with synthetic data.
# For examples using real data, please see our other tutorials.
# ## Theoretical Framework
# ### Experiments
# Let $E = \{ e_1, \ldots, e_n\}$ be a set of $n$ experiments (i.e., $|E|=n$). Each experiment $e \in E$ has an
# associated tuple $(m_{e},t_{e})$, giving the monetary cost and time duration required to perform experiment $e$.
# 
# Consider $P(E)$, the power set of experiments (i.e., every possible subset of experiments). Each subset of
# experiments $S\in P(E)$ has an associated value $v_{S}$, which is the value of the experiments contained in $S$.
# This may be given by the loss function associated with a prediction task where the information yielded from $S$
# is used as predictor variables, or some other notion of information value.
# 
# ### Arrangements
# If experiments within a subset $S$ can be performed simultaneously (in parallel), then each $S$ may be arranged
# optimally with respect to time. An arrangement $O_{S}$ of $S$ is a partition of the experiments in $S$ such that
# the size of each partition is not larger than the maximum number of experiments that may be done in parallel.
#
# Let $l$ be the number of partitions, and $o_{i}$ a partition in $O_{S}$. Then the arrangement is a surjection from $S$
# onto $O_{S}$. If no experiments can be done in parallel, then $l=|S|$. If all experiments are done in parallel, then
# $l=1$. Other arrangements fall between these extremes.
# 
# ### Optimal Arrangements
# To find the optimal arrangement for each $S$ we need to know the cost of $O_{S}$. The monetary cost of $O_{S}$ is simply
# the sum of the costs of each experiment: $m_{O_{S}}=\sum_{e\in S} m_{e}$.
# The total time required is the sum of the maximum time *of each partition*. This is because while each partition in the
# arrangement is done in serial, experiments within partitions are done in parallel. That is, $t_{O_{S}}=\sum_{i=1}^{l} \text{max} \{ t_{e}: e \in o_{i}\}$.
# Given these costs and a parameter $\lambda$ which controls the tradeoff between monetary cost and time, the combined
# cost of an arrangement is: $\lambda m_{O_{S}} + (1-\lambda) t_{O_{S}}$.
#
# For instance, consider the experiments $S = \{e_{1},e_{2},e_{3},e_{4}\}$, with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$.
# If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement
# $O_{S} = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_{O_{S}} = 4$ and $t_{O_{S}} = 10$.
#
# However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement
# $O_{S} = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_{O_{S}} = 4$, and $t_{O_{S}} = 3 + 4 = 7$.
#
# Continuing our example and assuming a maximum of two parallel experiments, the optimal arrangement is to conduct
# $e_1$ in parallel with $e_2$, and $e_3$ with $e_4$. This results in an arrangement $O_{S} = (\{ e_1, e_2 \}, \{ e_3, e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 2 + 4 = 6$.
#
# In fact, it can be readily demonstrated that the optimal arrangement can be found by ordering the experiments in
# S in descending order according to their execution times. Consequently, the experiments are grouped sequentially
# into partitions whose size equals the maximum number of parallel experiments, except possibly for the final set,
# if the maximum number of parallel experiments does not divide $S$ evenly.
# ## Synthetic Data Example
# We now present an example of finding cost-efficient designs for synthetic data using the CEEDesigns.jl package.
#
# First we load necessary packages.
using CEEDesigns, CEEDesigns.StaticDesigns
using Combinatorics: powerset
using DataFrames
using POMDPs, POMDPTools, MCTS
# We consider a situation where there are 3 experiments, and we draw a value of their "loss function"
# or "entropy" from the uniform distribution on the unit interval for each.
#
# For each $S\in P(E)$, we simulate the information value ($v_{S}$) of $S$ as the product of
# the values for each individual experiment.
# Therefore, because smaller values are better, any subset containing multiple experiments is guaranteed to be
# more "valuable" than any component experiment.
experiments = ["e1", "e2", "e3"];
experiments_val = Dict([e => rand() for e in experiments]);
experiments_evals = Dict(map(Set.(collect(powerset(experiments)))) do s
if length(s) > 0
s => prod([experiments_val[i] for i in s])
else
return s => 1.0
end
end);
# See our other tutorial on [heart disease triage](StaticDesigns.md) for an example of using CEEDesigns.jl's built-in
# compatability with machine learning models from `MLJ.jl` to evalute performance of experiments using
# predictive accuracy as information value.
#
# Next we set up the costs $(m_{e},t_{e})$ for each experiment.
# Better experiments are more costly, both in terms of time and monetary cost. We print
# the data frame showing each experiment and its associated costs.
experiments_costs = Dict(
sort(collect(keys(experiments_val)); by = k -> experiments_val[k], rev = true) .=>
tuple.(1:3, 1:3),
);
DataFrame(;
experiment = collect(keys(experiments_costs)),
time = getindex.(values(experiments_costs), 1),
cost = getindex.(values(experiments_costs), 2),
)
# We can plot the experiments ordered by their information value.
plot_evals(
experiments_evals;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "loss",
)
# We print the data frame showing each subset of experiments and its overall information value.
df_values = DataFrame(;
S = collect.(collect(keys(experiments_evals))),
value = collect(values(experiments_evals)),
)
sort(df_values, order(:value; rev = true))
# Now we are ready to find the subsets of experiments giving an optimal tradeoff between information
# value and combined cost. CEEDesigns exports a function `efficient_designs`
# which formulates the problem of finding optimal arrangements as a Markov Decision Process and solves
# optimal arrangements for each subset on the Pareto frontier.
#
# We set $\lambda=0.5$, the parameter controlling the relative weight given to monetary versus time costs
# with the tuple `tradeoff`.
max_parallel = 2;
tradeoff = (0.5, 0.5);
designs = efficient_designs(
experiments_costs,
experiments_evals;
max_parallel = max_parallel,
tradeoff = tradeoff,
);
# Finally we may produce a plot of the set of cost-efficient experimental designs. The set of designs
# is plotted along a Pareto frontier giving tradeoff between informatio value (y-axis) and combined cost (x-axis).
# Note that because we set the maximum number of parallel experiments equal to 2, the efficient design for the complete set
# of experiments groups the experiments with long execution times together (see plot legend; each group within a partition is
# prefixed with a number).
plot_front(designs; labels = make_labels(designs), ylabel = "loss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 6960 | # # Heart Disease Triage
# Consider a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# For details on the theoretical background and notation, please see our tutorial on [static experimental designs](SimpleStatic.md), this tutorial
# is a concrete application of the tools described in that document.
# ### Application to Predictive Modeling
# Let's generalize the example from [static experimental designs](SimpleStatic.md) to the case where we want to compute the information value $v_{S}$ as the predictive
# ability of a machine learning model which uses the measurements gained from experiments in $S$ to predict some $y$ of interest.
#
# Let's introduce some formal notation.
# Consider a dataset of historical readouts over $m$ features $X = \{x_1, \ldots, x_m\}$, and let $y$ denote the target variable that we want to predict.
# Assume that each experiment $e \in E$ yields readouts over a subset $X_e \subseteq X$ of features.
# Then, for each subset $S \subseteq E$ of experiments, we may model the value of information acquired by conducting the experiments in $S$ as the accuracy of a predictive model that predicts the value of $y$ based on readouts over features in $X_S = \bigcup_{e\in S} X_e$.
# Then this accuracy is our information value $v_{S}$ of $S$.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# ## Predictive Accuracy
# The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
# We may also provide additional zero-cost features, which are always available.
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# And we specify the target for prediction.
target = "HeartDisease"
# ### Classifier
# We use [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
using MLJ
import BetaML, MLJModels
using Random: seed!
# We provide appropriate scientific types of the features.
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
# Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with our dataset:
models(matching(data, data[:, "HeartDisease"]))
# Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 3
model = classifier(; n_trees = 20, max_depth = 10)
# ### Performance Evaluation
# We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as a measure of accuracy. It is possible to provide additional keyword arguments, which will be passed to `MLJ.evaluate` (such as `measure`, shown below).
using CEEDesigns, CEEDesigns.StaticDesigns
#
seed!(1) # evaluation process generally is not deterministic
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
# We plot performance measures evaluated for subsets of experiments, sorted by performance measure.
plot_evals(
perf_eval;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "logloss",
)
# ## Cost-Efficient Designs
# We specify the cost associated with the execution of each experiment.
costs = Dict(
## experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs.
designs = efficient_designs(costs, perf_eval)
#
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
# ### Parallel Experiments
# The previous example assumed that experiments had to be run sequentially. We can see how the optimal arrangement changes if we assume multiple experiments can be run in parallel. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments_costs = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
# We set the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
# Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
## Implicit, calculates accuracies automatically.
seed!(1) # evaluation process generally is not deterministic
designs = efficient_designs(
experiments_costs,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
# As we can see, the algorithm correctly suggests running experiments in parallel.
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 13892 | # # Heart Disease Triage With Early Droupout
# Consider again a situation where a group of patients is tested for a specific disease.
# It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# Moreover, we may assume that for some patients, the evidence gathered from proxy experiments can be considered 'conclusive'. Effectively, some patients may not need any additional triage; they might be deemed healthy or require immediate commencement of treatment. By doing so, we could save significant resources.
# ## Theoretical Framework
# We take as a basis the setup and notation from the basic framework presented in the [static experimental designs tutorial](SimpleStatic.md).
# We again have a set of experiments $E$, but now assume that a set of extrinsic decision-making rules is imposed on the experimental readouts.
# If the experimental evidence acquired for a given entity satisfies a specific criterion, that entity is then removed from the triage.
# However, other entities within the batch will generally continue in the experimental process.
# In general, the process of establishing such rules is largely dependent on the specific problem and requires comprehensive understanding of the subject area.
# We denote the expected fraction of entities that remain in the triage after conducting a set $S$ of experiments as the filtration rate, $f_S$. In the context of disease triage, this can be interpreted as the fraction of patients for whom the experimental evidence does not provide a 'conclusive' result.
# As previously, each experiment $e$ incurs a cost $(m_e, t_e)$. Again, we let $O_{S}$ denote an arrangement of experiments in $S$.
# Given a subset $S$ of experiments and their arrangement $O_{S}$, the total (discounted) monetary cost and execution time of the experimental design is given as $m_o = \sum_{i=1}^{l} r_{S_{i-1}}\sum_{e\in o_i} m_e$ and $t_o = \sum_{i=1}^{l} \max \{ t_e : e\in o_i\}$, respectively.
# Importantly, the new factor $r_{S_{i-1}}$ models the fact that a set of entities may have dropped out in the previous experiments, hence saving the resources on running the subsequent experiments.
# We note that these computations are based on the assumption that monetary cost is associated with the analysis of a single experimental entity, such as a patient. Therefore, the total monetary cost obtained for a specific arrangement is effectively the ["expected"](https://en.wikipedia.org/wiki/Expected_value) monetary cost, adjusted for a single entity. Conversely, we suppose that all entities can be concurrently examined in a specific experiment. As such, the total execution time is equivalent to the longest time until all experiments within an arrangement are finished or all entities have been eliminated (which ocurrs when the filtration rate the experiments conducted so far is zero). Importantly, this distinctly differs from calculating the 'expected lifespan' of an entity in the triage.
# For instance, consider the experiments $e_1,\, e_2,\, e_3$, and $e_4$ with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$, and filtration rates $0.9,\,0.8,\,0.7$, and $0.6$. For subsets of experiments, we simply assume that the filtration rates multiply, thereby treating the experiments as independent binary discriminators. In other words, the filtration rate for a set $S=\{ e_1, e_3 \}$ would equal $f_S = 0.9 * 0.7 = 0.63$.
# If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement $o = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_o = 1 + 0.9 * 1 + 0.72 * 1 + 0.504 * 1 = 3.124$ and $t_o = 10$.
# However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement $o = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_o = 2 + 0.63 * 2 = 3.26$, and $t_o = 3 + 4 = 7$.
# Given the constraint on the maximum number of parallel experiments, we construct an arrangement $o$ of experiments $S$ such that, for a fixed tradeoff $\lambda$ between monetary cost and execution time, the expected combined cost $c_{(o, \lambda)} = \lambda m_o + (1-\lambda) t_o$ is minimized. Significantly, our objective is to leverage the filtration rates within the experimental arrangement.
# ### A Note on Optimal Arrangements
# In situations when experiments within a set $S$ are executed sequentially, i.e., one after the other, it can be demonstrated that the experiments should be arranged in ascending order by $\frac{\lambda m_e + (1-\lambda) t_e}{1-f_e}$.
# Continuing our example and assuming that the experiments are conducted sequentially, the optimal arrangement $o$ would be to run experiments $e_4$ through $e_1$, yielding $m_o = 2.356$.
# When we allow simultaneous execution of experiments, the problem turns more complicated, and we currently are not aware of an 'analytical' solution for it. Instead, we proposed approximating the 'optimal' arrangement as the 'optimal' policy found for a particular Markov decision process, in which:
# - _state_ is the set of experiments that have been conducted thus far,
# - _actions_ are subsets of experiments which have not been conducted yet; the size of these subsets is restricted by the maximum number of parallel experiments;
# - _reward_ is a combined monetary cost and execution time, discounted by the filtration rate of previously conducted experiments.
# Provided we know the information values $v_S$, filtration rates $r_S$, and experimental costs $c_S$ for each set of experiments $S$, we find a collection of Pareto-efficient experimental designs that balance both the implied value of information and the experimental cost.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# In order to adapt the dataset to the current context, we can assume that, for every experiment, a medical specialist determined a range for 'conclusive' and 'inconclusive' outputs. This determination could be based on, say, optimizing the precision and recall factors of the resultant discriminative model. As an example, consider [A novel approach for heart disease prediction using strength scores with significant predictors](https://d-nb.info/1242792767/34) where rule mining for heart disease prediction is considered.\
# It should be noted that the readout ranges defined below are entirely fictional.
inconclusive_regions = Dict(
"ChestPainType" => ["NAP", "ASY"],
"RestingBP" => (50, 150),
"ExerciseAngina" => ["N"],
"FastingBS" => [0],
"RestingECG" => ["Normal"],
"MaxHR" => (50, 120),
"Cholesterol" => (0, 240),
"Oldpeak" => (-2.55, 2.55),
)
# We apply the rules to derive a binary dataset where 'true' signifies that the readout was inconclusive, requiring them to remain in the triage.
data_binary = DataFrame();
for colname in names(data[!, Not("HeartDisease")])
if haskey(inconclusive_regions, colname)
if inconclusive_regions[colname] isa Vector
data_binary[!, colname] =
map(x -> x ∈ inconclusive_regions[colname], data[!, colname])
else
lb, ub = inconclusive_regions[colname]
data_binary[!, colname] = map(x -> lb <= x <= ub, data[!, colname])
end
else
data_binary[!, colname] = trues(nrow(data))
end
end
data_binary[1:10, :]
# ## Discriminative Power and Filtration Rates
# In this scenario, we model the value of information $v_S$ acquired by conducting a set of experiments as the ratio of patients for whom the results across the experiments in $S$ were 'inconclusive', i.e., $|\cap_{e\in S}\{ \text{patient} : \text{inconclusive in } e \}| / |\text{patients}|$. Essentially, the very same measure is used here to estimate the filtration rate.
# The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
# We may also provide additional zero-cost features, which are always available.
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# For binary datasets, we may use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the discriminative power of subsets of experiments.
using CEEDesigns, CEEDesigns.StaticDesigns
#
perf_eval = evaluate_experiments(experiments, data_binary; zero_cost_features)
# Note that for each subset of experiments, the function returns a named tuple with fields `loss` and `filtration`.
# We plot discriminative power evaluated for subsets of experiments.
plot_evals(perf_eval; ylabel = "discriminative power")
# ## Cost-Efficient Designs
# We specify the cost associated with the execution of each experiment.
costs = Dict(
## experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs. Note that the filtration is enabled implicitly since we provided the filtration rates within `perf_eval`. Another form of `perf_eval` would be `subset of experiments => information measure`, in which case the filtration would equal one. That is, no dropout would be considered.
designs = efficient_designs(costs, perf_eval)
#
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
# Let us compare the above with the efficient front with disabled filtration.
## pass performance eval with discarded filtration rates (defaults to 1)
designs_no_filtration = efficient_designs(costs, Dict(k => v.loss for (k, v) in perf_eval))
#
using Plots
p = scatter(
map(x -> x[1][1], designs_no_filtration),
map(x -> x[1][2], designs_no_filtration);
label = "designs with filtration disabled",
c = :blue,
mscolor = nothing,
fontsize = 16,
)
scatter!(
p,
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
xlabel = "combined cost",
ylabel = "discriminative power",
label = "designs with filtration enabled",
c = :teal,
mscolor = nothing,
fontsize = 16,
)
# ## Arrangement of a Set of Experiments
# Importantly, the total execution cost of an experiment is generally not the sum of costs associated to each individual experiment. In fact, a non-zero dropout rate (`filtration < 1`) discounts the expected cost of subsequent experiments. As discussed previously, we are not aware of an 'analytical' solution to this problem.
# Instead, we approximate the 'optimal' arrangement as the 'optimal' policy for a particular Markov decision process. This can be accomplished using, for instance, the [Monte Carlo Tree Search algorithm](https://github.com/JuliaPOMDP/MCTS.jl) as implemented in the [POMDPs.jl](http://juliapomdp.github.io/POMDPs.jl/latest/) package.
# The following is a visualisation of the DPW search tree that was used to find an optimal arrangement for a set of experiments yielding the highest information value.
using MCTS, D3Trees
experiments = Set(vcat.(designs[end][2].arrangement...)[1])
(; planner) = CEEDesigns.StaticDesigns.optimal_arrangement(
costs,
perf_eval,
experiments;
mdp_kwargs = (; tree_in_info = true),
)
_, info = action_info(planner, Set{String}())
t = D3Tree(info[:tree]; init_expand = 2)
#
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
# ### Parallel Experiments
# We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments_costs = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
# We provide the maximum number of concurrent experiments. Additionally, we specify the tradeoff between monetary cost and execution time - in our case, we aim to minimize the execution time.
# Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
## Implicit, calculates accuracies automatically
designs = efficient_designs(
experiments_costs,
data_binary;
eval_options = (; zero_cost_features),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
# As we can see, the algorithm correctly suggests running experiments in parallel.
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 263 | module CEEDesigns
using DataFrames, Plots
export front, plot_front
export make_labels, plot_evals
# make Pareto fronts
include("fronts.jl")
# experimental designs
include("StaticDesigns/StaticDesigns.jl")
include("GenerativeDesigns/GenerativeDesigns.jl")
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 3944 | """
front(v)
front(f, v; atol1=0, atol2=0)
Construct a Pareto front of `v`. Elements of `v` will be masked by `f` in the computation.
The first and second (objective) coordinates have to differ by at least `atol1`, `atol2`, respectively, relatively to the latest point on the front.
# Examples
```jldocstest
v = [(1,2), (2,3), (2,1)]
front(v)
# output
[(1, 2), (2, 1)]
```
```jldoctest
v = [(1, (1, 2)), (2, (2, 3)), (3, (2, 1))]
front(x -> x[2], v)
# output
[(1, (1, 2)), (3, (2, 1))]
```
```jldoctest
v = [(1, 2), (2, 1.99), (3, 1)]
front(v; atol2 = 0.2)
# output
[(1, 2), (3, 1)]
```
"""
function front end
function front(v::T; atol1::Float64 = 0.0, atol2::Float64 = atol1) where {T<:AbstractVector}
return front(identity, v; atol1, atol2)
end
function front(
f::F,
v::T;
atol1::Float64 = 0.0,
atol2::Float64 = atol1,
) where {F<:Function,T<:AbstractVector}
# dict sort
v_sorted = sort(
v;
lt = (x, y) ->
(f(x)[1] < f(y)[1] || (f(x)[1] == f(y)[1] && f(x)[2] <= f(y)[2])),
)
# check if the second coordinate drops below the second coordinate of the last non-dominated point
ix_front = 1
ix_current = 2
while ix_current <= length(v_sorted)
if (f(v_sorted[ix_current])[2] < f(v_sorted[ix_front])[2] - atol2) &&
(f(v_sorted[ix_current])[1] > f(v_sorted[ix_front])[1] + atol1)
ix_front = ix_current
ix_current += 1
else
deleteat!(v_sorted, ix_current)
end
end
return v_sorted
end
"""
plot_front(designs; grad=cgrad(:Paired_12), xlabel, ylabel, labels=get_labels(designs))
Render scatter plot of efficient designs, as returned from `efficient_designs`.
You may optionally specify a color gradient, to draw the colors from.
# Examples
```julia
designs = efficient_designs(experiment, state)
plot_front(designs)
plot_front(designs; grad = cgrad(:Paired_12))
```
"""
function plot_front(
designs;
grad = cgrad(:Paired_12),
xlabel = "combined cost",
ylabel = "information measure",
labels = make_labels(designs),
)
xs = map(x -> x[1][1], designs)
ys = map(x -> x[1][2], designs)
p = scatter(
[xs[1]],
[ys[1]];
xlabel,
ylabel,
label = labels[1],
c = grad[1],
mscolor = nothing,
fontsize = 16,
)
for i = 2:length(designs)
scatter!(p, [xs[i]], [ys[i]]; label = labels[i], c = grad[i], mscolor = nothing)
end
return p
end
"""
make_labels(designs)
Make labels used plotting of experimental designs.
"""
function make_labels(designs)
return map(designs) do x
if !haskey(x[2], :arrangement) || isempty(x[2].arrangement)
"∅"
else
labels =
["$i: " * join(group, ", ") for (i, group) in enumerate(x[2].arrangement)]
join(labels, "; ")
end
end
end
"""
plot_evals(evals; f, ylabel="information measure")
Create a stick plot that visualizes the performance measures evaluated for subsets of experiments.
Argument `evals` should be the output of [`evaluate_experiments`](@ref CEEDesigns.StaticDesigns.evaluate_experiments) and the kwarg `f` (if provided) is a function that
should take as input `evals` and return a list of its keys in the order to be plotted on the x-axis.
By default they are sorted by length.
"""
function plot_evals(
evals;
ylabel = "information measure",
f = x -> sort(collect(keys(x)); by = length),
)
xs = f(evals)
ys = map(xs) do x
return evals[x] isa Number ? evals[x] : evals[x].loss
end
xformatter = i -> isempty(xs[Int(i)]) ? "∅" : join(xs[Int(i)], ", ")
return sticks(
1:length(evals),
ys;
ticks = 1:length(evals),
xformatter,
guidefontsize = 8,
tickfontsize = 8,
ylabel,
label = nothing,
xrotation = 30,
)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 9016 | """
EfficientValueMDP(costs; sampler, value, evidence=Evidence(), <keyword arguments>)
Structure that parametrizes the experimental decision-making process. It is used in the object interface of POMDPs.
In this experimental setup, our objective is to maximize the value of the experimental evidence (such as clinical utility), adjusted for experimental costs.
Internally, the reward associated with a particular experimental `evidence` and with total accumulated `monetary_cost` and (optionally) `execution_time` is computed as `value(evidence) - costs_tradeoff' * [monetary_cost, execution_time]`.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
# Keyword Arguments
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `value`: a function of `(evidence)`; it quantifies the utility of experimental evidence.
- `evidence=Evidence()`: initial experimental evidence.
- `max_parallel`: maximum number of parallel experiments.
- `discount`: this is the discounting factor utilized in reward computation.
"""
struct EfficientValueMDP <: POMDPs.MDP{State,Vector{String}}
# initial state
initial_state::State
# actions and costs
costs::Dict{String,ActionCost}
# maximum number of assays that can be run in parallel
max_parallel::Int
# discount
discount::Float64
## sample readouts from the posterior
sampler::Function
## measure of utility
value::Function
function EfficientValueMDP(
costs;
sampler,
value,
evidence = Evidence(),
max_parallel::Int = 1,
discount = 1.0,
)
state = State((evidence, Tuple(zeros(2))))
# Check if `sampler`, `uncertainty` are compatible
@assert hasmethod(sampler, Tuple{Evidence,Vector{String},AbstractRNG}) """`sampler` must implement a method accepting `(evidence, readout features, rng)` as its arguments."""
@assert hasmethod(value, Tuple{Evidence,Vector{Float64}}) """`value` must implement a method accepting `(evidence, costs)` as its argument."""
# actions and their costs
costs = Dict{String,ActionCost}(
try
if action isa Pair && action[2] isa Pair
string(action[1]) => (;
costs = Tuple(Float64[action[2][1]..., 0][1:2]),
features = convert(Vector{String}, action[2][2]),
)
elseif action isa Pair
string(action[1]) => (;
costs = Tuple(Float64[action[2]..., 0][1:2]),
features = String[action[1]],
)
else
error()
end
catch
error("could not parse $action as an action")
end for action in costs
)
return new(state, costs, max_parallel, discount, sampler, value)
end
end
function POMDPs.actions(m::EfficientValueMDP, state)
all_actions = filter!(collect(keys(m.costs))) do a
return !isempty(m.costs[a].features) &&
!in(first(m.costs[a].features), keys(state.evidence))
end
return collect(powerset(all_actions, 1, m.max_parallel))
end
POMDPs.isterminal(m::EfficientValueMDP, state) = isempty(actions(m, state))
POMDPs.discount(m::EfficientValueMDP) = m.discount
POMDPs.initialstate(m::EfficientValueMDP) = Deterministic(m.initial_state)
function POMDPs.transition(m::EfficientValueMDP, state, action_set)
# costs
cost_m, cost_t = 0.0, 0.0
for experiment in action_set
cost_m += m.costs[experiment].costs[1] # monetary cost
cost_t = max(cost_t, m.costs[experiment].costs[2]) # time
end
# readout features
features = vcat(map(action -> m.costs[action].features, action_set)...)
ImplicitDistribution() do rng
# sample readouts from history
observation = m.sampler(state.evidence, features, rng)
# create new evidence, add new information
return merge(state, observation, (cost_m, cost_t))
end
end
function POMDPs.reward(m::EfficientValueMDP, previous_state::State, _, state::State)
return m.value(state.evidence, state.costs) -
m.value(previous_state.evidence, previous_state.costs)
end
"""
efficient_value(costs; sampler, value, evidence=Evidence(), <keyword arguments>)
Estimate the maximum value of experimental evidence (such as clinical utility), adjusted for experimental costs.
Internally, an instance of the `EfficientValueMDP` structure is created and a summary over `repetitions` runoffs is returned.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
# Keyword Arguments
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `value`: a function of `(evidence, (monetary costs, execution time))`; it quantifies the utility of experimental evidence.
- `evidence=Evidence()`: initial experimental evidence.
- `solver=default_solver`: a POMDPs.jl compatible solver used to solve the decision process. The default solver is [`DPWSolver`](https://juliapomdp.github.io/MCTS.jl/dev/dpw/).
- `repetitions=0`: number of runoffs used to estimate the expected experimental cost.
- `mdp_options`: a `NamedTuple` of additional keyword arguments that will be passed to the constructor of [`EfficientValueMDP`](@ref).
# Example
```julia
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
value = (evidence, costs) -> (1 - uncertainty(evidence) + 0.005 * sum(costs));
# initialize evidence
evidence = Evidence("Age" => 35, "Sex" => "M")
# set up solver (or use default)
solver =
GenerativeDesigns.DPWSolver(; n_iterations = 10_000, depth = 3, tree_in_info = true)
design = efficient_value(
experiments;
sampler,
value,
evidence,
solver, # planner
mdp_options = (; max_parallel = 1),
repetitions = 5,
)
```
"""
function efficient_value(
costs;
sampler,
value,
evidence = Evidence(),
solver = default_solver,
repetitions = 0,
mdp_options = (;),
)
mdp = EfficientValueMDP(costs; sampler, value, evidence, mdp_options...)
# planner
planner = solve(solver, mdp)
action, info = action_info(planner, mdp.initial_state)
if repetitions > 0
queue = [Sim(mdp, planner) for _ = 1:repetitions]
stats = run_parallel(queue) do _, hist
monetary_cost, time = hist[end][:s].costs
return (;
monetary_cost,
time,
adjusted_value = value(
mdp.initial_state.evidence,
mdp.initial_state.costs,
) + discounted_reward(hist),
terminal_value = value(hist[end][:s].evidence, hist[end][:s].costs),
)
end
if haskey(info, :tree)
return (
value(mdp.initial_state.evidence, mdp.initial_state.costs) + info[:best_Q],
(;
planner,
arrangement = [action],
monetary_cost = mean(stats.monetary_cost),
time = mean(stats.time),
terminal_value = mean(stats.terminal_value),
tree = info[:tree],
stats,
),
)
else
(
value(mdp.initial_state.evidence, mdp.initial_state.costs) + info[:best_Q],
(;
planner,
arrangement = [action],
monetary_cost = mean(stats.monetary_cost),
time = mean(stats.time),
terminal_value = mean(stats.terminal_value),
stats,
),
)
end
else
if haskey(info, :tree)
return (
value(mdp.initial_state.evidence, mdp.initial_state.costs) + info[:best_Q],
(; planner, arrangement = [action], tree = info[:tree]),
)
else
(
value(mdp.initial_state.evidence, mdp.initial_state.costs) + info[:best_Q],
(; planner, arrangement = [action]),
)
end
end
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1760 | module GenerativeDesigns
using POMDPs
using POMDPTools
using Combinatorics
using DataFrames, ScientificTypes
using LinearAlgebra
using Statistics
using StatsBase: Weights, countmap, entropy, sample
using Random: default_rng, AbstractRNG
using MCTS
using ..CEEDesigns: front
export UncertaintyReductionMDP, DistanceBased
export QuadraticDistance, DiscreteDistance, SquaredMahalanobisDistance
export Exponential
export Variance, Entropy
export Evidence, State
export efficient_design, efficient_designs
export efficient_value
"""
Represent experimental evidence as an immutable dictionary.
"""
const Evidence = Base.ImmutableDict{String,Any}
function Base.merge(d::Evidence, dsrc::Dict)
for (k, v) in dsrc
d = Evidence(d, k, v)
end
return d
end
Evidence(p1::Pair, pairs::Pair...) = merge(Evidence(), Dict(p1, pairs...))
"""
Represent experimental state as a tuple of experimental costs and evidence.
"""
const State = NamedTuple{(:evidence, :costs),Tuple{Evidence,NTuple{2,Float64}}}
function Base.merge(state::State, evidence, costs)
return State((merge(state.evidence, evidence), state.costs .+ costs))
end
include("distancebased.jl")
"""
Represent action as a named tuple `(; costs=(monetary cost, time), features)`.
"""
const ActionCost = NamedTuple{(:costs, :features),<:Tuple{NTuple{2,Float64},Vector{String}}}
const const_bigM = 1_000_000
const default_solver = DPWSolver(; n_iterations = 100_000, tree_in_info = true)
# minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
include("UncertaintyReductionMDP.jl")
# maximize the value of the experimental evidence (such as clinical utility), adjusted for experimental costs.
include("EfficientValueMDP.jl")
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 14160 | """
UncertaintyReductionMDP(costs; sampler, uncertainty, threshold, evidence=Evidence(), <keyword arguments>)
Structure that parametrizes the experimental decision-making process. It is used in the object interface of POMDPs.
In this experimental setup, our objective is to minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
Internally, a state of the decision process is modeled as a tuple `(evidence::Evidence, [total accumulated monetary cost, total accumulated execution time])`.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
# Keyword Arguments
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `uncertainty`: a function of `evidence`; it returns the measure of variance or uncertainty about the target variable, conditioned on the experimental evidence acquired so far.
- `threshold`: a number representing the acceptable level of uncertainty about the target variable.
- `evidence=Evidence()`: initial experimental evidence.
- `costs_tradeoff`: tradeoff between monetary cost and execution time of an experimental designs, given as a tuple of floats.
- `max_parallel`: maximum number of parallel experiments.
- `discount`: this is the discounting factor utilized in reward computation.
- `bigM`: it refers to the penalty that arises in a scenario where further experimental action is not an option, yet the uncertainty exceeds the allowable limit.
- `max_experiments`: this denotes the maximum number of experiments that are permissible to be conducted.
"""
struct UncertaintyReductionMDP <: POMDPs.MDP{State,Vector{String}}
# initial state
initial_state::State
# uncertainty threshold
threshold::Float64
# actions and costs
costs::Dict{String,ActionCost}
# monetary cost v. time tradeoff
costs_tradeoff::NTuple{2,Float64}
# maximum number of assays that can be run in parallel
max_parallel::Int
# discount
discount::Float64
# max experiments
max_experiments::Int64
# penalty if max number of experiments exceeded
bigM::Int64
## sample readouts from the posterior
sampler::Function
## measure of uncertainty about the ground truth
uncertainty::Function
function UncertaintyReductionMDP(
costs;
sampler,
uncertainty,
threshold,
evidence = Evidence(),
costs_tradeoff = (1, 0),
max_parallel::Int = 1,
discount = 1.0,
bigM = const_bigM,
max_experiments = bigM,
)
state = State((evidence, Tuple(zeros(2))))
# check if `sampler`, `uncertainty` are compatible
@assert hasmethod(sampler, Tuple{Evidence,Vector{String},AbstractRNG}) """`sampler` must implement a method accepting `(evidence, readout features, rng)` as its arguments."""
@assert hasmethod(uncertainty, Tuple{Evidence}) """`uncertainty` must implement a method accepting `evidence` as its argument."""
# actions and their costs
costs = Dict{String,ActionCost}(
try
if action isa Pair && action[2] isa Pair
string(action[1]) => (;
costs = Tuple(Float64[action[2][1]..., 0][1:2]),
features = convert(Vector{String}, action[2][2]),
)
elseif action isa Pair
string(action[1]) => (;
costs = Tuple(Float64[action[2]..., 0][1:2]),
features = String[action[1]],
)
else
error()
end
catch
error("could not parse $action as an action")
end for action in costs
)
return new(
state,
threshold,
costs,
costs_tradeoff,
max_parallel,
discount,
max_experiments,
bigM,
sampler,
uncertainty,
)
end
end
"""
A penalized action that results in a terminal state, e.g., in situations where conducting additional experiments is not possible, but the level of uncertainty remains above an acceptable threshold.
"""
const eox = "EOX"
function POMDPs.actions(m::UncertaintyReductionMDP, state)
all_actions = filter!(collect(keys(m.costs))) do a
return !isempty(m.costs[a].features) &&
!in(first(m.costs[a].features), keys(state.evidence))
end
if !isempty(all_actions) && (length(state.evidence) < m.max_experiments)
collect(powerset(all_actions, 1, m.max_parallel))
else
[[eox]]
end
end
function POMDPs.isterminal(m::UncertaintyReductionMDP, state)
return haskey(state.evidence, eox) || (m.uncertainty(state.evidence) <= m.threshold)
end
POMDPs.discount(m::UncertaintyReductionMDP) = m.discount
POMDPs.initialstate(m::UncertaintyReductionMDP) = Deterministic(m.initial_state)
function POMDPs.transition(m::UncertaintyReductionMDP, state, action_set)
if action_set == [eox]
Deterministic(merge(state, Dict(eox => -1), (0.0, 0.0)))
else
# costs
cost_m, cost_t = 0.0, 0.0
for experiment in action_set
cost_m += m.costs[experiment].costs[1] # monetary cost
cost_t = max(cost_t, m.costs[experiment].costs[2]) # time
end
# readout features
features = vcat(map(action -> m.costs[action].features, action_set)...)
ImplicitDistribution() do rng
# sample readouts from history
observation = m.sampler(state.evidence, features, rng)
# create new evidence, add new information
return merge(state, observation, (cost_m, cost_t))
end
end
end
function POMDPs.reward(m::UncertaintyReductionMDP, _, action, state)
if action == [eox]
-m.bigM
else
-sum(state.costs .* m.costs_tradeoff)
end
end
"""
efficient_design(costs; sampler, uncertainty, threshold, evidence=Evidence(), <keyword arguments>)
In the uncertainty reduction setup, minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
# Keyword Arguments
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `uncertainty`: a function of `evidence`; it returns the measure of variance or uncertainty about the target variable, conditioned on the experimental evidence acquired so far.
- `threshold`: uncertainty threshold.
- `evidence=Evidence()`: initial experimental evidence.
- `solver=default_solver`: a POMDPs.jl compatible solver used to solve the decision process. The default solver is [`DPWSolver`](https://juliapomdp.github.io/MCTS.jl/dev/dpw/).
- `repetitions=0`: number of runoffs used to estimate the expected experimental cost.
- `mdp_options`: a `NamedTuple` of additional keyword arguments that will be passed to the constructor of [`UncertaintyReductionMDP`](@ref).
- `realized_uncertainty=false`: whenever the initial state uncertainty is below the selected threshold, return the actual uncertainty of this state.
# Example
```julia
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
# initialize evidence
evidence = Evidence("Age" => 35, "Sex" => "M")
# set up solver (or use default)
solver = GenerativeDesigns.DPWSolver(; n_iterations = 60_000, tree_in_info = true)
designs = efficient_design(
costs;
experiments,
sampler,
uncertainty,
threshold = 0.6,
evidence,
solver, # planner
mdp_options = (; max_parallel = 1),
repetitions = 5,
)
```
"""
function efficient_design(
costs;
sampler,
uncertainty,
threshold,
evidence = Evidence(),
solver = default_solver,
repetitions = 0,
realized_uncertainty = false,
mdp_options = (;),
)
mdp = UncertaintyReductionMDP(
costs;
sampler,
uncertainty,
threshold,
evidence,
mdp_options...,
)
if isterminal(mdp, mdp.initial_state)
return (
(0.0, if realized_uncertainty
mdp.uncertainty(mdp.initial_state.evidence)
else
threshold
end),
(; monetary_cost = 0.0, time = 0.0),
)
else
# planner
planner = solve(solver, mdp)
action, info = action_info(planner, mdp.initial_state)
if repetitions > 0
queue = [Sim(mdp, planner) for _ = 1:repetitions]
stats = run_parallel(queue) do _, hist
monetary_cost, time = hist[end][:s].costs
return (;
monetary_cost,
time,
combined_cost = -discounted_reward(hist),
actions = hist[:a],
)
end
if haskey(info, :tree)
return (
(-info[:best_Q], threshold),
(;
planner,
arrangement = [action],
monetary_cost = mean(stats.monetary_cost),
time = mean(stats.time),
tree = info[:tree],
stats,
),
)
else
return (
(-info[:best_Q], threshold),
(;
planner,
arrangement = [action],
monetary_cost = mean(stats.monetary_cost),
time = mean(stats.time),
stats,
),
)
end
else
if haskey(info, :tree)
return (
(-info[:best_Q], threshold),
(; planner, arrangement = [action], tree = info[:tree]),
)
else
return ((-info[:best_Q], threshold), (; planner, arrangement = [action]))
end
end
end
end
"""
efficient_designs(costs; sampler, uncertainty, thresholds, evidence=Evidence(), <keyword arguments>)
In the uncertainty reduction setup, minimize the expected experimental resource spend over a range of uncertainty thresholds, and return the set of Pareto-efficient designs in the dimension of cost and uncertainty threshold.
Internally, an instance of the `UncertaintyReductionMDP` structure is created for every selected uncertainty threshold and the corresponding runoffs are simulated.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
# Keyword Arguments
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `uncertainty`: a function of `evidence`; it returns the measure of variance or uncertainty about the target variable, conditioned on the experimental evidence acquired so far.
- `thresholds`: number of thresholds to consider uniformly in the range between 0 and 1, inclusive.
- `evidence=Evidence()`: initial experimental evidence.
- `solver=default_solver`: a POMDPs.jl compatible solver used to solve the decision process. The default solver is [`DPWSolver`](https://juliapomdp.github.io/MCTS.jl/dev/dpw/).
- `repetitions=0`: number of runoffs used to estimate the expected experimental cost.
- `mdp_options`: a `NamedTuple` of additional keyword arguments that will be passed to the constructor of [`UncertaintyReductionMDP`](@ref).
- `realized_uncertainty=false`: whenever the initial state uncertainty is below the selected threshold, return the actual uncertainty of this state.
# Example
```julia
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
# initialize evidence
evidence = Evidence("Age" => 35, "Sex" => "M")
# set up solver (or use default)
solver = GenerativeDesigns.DPWSolver(; n_iterations = 60_000, tree_in_info = true)
designs = efficient_designs(
costs;
experiments,
sampler,
uncertainty,
thresholds = 6,
evidence,
solver, # planner
mdp_options = (; max_parallel = 1),
repetitions = 5,
)
```
"""
function efficient_designs(
costs;
sampler,
uncertainty,
thresholds,
evidence = Evidence(),
solver = default_solver,
repetitions = 0,
realized_uncertainty = false,
mdp_options = (;),
)
designs = []
for threshold in range(0.0, 1.0, thresholds)
@info "Current threshold level : $threshold"
push!(
designs,
efficient_design(
costs;
sampler,
uncertainty,
threshold,
evidence,
solver,
repetitions,
realized_uncertainty,
mdp_options,
),
)
end
## rewrite
return front(x -> x[1], designs)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 12219 | # function to compute the distance between a readout and column entries
"""
QuadraticDistance(; λ=1, standardize=true)
This returns an anonymous function `(x, col; prior) -> λ * (x .- col).^2 / σ`.
If `standardize` is set to `true`, `σ` represents `col`'s variance calculated in relation to `prior`, otherwise `σ` equals one.
"""
function QuadraticDistance(; λ = 1, standardize = true)
σ = nothing
function (x, col; prior = ones(length(col)))
if isnothing(σ)
σ = standardize ? var(col, Weights(prior); corrected = false) : 1
end
return λ * (x .- col) .^ 2 / σ
end
end
"""
DiscreteDistance(; λ=1)
Return an anonymous function `(x, col) -> λ * (x .== col)`.
"""
DiscreteDistance(; λ = 1) = function (x, col; _...)
return map(y -> y == x ? λ : 0.0, col)
end
# Default similarity functional
"""
Exponential(; λ=1)
Return an anonymous function `x -> exp(-λ * sum(x; init=0))`.
"""
Exponential(; λ = 1 / 2) = x -> exp(-λ * x)
# default uncertainty functionals
function compute_variance(data::AbstractVector; weights)
var(data, Weights(weights); corrected = false)
end
function compute_variance(data; weights)
sum(var(Matrix(data), Weights(weights), 1; corrected = false))
end
"""
Variance()
Return a function of `(data; prior)`. When this function is called as part of an instantiation procedure in [`DistanceBased`](@ref),
it returns an internal function of `weights` that computes the fraction of variance in the data, relative to the variance calculated with respect to a specified `prior`.
"""
Variance() = function (data; prior)
initial = compute_variance(data; weights = prior)
return weights -> (compute_variance(data; weights) / initial)
end
function compute_entropy(labels; weights)
aggregate_weights = collect(values(countmap(labels, Weights(weights))))
return entropy(aggregate_weights ./ sum(aggregate_weights))
end
"""
Entropy()
Return a function of `(labels; prior)`. When this function is called as part of an instantiation procedure in [`DistanceBased`](@ref),
it returns an internal function of `weights` that computes the fraction of information entropy, relative to the entropy calculated with respect to a specified `prior`.
"""
function Entropy()
function (labels; prior)
@assert elscitype(labels) <: Multiclass "labels must be of `Multiclass` scitype, but `elscitype(labels)=$(elscitype(labels))`"
initial = compute_entropy(labels; weights = prior)
return weights -> (compute_entropy(labels; weights) / initial)
end
end
# Return a function that calculates the sum of distances in each row, column-wise, and applies weights based on the prior.
function sum_of_distances(data::DataFrame, targets::Vector, distances; prior::Weights)
function (evidence::Evidence)
if isempty(evidence)
return zeros(nrow(data))
else
array_distances = zeros((nrow(data), length(evidence)))
for (i, colname) in enumerate(keys(evidence))
if colname ∈ targets
continue
else
array_distances[:, i] .=
distances[colname](evidence[colname], data[!, colname]; prior)
end
end
distances_sum = vec(sum(array_distances; init = 0.0, dims = 2))
return distances_sum
end
end
end
"""
SquaredMahalanobisDistance(; diagonal=0)
Returns a function that computes [squared Mahalanobis distance](https://en.wikipedia.org/wiki/Mahalanobis_distance) between each row of `data` and the evidence.
For a singular covariance matrix, consider adding entries to the matrix's diagonal via the `diagonal` keyword.
To accommodate missing values, we have implemented an approach described in https://www.jstor.org/stable/3559861, on page 285.
# Arguments
- `diagonal`: A scalar to be added to the diagonal entries of the covariance matrix.
# Returns
It returns a high-level function of `(data, targets, prior)`.
When called, that function will return an internal function `compute_distances` that takes an `Evidence` and computes the squared Mahalanobis distance based on the input data and the evidence.
"""
function SquaredMahalanobisDistance(; diagonal = 0)
function (data, targets, prior)
non_targets = setdiff(names(data), targets)
if !all(t -> t <: Real, eltype.(eachcol(data[!, non_targets])))
@warn "Not all column types in the predictor matrix are numeric ($(eltype.(eachcol(data)))). This may cause errors."
end
Λ = Dict(
Set(features) => begin
Σ = cov(Matrix(data[!, features]), Weights(prior); corrected = false)
# Add diagonal entries.
foreach(i -> Σ[i, i] += diagonal, axes(Σ, 1))
inv(Σ)
end for features in powerset(non_targets, 1, length(non_targets))
)
compute_distances = function (evidence::Evidence)
evidence_keys = collect(keys(evidence) ∩ non_targets)
if length(evidence_keys) == 0
return zeros(nrow(data))
end
vec_evidence = map(k -> evidence[k], evidence_keys)
factor_p_q = length(non_targets) / length(evidence_keys)
distances = map(eachrow(data)) do row
# We retrieve the precomputed inverse of the covariance matrix coresponding to the "observed part"
# See #12 and, in particular, https://www.jstor.org/stable/3559861
Λ_marginal = Λ[Set(evidence_keys)]
factor_p_q * dot(
(vec_evidence - Vector(row[evidence_keys])),
Λ_marginal * (vec_evidence - Vector(row[evidence_keys])),
)
end
return distances
end
return compute_distances
end
end
"""
DistanceBased(data; target, uncertainty=Entropy(), similarity=Exponential(), distance=Dict(); prior=ones(nrow(data)))
Compute distances between experimental evidence and historical readouts, and apply a 'similarity' functional to obtain probability mass for each row.
Consider using [`QuadraticDistance`](@ref), [`DiscreteDistance`](@ref), and [`SquaredMahalanobisDistance`](@ref).
# Return value
A named tuple with the following fields:
- `sampler`: a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator; it returns a dictionary mapping the features to outcomes.
- `uncertainty`: a function of `evidence`; it returns the measure of variance or uncertainty about the target variable, conditioned on the experimental evidence acquired so far.
- `weights`: a function of `evidence`; it returns probabilities (posterior) acrss the rows in `data`.
# Arguments
- `data`: a dataframe with historical data.
- `target`: target column name or a vector of target columns names.
# Keyword Argumets
- `uncertainty`: a function that takes the subdataframe containing columns in targets along with prior, and returns an anonymous function taking a single argument (a probability vector over observations) and returns an uncertainty measure over targets.
- `similarity`: a function that, for each row, takes distances between `row[col]` and `readout[col]`, and returns a non-negative probability mass for the row.
- `distance`: a dictionary of pairs `colname => similarity functional`, where a similarity functional must implement the signature `(readout, col; prior)`. Defaults to [`QuadraticDistance`](@ref) and [`DiscreteDistance`](@ref) for `Continuous` and `Multiclass` scitypes, respectively.
- `prior`: prior across rows, uniform by default.
- `filter_range`: a dictionary of pairs `colname => (lower bound, upper bound)`. If there's data in the current state for a specific column specified in this list, only historical observations within the defined range for that column are considered.
- `importance_weights`: a dictionary of pairs `colname` with either `weights` or a function `x -> weight`, which will be applied to each element of the column to obtain the vector of weights. If data for a given column is available in the current state, the product of the corresponding weights is used to adjust the similarity vector.
# Example
```julia
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
```
"""
function DistanceBased(
data::DataFrame;
target,
uncertainty = Variance(),
similarity = Exponential(),
distance = Dict(),
prior = ones(nrow(data)),
filter_range = Dict(),
importance_weights = Dict(),
)
prior = Weights(prior)
targets = target isa AbstractVector ? target : [target]
if distance isa Dict
distances = Dict(
try
if haskey(distance, colname)
string(colname) => distance[colname]
elseif elscitype(data[!, colname]) <: Continuous
string(colname) => QuadraticDistance()
elseif elscitype(data[!, colname]) <: Multiclass
string(colname) => DiscreteDistance()
else
error()
end
catch
error(
"""column $colname has scitype $(elscitype(data[!, colname])), which is not supported by default.
Please provide a custom readout-column distances functional of the signature `(x, col; prior)`.""",
)
end for colname in names(data[!, Not(target)])
)
compute_distances = sum_of_distances(data, targets, distances; prior)
elseif applicable(distance, data, targets, prior)
compute_distances = distance(data, targets, prior)
else
error("distance $distance does not accept `(data, targets, prior)`")
end
# Compute "column-wise" priors.
weights = Dict{String,Vector{Float64}}()
# If "importance weight" is a function, apply it to the column to get a numeric vector.
for (colname, val) in importance_weights
push!(
weights,
string(colname) =>
(val isa Function ? map(x -> val(x), data[!, colname]) : val),
)
end
# Convert "desirable ranges" into importance weights.
for (colname, range) in filter_range
colname = string(colname)
within_range = (data[!, colname] .>= range[1]) .&& (data[!, colname] .<= range[2])
weights[colname] = within_range .* get(weights, colname, ones(nrow(data)))
end
@show weights
# Convert distances into probabilistic weights.
compute_weights = function (evidence::Evidence)
similarities = prior .* map(x -> similarity(x), compute_distances(evidence))
# Perform hard match on target columns.
for colname in collect(keys(evidence)) ∩ targets
similarities .*= data[!, colname] .== evidence[colname]
end
# Adjustment based on "column-wise" priors.
for colname in keys(evidence)
if haskey(weights, colname)
similarities .*= weights[colname]
end
end
# If all similarities were zero, the `Weights` constructor would error.
if sum(similarities) ≈ 0
similarities .= 1
for colname in collect(keys(evidence)) ∩ targets
similarities .*= data[!, colname] .== evidence[colname]
end
end
return Weights(similarities ./ sum(similarities))
end
sampler = function (evidence::Evidence, columns, rng = default_rng())
observed = data[sample(rng, compute_weights(evidence)), :]
return Dict(c => observed[c] for c in columns)
end
f_uncertainty = uncertainty(data[!, target]; prior)
compute_uncertainty = function (evidence::Evidence)
return f_uncertainty(compute_weights(evidence))
end
return (; sampler, uncertainty = compute_uncertainty, weights = compute_weights)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 10933 | module StaticDesigns
using DataFrames
using MLJ: evaluate, PerformanceEvaluation
using Combinatorics: powerset
using POMDPs
using POMDPTools: Deterministic
using MCTS
using ..CEEDesigns: front
export evaluate_experiments, efficient_designs
# performance evaluation: predictive loss, fraction of population not filtered out by the experiment
const ExperimentalEval = NamedTuple{(:loss, :filtration),NTuple{2,Float64}}
# optimal arrangement as a MDP task
include("arrangements.jl")
# there are two methods of evaluate_experiments function. These two methods differ in their use cases and the type of input data they take:
# The first version of the evaluate_experiments function takes a predictive model as an input along with data (X and y) and evaluates the predictive accuracy over subsets of experiments using MLJ.evaluate function. This version is used when the target is a prediction task. The scores (predictive accuracy) for each subset of experiments are returned.
# The second version of the evaluate_experiments function takes dichotomous data (X) and evaluates the discriminative power of each subset of the experiments. This version is used for classifying binary labels indicating whether an entity was filtered out by the experiment or not. The result is a dictionary in which each key is a set of experiments and the value is the fraction of surviving population taken as metrics.
# The need for several methods arises from the flexibility provided by Julia's multiple dispatch system, which allows developers to define different behaviors of a function based on the type and number of its inputs, making the code more readable and optimizing the function's performance for different types of input. This feature is useful in dealing with different data types and tasks.
"""
evaluate_experiments(experiments, model, X, y; zero_cost_features=[], evaluate_empty_subset=true, return_full_metrics=false, kwargs...)
Evaluate predictive accuracy over subsets of experiments, and return the metrics. The evaluation is facilitated by `MLJ.evaluate`; additional keyword arguments to this function will be passed to `evaluate`.
Evaluations are run in parallel.
# Arguments
- `experiments`: a dictionary containing pairs `experiment => (cost =>) features`, where `features` is a subset of column names in `data`.
- `model`: a predictive model whose accuracy will be evaluated.
- `X`: a dataframe with features used for prediction.
- `y`: the variable that we aim to predict.
# Keyword arguments
- `max_cardinality`: maximum cardinality of experimental subsets (defaults to the number of experiments).
- `zero_cost_features`: additional zero-cost features available for each experimental subset (defaults to an empty list).
- `evaluate_empty_subset`: flag indicating whether to evaluate empty experimental subset. A constant column will be added if `zero_cost_features` is empty (defaults to true).
- `return_full_metrics`: flag indicating whether to return full `MLJ.PerformanceEvaluation` metrics. Otherwise return an aggregate "measurement" for the first measure (defaults to false).
# Example
```julia
evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
```
"""
function evaluate_experiments(
experiments::Dict{String,T},
model,
X,
y;
max_cardinality = length(experiments),
zero_cost_features = [],
evaluate_empty_subset::Bool = true,
return_full_metrics::Bool = false,
kwargs...,
) where {T}
# predictive accuracy scores over subsets of experiments
scores = Dict{Set{String},return_full_metrics ? PerformanceEvaluation : Float64}()
# generate all the possible subsets from the set of experiments, with a minimum size of 1 and maximum size of 'max_cardinality'
experimental_subsets = collect(powerset(collect(keys(experiments)), 1, max_cardinality))
# lock
lk = ReentrantLock()
Threads.@threads for exp_set in collect(experimental_subsets)
features = eltype(names(X))[zero_cost_features...]
foreach(
x -> append!(
features,
experiments[x] isa Pair ? experiments[x][2] : experiments[x],
),
exp_set,
)
perf_eval = evaluate(model, X[:, features], y; kwargs...)
# acquire the lock to prevent race conditions
lock(lk) do
return push!(
scores,
Set(exp_set) =>
return_full_metrics ? perf_eval : first(perf_eval.measurement),
)
end
end
if evaluate_empty_subset
X_ = if !isempty(zero_cost_features)
X[!, zero_cost_features]
else
DataFrame(; dummy = fill(0.0, nrow(data)))
end
perf_eval = evaluate(model, X_, y; kwargs...)
push!(
scores,
Set{String}() => return_full_metrics ? perf_eval : first(perf_eval.measurement),
)
end
return scores
end
"""
evaluate_experiments(experiments, X; zero_cost_features=[], evaluate_empty_subset=true)
Evaluate discriminative power for subsets of experiments, and return the metrics.
Evaluations are run in parallel.
# Arguments
- `experiments`: a dictionary containing pairs `experiment => (cost =>) features`, where `features` is a subset of column names in `X`.
- `X`: a dataframe containing binary labels, where `false` indicated that an entity was filtered out by the experiment (and should be removed from the triage).
# Keyword arguments
- `zero_cost_features`: additional zero-cost features available for each experimental subset (defaults to an empty list).
- `evaluate_empty_subset`: flag indicating whether to evaluate empty experimental subset.
# Example
```julia
evaluate_experiments(experiments, data_binary; zero_cost_features)
```
"""
function evaluate_experiments(
experiments::Dict{String,T},
X::DataFrame;
zero_cost_features = [],
evaluate_empty_subset::Bool = true,
) where {T}
scores = Dict{Set{String},ExperimentalEval}()
for exp_set in powerset(collect(keys(experiments)), 1)
features = eltype(names(X))[zero_cost_features...]
foreach(
x -> append!(
features,
experiments[x] isa Pair ? experiments[x][2] : experiments[x],
),
exp_set,
)
# calculate fraction of surviving population
perf_eval = count(all, eachrow(X[!, features])) / nrow(X)
push!(scores, Set(exp_set) => (; loss = perf_eval, filtration = perf_eval))
end
if evaluate_empty_subset
if !isempty(zero_cost_features)
perf_eval = count(all, eachrow(X[!, zero_cost_features])) / nrow(X)
else
perf_eval = 1.0
end
push!(scores, Set{String}() => (; loss = perf_eval, filtration = perf_eval))
end
return scores
end
"""
efficient_designs(experiments, evals; max_parallel=1, tradeoff=(1, 0), mdp_kwargs=default_mdp_kwargs)
Return the set of Pareto-efficient experimental designs, given experimental costs, predictive accuracy (loss), and estimated filtration rates for experimental subsets.
# Arguments
- `experiments`: a dictionary containing pairs `experiment => cost (=> features)`, where `cost` can either be scalar cost or a tuple `(monetary cost, execution time)`.
- `evals`: a dictionary containing pairs `experimental subset => (; predictive loss, filtration)`.
# Keyword arguments
- `parallel`: to estimate the execution time of the design, define the number of experiments that can run concurrently.
The experiments will subsequently be arranged in descending order based on their individual durations,
and they will be then iteratively allocated into consecutive groups that represent parallel experiments.
- `tradeoff`: determines how to project the monetary cost and execution time of an experimental design onto a single combined cost.
# Example
```julia
efficient_designs(
experiments_costs,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
```
"""
function efficient_designs(
experiments::Dict{String,T},
evals::Dict{Set{String},S};
max_parallel::Int = 1,
tradeoff = (1, 0),
mdp_kwargs = default_mdp_kwargs,
) where {T,S}
experimental_costs = Dict(e => v isa Pair ? v[1] : v for (e, v) in experiments)
evals = Dict{Set{String},ExperimentalEval}(
if e isa Number
s => (; loss = convert(Float64, e), filtration = 1.0)
else
s => (;
loss = convert(Float64, e.loss),
filtration = convert(Float64, e.filtration),
)
end for (s, e) in evals
)
# find the optimal arrangement for each experimental subset
designs = []
# lock to prevent race condition
lk = ReentrantLock()
Threads.@threads for design in collect(evals)
arrangement = optimal_arrangement(
experimental_costs,
evals,
design[1];
max_parallel,
tradeoff,
mdp_kwargs,
)
lock(lk) do
return push!(
designs,
(
(arrangement.combined_cost, design[2].loss),
(;
arrangement = arrangement.arrangement,
monetary_cost = arrangement.monetary_cost,
time = arrangement.time,
),
),
)
end
end
return front(x -> x[1], designs)
end
"""
efficient_designs(experiments, args...; eval_options, arrangement_options)
Evaluate predictive power for subsets of experiments, and return the set of Pareto-efficient experimental designs.
Internally, [`evaluate_experiments`](@ref) is called first, followed by [`efficient_designs`](@ref StaticDesigns.efficient_designs(experiments, ::Dict{Set{String}, Float64})).
# Keyword arguments
- `eval_options`: keyword arguments to [`evaluate_experiments`](@ref).
- `arrangement_options`: keyword arguments to [`efficient_designs`](@ref StaticDesigns.efficient_designs(experiments, ::Dict{Set{String}, Float64})).
# Example
```julia
efficient_designs(
experiments_costs,
data_binary;
eval_options = (; zero_cost_features),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
```
"""
function efficient_designs(
experiments::Dict{String,T},
args...;
eval_options = (;),
arrangement_options = (;),
) where {T}
evals = evaluate_experiments(experiments, args...; eval_options...)
return efficient_designs(experiments, evals; arrangement_options...)
end
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 4154 | ## optimal arrangement as a MDP policy
"""
ArrangementMDP(; experiments, experimental_costs, evals, max_parallel=1, tradeoff=(1, 0))
Structure to parametrize a MDP that is used to approximate the optimal experimental arrangement.
"""
Base.@kwdef struct ArrangementMDP{T1<:Number,T2<:Number} <:
POMDPs.MDP{Set{String},Set{String}}
# experiments
experiments::Set{String}
# experimental costs
experimental_costs::Dict{String,NTuple{2,Float64}}
# loss, filtration
evals::Dict{Set{String},ExperimentalEval}
# maximum number of parallel experiments
max_parallel::Int = 1
# monetary cost v. time tradeoff
tradeoff::Tuple{T1,T2} = (1, 0)
end
function POMDPs.actions(m::ArrangementMDP, state)
return Set.(
collect(powerset(collect(setdiff(m.experiments, state)), 1, m.max_parallel))
)
end
POMDPs.isterminal(m::ArrangementMDP, state) = m.experiments == state
POMDPs.initialstate(::ArrangementMDP) = Deterministic(Set{String}())
function POMDPs.transition(::ArrangementMDP, state, action)
# readout features
return Deterministic(state ∪ action)
end
function POMDPs.reward(m::ArrangementMDP, state, action)
monetary_cost = m.evals[state].filtration * sum(a -> m.experimental_costs[a][1], action)
time = maximum(a -> m.experimental_costs[a][2], action)
return -sum(m.tradeoff .* (monetary_cost, time))
end
POMDPs.discount(::ArrangementMDP) = 1.0
const default_mdp_kwargs = (; n_iterations = 10_000, depth = 10, exploration_constant = 3.0)
"""
optimal_arrangement(costs, evals, experiments; max_parallel=1, tradeoff=(1, 0), pomdp_kwargs=default_mdp_kwargs)
Find the optimal arrangement of a set of `experiments` given their costs and associated filtration rates.
Otherwise, the function returns a named tuple `(; arrangement, combined cost, monetary cost, time, planner)`, where `planner` is the MDP planner.
# Arguments
- `costs`: a dictionary containing pairs `experiment => cost`, where `cost` can either be a scalar cost (modelled as a monetary cost) or a tuple `(monetary cost, execution time)`.
- `evals`: a dictionary containing pairs `experimental subset => (; filtration rate, loss)`.
- `experiments`: a set of experiments to be executed.
# Keyword arguments
- `parallel`: to estimate the execution time of the design, define the number of experiments that can run concurrently.
The experiments will subsequently be arranged in descending order based on their individual durations,
and they will be then iteratively allocated into consecutive groups that represent parallel experiments.
- `tradeoff`: determines how to project the monetary cost and execution time of an experimental design onto a single combined cost.
- `mdp_kwargs`: arguments to a MDP solver [`DPWSolver`](https://juliapomdp.github.io/MCTS.jl/dev/dpw/#Double-Progressive-Widening).
"""
# if the execution times for the experimental setup are specified
function optimal_arrangement(
costs::Dict{String,T},
evals::Dict{Set{String},ExperimentalEval},
experiments::Set{String};
max_parallel = 1,
tradeoff = (1, 0),
mdp_kwargs = default_mdp_kwargs,
) where {T}
experimental_costs = Dict{String,NTuple{2,Float64}}(
k => if v isa Number
(convert(Float64, v), v)
else
(convert(Float64, v[1]), convert(Float64, v[2]))
end for (k, v) in costs
)
mdp = ArrangementMDP(; experiments, experimental_costs, evals, max_parallel, tradeoff)
solver = DPWSolver(; mdp_kwargs...)
planner = solve(solver, mdp)
monetary_cost = time = 0.0
state = Set{String}()
arrangement = Set{String}[]
while state != experiments
next_action = action(planner, state)
push!(arrangement, next_action)
monetary_cost +=
evals[state].filtration * sum(a -> experimental_costs[a][1], next_action)
time += maximum(a -> experimental_costs[a][2], next_action)
state = state ∪ next_action
end
return (;
arrangement,
monetary_cost,
time,
combined_cost = sum(tradeoff .* (monetary_cost, time)),
planner,
)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 2645 | using CEEDesigns, CEEDesigns.StaticDesigns
using CSV, DataFrames
## heart failure prediction dataset
# https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction
data = CSV.File("data/heart.csv") |> DataFrame
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => 1.0 => ["RestingBP"],
#"ECG" => 5. => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
#"BloodCholesterol" => 20. => ["Cholesterol"],
"BloodSugar" => 20 => ["FastingBS"],
)
# features that are always available
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# prediction target
target = "HeartDisease"
using MLJ
import BetaML, MLJModels
# fix scitypes
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types)
# models(matching(data, data[:, "HeartDisease"]))
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 3
model = classifier(; n_trees = 20, max_depth = 10)
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
# explicit, use accuracies computed above
designs1 = efficient_designs(experiments, perf_eval)
# implicit, calculate accuracies automatically
designs2 = efficient_designs(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
)
# switch to plotly backend
CEEDesigns.plotly()
designs = designs2
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
# test with (monetary cost, execution time)
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
# implicit, calculate accuracies automatically
designs = efficient_designs(experiments, perf_eval; max_parallel = 2, tradeoff = (0.0, 1))
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1410 |
using CEEDesigns, CEEDesigns.StaticDesigns
using CSV, DataFrames
## synthetic heart disease dataset with binary labels
data = CSV.File("data/heart_binary.csv") |> DataFrame
# available predictions
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20 => ["FastingBS"],
)
perf_eval = evaluate_experiments(experiments, data; zero_cost_features)
# explicit, use accuracies computed above
designs = efficient_designs(experiments, perf_eval)
# switch to plotly backend
CEEDesigns.plotly()
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative pwr")
# test with (monetary cost, execution time)
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (1.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (1.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (1.0, 20.0) => ["FastingBS"],
)
designs = efficient_designs(experiments, data; eval_options = (; zero_cost_features))
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative pwr")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 6846 | # # Cost-Efficient Experimental Designs: Heart Disease Prediction
# Consider a situation where a group of patients has to be tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer; instead, we want to utilize various proxy experiments that yield partial information about the presence of the disease.
# ## Theoretical Framework
# In terms of machine learning, let us assume that a dataset of historical readouts over $n$ features $x_1, \ldots, x_n$ is available, and let $y$ denote the target variable that we want to predict.
# For each subset $S \subseteq {x_1, ..., x_n}$ of features, we evaluate the accuracy $a_S$ of a predictive model that predicts the value of $y$ based on readouts over features in $S$. Assuming the patient population follows the same distribution as the historical observations, the predictive accuracy serves as a proxy for the information gained from observing the features in $S$.
# In the cost-sensitive setting of CEEDesigns, observing the features $S$ incurs a cost $c_S$. Generally, this cost is specified in terms of monetary cost and execution time of an experiment. Considering the constraint of a maximum number of parallel experiments, the algorithm recommends an arrangement of experiments that minimizes the total running time. Eventually, for a fixed tradeoff between monetary cost and execution time, a combined cost $c_S$ is obtained.
# Assuming we know the accuracies $a_S$ and experimental costs $c_S$ for each subset $S \subseteq {x_1, ..., x_n}$, we can generate a set of Pareto-efficient experimental designs considering both predictive accuracy and cost.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
# ## Predictive Accuracy
# The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
# We may also provide additional zero-cost features, which are always available.
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# And we specify the target for prediction.
target = "HeartDisease"
# ### Classifier
# We use [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
using MLJ
import BetaML, MLJModels
# We have to provide appropriate scientific types of the features.
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types)
# Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with our dataset:
models(matching(data, data[:, "HeartDisease"]))
# Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 3
model = classifier(; n_trees = 20, max_depth = 10)
# ### Performance Evaluation
# We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as the measure of accuracy. It is possible to pass additional keyword arguments that will propagate `MLJ.evaluate` (such as `measure`).
using CEEDesigns, CEEDesigns.StaticDesigns
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
# We plot performance measures evaluated for subsets of experiments.
plot_evals(perf_eval; ylabel = "logloss")
# ## Cost-Efficient Designs
# We specify the cost associated with the execution of each experiment. When it comes to groups of experiments, the costs simply sum up.
costs = Dict(
## experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs.
designs = efficient_designs(costs, perf_eval)
## Switch to plotly backend for plotting
CEEDesigns.plotly()
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
# ### Duration of Experiment
# We may additionally specify the duration of an experiment. Furthermore, we demonstrating the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generates efficient designs.
# test with (monetary cost, execution time)
# experiment => cost => features
experiments_costs = Dict(
# experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
# We have to provide the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time - in our case, we aim to minimize the execution time.
# Internally, `evaluate_experiments`is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
## Implicit, calculates accuracies automatically
designs = efficient_designs(
experiments_costs,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
# As we can see, the algorithm correctly suggests running experiments in parallel.
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 604 | using CSV, DataFrames
using Distributions
features_discriminative_power = Dict(
f => rand(0.7:0.05:0.95) for f in [
"RestingBP",
"RestingECG",
"Oldpeak",
"ST_Slope",
"MaxHR",
"Cholesterol",
"FastingBS",
]
)
merge!(
features_discriminative_power,
Dict(
f => rand(0.9:0.05:0.95) for f in ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
),
)
data = DataFrame()
n_rows = 10_000
for (feat, p) in features_discriminative_power
data[!, feat] = rand(Bernoulli(p), n_rows)
end
CSV.write("data/heart_binary.csv", data)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1449 | using Test
using CEEDesigns
@testset "`front(v)` tests" begin
v = []
@test front(v) == []
v = [
(-1.7833642139623433, 0.5134779462662945),
(0.2772266621984681, -0.03423972427378738),
(-0.0813001903247021, -0.8405030837117491),
(-0.1648539657094688, -0.3577662002763534),
(-0.25324461343172333, -0.6300191234260538),
(-0.66785364505844, -0.6736690806341213),
]
@test front(v) == [
(-1.7833642139623433, 0.5134779462662945),
(-0.66785364505844, -0.6736690806341213),
(-0.0813001903247021, -0.8405030837117491),
]
v = [(1, 2), (2, 3), (2, 1)]
@test front(v) == [(1, 2), (2, 1)]
end
@testset "`front(f, v)` tests" begin
v = []
@test front(identity, v) == []
v = [
(1, (-1.7833642139623433, 0.5134779462662945)),
(2, (0.2772266621984681, -0.03423972427378738)),
(3, (-0.0813001903247021, -0.8405030837117491)),
(4, (-0.1648539657094688, -0.3577662002763534)),
(5, (-0.25324461343172333, -0.6300191234260538)),
(6, (-0.66785364505844, -0.6736690806341213)),
]
@test front(x -> x[2], v) == [
(1, (-1.7833642139623433, 0.5134779462662945)),
(6, (-0.66785364505844, -0.6736690806341213)),
(3, (-0.0813001903247021, -0.8405030837117491)),
]
v = [(1, (1, 2)), (2, (2, 3)), (3, (2, 1))]
@test front(x -> x[2], v) == [(1, (1, 2)), (3, (2, 1))]
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 345 | using SafeTestsets, BenchmarkTools
@time begin
@time @safetestset "fronts tests" begin
include("fronts.jl")
end
@time @safetestset "`StaticDesigns` tests" begin
include("StaticDesigns/test.jl")
end
@time @safetestset "`GenerativeDesigns` tests" begin
include("GenerativeDesigns/test.jl")
end
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 199 | # test with the sum distances
include("test_distances_sum.jl")
# test with the squared Mahalanobis distance
include("test_mahalanobis.jl")
# test active sampling
include("test_active_sampling.jl")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1753 | using Test
using DataFrames
using CEEDesigns.GenerativeDesigns: DistanceBased, Evidence
using ScientificTypes
using CEEDesigns, CEEDesigns.GenerativeDesigns
# Define the types for each column
types = Dict(:A => Continuous, :B => Continuous, :Y => Continuous)
# Sample data for testing with all numerical values
data = DataFrame(; A = 1:10, B = 1:10, Y = rand(1:10, 10))
# Coerce the data to the correct types
data = coerce(data, types)
# Define a dummy uncertainty function
dummy_uncertainty(data; prior) = weights -> sum(weights)
# Define a dummy similarity function
dummy_similarity = x -> exp(-sum(x))
# Define desirable ranges for dimension "A"
filter_range = Dict("A" => (3, 8))
# Define importance weights for dimension "B"
importance_weights = Dict("B" => x -> 2 <= x <= 7)
# Create the DistanceBased function with the new features
(; weights) = DistanceBased(
data;
target = ["Y"],
uncertainty = dummy_uncertainty,
similarity = dummy_similarity,
filter_range,
importance_weights,
)
# Test the weights computation considering the desirable range and importance sampling
@testset "`DistanceBased` tests for active sampling" begin
evidence_1 = Evidence("A" => 5)
assigned_weights_1 = weights(evidence_1)
# Check if weights are zero only in the given range
@test all(assigned_weights_1[1:2] .== 0.0)
@test all(assigned_weights_1[9:10] .== 0.0)
@test all(assigned_weights_1[3:8] .> 0)
evidence_2 = Evidence("B" => 5)
assigned_weights_2 = weights(evidence_2)
@show assigned_weights_2
# Check if weights are zero only in the given range
@test all(assigned_weights_2[1] == 0.0)
@test all(assigned_weights_2[8:10] .== 0)
@test all(assigned_weights_2[2:7] .> 0.0)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 3045 | using CSV, DataFrames
data = CSV.File("GenerativeDesigns/data/heart_disease.csv") |> DataFrame
using ScientificTypes
types = Dict(
:MaxHR => Continuous,
:Cholesterol => Continuous,
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
using CEEDesigns, CEEDesigns.GenerativeDesigns
evidence = Evidence("Age" => 35, "Sex" => "M")
# test `DistanceBased` sampler
r = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
@test all(x -> hasproperty(r, x), [:sampler, :uncertainty, :weights])
(; sampler, uncertainty, weights) = r
# test signatures
using Random: default_rng
@test applicable(sampler, evidence, ["HeartDisease"], default_rng)
@test applicable(uncertainty, evidence)
@test applicable(weights, evidence)
experiments = Dict(
## experiment => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20.0 => ["FastingBS"],
"HeartDisease" => 100.0,
)
# test `UncertaintyReductionMDP`
solver = GenerativeDesigns.DPWSolver(; n_iterations = 100, tree_in_info = true)
design = efficient_design(
experiments;
sampler,
uncertainty,
threshold = 0.0,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
@test design isa Tuple
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
@test designs isa Vector
@test all(design -> (design[1][1] ≈ 0) || hasproperty(design[2], :stats), designs)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
mdp_options = (; max_parallel = 1),
);
@test !hasproperty(designs[1][2], :stats)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
realized_uncertainty = true,
mdp_options = (; max_parallel = 1),
);
@test designs[begin][1][2] ≈ uncertainty(evidence)
# test `EfficientValueMDP``
value = function (evidence, (monetary_cost, execution_time))
return (1 - uncertainty(evidence)) - (0.005 * sum(monetary_cost))
end
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(; n_iterations = 100, depth = 2, tree_in_info = true)
design = efficient_value(experiments; sampler, value, evidence, solver, repetitions = 5);
@test design isa Tuple
@test hasproperty(design[2], :stats)
design = efficient_value(experiments; sampler, value, evidence, solver);
@test design isa Tuple
@test !hasproperty(design[2], :stats)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 3028 | using CSV, DataFrames
data = CSV.File("GenerativeDesigns/data/heart_disease.csv") |> DataFrame
using ScientificTypes
types = Dict(
:MaxHR => Continuous,
:Cholesterol => Continuous,
:Oldpeak => Continuous,
:Age => Continuous,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
)
data = coerce(data, types);
continuous_cols = filter(colname -> eltype(data[!, colname]) == Float64, names(data))
data = data[!, continuous_cols∪["HeartDisease"]]
using CEEDesigns, CEEDesigns.GenerativeDesigns
evidence = Evidence()
# test `DistanceBased` sampler
r = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Variance(),
similarity = Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 1),
);
@test all(x -> hasproperty(r, x), [:sampler, :uncertainty, :weights])
(; sampler, uncertainty, weights) = r
# test signatures
using Random: default_rng
@test applicable(sampler, evidence, ["HeartDisease"], default_rng)
@test applicable(uncertainty, evidence)
@test applicable(weights, evidence)
experiments = Dict(
## experiment => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["Oldpeak", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20.0 => ["FastingBS"],
"HeartDisease" => 100.0,
)
# test `UncertaintyReductionMDP`
solver = GenerativeDesigns.DPWSolver(; n_iterations = 100, tree_in_info = true)
design = efficient_design(
experiments;
sampler,
uncertainty,
threshold = 0.0,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
@test design isa Tuple
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
@test designs isa Vector
@test all(design -> (design[1][1] ≈ 0) || hasproperty(design[2], :stats), designs)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
mdp_options = (; max_parallel = 1),
);
@test !hasproperty(designs[1][2], :stats)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 4,
evidence,
solver,
realized_uncertainty = true,
mdp_options = (; max_parallel = 1),
);
@test designs[begin][1][2] ≈ uncertainty(evidence)
# test `EfficientValueMDP``
value = function (evidence, (monetary_cost, execution_time))
return (1 - uncertainty(evidence)) - (0.005 * sum(monetary_cost))
end
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(; n_iterations = 100, depth = 2, tree_in_info = true)
design = efficient_value(experiments; sampler, value, evidence, solver, repetitions = 5);
@test design isa Tuple
@test hasproperty(design[2], :stats)
design = efficient_value(experiments; sampler, value, evidence, solver);
@test design isa Tuple
@test !hasproperty(design[2], :stats)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 2572 | using Random: seed!
using CEEDesigns, CEEDesigns.StaticDesigns
using CSV, DataFrames
## predictive model from `MLJ`
# https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction
data = CSV.File("StaticDesigns/data/heart_disease.csv") |> DataFrame
# available predictions
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20 => ["FastingBS"],
)
# prediction target
target = "HeartDisease"
using MLJ
import BetaML, MLJModels
# fix scitypes
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types)
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 0
model = classifier(; n_trees = 20, max_depth = 10)
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
@test perf_eval isa Dict{Set{String},Float64}
## binary dataset, use filtration
data = CSV.File("StaticDesigns/data/heart_binary.csv") |> DataFrame
# available predictions
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20 => ["FastingBS"],
)
seed!(1)
perf_eval = evaluate_experiments(experiments, data; zero_cost_features)
@test perf_eval isa
Dict{Set{String},NamedTuple{(:loss, :filtration),Tuple{Float64,Float64}}}
seed!(1)
designs = efficient_designs(experiments, perf_eval)
@test designs isa Vector
# test with (monetary cost, execution time)
# experiment => cost => features
experiments = Dict(
# experiment => cost => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (1.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (1.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (1.0, 20.0) => ["FastingBS"],
)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 10253 | # # Active Sampling for Generative Designs
# ## Background on Active Sampling
# In multi-objective optimization (MOO), particularly in the context of active learning and reinforcement learning (RL),
# conditional sampling plays a critical role in achieving optimized outcomes that align with specific desirable criteria.
# The essence of conditional sampling is to direct the generative process not only towards the global objectives but also to adhere to additional, domain-specific constraints or features. This approach is crucial for several reasons:
# MOO often involves balancing several competing objectives, such as minimizing cost while maximizing performance.
# Conditional sampling allows for the integration of additional constraints or preferences,
# ensuring that the optimization does not overly favor one objective at the expense of others.
# On a related note, many optimization problems have domain-specific constraints or desirable features that are not explicitly part of the primary objectives.
# For example, in drug design, beyond just optimizing for efficacy and safety, one might need to consider factors like solubility or synthesizability.
# Conditional sampling ensures that solutions not only meet the primary objectives but also align with these additional practical considerations.
# ## Application to Generative Designs
# In the context of CEEDesigns.jl, active sampling can be used to selectively prioritize historical observations.
# For example, if the goal is to understand a current trend or pattern,
# active sampling can be used to assign more weight to recent data points or deprioritize those that may not be relevant to the current context.
# This way, the sampled data will offer a more precise representation of the current state or trend.
# For details on the theoretical background of generative designs and notation, please see our [introductory tutorial](SimpleGenerative.md) and an [applied tutorial](GenerativeDesigns.jl).
# Here we will again assume that the generative process is based on sampling from a historical dataset, which gives measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
# (with entities and features representing rows and columns, respectively).
# Each experiment $e$ may yield measurements on some
# subset of features $(X_{e}\subseteq X)$.
# Given the current state, i.e., experimental evidence acquired thus far for the new entity, we assign probabilistic weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
# weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
# $q(e_{S^{\prime}}|e_{S})$.
# In the context of active sampling, we aim to further adjust the weights, $w_{j}$, calculated by the algorithm.
# This adjustment can be accomplished by introducing a "prior", which is essentially a vector of weights that will multiply the computed weights, $w_{j}$, in an element-wise manner.
# If we denote the "prior" weights as $p_{j}$, then the final weights assigned to the $j$-th row are computed as $w'_{j} = p_{j} * w_{j}$.
# Alternatively, we can use "feature-wise" priors, which are considered when a readout for the specific feature is available for the new entity. # It is important to note here that the distance, which forms the basis of the probabilistic weights, is inherently computed only over the observed features.
# To be more precise, for each experiment $e\in E$, we let $p^e_j$ denote the "prior" associated with that specific experiment.
# If $S$ represents the set of experiments that have been performed for the new compound so far, we compute the reweighted probabilistic weight as $w'_{j} = \product_{e\in S} p^e_j \cdot w_j$.
# We remark that this method can be used to filter out certain rows by setting their weight to zero.
# Considering feature-wise priors can offer a more detailed and nuanced understanding of the data. These priors can be used to dynamically adjust the weight of historical observations, based on the specific readouts considered for the observation across different features.
# For more information about active sampling, refer to the following articles.
# - [Evolutionary Multiobjective Optimization via Efficient Sampling-Based Strategies](https://link.springer.com/article/10.1007/s40747-023-00990-z).
# - [Sample-Efficient Multi-Objective Learning via Generalized Policy Improvement Prioritization](https://arxiv.org/abs/2301.07784).
# - [Conditional gradient method for multiobjective optimization](https://link.springer.com/article/10.1007/s10589-020-00260-5)
# - [A practical guide to multi-objective reinforcement learning and planning](https://link.springer.com/article/10.1007/s10458-022-09552-y)
# ## Synthetic Data Example
using CEEDesigns, CEEDesigns.GenerativeDesigns
# We create a synthetic dataset with continuous variables, `x1`, `x2`, and `y`. Both `x1` and `x2` are modeled as independent random variables that follow a normal distribution.
# The target variable, `y`, is given as a weighted sum of `x1` and `x2`, with an additional noise component. The corrected version of your sentence should be: Consequently, if the value of `x2`, for example,
# falls into a "sparse" region, we want the algorithm to avoid overfitting and focus its attention more on the other variable.
using Random
using DataFrames
## Define the size of the dataset.
n = 1000;
## Generate `x1` and `x2` as independent random variables with normal distribution.
x1 = randn(n)
x2 = randn(n);
## Compute `y` as the sum of `x1`, `x2`, and the noise.
y = x1 .+ 0.2 * x2 .+ 0.1 * randn(n);
## Create a data frame.
data = DataFrame(; x1 = x1, x2 = x2, y = y);
data[1:10, :]
# ### Active Sampling
# We again use the default method `DistanceBased` to assign the probabilistic weights across historical observations.
# In addition, we will demonstrate the use of two additional keyword arguments of `DistanceBased`, related to active sampling:
# - `importance_weights`: this is a dictionary of pairs `colname` with either `weights` or a function `x -> weight`, which will be applied to each element of the column to obtain the vector of weights. If data for a given column is available in the current state, the product of the corresponding weights is used to adjust the similarity vector.
#
# For filtering out certain rows where the readouts fall outside a selected range, we can use the following keyword:
# - `filter_range`: this is a dictionary of pairs `colname => (lower bound, upper bound)`. If there's data in the current state for a specific column specified in this list, only historical observations within the defined range for that column are considered.
# In the current setup, we aim to adaptively filter out the values `x1` or `x2` that lie outside of one standard deviation from the mean.
filter_range = Dict()
filter_range = Dict("x1" => (-1, 1), "x2" => (-1, 1))
# We then call `DistanceBased` as follows:
(sampler_active, uncertainty_active, weights_active) = DistanceBased(
data;
target = "y",
similarity = Exponential(; λ = 0.5),
filter_range = filter_range,
);
# To compare behavior with and without active sampling, we call `DistanceBased` again:
(; sampler, uncertainty, weights) =
DistanceBased(data; target = "y", similarity = Exponential(; λ = 0.5));
# We plot the weights $w_j$ assigned to historical observations for both cases - with active sampling and without. The actual observation is shown in orange.
evidence = Evidence("x1" => 5.0, "x2" => 0.5)
#
using Plots
## The plotting engine (GR) requires us to use RGB instead of RGBA.
rgba_to_rgb(a) = RGB(((1 - a) .* (1, 1, 1) .+ a .* (0.0, 0.5, 0.5))...)
alphas_active = max.(0.1, weights_active(evidence) ./ maximum(weights_active(evidence)))
p1 = scatter(
data[!, "x1"],
data[!, "x2"];
color = map(a -> rgba_to_rgb(a), alphas_active),
title = "weights\n(active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p1,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p1
#
alphas = max.(0.1, weights(evidence) ./ maximum(weights(evidence)))
p2 = scatter(
data[!, "x1"],
data[!, "x2"];
color = map(a -> rgba_to_rgb(a), alphas),
title = "weights\n(no active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p2,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p2
#
# As it turns out, when active sampling was not used, the algorithm tended to overfit to the closest yet sparse points, which did not represent the true distribution accurately.
# We can also compare the estimated uncertainty, which is computed as the variance of the posterior.
#
# Without using active sampling, we obtain:
round(uncertainty_active(evidence); digits = 1)
#
# While for active sampling, we get:
round(uncertainty(evidence); digits = 1)
# #### Experimental Designs for Uncertainty Reduction
# We compare the set of cost-efficient designs in cases where active sampling is used and where it is not.
#
# We specify the experiments along with the associated features:
experiments = Dict("x1" => 1.0, "x2" => 1.0, "y" => 6.0)
# We specify the initial state.
evidence = Evidence("x2" => 5.0)
# Next we compute the set of efficient designs.
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
designs_active = efficient_designs(
experiments;
sampler = sampler_active,
uncertainty = uncertainty_active,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
# We can compare the fronts.
p = scatter(
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
ylabel = "% uncertainty",
label = "efficient designs (no active sampling)",
title = "efficient front",
color = :blue,
mscolor = nothing,
)
scatter!(
p,
map(x -> x[1][1], designs_active),
map(x -> x[1][2], designs_active);
label = "efficient designs (active sampling)",
color = :teal,
mscolor = nothing,
)
p
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 10515 | # # Heart Disease Triage Meets Generative Modeling
# Consider again a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer; instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# For details on the theoretical background and notation, please see our tutorial on [generative experimental designs](SimpleGenerative.md). This tutorial
# is a concrete application of the tools described in that document.
# Importantly, we aim to design personalized adaptive policies for each patient. At the beginning of the triage process, we use a patient's prior data, such as sex, age, or type of chest pain, to project a range of cost-efficient experimental designs. Internally, while constructing these designs, we incorporate multiple-step-ahead lookups to model probable experimental outcomes and consider the subsequent decisions for each outcome. Then after choosing a specific decision policy from this set and acquiring additional experimental readouts, we adjust the continuation based on this evidence.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# We provide appropriate scientific types of the features.
using ScientificTypes
types = Dict(
:MaxHR => Continuous,
:Cholesterol => Continuous,
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
# ## Generative Model for Outcomes Sampling
using CEEDesigns, CEEDesigns.GenerativeDesigns
# As previously discussed, we provide a dataset of historical records, the target variable, along with an information-theoretic measure to quantify the uncertainty about the target variable.
# In what follows, we obtain three functions:
# - `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator,
# - `uncertainty`: this is a function of `evidence`,
# - `weights`: this represents a function of `evidence` that distributes probabilistic weights across the rows in the dataset.
# Note that internally, a state of the decision process is represented as a tuple `(evidence, costs)`.
# You can specify the method for computing the distance using the `distance` keyword. By default, the Kronecker delta and quadratic distance will be utilised for categorical and continuous features, respectively.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
# Alternatively, you can provide a dictionary of `feature => distance` pairs. The implemented distance functionals are `DiscreteDistance(; λ)` and `QuadraticDistance(; λ, standardize=true)`. In that case, the specified distance will be applied to the respective feature, after which the distances will be collated across the range of features.
# The above call is therefore equivalent to:
numeric_feats = filter(c -> c <: Real, eltype.(eachcol(data)))
categorical_feats = setdiff(names(data), numeric_feats)
DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = merge(
Dict(c => DiscreteDistance() for c in categorical_feats),
Dict(c => QuadraticDistance() for c in numeric_feats),
),
);
# You can also use the squared Mahalanobis distance (`SquaredMahalanobisDistance(; diagonal)`). As the squared Mahalanobis distance only works with numeric features, we have to select a few, along with the target variable. For example, we could write:
DistanceBased(
data[!, ["RestingBP", "MaxHR", "Cholesterol", "FastingBS", "HeartDisease"]];
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 1),
);
# The package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20.0 => ["FastingBS"],
"HeartDisease" => 100.0,
)
# Let us inspect the distribution of belief for the following experimental evidence:
evidence = Evidence("Age" => 55, "Sex" => "M")
#
using StatsBase: countmap
using Plots
#
target_belief = countmap(data[!, "HeartDisease"], weights(evidence))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
# Let us next add an outcome of blood pressure measurement:
evidence_with_bp = merge(evidence, Dict("RestingBP" => 190))
target_belief = countmap(data[!, "HeartDisease"], weights(evidence_with_bp))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence_with_bp), digits=2))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
# ## Cost-Efficient Experimental Designs for Uncertainty Reduction
# In this experimental setup, our objective is to minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs for various levels of uncertainty threshold. In the following example, we generate 6 thresholds spaces evenly between 0 and 1, inclusive.
# Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl) is created, and the `POMDPs.solve` is called on the problem. Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
## set seed for reproducibility
using Random: seed!
seed!(1)
#
evidence = Evidence("Age" => 35, "Sex" => "M")
#
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 20_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
# We plot the Pareto-efficient actions:
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# We render the search tree for the second design, sorted in descending order based on the uncertainty threshold:
using D3Trees
d3tree = D3Tree(designs[2][2].tree; init_expand = 2)
# ### Parallel Experiments
# We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
"HeartDisease" => (100.0, 100.0),
)
# We have to provide the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
## minimize time, two concurrent experiments at maximum
seed!(1)
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 2_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 2, costs_tradeoff = (0, 1.0)),
repetitions = 5,
);
# We plot the Pareto-efficient actions:
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# ## Efficient Value Experimental Designs
# In this experimental setup, we aim to maximize the value of experimental evidence, adjusted for the incurred experimental costs.
# For this purpose, we need to specify a function that quantifies the "value" of decision-process making state, modeled as a tuple of experimental evidence and costs.
value = function (evidence, (monetary_cost, execution_time))
return (1 - uncertainty(evidence)) - (0.005 * sum(monetary_cost))
end
# Considering a discount factor $\lambda$, the total reward associated with the experimental state in an $n$-step decision process is given by $r = r_1 + \sum_{i=2}^n \lambda^{i-1} (r_i - r_{i-1})$, where $r_i$ is the value associated with the $i$-th state.
# In the following example, we also limit the maximum rollout horizon to 4.
#
seed!(1)
## use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(; n_iterations = 2_000, depth = 4, tree_in_info = true)
design = efficient_value(
experiments;
sampler,
value,
evidence,
solver,
repetitions = 5,
mdp_options = (; discount = 0.8),
);
#
design[1] # optimized cost-adjusted value
#
d3tree = D3Tree(design[2].tree; init_expand = 2)
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 26316 | # # Generative Experimental Designs
# This document describes the theoretical background behind tools in CEEDesigns.jl for generative experimental designs
# and demonstrates uses on synthetic data examples.
# ## Setting
# Generative experimental designs differ from static designs in that the experimental design is specific for (or "personalized") to an incoming entity.
# Personalized cost-efficient experimental designs for the new entity are made based on existing information (if any) about the new entity,
# and from posterior distributions of unobserved features of that entity conditional on its observed features and historical data.
# The entities may be patients, molecular compounds, or any other objects where one has a store of historical data
# and seeks to find efficient experimental designs to learn more about a new arrival.
#
# The personalized experimental designs are motivated by the fact that the value of information collected from an experiment
# often differs across subsets of the population of entities.
# 
# In the context of static designs, we do not aspire to capture variation in information gain across different entities. Instead, we assume all entities come from a "Population" with a uniform information gain, in which case "Experiment C" would provide the maximum information value.
# On the other hand, if we have the ability to discern if the entity belong to subpopulations "Population 1" or "Population 2," then we can tailor our
# design to suggest either "Experiment A" or "Experiment B." Clearly, in the limit of a maximally heterogenous population, each
# entity has its own "row." Our tools are able to handle the entire spectrum of such scenarios though distance based similarity,
# described below.
# ## Theoretical Framework
# ### Historical Data
# Like static designs, we consider a set $E$ of $n$ experiments, each with an associated tuple $(m_{e},t_{e})$ of monetary and
# time costs (for more details on experiments and arrangements, see the tutorial on [static experimental designs](SimpleStatic.md)).
#
# Additionally, consider a historical dataset giving measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
# (with entities and features representing rows and columns, respectively). Each experiment $e$ may yield measurements on some
# subset of features $(X_{e}\subseteq X)$.
#
# Furthermore there is an additional column $y$ which is a target variable we want to predict (CEEDesigns.jl may allow $y$
# to be a vector, but we assume it is scalar here for ease of presentation).
#
# Letting $m=3$, then the historical dataset may be visualized as the following table:
# 
# ### New Entity
# When a new entity arrives, it will have an unknown outcome $y$ and unknown values of some or all features $x_{i} \in X$.
# We call the _state_ of the new entity the set of experiments conducted upon it so far (if any), along with the
# measurements on any features produced by those experiments (if any), called _evidence_.
#
# Consider the case where there are $n=3$ experiments, each of which yields a measurement on a single feature. Then
# the state of a new entity arriving for which $e_{1}$ has already been performed will look like:
# 
# Letting $S$ denote the set of experiments which have been performed so far, then $S^{\prime}=E\S$ are unperformed experiments.
# Then, _actions_ one can perform to learn more about the new entity are subsets of $S^{\prime}$. The size of subsets
# is limited by the maximum number of parallel experiments.
#
# In our running example, if the maximum number of parallel experiments is at least 2, then the available actions are:
# 
# ### Posterior Distributions
# Let $e_{S}$ be a random variable denoting the outcome of some experiments $S$ on the new entity. Then, there exists a
# posterior distribution $q(e_{S^{\prime}}|e_{S})$ over outcomes of unperformed experiments $S^{\prime}$, conditioned on the current
# state.
#
# Furthermore, there also exists a posterior distribution over the unobserved target variable $q(y|e_{S})$. The information
# value of the current state, derived from experimental evidence, can be defined as any statistical or information-theoretic
# measure applied to $q(y|e_{S})$. This can include variance or entropy (among others). The information value
# of the set of experiments performed in $S$ is analogous to $v_{S}$ defined in [static experimental designs](SimpleStatic.md).
# ### Similarity Weighting
# There may be many ways to define these posterior distributions, but our approach uses distance-based similarity
# scores to construct weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
# weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
# $q(e_{S^{\prime}}|e_{S})$.
#
# If there is no evidence associated with a new entity, we assign $w_{j}$ according to some prior distribution (uniform by default).
# Otherwise we use some particular distance and similarity metrics.
#
# For each feature $x\in X$, we consider a function $\rho_x$, which measures the distance between two outputs. Please be aware that the "distances" discussed here do not conform to the mathematical definition of "metrics", even though they are functions derived from underlying metrics (i.e., a square of a metric). This is justified when considering how these "distances" are subsequently converted into probabilistic weights.
#
# By default, we consider the following distances:
# - Rescaled Kronecker delta (i.e., $\rho(x, y)=0$ only when $x=y$, and $\rho(x, y)= \lambda$ under any other circumstances, with $\lambda > 0$) for discrete features (i.e., features whose types are modeled as `MultiClass` type in [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl));
# - Rescaled ("standardized", by default) squared distance $\rho(x, y) = λ \frac{(x - y)^2}{\sigma^2}$, where $\sigma^2$ is the variance of the feature column, estimated with respect to the prior for continuous features.
# - Squared Mahalanobis distance $\rho(x,y) = (x-y)^{⊤}\Sigma^{-1}(x-y)$, where $\Sigma$ is the empirical covariance matrix of the historical data.
#
# For distance metrics assuming independence of features (Kronecker delta and squared distance), given the new entity's experimental state with readouts over the feature set $F = \bigcup X_{e}$, where $e \in S$, we can calculate
# the distance from the $j$-th historical entity as $d_j = \sum_{x\in F} \rho_x (\hat x, x_j)$, where $\hat x$ and $x_j$ denote the readout
# for feature $x$ for the entity being tested and the entity recorded in $j$-th column.
# The squared Mahalanobis distance directly takes in "rows", $\rho(\hat{x},x_{j})$.
#
# Next, we convert distances $d_j$ into probabilistic weights $w_j$. By default, we use a rescaled exponential function, i.e.,
# we put $w_j = \exp(-\lambda d_j)$ with $\lambda=0.5$. Notably, $\lambda$'s value determines how belief is distributed across the historical entities.
# Larger values of $\lambda$ concentrate the belief tightly around the "closest" historical entities, while smaller values distribute more belief to more distant entities.
#
# Note that by choosing the squared Mahalanobis distance and the exponential function with a factor of $\lambda=0.5$, the resulting weight effectively equals the density of a [multivariate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function) fitted to the historical data. A similar assertion applies when we use the sum of "standardized" squared distances instead. However, in this latter case, we "enforce" the independence of the features.
#
# The proper choice of distance and similarity metrics depends on insight into the dataset at hand. Weights can then be used to construct
# weighted histograms or density estimators for the posterior distributions of interest, or to directly resample historical rows.
# 
# ### Policy Search
# Given these parts, searching for optimal experimental designs (actions arranged in an efficient way) depends on what our objective sense is.
#
# - The search may continue until the uncertainty about the posterior distribution of the target variable falls below a certain level. Our aim is to minimize the anticipated combined monetary cost and execution time of the search (considered as a "negative" reward). If all experiments are conducted without reaching below the required uncertainty level, or if the maximum number of experiments is exceeded, we penalize this scenario with an "infinitely negative" reward.
# - We may aim to minimize the expected uncertainty while being constrained by the combined costs of the experiment.
# - Alternatively, we could maximize the value of experimental evidence, adjusted for the incurred experimental costs.
# Standard Markov decision process (MDP) algorithms can be used to solve this problem (offline learning) or construct the policy (online learning) for the sequential decision-making.
# Our MDP's state space is finite-dimensional but generally continuous due to the allowance of continuous features, which complicates the problem and few algorithms specialize in this area.
# We used the Double Progressive Widening Algorithm for this task as detailed in [A Comparison of Monte Carlo Tree Search and Mathematical Optimization for Large Scale Dynamic Resource Allocation](https://arxiv.org/abs/1405.5498).
# In a nutshell, the Double Progressive Widening (DPW) algorithm is designed for online learning in complex environments, particularly those known as Continuous Finite-dimensional Markov Decision Processes where the state space is continuous. The key idea behind DPW is to progressively expand the search tree during the Monte Carlo Tree Search (MCTS) process. The algorithm does so by dynamically and selectively adding states and actions to the tree based on defined heuristics.
# In the context of online learning, this algorithm addresses the complexity and challenges of real-time decision-making in domains with a large or infinite number of potential actions. As information is gathered in actual runtime, the algorithm explores and exploits this information to make optimal or near-optimal decisions. In other words, DPW permits the learning process to adapt on-the-fly as more data is made available, making it an effective tool for the dynamic and uncertain nature of online environments.
# In particular, at the core of the Double Progressive Widening (DPW) algorithm are several key components, including expansion, search, and rollout.
# The search component is where the algorithm sifts through the search tree to determine the most promising actions or states to explore next. By using exploration-exploitation strategies, it can effectively balance its efforts between investigating previously successful actions and venturing into unexplored territories.
# The expansion phase is where the algorithm grows the search tree by adding new nodes, representing new state-action pairs, to the tree. This is done based on a predefined rule that dictates when and how much the tree should be expanded. This allows the algorithm to methodically discover and consider new potential actions without becoming overwhelmed with choices.
# Lastly, the rollout stage, also known as a simulation stage, is where the algorithm plays out a series of actions to the end of a game or scenario using a specific policy (like a random policy). The results of these rollouts are then used to update the estimates of the values of state-action pairs, increasing the accuracy of future decisions.
# 
# In the above figure, nodes represent states of the decision process, while edges correspond to actions connecting these states.
# A graphical summary of a single step of the overall search process to find the next best action, using our running example where a new entity
# has had $e_{1}$ performed out of 3 possible experiments is below:
# 
# ## Synthetic Data Example with Continuous $y$
# We now present an example of finding cost-efficient generative designs on synthetic data using the CEEDesigns.jl package.
#
# First we load necessary packages.
using CEEDesigns, CEEDesigns.GenerativeDesigns
using DataFrames
using ScientificTypes
import Distributions
using Copulas
using POMDPs, POMDPTools, MCTS
using Plots, StatsPlots, StatsBase
# ### Synthetic Data
# We use the "Friedman #3" method to make synthetic data for a regression problem from [scikit-learn](https://scikit-learn.org/stable/datasets/sample_generators.html#generators-for-regression).
# It considers $m=4$ features which predict a continuous $y$ via some nonlinear transformations. The marginal
# distributions of each feature are given by the scikit-learn documentation. We additionally use a Gaussian copula
# to induce a specified correlation structure on the features to illustrate the difference between Euclidean and Mahalanobis
# distance metrics. We sample $l=1000$ rows of the historical data.
make_friedman3 = function (U, noise = 0, friedman3 = true)
size(U, 2) == 4 || error("input U must have 4 columns, has $(size(U,2))")
n = size(U, 1)
X = DataFrame(zeros(Float64, n, 4), :auto)
for i = 1:4
X[:, i] .= U[:, i]
end
ϵ = noise > 0 ? rand(Distributions.Normal(0, noise), size(X, 1)) : 0
if friedman3
X.y = @. atan((X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4])) / X[:, 1]) + ϵ
else
## Friedman #2
X.y = @. (X[:, 1]^2 + (X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4]))^2)^0.5 + ϵ
end
return X
end
ρ12, ρ13, ρ14, ρ23, ρ24, ρ34 = 0.8, 0.5, 0.3, 0.5, 0.25, 0.4
Σ = [
1 ρ12 ρ13 ρ14
ρ12 1 ρ23 ρ24
ρ13 ρ23 1 ρ34
ρ14 ρ24 ρ34 1
]
X1 = Distributions.Uniform(0, 100)
X2 = Distributions.Uniform(40 * π, 560 * π)
X3 = Distributions.Uniform(0, 1)
X4 = Distributions.Uniform(1, 11)
C = GaussianCopula(Σ)
D = SklarDist(C, (X1, X2, X3, X4))
X = rand(D, 1000)
data = make_friedman3(transpose(X), 0.01)
data[1:10, :]
# We can check that the empirical correlation is roughly the same as the specified theoretical values:
cor(Matrix(data[:, Not(:y)]))
# We ensure that our algorithms know that we have provided data of specified types.
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Continuous,
)
data = coerce(data, types);
# We may plot each feature $x_{i} \in X = {x_{1},x_{2},x_{3},x_{4}}$ against $y$.
p1 = scatter(data.x1, data.y; legend = false, xlab = "x1")
p2 = scatter(data.x2, data.y; legend = false, xlab = "x2")
p3 = scatter(data.x3, data.y; legend = false, xlab = "x3")
p4 = scatter(data.x4, data.y; legend = false, xlab = "x4")
plot(p1, p2, p3, p4; layout = (2, 2), legend = false)
# ### Distance-based Similarity
# Given historical data, a target variable $y$, and metric to quantify uncertainty around
# the posterior distribution on the target $q(y|e_{S})$, the function `DistanceBased`
# returns three functions needed by CEEDesigns.jl:
# - `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator;
# - `uncertainty`: this is a function of `evidence`,
# - `weights`: this represents a function of `evidence` that generates probability weights $w_j$ to each row in the historical data.
#
# By default, Euclidean distance is used as the distance metric. In the second
# call to `DistanceBased`, we instead use the squared Mahalanobis distance.
# It is possible to specify different distance metrics for each feature, see our
# [heart disease generative modeling](GenerativeDesigns.md) tutorial for more information.
# In both cases, the squared exponential function is used to convert distances
# to weights.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
(sampler_mh, uncertainty_mh, weights_mh) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 0),
);
# We can look at the uncertainty in $y$ for a state where a single
# feature is "observed" at its mean value.
# As we consider only a single non-missing entry, note that the probabilistic weights assigned by the squared Mahalanobis distance
# are generally less "spread out." This is because the variant of the squared Mahalanobis distance, which we implemented for handling missing values,
# effectively multiplies the other quadratic distance by a factor greater than one.
# For more details, refer to page 285 of
# [Multivariate outlier detection in incomplete survey data: The epidemic algorithm and transformed rank correlations](https://www.jstor.org/stable/3559861).
# The interaction with uncertainties is more complex as the uncertainty depends on the values of the target variable that correspond to the rows in the historical data.
data_uncertainties =
[i => uncertainty(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
data_uncertainties_mh =
[i => uncertainty_mh(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties_mh; by = x -> x[2], rev = true)
p1 = sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
title = "Uncertainty\n(Euclidean distance)",
)
p2 = sticks(
eachindex(data_uncertainties_mh),
[i[2] for i in data_uncertainties_mh];
xformatter = i -> data_uncertainties_mh[Int(i)][1],
label = false,
title = "Uncertainty\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
# We can view the posterior distribution $q(y|e_{S})$ conditioned on a state (here arbitrarily set to $S = e_{3}$, giving evidence for $x_{3}$).
evidence = Evidence("x3" => mean(data.x3))
plot_weights = StatsBase.weights(weights(evidence))
plot_weights_mh = StatsBase.weights(weights_mh(evidence))
p1 = Plots.histogram(
data.y;
weights = plot_weights,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Euclidean distance)",
)
p2 = Plots.histogram(
data.y;
weights = plot_weights_mh,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
# Like static designs, generative designs need to be provided a `DataFrame` assigning to each experiment
# a tuple of monetary and time costs $(m_{e},t_{e})$, and what features each experiment provides observations of.
# We'll set up the experimental costs such that experiments which have less marginal uncertainty are more costly
# We finally add a very expensive "final" experiment which can directly observe the target variable.
observables_experiments = Dict(["x$i" => "e$i" for i = 1:4])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(data_uncertainties_mh)
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
# ### Find Cost-efficient Experimental Designs
# We can now find cost-efficient experimental designs for a new entity that has no measurements (`Evidence()`).
# Our objective sense is to minimize expected experimental combined cost while trying to reduce uncertainty to
# a threshold value. We examine 7 different threshold levels of uncertainty, evenly spaced between 0 and 1, inclusive.
# Additionally we set the `costs_tradeoff` such that equal weight is given to time and monetary cost when
# constructing the combined costs of experiments.
#
# Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl)
# is created, and the `POMDPs.solve` is called on the problem.
# Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
#
# Note that we use the Euclidean distance, due to somewhat faster runtime.
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
# We plot the Pareto-efficient actions.
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
# ## Synthetic Data Example with Discrete $y$
# ### Synthetic Data
# We use n-class classification problem generator from [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html#sklearn.datasets.make_classification)
# We used parameters given below, for a total of $m=5$ features, with 4 of those informative and 1 redundant (linear combination of the other 4) feature.
# The $y$ has 2 classes, with some added noise. We again sample $l=1000$ rows of historical entities.
#
# The dataset can be approximately reproduced as below:
## using PyCall
## sklearn = PyCall.pyimport_conda("sklearn", "scikit-learn")
## py"""
## import sklearn as sk
## from sklearn.datasets import make_classification
## """
## X, y = py"make_classification(n_samples=1000,n_features=5,n_informative=4,n_redundant=1,n_repeated=0,n_classes=2,n_clusters_per_class=2,flip_y=0.1)"
## using DataFrames, CSV
## dat = DataFrame(X, :auto)
## dat.y = y
## CSV.write("./class.csv",dat)
using CSV
data = CSV.read("./data/class.csv", DataFrame)
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Multiclass,
)
data = coerce(data, types);
# ### Distance-based Similarity
# We now set up the distance based similarity functions. We use `Entropy` as our metric of uncertainty this time,
# which is more suitable for discrete $y$.
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Entropy(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
# We may also look at the uncertainty from each marginal distribution of features.
# This is a bit nonsensical as the data generating function will create multimodal clusters
# so it will look artifically as if nothing is informative, but that is not the case.
data_uncertainties =
[i => uncertainty(Evidence(i => mode(data[:, i]))) for i in names(data)[1:end-1]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
ylab = "Uncertainty",
)
# We can view the posterior distribution $q(y|e_{S})$ when we consider the state as evidence a single measurement
# of the first feature, set to the mean of that distribution.
evidence = Evidence("x1" => mean(data.x1))
plot_weights = StatsBase.weights(weights(evidence))
target_belief = countmap(data[!, "y"], plot_weights)
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["0", "1"]);
p
# Like previous examples, we'll set up the experimental costs such that experiments which have less marginal uncertainty
# are more costly, add a final very expensive experiment directly on the target variable.
observables_experiments = Dict(["x$i" => "e$i" for i = 1:5])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(sort(data_uncertainties; by = x -> x[2], rev = true))
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
# ### Find Cost-efficient Experimental Designs
# We can now find sets of cost-efficient experimental designs for a new entity with no measurements (`Evidence()`).
# We use the same solver parameters as for the exaple with continuous $y$, and plot the resulting
# Pareto front.
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 9309 | # # Static Experimental Designs
# In this document we describe the theoretical background behind the tools in CEEDesigns.jl for producing optimal "static experimental designs," i.e.,
# arrangements of experiments that exist along a Pareto-optimal tradeoff between cost and information gain.
# We also show an example with synthetic data.
# ## Setting
# Consider the following scenario. There exists a set of experiments, each of which, when performed, yields
# measurements on one or more observables (features). Each subset of observables (and therefore each subset of experiments)
# has some "information value," which is intentionally vaguely defined for generality, but for example, may be
# a loss function if that subset is used to train some machine learning model. It is generally the value of acquiring that information.
# Finally, each experiment has some monetary cost and execution time to perform the experiment, and
# the user has some known tradeoff between overall execution time and cost.
#
# CEEDesigns.jl provides tools to take these inputs and produce a set of optimal "arrangements" of experiments for each
# subset of experiments that form a Pareto front along the tradeoff between information gain and total combined cost
# (monetary and time). This allows informed decisions to be made, for example, regarding how to allocate scarce
# resources to a set of experiments that attain some acceptable level of information (or, conversely, reduce
# uncertainty below some level).
#
# The arrangements produced by the tools introduced in this tutorial are called "static" because they inherently
# assume that for each experiment, future data will deterministically yield the same information gain as the "historical" data did.
# This information gain from the "historical" data is quantified based on certain aggregate statistics.
#
# We can also consider "generative experimental designs," where the information gain is modeled as a random variable. This concept is detailed in another [tutorial](./SimpleGenerative.jl).
#
# This tutorial introduces the theoretical framework behind static experimental designs with synthetic data.
# For examples using real data, please see our other tutorials.
# ## Theoretical Framework
# ### Experiments
# Let $E = \{ e_1, \ldots, e_n\}$ be a set of $n$ experiments (i.e., $|E|=n$). Each experiment $e \in E$ has an
# associated tuple $(m_{e},t_{e})$, giving the monetary cost and time duration required to perform experiment $e$.
# 
# Consider $P(E)$, the power set of experiments (i.e., every possible subset of experiments). Each subset of
# experiments $S\in P(E)$ has an associated value $v_{S}$, which is the value of the experiments contained in $S$.
# This may be given by the loss function associated with a prediction task where the information yielded from $S$
# is used as predictor variables, or some other notion of information value.
# 
# ### Arrangements
# If experiments within a subset $S$ can be performed simultaneously (in parallel), then each $S$ may be arranged
# optimally with respect to time. An arrangement $O_{S}$ of $S$ is a partition of the experiments in $S$ such that
# the size of each partition is not larger than the maximum number of experiments that may be done in parallel.
#
# Let $l$ be the number of partitions, and $o_{i}$ a partition in $O_{S}$. Then the arrangement is a surjection from $S$
# onto $O_{S}$. If no experiments can be done in parallel, then $l=|S|$. If all experiments are done in parallel, then
# $l=1$. Other arrangements fall between these extremes.
# 
# ### Optimal Arrangements
# To find the optimal arrangement for each $S$ we need to know the cost of $O_{S}$. The monetary cost of $O_{S}$ is simply
# the sum of the costs of each experiment: $m_{O_{S}}=\sum_{e\in S} m_{e}$.
# The total time required is the sum of the maximum time *of each partition*. This is because while each partition in the
# arrangement is done in serial, experiments within partitions are done in parallel. That is, $t_{O_{S}}=\sum_{i=1}^{l} \text{max} \{ t_{e}: e \in o_{i}\}$.
# Given these costs and a parameter $\lambda$ which controls the tradeoff between monetary cost and time, the combined
# cost of an arrangement is: $\lambda m_{O_{S}} + (1-\lambda) t_{O_{S}}$.
#
# For instance, consider the experiments $S = \{e_{1},e_{2},e_{3},e_{4}\}$, with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$.
# If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement
# $O_{S} = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_{O_{S}} = 4$ and $t_{O_{S}} = 10$.
#
# However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement
# $O_{S} = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_{O_{S}} = 4$, and $t_{O_{S}} = 3 + 4 = 7$.
#
# Continuing our example and assuming a maximum of two parallel experiments, the optimal arrangement is to conduct
# $e_1$ in parallel with $e_2$, and $e_3$ with $e_4$. This results in an arrangement $O_{S} = (\{ e_1, e_2 \}, \{ e_3, e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 2 + 4 = 6$.
#
# In fact, it can be readily demonstrated that the optimal arrangement can be found by ordering the experiments in
# S in descending order according to their execution times. Consequently, the experiments are grouped sequentially
# into partitions whose size equals the maximum number of parallel experiments, except possibly for the final set,
# if the maximum number of parallel experiments does not divide $S$ evenly.
# ## Synthetic Data Example
# We now present an example of finding cost-efficient designs for synthetic data using the CEEDesigns.jl package.
#
# First we load necessary packages.
using CEEDesigns, CEEDesigns.StaticDesigns
using Combinatorics: powerset
using DataFrames
using POMDPs, POMDPTools, MCTS
# We consider a situation where there are 3 experiments, and we draw a value of their "loss function"
# or "entropy" from the uniform distribution on the unit interval for each.
#
# For each $S\in P(E)$, we simulate the information value ($v_{S}$) of $S$ as the product of
# the values for each individual experiment.
# Therefore, because smaller values are better, any subset containing multiple experiments is guaranteed to be
# more "valuable" than any component experiment.
experiments = ["e1", "e2", "e3"];
experiments_val = Dict([e => rand() for e in experiments]);
experiments_evals = Dict(map(Set.(collect(powerset(experiments)))) do s
if length(s) > 0
s => prod([experiments_val[i] for i in s])
else
return s => 1.0
end
end);
# See our other tutorial on [heart disease triage](StaticDesigns.md) for an example of using CEEDesigns.jl's built-in
# compatability with machine learning models from `MLJ.jl` to evalute performance of experiments using
# predictive accuracy as information value.
#
# Next we set up the costs $(m_{e},t_{e})$ for each experiment.
# Better experiments are more costly, both in terms of time and monetary cost. We print
# the data frame showing each experiment and its associated costs.
experiments_costs = Dict(
sort(collect(keys(experiments_val)); by = k -> experiments_val[k], rev = true) .=>
tuple.(1:3, 1:3),
);
DataFrame(;
experiment = collect(keys(experiments_costs)),
time = getindex.(values(experiments_costs), 1),
cost = getindex.(values(experiments_costs), 2),
)
# We can plot the experiments ordered by their information value.
plot_evals(
experiments_evals;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "loss",
)
# We print the data frame showing each subset of experiments and its overall information value.
df_values = DataFrame(;
S = collect.(collect(keys(experiments_evals))),
value = collect(values(experiments_evals)),
)
sort(df_values, order(:value; rev = true))
# Now we are ready to find the subsets of experiments giving an optimal tradeoff between information
# value and combined cost. CEEDesigns exports a function `efficient_designs`
# which formulates the problem of finding optimal arrangements as a Markov Decision Process and solves
# optimal arrangements for each subset on the Pareto frontier.
#
# We set $\lambda=0.5$, the parameter controlling the relative weight given to monetary versus time costs
# with the tuple `tradeoff`.
max_parallel = 2;
tradeoff = (0.5, 0.5);
designs = efficient_designs(
experiments_costs,
experiments_evals;
max_parallel = max_parallel,
tradeoff = tradeoff,
);
# Finally we may produce a plot of the set of cost-efficient experimental designs. The set of designs
# is plotted along a Pareto frontier giving tradeoff between informatio value (y-axis) and combined cost (x-axis).
# Note that because we set the maximum number of parallel experiments equal to 2, the efficient design for the complete set
# of experiments groups the experiments with long execution times together (see plot legend; each group within a partition is
# prefixed with a number).
plot_front(designs; labels = make_labels(designs), ylabel = "loss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 6960 | # # Heart Disease Triage
# Consider a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# For details on the theoretical background and notation, please see our tutorial on [static experimental designs](SimpleStatic.md), this tutorial
# is a concrete application of the tools described in that document.
# ### Application to Predictive Modeling
# Let's generalize the example from [static experimental designs](SimpleStatic.md) to the case where we want to compute the information value $v_{S}$ as the predictive
# ability of a machine learning model which uses the measurements gained from experiments in $S$ to predict some $y$ of interest.
#
# Let's introduce some formal notation.
# Consider a dataset of historical readouts over $m$ features $X = \{x_1, \ldots, x_m\}$, and let $y$ denote the target variable that we want to predict.
# Assume that each experiment $e \in E$ yields readouts over a subset $X_e \subseteq X$ of features.
# Then, for each subset $S \subseteq E$ of experiments, we may model the value of information acquired by conducting the experiments in $S$ as the accuracy of a predictive model that predicts the value of $y$ based on readouts over features in $X_S = \bigcup_{e\in S} X_e$.
# Then this accuracy is our information value $v_{S}$ of $S$.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# ## Predictive Accuracy
# The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
# We may also provide additional zero-cost features, which are always available.
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# And we specify the target for prediction.
target = "HeartDisease"
# ### Classifier
# We use [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
using MLJ
import BetaML, MLJModels
using Random: seed!
# We provide appropriate scientific types of the features.
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
# Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with our dataset:
models(matching(data, data[:, "HeartDisease"]))
# Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 3
model = classifier(; n_trees = 20, max_depth = 10)
# ### Performance Evaluation
# We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as a measure of accuracy. It is possible to provide additional keyword arguments, which will be passed to `MLJ.evaluate` (such as `measure`, shown below).
using CEEDesigns, CEEDesigns.StaticDesigns
#
seed!(1) # evaluation process generally is not deterministic
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
# We plot performance measures evaluated for subsets of experiments, sorted by performance measure.
plot_evals(
perf_eval;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "logloss",
)
# ## Cost-Efficient Designs
# We specify the cost associated with the execution of each experiment.
costs = Dict(
## experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs.
designs = efficient_designs(costs, perf_eval)
#
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
# ### Parallel Experiments
# The previous example assumed that experiments had to be run sequentially. We can see how the optimal arrangement changes if we assume multiple experiments can be run in parallel. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments_costs = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
# We set the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
# Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
## Implicit, calculates accuracies automatically.
seed!(1) # evaluation process generally is not deterministic
designs = efficient_designs(
experiments_costs,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
# As we can see, the algorithm correctly suggests running experiments in parallel.
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 13892 | # # Heart Disease Triage With Early Droupout
# Consider again a situation where a group of patients is tested for a specific disease.
# It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
# Moreover, we may assume that for some patients, the evidence gathered from proxy experiments can be considered 'conclusive'. Effectively, some patients may not need any additional triage; they might be deemed healthy or require immediate commencement of treatment. By doing so, we could save significant resources.
# ## Theoretical Framework
# We take as a basis the setup and notation from the basic framework presented in the [static experimental designs tutorial](SimpleStatic.md).
# We again have a set of experiments $E$, but now assume that a set of extrinsic decision-making rules is imposed on the experimental readouts.
# If the experimental evidence acquired for a given entity satisfies a specific criterion, that entity is then removed from the triage.
# However, other entities within the batch will generally continue in the experimental process.
# In general, the process of establishing such rules is largely dependent on the specific problem and requires comprehensive understanding of the subject area.
# We denote the expected fraction of entities that remain in the triage after conducting a set $S$ of experiments as the filtration rate, $f_S$. In the context of disease triage, this can be interpreted as the fraction of patients for whom the experimental evidence does not provide a 'conclusive' result.
# As previously, each experiment $e$ incurs a cost $(m_e, t_e)$. Again, we let $O_{S}$ denote an arrangement of experiments in $S$.
# Given a subset $S$ of experiments and their arrangement $O_{S}$, the total (discounted) monetary cost and execution time of the experimental design is given as $m_o = \sum_{i=1}^{l} r_{S_{i-1}}\sum_{e\in o_i} m_e$ and $t_o = \sum_{i=1}^{l} \max \{ t_e : e\in o_i\}$, respectively.
# Importantly, the new factor $r_{S_{i-1}}$ models the fact that a set of entities may have dropped out in the previous experiments, hence saving the resources on running the subsequent experiments.
# We note that these computations are based on the assumption that monetary cost is associated with the analysis of a single experimental entity, such as a patient. Therefore, the total monetary cost obtained for a specific arrangement is effectively the ["expected"](https://en.wikipedia.org/wiki/Expected_value) monetary cost, adjusted for a single entity. Conversely, we suppose that all entities can be concurrently examined in a specific experiment. As such, the total execution time is equivalent to the longest time until all experiments within an arrangement are finished or all entities have been eliminated (which ocurrs when the filtration rate the experiments conducted so far is zero). Importantly, this distinctly differs from calculating the 'expected lifespan' of an entity in the triage.
# For instance, consider the experiments $e_1,\, e_2,\, e_3$, and $e_4$ with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$, and filtration rates $0.9,\,0.8,\,0.7$, and $0.6$. For subsets of experiments, we simply assume that the filtration rates multiply, thereby treating the experiments as independent binary discriminators. In other words, the filtration rate for a set $S=\{ e_1, e_3 \}$ would equal $f_S = 0.9 * 0.7 = 0.63$.
# If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement $o = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_o = 1 + 0.9 * 1 + 0.72 * 1 + 0.504 * 1 = 3.124$ and $t_o = 10$.
# However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement $o = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_o = 2 + 0.63 * 2 = 3.26$, and $t_o = 3 + 4 = 7$.
# Given the constraint on the maximum number of parallel experiments, we construct an arrangement $o$ of experiments $S$ such that, for a fixed tradeoff $\lambda$ between monetary cost and execution time, the expected combined cost $c_{(o, \lambda)} = \lambda m_o + (1-\lambda) t_o$ is minimized. Significantly, our objective is to leverage the filtration rates within the experimental arrangement.
# ### A Note on Optimal Arrangements
# In situations when experiments within a set $S$ are executed sequentially, i.e., one after the other, it can be demonstrated that the experiments should be arranged in ascending order by $\frac{\lambda m_e + (1-\lambda) t_e}{1-f_e}$.
# Continuing our example and assuming that the experiments are conducted sequentially, the optimal arrangement $o$ would be to run experiments $e_4$ through $e_1$, yielding $m_o = 2.356$.
# When we allow simultaneous execution of experiments, the problem turns more complicated, and we currently are not aware of an 'analytical' solution for it. Instead, we proposed approximating the 'optimal' arrangement as the 'optimal' policy found for a particular Markov decision process, in which:
# - _state_ is the set of experiments that have been conducted thus far,
# - _actions_ are subsets of experiments which have not been conducted yet; the size of these subsets is restricted by the maximum number of parallel experiments;
# - _reward_ is a combined monetary cost and execution time, discounted by the filtration rate of previously conducted experiments.
# Provided we know the information values $v_S$, filtration rates $r_S$, and experimental costs $c_S$ for each set of experiments $S$, we find a collection of Pareto-efficient experimental designs that balance both the implied value of information and the experimental cost.
# ## Heart Disease Dataset
# In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
# In order to adapt the dataset to the current context, we can assume that, for every experiment, a medical specialist determined a range for 'conclusive' and 'inconclusive' outputs. This determination could be based on, say, optimizing the precision and recall factors of the resultant discriminative model. As an example, consider [A novel approach for heart disease prediction using strength scores with significant predictors](https://d-nb.info/1242792767/34) where rule mining for heart disease prediction is considered.\
# It should be noted that the readout ranges defined below are entirely fictional.
inconclusive_regions = Dict(
"ChestPainType" => ["NAP", "ASY"],
"RestingBP" => (50, 150),
"ExerciseAngina" => ["N"],
"FastingBS" => [0],
"RestingECG" => ["Normal"],
"MaxHR" => (50, 120),
"Cholesterol" => (0, 240),
"Oldpeak" => (-2.55, 2.55),
)
# We apply the rules to derive a binary dataset where 'true' signifies that the readout was inconclusive, requiring them to remain in the triage.
data_binary = DataFrame();
for colname in names(data[!, Not("HeartDisease")])
if haskey(inconclusive_regions, colname)
if inconclusive_regions[colname] isa Vector
data_binary[!, colname] =
map(x -> x ∈ inconclusive_regions[colname], data[!, colname])
else
lb, ub = inconclusive_regions[colname]
data_binary[!, colname] = map(x -> lb <= x <= ub, data[!, colname])
end
else
data_binary[!, colname] = trues(nrow(data))
end
end
data_binary[1:10, :]
# ## Discriminative Power and Filtration Rates
# In this scenario, we model the value of information $v_S$ acquired by conducting a set of experiments as the ratio of patients for whom the results across the experiments in $S$ were 'inconclusive', i.e., $|\cap_{e\in S}\{ \text{patient} : \text{inconclusive in } e \}| / |\text{patients}|$. Essentially, the very same measure is used here to estimate the filtration rate.
# The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
# We specify the experiments along with the associated features:
experiments = Dict(
## experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
# We may also provide additional zero-cost features, which are always available.
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
# For binary datasets, we may use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the discriminative power of subsets of experiments.
using CEEDesigns, CEEDesigns.StaticDesigns
#
perf_eval = evaluate_experiments(experiments, data_binary; zero_cost_features)
# Note that for each subset of experiments, the function returns a named tuple with fields `loss` and `filtration`.
# We plot discriminative power evaluated for subsets of experiments.
plot_evals(perf_eval; ylabel = "discriminative power")
# ## Cost-Efficient Designs
# We specify the cost associated with the execution of each experiment.
costs = Dict(
## experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
# We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs. Note that the filtration is enabled implicitly since we provided the filtration rates within `perf_eval`. Another form of `perf_eval` would be `subset of experiments => information measure`, in which case the filtration would equal one. That is, no dropout would be considered.
designs = efficient_designs(costs, perf_eval)
#
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
# Let us compare the above with the efficient front with disabled filtration.
## pass performance eval with discarded filtration rates (defaults to 1)
designs_no_filtration = efficient_designs(costs, Dict(k => v.loss for (k, v) in perf_eval))
#
using Plots
p = scatter(
map(x -> x[1][1], designs_no_filtration),
map(x -> x[1][2], designs_no_filtration);
label = "designs with filtration disabled",
c = :blue,
mscolor = nothing,
fontsize = 16,
)
scatter!(
p,
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
xlabel = "combined cost",
ylabel = "discriminative power",
label = "designs with filtration enabled",
c = :teal,
mscolor = nothing,
fontsize = 16,
)
# ## Arrangement of a Set of Experiments
# Importantly, the total execution cost of an experiment is generally not the sum of costs associated to each individual experiment. In fact, a non-zero dropout rate (`filtration < 1`) discounts the expected cost of subsequent experiments. As discussed previously, we are not aware of an 'analytical' solution to this problem.
# Instead, we approximate the 'optimal' arrangement as the 'optimal' policy for a particular Markov decision process. This can be accomplished using, for instance, the [Monte Carlo Tree Search algorithm](https://github.com/JuliaPOMDP/MCTS.jl) as implemented in the [POMDPs.jl](http://juliapomdp.github.io/POMDPs.jl/latest/) package.
# The following is a visualisation of the DPW search tree that was used to find an optimal arrangement for a set of experiments yielding the highest information value.
using MCTS, D3Trees
experiments = Set(vcat.(designs[end][2].arrangement...)[1])
(; planner) = CEEDesigns.StaticDesigns.optimal_arrangement(
costs,
perf_eval,
experiments;
mdp_kwargs = (; tree_in_info = true),
)
_, info = action_info(planner, Set{String}())
t = D3Tree(info[:tree]; init_expand = 2)
#
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
# ### Parallel Experiments
# We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
experiments_costs = Dict(
## experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
# We provide the maximum number of concurrent experiments. Additionally, we specify the tradeoff between monetary cost and execution time - in our case, we aim to minimize the execution time.
# Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
## Implicit, calculates accuracies automatically
designs = efficient_designs(
experiments_costs,
data_binary;
eval_options = (; zero_cost_features),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
# As we can see, the algorithm correctly suggests running experiments in parallel.
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 23002 | ### A Pluto.jl notebook ###
# v0.19.27
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try
Base.loaded_modules[Base.PkgId(
Base.UUID("6e696c72-6542-2067-7265-42206c756150"),
"AbstractPlutoDingetjes",
)].Bonds.initial_value
catch
b -> missing
end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ fc17a594-02f3-46b5-a012-136ab5d0ba38
# ╠═╡ show_logs = false
begin
import Pkg
Pkg.activate("..")
using PlutoUI
md"""
Case [_TCGA-HT-8564_](https://portal.gdc.cancer.gov/cases/f625e522-226b-450f-af94-dd2f5adb605e?filters=%7B%22content%22%3A%5B%7B%22content%22%3A%7B%22field%22%3A%22cases.project.project_id%22%2C%22value%22%3A%5B%22TCGA-LGG%22%5D%7D%2C%22op%22%3A%22in%22%7D%5D%2C%22op%22%3A%22and%22%7D), Diagnosis _Astrocytoma, anaplastic_:
$(LocalResource("glioma_slide.jpeg", :width => 500, :style => "display: block; margin-left: auto; margin-right: auto;"))
"""
end
# ╔═╡ d66ad52c-4ac9-4a04-884b-bfa013f9acd9
begin
using CSV, DataFrames
data = CSV.File("../data/glioma_grading.csv") |> DataFrame
end
# ╔═╡ b7b62e65-9bd3-4bd8-9a71-2bea4ba109c4
begin
using MLJ
import BetaML, MLJModels
using Random: seed!
md"We fix the scientific types of features."
end
# ╔═╡ 6ebd71e0-b49a-4d12-b441-4805efc69520
begin
using CEEDesigns, CEEDesigns.StaticDesigns
md"""
### Cost-Efficient Feature Selection
We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as a measure of accuracy. It is possible to pass additional keyword arguments, which will be passed to `MLJ.evaluate` (such as `measure`, shown below).
"""
end
# ╔═╡ 7f2e19e0-4cf3-11ee-0e10-dba25ffccc94
md"""
# Cost-Efficient Experimental Design Towards Glioma Grading
Gliomas are the most common primary tumors of the brain. They can be graded as LGG (Lower-Grade Glioma) or GBM (Glioblastoma Multiforme), depending on the histological and imaging criteria. Clinical and molecular or genetic factors are also very crucial for the grading process. The ultimate aim is to identify the optimal subset of clinical, molecular or genetic, and histological features for the glioma grading process to improve diagnostic accuracy and reduce costs.
## Theoretical Framework
Let us consider a set of $n$ experiments $E = \{ e_1, \ldots, e_n\}$.
For each subset $S \subseteq E$ of experiments, we denote by $v_S$ the value of information acquired from conducting experiments in $S$.
In the cost-sensitive setting of CEEDesigns, conducting an experiment $e$ incurs a cost $(m_e, t_e)$. Generally, this cost is specified in terms of monetary cost and execution time of the experiment.
To compute the cost associated with carrying out a set of experiments $S$, we first need to introduce the notion of an arrangement $o$ of the experiments $S$. An arrangement is modeled as a sequence of mutually disjoint subsets of $S$. In other words, $o = (o_1, \ldots, o_l)$ for a given $l\in\mathbb N$, where $\bigcup_{i=1}^l o_i = S$ and $o_i \cap o_j = \emptyset$ for each $1\leq i < j \leq l$.
Given a subset $S$ of experiments and their arrangement $o$, the total monetary cost and execution time of the experimental design is given as $m_o = \sum_{e\in S} m_e$ and $t_o = \sum_{i=1}^l \max \{ t_e : e\in o_i\}$, respectively.
For instance, consider the experiments $e_1,\, e_2,\, e_3$, and $e_4$ with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$. If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement $o = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 10$.
However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement $o = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_o = 4$, and $t_o = 3 + 4 = 7$.
Given the constraint on the maximum number of parallel experiments, we devise an arrangement $o$ of experiments $S$ such that, for a fixed tradeoff between monetary cost and execution time, the expected combined cost $c_{(o, \lambda)} = \lambda m_o + (1-\lambda) t_o$ is minimized (i.e., the execution time is minimized).
In fact, it can be readily demonstrated that the optimal arrangement can be found by ordering the experiments in set $S$ in descending order according to their execution times. Consequently, the experiments are grouped sequentially into sets whose size equals to the maximum number of parallel experiments, except possibly for the final set.
Continuing our example and assuming a maximum of two parallel experiments, the optimal arrangement is to conduct $e_1$ in parallel with $e_2$, and $e_3$ with $e_4$. This results in an arrangement $o = (\{ e_1, e_2 \}, \{ e_3, e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 2 + 4 = 6$.
Assuming the information values $v_S$ and optimized experimental costs $c_S$ for each subset $S \subseteq E$ of experiments, we then generate a set of cost-efficient experimental designs.
### Application to Predictive Modeling
Consider a dataset of historical readouts over $m$ features $X = \{x_1, \ldots, x_m\}$, and let $y$ denote the target variable that we want to predict.
We assume that each experiment $e \in E$ yields readouts over a subset $X_e \subseteq X$ of features.
Then, for each subset $S \subseteq E$ of experiments, we may model the value of information acquired by conducting the experiments in $S$ as the accuracy of a predictive model that predicts the value of $y$ based on readouts over features in $X_S = \bigcup_{e\in S} X_e$.
"""
# ╔═╡ 2edaa133-6907-44f9-b39c-da06dae3eead
md"""
## Glioma Grading Clinical and Mutation Dataset
In this dataset, the instances represent patient records of those diagnosed with brain glioma. The dataset is publicly available at [Glioma Grading Clinical and Mutation Features](https://archive.ics.uci.edu/dataset/759/glioma+grading+clinical+and+mutation+features+dataset). It is constructed based on the TCGA-LGG and TCGA-GBM brain glioma projects available at the [NIH GDC Data Portal](https://portal.gdc.cancer.gov).
Each record is characterized by
- 3 clinical features (age, gender, race),
- 5 mutation factors (IDH1, TP53, ATRX, PTEN, EGFR; each of which can be 'mutated' or 'not_mutated').
We list somatic mutations with the highest number of affected cases in cohort:
"""
# ╔═╡ 6737a98e-20b9-4016-85f6-c8f4a07d04f8
md"""$(LocalResource("mutations.png", :width => 500, :style => "display: block; margin-left: auto; margin-right: auto;"))"""
# ╔═╡ 1364c91a-4331-4a1b-8c3d-fb40743c1df7
md"We load the dataset:"
# ╔═╡ 87f9826f-865f-4d1f-b122-e1ccae51bfdf
md"## Assessing the Predictive Accuracy
We specify the clinical features and mutation factors."
# ╔═╡ 9835f38b-b720-429d-8a8b-eab742fe7e05
features_clinical = ["Age_at_diagnosis", "Gender", "Race"]
# ╔═╡ 0bb794a2-d0b4-493d-8a10-d19a515271ec
features_mutation = ["IDH1", "TP53", "ATRX", "PTEN", "EGFR", "CIC", "MUC16"]
# ╔═╡ 1c72a85d-19cb-44f3-b330-a312b9ef9b7c
md"Classification target is just the glioma grade"
# ╔═╡ 7e2bb98c-1175-4964-8c41-8e3ac8e6eb9f
target = "Grade"
# ╔═╡ d74684f6-7fd4-41c8-9917-d99dfc1f5f64
md"In the cost-sensitive setting of CEEDesigns, obtaining additional experimental evidence comes with a cost. We assume that each gene mutation factor is obtained through a separate experiment."
# ╔═╡ f176f8cf-8941-4257-ba41-60fff864aa56
# We assume that each feature is measured separately and the measurement incurs a monetary cost.
experiments = Dict(
## experiment => features
"TP53" => 3.0 => ["TP53"],
"EGFR" => 2.0 => ["EGFR"],
"PTEN" => 4.0 => ["PTEN"],
"ATRX" => 2.0 => ["ATRX"],
"IDH1" => 3.0 => ["IDH1"],
"CIC" => 1.0 => ["CIC"],
"MUC16" => 2.0 => ["MUC16"],
)
# ╔═╡ 9547fc15-7dff-49a3-b5d2-43b54a6dc443
md"""
### Classifier
We use a package called [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
"""
# ╔═╡ 61219167-805c-4624-932e-d050a13ada07
begin
types = Dict(
name => Multiclass for name in [Symbol.(features_mutation); :Grade; :Gender; :Race]
)
data_typefix = coerce(data, types)
schema(data_typefix)
end
# ╔═╡ 63b7b1f3-660d-4a42-8b2c-3c0851d2b859
md"Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with the dataset:"
# ╔═╡ d0973a67-f24e-4ffd-8343-7fe7be400d07
models(matching(data_typefix, data_typefix[:, target]))
# ╔═╡ f797ccd0-e98e-4617-a966-455469d16096
md"Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)"
# ╔═╡ b987567b-f500-4837-8f23-412a2eecec51
classifier = @load RandomForestClassifier pkg = BetaML verbosity = -1
# ╔═╡ 88a20956-e665-4b0f-81f2-0e7ec8a1e28f
model = classifier(; n_trees = 8, max_depth = 5)
# ╔═╡ c1860fca-f304-4bb4-9266-5a6d71467e27
# ╠═╡ show_logs = false
begin
seed!(1) # evaluation process generally is not deterministic
perf_eval = evaluate_experiments(
experiments,
model,
data_typefix[!, Not(target)],
data_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 10),
)
end
# ╔═╡ ccdef55c-0570-404a-bb3d-ea0b9487c321
# ╠═╡ show_logs = false
begin
using Plots
plotly()
designs = efficient_designs(experiments, perf_eval)
function plot_front_invert(
designs;
grad = cgrad(:Paired_12),
xlabel = "combined cost",
ylabel = "information measure",
labels = make_labels(designs),
)
xs = map(x -> x[1][1], designs)
ys = map(x -> x[1][2], designs)
p = scatter(
[xs[1]],
[1 - ys[1]];
xlabel,
ylabel,
label = labels[1],
c = grad[1],
mscolor = nothing,
fontsize = 16,
legendposition = :bottomright,
title = "cost-efficient experimental designs",
)
for i = 2:length(designs)
if xs[i] < 10_000
scatter!(
p,
[xs[i]],
[1 - ys[i]];
label = labels[i],
c = grad[i],
mscolor = nothing,
)
end
end
return p
end
plot_front_invert(
designs;
labels = make_labels(designs),
ylabel = "accuracy (1-logloss)",
) # fill("", (1, length(designs)))
end
# ╔═╡ 01646835-55a9-42af-8eb3-29816c9780b7
md"We proceed to construct the set of cost-efficient experimental designs. In doing so, our goal is to identify the optimal sets of mutation factors for the glioma grading task, balancing the conflicting objectives of enhancing prediction accuracy and reducing incurred costs."
# ╔═╡ dcd790bd-36a5-4536-9e21-4f54fe2cf4e4
begin
function predict(
X;
positive_label = 1,
negative_label = 0,
sensitivity::Float64,
specificity::Float64,
)
y_pred = similar(X, Union{typeof(positive_label),typeof(negative_label)})
# simulate a predictor with given sensitivity and specificity
for i in eachindex(X)
if X[i] == positive_label
y_pred[i] = rand() < sensitivity ? positive_label : negative_label
else
y_pred[i] = rand() < (1 - specificity) ? positive_label : negative_label
end
end
return y_pred
end
sensitivity_slider =
@bind sensitivity Slider(0:0.01:1, default = 0.73, show_value = true)
specificity_slider =
@bind specificity Slider(0:0.01:1, default = 0.74, show_value = true)
cost_slider = @bind cost Slider(1:1:10, default = 1, show_value = true)
md"""
## Assessing the Impact of Histoathology Image Analysis on the Experimental Cost-Efficiency
Building on the previous example, we will consider the introduction of a new feature in the task of glioma grading, where this feature will essentially function as a predictor of the glioma grade.
In [Glioma Grading via Analysis of Digital Pathology Images Using Machine Learning](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7139732/), the authors proposed a computational method that exploits pattern analysis methods for grade prediction in gliomas using digital pathology images.
From the abstract, _according to the remarkable performance of computational approaches in the digital pathology domain, we hypothesized that machine learning can help to distinguish low-grade gliomas (LGG) from high-grade gliomas (HGG) by exploiting the rich phenotypic information that reflects the microvascular proliferation level, mitotic activity, presence of necrosis, and nuclear atypia present in digital pathology images. A set of 735 whole-slide digital pathology images of glioma patients (median age: 49.65 years, male: 427, female: 308, median survival: 761.26 days) were obtained from TCGA. Sub-images that contained a viable tumor area, showing sufficient histologic characteristics, and that did not have any staining artifact were extracted. Several clinical measures and imaging features, including conventional (intensity, morphology) and advanced textures features (gray-level co-occurrence matrix and gray-level run-length matrix), extracted from the sub-images were further used for training the support vector machine model with linear configuration._
$(LocalResource("architecture.png", :width => 600, :style => "display: block; margin-left: auto; margin-right: auto;"))
The authors aimed to evaluate the combined effect of conventional imaging, clinical, and texture features by assessing the predictive value of each feature type and their combinations through a predictive classifier.
For our specific intent, we will focus on the predictive accuracy of a classifier that utilizes only imaging features.
$(LocalResource("accuracy.png", :width => 600, :style => "display: block; margin-left: auto; margin-right: auto;"))
We will artificially produce the grade predictions, modelling them as predictor outputs with the defined sensitivity and specificity. Note that we will not incorporate any further correlations with other features such as clinical factors, mutation factors, or histology.
In addition, we consider the cost of the predictive classifier development.
| parameter | value picker |
| :-----: | :------: |
| sensitivity | $sensitivity_slider |
| specificity | $specificity_slider |
| cost | $cost_slider |
"""
end
# ╔═╡ c2121983-7135-4833-a33a-2dbc331272f3
digital_pathology = map(
x -> x == "LGG" ? "lower grade" : "glioblastoma",
predict(
data_typefix[!, target];
positive_label = "GBM",
negative_label = "LGG",
sensitivity,
specificity,
),
)
# ╔═╡ a271f163-046e-40cc-8134-c7619bf6a63a
begin
experiments_new_feature =
push!(copy(experiments), "digital_pathology" => cost => ["digital_pathology"])
end
# ╔═╡ 9ee21001-8404-4d5d-875b-6ea7952f65b8
md"We add the new feature to the dataset:"
# ╔═╡ bc31504a-9374-4da3-9d68-030994ba8fcf
begin
data_new_feature = data_new_feature = copy(data_typefix)
data_new_feature.digital_pathology = digital_pathology
data_new_feature_typefix = coerce(
data_new_feature,
Dict(
(
name => Multiclass for
name in [Symbol.(features_mutation); :Grade; :Gender; :Race]
)...,
:new_feature => Multiclass,
),
)
data_new_feature_typefix[
!,
[
["IDH1", "digital_pathology"]
setdiff(names(data_new_feature_typefix), ("digital_pathology", "IDH1"))
],
]
end
# ╔═╡ 0c58ddff-ad6f-4e80-8f1a-3c0c8d5245d2
# ╠═╡ show_logs = false
begin
seed!(1) # evaluation process generally is not deterministic
perf_eval_new_feature = evaluate_experiments(
experiments_new_feature,
model,
data_new_feature_typefix[!, Not(target)],
data_new_feature_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 10),
)
end
# ╔═╡ 3d710dad-9b8c-47a3-966b-9718cb76fad8
md"We evaluate performance measures across different experimental subsets, comparing those that include the histology feature and those that do not."
# ╔═╡ 6ed9b5e5-754c-47f6-b1e4-2514d23039d2
begin
evals1_new_feature = filter(x -> "digital_pathology" ∉ x[1], perf_eval_new_feature)
xs1_new_feature =
sort!(collect(keys(evals1_new_feature)); by = x -> -perf_eval_new_feature[x])
#xs1_new_feature = xs1_new_feature[begin:2:end]
ys1_new_feature = map(xs1_new_feature) do x
return if perf_eval_new_feature[x] isa Number
perf_eval_new_feature[x]
else
perf_eval_new_feature[x].loss
end
end
evals2_new_feature = filter(x -> "digital_pathology" ∈ x[1], perf_eval_new_feature)
xs2_new_feature_new_feature = sort!(
collect(keys(evals2_new_feature));
by = x -> -perf_eval_new_feature[setdiff(x, ["histology"])],
)
#xs2_new_feature_new_feature = xs2_new_feature_new_feature[begin:2:end]
ys2_new_feature = map(xs2_new_feature_new_feature) do x
return if perf_eval_new_feature[x] isa Number
perf_eval_new_feature[x]
else
perf_eval_new_feature[x].loss
end
end
p_evals_new_feature = Plots.sticks(
1:length(xs2_new_feature_new_feature),
1 .- min.(ys1_new_feature, ys2_new_feature);
ticks = 1:4:length(evals2_new_feature),
#xformatter=i -> isempty(xs2_new_feature_new_feature[Int(i)]) ? "∅" : join(xs1_new_feature[Int(i)], ", "),
guidefontsize = 8,
tickfontsize = 8,
ylabel = "accuracy",
c = CEEDesigns.colorant"rgb(110,206,178)",
label = "w/ histology feature",
xrotation = 50,
)
Plots.sticks!(
p_evals_new_feature,
1:length(xs1_new_feature),
1 .- ys1_new_feature;
ticks = 1:4:length(evals1_new_feature),
xformatter = i ->
isempty(xs1_new_feature[Int(i)]) ? "∅" : join(xs1_new_feature[Int(i)], ", "),
guidefontsize = 8,
tickfontsize = 8,
ylabel = "accuracy",
c = CEEDesigns.colorant"rgb(104,140,232)",
label = "w/o histology feature",
width = 2,
xrotation = 50,
)
end
# ╔═╡ 765ed41a-50e5-4989-98a1-1d2abfa3ba28
md"We proceed to construct the set of cost-efficient experimental designs, comparing the frontier that incorporates the histology feature with the one that does not."
# ╔═╡ 95567d4d-6594-4a25-8449-b7b95738c56c
# ╠═╡ show_logs = false
begin
experiments_new_feature_no_feature = copy(experiments_new_feature)
delete!(experiments_new_feature_no_feature, "digital_pathology")
seed!(1)
perf_eval_new_feature_no_feature = evaluate_experiments(
experiments_new_feature_no_feature,
model,
data_new_feature_typefix[!, Not(target)],
data_new_feature_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 10),
)
for (k, v) in perf_eval_new_feature_no_feature
perf_eval_new_feature[k] = v
end
design_new_feature = efficient_designs(experiments_new_feature, perf_eval_new_feature)
design_new_feature_no_feature = efficient_designs(
experiments_new_feature_no_feature,
perf_eval_new_feature_no_feature,
)
p_new_feature = scatter(
map(x -> x[1][1], design_new_feature),
map(x -> 1 - x[1][2], design_new_feature);
xlabel = "combined cost",
ylabel = "accuracy",
label = "w/ histology feature",
c = CEEDesigns.colorant"rgb(110,206,178)",
mscolor = nothing,
fontsize = 16,
#fill = (0, CEEDesigns.colorant"rgb(110,206,178)"),
fillalpha = 0.2,
legend = :bottomright,
)
scatter!(
p_new_feature,
map(x -> x[1][1], design_new_feature_no_feature),
map(x -> 1 - x[1][2], design_new_feature_no_feature);
label = "w/o histology feature",
c = CEEDesigns.colorant"rgb(104,140,232)",
mscolor = nothing,
fontsize = 16,
#fill = (0, CEEDesigns.colorant"rgb(104,140,232)"),
fillalpha = 0.15,
title = "sensitivity = $sensitivity, specificity = $specificity, cost = $cost",
)
end
# ╔═╡ 53023ce3-2c74-46b7-82eb-589a78ca89c0
md"This is a dynamic illustration demonstrating the efficient frontiers generated for a range of predictive model parameters."
# ╔═╡ 6900000d-8bfd-4f8b-bf5b-46cefce652e4
LocalResource("anim.gif")
# ╔═╡ 471eaf63-ca16-486e-b63a-ea3852768a0f
html"""<style>
main {
text-align: justify;
text-justify: inter-word;
}
"""
# ╔═╡ Cell order:
# ╟─7f2e19e0-4cf3-11ee-0e10-dba25ffccc94
# ╟─2edaa133-6907-44f9-b39c-da06dae3eead
# ╟─6737a98e-20b9-4016-85f6-c8f4a07d04f8
# ╟─fc17a594-02f3-46b5-a012-136ab5d0ba38
# ╟─1364c91a-4331-4a1b-8c3d-fb40743c1df7
# ╟─d66ad52c-4ac9-4a04-884b-bfa013f9acd9
# ╟─87f9826f-865f-4d1f-b122-e1ccae51bfdf
# ╟─9835f38b-b720-429d-8a8b-eab742fe7e05
# ╟─0bb794a2-d0b4-493d-8a10-d19a515271ec
# ╟─1c72a85d-19cb-44f3-b330-a312b9ef9b7c
# ╟─7e2bb98c-1175-4964-8c41-8e3ac8e6eb9f
# ╟─d74684f6-7fd4-41c8-9917-d99dfc1f5f64
# ╟─f176f8cf-8941-4257-ba41-60fff864aa56
# ╟─9547fc15-7dff-49a3-b5d2-43b54a6dc443
# ╟─b7b62e65-9bd3-4bd8-9a71-2bea4ba109c4
# ╟─61219167-805c-4624-932e-d050a13ada07
# ╟─63b7b1f3-660d-4a42-8b2c-3c0851d2b859
# ╟─d0973a67-f24e-4ffd-8343-7fe7be400d07
# ╟─f797ccd0-e98e-4617-a966-455469d16096
# ╟─b987567b-f500-4837-8f23-412a2eecec51
# ╟─88a20956-e665-4b0f-81f2-0e7ec8a1e28f
# ╟─6ebd71e0-b49a-4d12-b441-4805efc69520
# ╟─c1860fca-f304-4bb4-9266-5a6d71467e27
# ╟─01646835-55a9-42af-8eb3-29816c9780b7
# ╟─ccdef55c-0570-404a-bb3d-ea0b9487c321
# ╟─dcd790bd-36a5-4536-9e21-4f54fe2cf4e4
# ╟─c2121983-7135-4833-a33a-2dbc331272f3
# ╟─a271f163-046e-40cc-8134-c7619bf6a63a
# ╟─9ee21001-8404-4d5d-875b-6ea7952f65b8
# ╟─bc31504a-9374-4da3-9d68-030994ba8fcf
# ╟─0c58ddff-ad6f-4e80-8f1a-3c0c8d5245d2
# ╟─3d710dad-9b8c-47a3-966b-9718cb76fad8
# ╟─6ed9b5e5-754c-47f6-b1e4-2514d23039d2
# ╟─765ed41a-50e5-4989-98a1-1d2abfa3ba28
# ╟─95567d4d-6594-4a25-8449-b7b95738c56c
# ╟─53023ce3-2c74-46b7-82eb-589a78ca89c0
# ╟─6900000d-8bfd-4f8b-bf5b-46cefce652e4
# ╟─471eaf63-ca16-486e-b63a-ea3852768a0f
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 17460 | ### A Pluto.jl notebook ###
# v0.19.27
#= features_histology = [
"percent_tumor_nuclei",
"percent_normal_cells",
"percent_stromal_cells",
"percent_necrosis",
"percent_tumor_cells",
]
=#
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try
Base.loaded_modules[Base.PkgId(
Base.UUID("6e696c72-6542-2067-7265-42206c756150"),
"AbstractPlutoDingetjes",
)].Bonds.initial_value
catch
b -> missing
end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ fc17a594-02f3-46b5-a012-136ab5d0ba38
# ╠═╡ show_logs = false
begin
#import Pkg
#Pkg.activate("..")
using PlutoUI
end
# ╔═╡ d66ad52c-4ac9-4a04-884b-bfa013f9acd9
begin
using CSV, DataFrames
data = CSV.File("data/glioma_grading.csv") |> DataFrame
end
# ╔═╡ b7b62e65-9bd3-4bd8-9a71-2bea4ba109c4
begin
using MLJ
import BetaML, MLJModels
using Random: seed!
md"We fix the scientific types of features."
end
# ╔═╡ 6ebd71e0-b49a-4d12-b441-4805efc69520
begin
using CEEDesigns, CEEDesigns.StaticDesigns
md"""
### Performance Evaluation
We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as a measure of accuracy. It is possible to pass additional keyword arguments, which will be passed to `MLJ.evaluate` (such as `measure`, shown below).
"""
end
# ╔═╡ 7f2e19e0-4cf3-11ee-0e10-dba25ffccc94
md"""
# Cost-Efficient Experimental Design Towards Glioma Grading
Gliomas are the most common primary tumors of the brain. They can be graded as LGG (Lower-Grade Glioma) or GBM (Glioblastoma Multiforme), depending on the histological and imaging criteria. Clinical and molecular or genetic factors are also very crucial for the grading process. The ultimate aim is to identify the optimal subset of clinical, molecular or genetic, and histological features for the glioma grading process to improve diagnostic accuracy and reduce costs.
## Theoretical Framework
Let us consider a set of $n$ experiments $E = \{ e_1, \ldots, e_n\}$.
For each subset $S \subseteq E$ of experiments, we denote by $v_S$ the value of information acquired from conducting experiments in $S$.
In the cost-sensitive setting of CEEDesigns, conducting an experiment $e$ incurs a cost $(m_e, t_e)$. Generally, this cost is specified in terms of monetary cost and execution time of the experiment.
To compute the cost associated with carrying out a set of experiments $S$, we first need to introduce the notion of an arrangement $o$ of the experiments $S$. An arrangement is modeled as a sequence of mutually disjoint subsets of $S$. In other words, $o = (o_1, \ldots, o_l)$ for a given $l\in\mathbb N$, where $\bigcup_{i=1}^l o_i = S$ and $o_i \cap o_j = \emptyset$ for each $1\leq i < j \leq l$.
Given a subset $S$ of experiments and their arrangement $o$, the total monetary cost and execution time of the experimental design is given as $m_o = \sum_{e\in S} m_e$ and $t_o = \sum_{i=1}^l \max \{ t_e : e\in o_i\}$, respectively.
For instance, consider the experiments $e_1,\, e_2,\, e_3$, and $e_4$ with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$. If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement $o = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 10$.
However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement $o = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_o = 4$, and $t_o = 3 + 4 = 7$.
Given the constraint on the maximum number of parallel experiments, we devise an arrangement $o$ of experiments $S$ such that, for a fixed tradeoff between monetary cost and execution time, the expected combined cost $c_{(o, \lambda)} = \lambda m_o + (1-\lambda) t_o$ is minimized (i.e., the execution time is minimized).
In fact, it can be readily demonstrated that the optimal arrangement can be found by ordering the experiments in set $S$ in descending order according to their execution times. Consequently, the experiments are grouped sequentially into sets whose size equals to the maximum number of parallel experiments, except possibly for the final set.
Continuing our example and assuming a maximum of two parallel experiments, the optimal arrangement is to conduct $e_1$ in parallel with $e_2$, and $e_3$ with $e_4$. This results in an arrangement $o = (\{ e_1, e_2 \}, \{ e_3, e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 2 + 4 = 6$.
Assuming the information values $v_S$ and optimized experimental costs $c_S$ for each subset $S \subseteq E$ of experiments, we then generate a set of cost-efficient experimental designs.
### Application to Predictive Modeling
Consider a dataset of historical readouts over $m$ features $X = \{x_1, \ldots, x_m\}$, and let $y$ denote the target variable that we want to predict.
We assume that each experiment $e \in E$ yields readouts over a subset $X_e \subseteq X$ of features.
Then, for each subset $S \subseteq E$ of experiments, we may model the value of information acquired by conducting the experiments in $S$ as the accuracy of a predictive model that predicts the value of $y$ based on readouts over features in $X_S = \bigcup_{e\in S} X_e$.
"""
# ╔═╡ 2edaa133-6907-44f9-b39c-da06dae3eead
md"""
## Glioma Grading Clinical and Mutation Dataset
In this dataset, the instances represent the records of patients who have brain glioma. The dataset was constructed based on TCGA-LGG and TCGA-GBM brain glioma projects.
Each record is characterized by
- 3 clinical features (age, gender, race),
- 5 mutation factors (IDH1, TP53, ATRX, PTEN, EGFR; each of which can be 'mutated' or 'not_mutated'),
- and 5 histological features (percent tumor nuclei, percent normalcells, percent stromal cells, percent necrosis, percent tumor cells) that were obtained from inspecting the slides.
For this purpose, we merged a publicly available dataset [Glioma Grading Clinical and Mutation Features](https://archive.ics.uci.edu/dataset/759/glioma+grading+clinical+and+mutation+features+dataset) with biospecimen records obtained directly from [GDC Data Portal](https://portal.gdc.cancer.gov/).
"""
# ╔═╡ 6737a98e-20b9-4016-85f6-c8f4a07d04f8
md"""
_Somatic mutations sorted by affected cases in cohort_"""
# ╔═╡ 1364c91a-4331-4a1b-8c3d-fb40743c1df7
md"We load the dataset:"
# ╔═╡ 87f9826f-865f-4d1f-b122-e1ccae51bfdf
md"## Predictive Accuracy
We specify the clinical features, mutation factors, and histological features. "
# ╔═╡ 9835f38b-b720-429d-8a8b-eab742fe7e05
features_clinical = ["Age_at_diagnosis", "Gender", "Race"]
# ╔═╡ 0bb794a2-d0b4-493d-8a10-d19a515271ec
features_mutation = ["IDH1", "TP53", "ATRX", "PTEN", "EGFR"]
# ╔═╡ 2a368d5d-dc8d-4369-8642-7963e6fc4dba
features_histology = [
"percent_tumor_nuclei",
"percent_normal_cells",
"percent_stromal_cells",
"percent_necrosis",
"percent_tumor_cells",
]
# ╔═╡ 1c72a85d-19cb-44f3-b330-a312b9ef9b7c
md"Classification target is just the glioma grade"
# ╔═╡ 7e2bb98c-1175-4964-8c41-8e3ac8e6eb9f
target = "Grade"
# ╔═╡ d74684f6-7fd4-41c8-9917-d99dfc1f5f64
md"In the cost-sensitive setting of CEEDesigns, obtaining additional experimental evidence comes with a cost. We assume that each gene mutation is observed individually, while all histological features are gathered in one single experiment."
# ╔═╡ f176f8cf-8941-4257-ba41-60fff864aa56
# We assume that each feature is measured separately and the measurement incurs a monetary cost.
experiments = Dict(
## experiment => features
"TP53" => 3.0 => ["TP53"],
"EGFR" => 2.0 => ["EGFR"],
"PTEN" => 4.0 => ["PTEN"],
"ATRX" => 2.0 => ["ATRX"],
"IDH1" => 3.0 => ["IDH1"],
"CIC" => 1.0 => ["CIC"],
"MUC16" => 2.0 => ["MUC16"],
)
# ╔═╡ 9547fc15-7dff-49a3-b5d2-43b54a6dc443
md"""
### Classifier
We use a package called [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
"""
# ╔═╡ 61219167-805c-4624-932e-d050a13ada07
begin
types = Dict(
name => Multiclass for name in [Symbol.(features_mutation); :Grade; :Gender; :Race]
)
data_typefix = coerce(data, types)
schema(data_typefix)
end
# ╔═╡ 63b7b1f3-660d-4a42-8b2c-3c0851d2b859
md"Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with the dataset:"
# ╔═╡ d0973a67-f24e-4ffd-8343-7fe7be400d07
models(matching(data_typefix, data_typefix[:, target]))
# ╔═╡ f797ccd0-e98e-4617-a966-455469d16096
md"Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)"
# ╔═╡ b987567b-f500-4837-8f23-412a2eecec51
classifier = @load RandomForestClassifier pkg = BetaML verbosity = -1
# ╔═╡ 88a20956-e665-4b0f-81f2-0e7ec8a1e28f
model = classifier(; n_trees = 8, max_depth = 5)
# ╔═╡ c1860fca-f304-4bb4-9266-5a6d71467e27
# ╠═╡ show_logs = false
begin
seed!(1) # evaluation process generally is not deterministic
perf_eval = evaluate_experiments(
experiments,
model,
data_typefix[!, Not(target)],
data_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 6),
)
end
# ╔═╡ b93fa225-7a2e-48ef-b86a-18b1bbc42cc5
# ╠═╡ show_logs = false
begin
using Plots
plotly()
end
# ╔═╡ 3b520f8f-4b2e-47ad-9a44-7b365cd8395a
md"We plot performance measures evaluated for subsets of experiments, both with and without histology features:"
# ╔═╡ 01646835-55a9-42af-8eb3-29816c9780b7
md"We proceed to construct the set of cost-efficient experimental designs, considering all possible subsets of experiments."
# ╔═╡ ccdef55c-0570-404a-bb3d-ea0b9487c321
begin
designs = efficient_designs(experiments, perf_eval)
function plot_front_invert(
designs;
grad = cgrad(:Paired_12),
xlabel = "combined cost",
ylabel = "information measure",
labels = make_labels(designs),
)
xs = map(x -> x[1][1], designs)
ys = map(x -> x[1][2], designs)
p = scatter(
[xs[1]],
[1 - ys[1]];
xlabel,
ylabel,
label = labels[1],
c = grad[1],
mscolor = nothing,
fontsize = 16,
legendposition = :bottomright,
title = "cost-efficient designs",
)
for i = 2:length(designs)
if xs[i] < 10_000
scatter!(
p,
[xs[i]],
[1 - ys[i]];
label = labels[i],
c = grad[i],
mscolor = nothing,
)
end
end
return p
end
plot_front_invert(
designs;
labels = make_labels(designs),
ylabel = "accuracy (1-logloss)",
) # fill("", (1, length(designs)))
end
# ╔═╡ abb06c5b-04db-47ae-afd6-4c0241548f85
md"""As it turns out, in this specific scenario, the histological evidence (i.e., "percent tumor nuclei", "percent normal cells", "percent stromal cells", "percent necrosis", and "percent tumor cells") does not add any additional information value to that obtained from mutation factors."""
# ╔═╡ dcd790bd-36a5-4536-9e21-4f54fe2cf4e4
begin
function predict(X; positive_label = 1, sensitivity::Float64, specificity::Float64)
y_pred = similar(X, Float64)
# simulate a predictor with given sensitivity and specificity
for i in eachindex(X)
if X[i] == positive_label
y_pred[i] = rand() < sensitivity ? 1 : 0
else
y_pred[i] = rand() < (1 - specificity) ? 1 : 0
end
end
return y_pred
end
end
function make_plot(specificity, sensitivity, cost, perf_eval)
# ╔═╡ c2121983-7135-4833-a33a-2dbc331272f3
new_feature =
predict(data_typefix[!, target]; positive_label = "GBM", sensitivity, specificity)
# ╔═╡ a271f163-046e-40cc-8134-c7619bf6a63a
begin
experiments_new_feature =
push!(copy(experiments), "new_experiment" => cost => ["new_feature"])
end
# ╔═╡ bc31504a-9374-4da3-9d68-030994ba8fcf
begin
data_new_feature = copy(data_typefix)
data_new_feature.new_feature = new_feature
data_new_feature_typefix = coerce(
data_new_feature,
Dict(
(
name => Multiclass for
name in [Symbol.(features_mutation); :Grade; :Gender; :Race]
)...,
:new_feature => Multiclass,
),
)
data_new_feature_typefix
end
# ╔═╡ 0c58ddff-ad6f-4e80-8f1a-3c0c8d5245d2
# ╠═╡ show_logs = false
begin
seed!(1) # evaluation process generally is not deterministic
perf_eval_new_feature = evaluate_experiments(
experiments_new_feature,
model,
data_new_feature_typefix[!, Not(target)],
data_new_feature_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 6),
)
end
# ╔═╡ 95567d4d-6594-4a25-8449-b7b95738c56c
# ╠═╡ show_logs = false
begin
# we may get higher accuracy for this evaluation, but now only want to "add" the new feature
for (k, v) in perf_eval
perf_eval_new_feature[k] = v
end
@show perf_eval
@show perf_eval_new_feature
design_new_feature =
efficient_designs(experiments_new_feature, perf_eval_new_feature)
p_new_feature = scatter(
map(x -> x[1][1], design_new_feature),
map(x -> 1 - x[1][2], design_new_feature);
xlabel = "combined cost",
ylabel = "accuracy",
label = "w/ histology feature",
c = CEEDesigns.colorant"rgb(110,206,178)",
mscolor = nothing,
fontsize = 16,
#fill = (0, CEEDesigns.colorant"rgb(110,206,178)"),
fillalpha = 0.2,
legend = :bottomright,
)
design = efficient_designs(experiments, perf_eval)
@show design_new_feature
@show design
scatter!(
p_new_feature,
map(x -> x[1][1], design),
map(x -> 1 - x[1][2], design);
label = "w/o histology feature",
c = CEEDesigns.colorant"rgb(104,140,232)",
mscolor = nothing,
fontsize = 16,
#fill = (0, CEEDesigns.colorant"rgb(104,140,232)"),
fillalpha = 0.15,
title = "sensitivity = $sensitivity, specificity = $specificity, cost = $cost",
)
return p_new_feature
end
end
# w/o new feature
seed!(1)
perf_eval = evaluate_experiments(
experiments,
model,
data_typefix[!, Not(target)],
data_typefix[!, target];
zero_cost_features = features_clinical,
measure = LogLoss(),
resampling = CV(; nfolds = 6),
)
#
gr()
anim = @animate for sens = 0.5:0.2:0.9, spec = 0.5:0.2:0.9, cost = 1:2:5
println("sensitivity = $sens, specificity = $spec, cost = $cost")
p = make_plot(spec, sens, cost, perf_eval)
p
end
# ╔═╡ 471eaf63-ca16-486e-b63a-ea3852768a0f
html"""<style>
main {
text-align: justify;
text-justify: inter-word;
}
"""
# ╔═╡ Cell order:
# ╟─7f2e19e0-4cf3-11ee-0e10-dba25ffccc94
# ╟─2edaa133-6907-44f9-b39c-da06dae3eead
# ╟─6737a98e-20b9-4016-85f6-c8f4a07d04f8
# ╟─fc17a594-02f3-46b5-a012-136ab5d0ba38
# ╟─1364c91a-4331-4a1b-8c3d-fb40743c1df7
# ╟─d66ad52c-4ac9-4a04-884b-bfa013f9acd9
# ╟─87f9826f-865f-4d1f-b122-e1ccae51bfdf
# ╟─9835f38b-b720-429d-8a8b-eab742fe7e05
# ╟─0bb794a2-d0b4-493d-8a10-d19a515271ec
# ╟─2a368d5d-dc8d-4369-8642-7963e6fc4dba
# ╟─1c72a85d-19cb-44f3-b330-a312b9ef9b7c
# ╟─7e2bb98c-1175-4964-8c41-8e3ac8e6eb9f
# ╟─d74684f6-7fd4-41c8-9917-d99dfc1f5f64
# ╟─f176f8cf-8941-4257-ba41-60fff864aa56
# ╟─9547fc15-7dff-49a3-b5d2-43b54a6dc443
# ╟─b7b62e65-9bd3-4bd8-9a71-2bea4ba109c4
# ╟─61219167-805c-4624-932e-d050a13ada07
# ╟─63b7b1f3-660d-4a42-8b2c-3c0851d2b859
# ╟─d0973a67-f24e-4ffd-8343-7fe7be400d07
# ╟─f797ccd0-e98e-4617-a966-455469d16096
# ╟─b987567b-f500-4837-8f23-412a2eecec51
# ╟─88a20956-e665-4b0f-81f2-0e7ec8a1e28f
# ╟─6ebd71e0-b49a-4d12-b441-4805efc69520
# ╟─c1860fca-f304-4bb4-9266-5a6d71467e27
# ╟─3b520f8f-4b2e-47ad-9a44-7b365cd8395a
# ╟─b93fa225-7a2e-48ef-b86a-18b1bbc42cc5
# ╟─01646835-55a9-42af-8eb3-29816c9780b7
# ╟─ccdef55c-0570-404a-bb3d-ea0b9487c321
# ╟─abb06c5b-04db-47ae-afd6-4c0241548f85
# ╟─dcd790bd-36a5-4536-9e21-4f54fe2cf4e4
# ╟─c2121983-7135-4833-a33a-2dbc331272f3
# ╟─a271f163-046e-40cc-8134-c7619bf6a63a
# ╟─9ee21001-8404-4d5d-875b-6ea7952f65b8
# ╟─bc31504a-9374-4da3-9d68-030994ba8fcf
# ╟─0c58ddff-ad6f-4e80-8f1a-3c0c8d5245d2
# ╟─6ed9b5e5-754c-47f6-b1e4-2514d23039d2
# ╟─95567d4d-6594-4a25-8449-b7b95738c56c
# ╟─471eaf63-ca16-486e-b63a-ea3852768a0f
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | code | 1312 | begin
using Plots
plotly()
evals1 = filter(x -> "histology" ∉ x[1], perf_eval)
xs1 = sort!(collect(keys(evals1)); by = x -> -perf_eval[x])
ys1 = map(xs1) do x
return perf_eval[x] isa Number ? perf_eval[x] : perf_eval[x].loss
end
evals2 = filter(x -> "histology" ∈ x[1], perf_eval)
xs2 = sort!(collect(keys(evals2)); by = x -> -perf_eval[setdiff(x, ["histology"])])
ys2 = map(xs2) do x
return perf_eval[x] isa Number ? perf_eval[x] : perf_eval[x].loss
end
p_evals = Plots.sticks(
1:length(xs2),
1 .- min.(ys1, ys2);
ticks = 1:length(evals2),
#xformatter=i -> isempty(xs2[Int(i)]) ? "∅" : join(xs1[Int(i)], ", "),
guidefontsize = 8,
tickfontsize = 8,
ylabel = "accuracy",
c = CEEDesigns.colorant"rgb(110,206,178)",
label = "w/ histology",
xrotation = 50,
)
Plots.sticks!(
p_evals,
1:length(xs1),
1 .- ys1;
ticks = 1:length(evals1),
xformatter = i -> isempty(xs1[Int(i)]) ? "∅" : join(xs1[Int(i)], ", "),
guidefontsize = 8,
tickfontsize = 8,
ylabel = "accuracy",
c = CEEDesigns.colorant"rgb(104,140,232)",
label = "w/o histology",
width = 2,
xrotation = 50,
)
end
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 4929 | <p align="left">
<img src="docs/src/assets/ceed_light.svg#gh-light-mode-only" alt="CEEDesigns.jl logo"/>
<img src="docs/src/assets/ceed_dark.svg#gh-dark-mode-only" alt="CEEDesigns.jl logo"/>
</p>
_______
[](https://merck.github.io/CEEDesigns.jl/)
A decision-making framework for the cost-efficient design of experiments, balancing the value of acquired experimental evidence and incurred costs. We have considered two different experimental setups, which are outlined below.
<a><img src="docs/src/assets/front_static.png" align="right" alt="code" width="400"></a>
### Static experimental designs
Here we assume that the same experimental design will be used for a population of examined entities, hence the word "static".
For each subset of experiments, we consider an estimate of the value of acquired information. To give an example, if a set of experiments is used to predict the value of a specific target variable, our framework can leverage a built-in integration with [MLJ.jl](https://github.com/alan-turing-institute/MLJ.jl) to estimate predictive accuracies of machine learning models fitted over subset of experimental features.
In the cost-sensitive setting of CEEDesigns, a user provides the monetary cost and execution time of each experiment. Given the constraint on the maximum number of parallel experiments along with a fixed tradeoff between monetary cost and execution time, we devise an arrangement of each subset of experiments such that the expected combined cost is minimized.
Assuming the information values and optimized experimental costs for each subset of experiments, we then generate a set of cost-efficient experimental designs.
<a><img src="docs/src/assets/front_generative.png" align="right" alt="code" width="400"></a>
### Generative experimental designs
We consider 'personalized' experimental designs that dynamically adjust based on the evidence gathered from the experiments. This approach is motivated by the fact that the value of information collected from an experiment generally differs across subpopulations of the entities involved in the triage process.
At the beginning of the triage process, an entity's prior data is used to project a range of cost-efficient experimental designs. Internally, while constructing these designs, we incorporate multiple-step-ahead lookups to model likely experimental outcomes and consider the subsequent decisions for each outcome. Then after choosing a specific decision policy from this set and acquiring additional experimental readouts (sampled from a generative model, hence the word "generative"), we adjust the continuation based on this evidence.
<a><img src="docs/src/assets/search_tree.png" align="left" alt="code" width="400"></a>
We conceptualized the triage as a Markov decision process, in which we iteratively choose to conduct a subset of experiments and then, based on the experimental evidence, update our belief about the distribution of outcomes for the experiments that have not yet been conducted. The information value associated with the state, derived from experimental evidence, can be modeled through any statistical or information-theoretic measure such as the variance or uncertainty associated with the target variable posterior.
We implemented the following two variants of the decision-making process: Firstly, assuming that the decision-making process only terminates when the uncertainty drops below a given threshold, we minimize the expected resource spend. Secondly, we can optimize the value of experimental evidence, adjusted for the incurred experimental costs.
## Context: Dynamics of Value Evolution (DyVE)
The package is an integral part of the **Dynamics of Value Evolution (DyVE)** computational framework for learning, designing, integrating, simulating, and optimizing R&D process models, to better inform strategic decisions in science and business.
As the framework evolves, multiple functionalities have matured enough to become standalone packages.
This includes **[ReactiveDynamics.jl](https://github.com/Merck/ReactiveDynamics.jl)**, a package which implements a category of reaction (transportation) network-type dynamical systems. The central concept of the package is of a stateful, parametric transition; simultaneous action of the transitions then evolves the dynamical system. Moreover, a network's dynamics can be specified using a compact modeling metalanguage.
Another package is **[AlgebraicAgents.jl](https://github.com/Merck/AlgebraicAgents.jl)**, a lightweight package to enable hierarchical, heterogeneous dynamical systems co-integration. It implements a highly scalable, fully customizable interface featuring sums and compositions of dynamical systems. In present context, we note it can be used to co-integrate a reaction network problem with, e.g., a stochastic ordinary differential problem! | CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 953 | # API Documentation
```@meta
CurrentModule = CEEDesigns
```
## `StaticDesigns`
```@docs
CEEDesigns.StaticDesigns.efficient_designs
CEEDesigns.StaticDesigns.evaluate_experiments
```
## `GenerativeDesigns`
```@docs
CEEDesigns.GenerativeDesigns.UncertaintyReductionMDP
CEEDesigns.GenerativeDesigns.EfficientValueMDP
CEEDesigns.GenerativeDesigns.State
CEEDesigns.GenerativeDesigns.Variance
CEEDesigns.GenerativeDesigns.Entropy
```
```@docs
CEEDesigns.GenerativeDesigns.efficient_design
CEEDesigns.GenerativeDesigns.efficient_designs
CEEDesigns.GenerativeDesigns.efficient_value
```
### Distance-Based Sampling
```@docs
CEEDesigns.GenerativeDesigns.DistanceBased
CEEDesigns.GenerativeDesigns.QuadraticDistance
CEEDesigns.GenerativeDesigns.DiscreteDistance
CEEDesigns.GenerativeDesigns.SquaredMahalanobisDistance
CEEDesigns.GenerativeDesigns.Exponential
```
## Plotting
```@docs
CEEDesigns.plot_front
CEEDesigns.make_labels
CEEDesigns.plot_evals
``` | CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 3399 | # CEEDesigns.jl: Overview
A decision-making framework for the cost-efficient design of experiments, balancing the value of acquired experimental evidence and incurred costs. We have considered two different experimental setups, which are outlined below.
```@raw html
<a><img src="assets/front_static.png" align="right" alt="code" width="400"></a>
```
## Static experimental designs
Here we assume that the same experimental design will be used for a population of examined entities, hence the word "static".
For each subset of experiments, we consider an estimate of the value of acquired information. To give an example, if a set of experiments is used to predict the value of a specific target variable, our framework can leverage a built-in integration with [MLJ.jl](https://github.com/alan-turing-institute/MLJ.jl) to estimate predictive accuracies of machine learning models fitted over subset of experimental features.
In the cost-sensitive setting of CEEDesigns.jl, a user provides the monetary cost and execution time of each experiment. Given the constraint on the maximum number of parallel experiments along with a fixed tradeoff between monetary cost and execution time, we devise an arrangement of each subset of experiments such that the expected combined cost is minimized.
Assuming the information values and optimized experimental costs for each subset of experiments, we then generate a set of cost-efficient experimental designs.
```@raw html
<a><img src="assets/front_generative.png" align="right" alt="code" width="400"></a>
```
## Generative experimental designs
We consider 'personalized' experimental designs that dynamically adjust based on the evidence gathered from the experiments. This approach is motivated by the fact that the value of information collected from an experiment generally differs across subpopulations of the entities involved in the triage process.
At the beginning of the triage process, an entity's prior data is used to project a range of cost-efficient experimental designs. Internally, while constructing these designs, we incorporate multiple-step-ahead lookups to model likely experimental outcomes and consider the subsequent decisions for each outcome. Then after choosing a specific decision policy from this set and acquiring additional experimental readouts (sampled from a generative model, hence the word "generative"), we adjust the continuation based on this evidence.
```@raw html
<a><img src="assets/search_tree.png" align="left" alt="code" width="400"></a>
```
We conceptualized the triage as a Markov decision process, in which we iteratively choose to conduct a subset of experiments and then, based on the experimental evidence, update our belief about the distribution of outcomes for the experiments that have not yet been conducted. The information value associated with the state, derived from experimental evidence, can be modeled through any statistical or information-theoretic measure such as the variance or uncertainty associated with the target variable posterior.
We implemented the following two variants of the decision-making process: Firstly, assuming that the decision-making process only terminates when the uncertainty drops below a given threshold, we minimize the expected resource spend. Secondly, we can optimize the value of experimental evidence, adjusted for the incurred experimental costs. | CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 10545 | ```@meta
EditURL = "ActiveSampling.jl"
```
# Active Sampling for Generative Designs
## Background on Active Sampling
In multi-objective optimization (MOO), particularly in the context of active learning and reinforcement learning (RL),
conditional sampling plays a critical role in achieving optimized outcomes that align with specific desirable criteria.
The essence of conditional sampling is to direct the generative process not only towards the global objectives but also to adhere to additional, domain-specific constraints or features. This approach is crucial for several reasons:
MOO often involves balancing several competing objectives, such as minimizing cost while maximizing performance.
Conditional sampling allows for the integration of additional constraints or preferences,
ensuring that the optimization does not overly favor one objective at the expense of others.
On a related note, many optimization problems have domain-specific constraints or desirable features that are not explicitly part of the primary objectives.
For example, in drug design, beyond just optimizing for efficacy and safety, one might need to consider factors like solubility or synthesizability.
Conditional sampling ensures that solutions not only meet the primary objectives but also align with these additional practical considerations.
## Application to Generative Designs
In the context of CEEDesigns.jl, active sampling can be used to selectively prioritize historical observations.
For example, if the goal is to understand a current trend or pattern,
active sampling can be used to assign more weight to recent data points or deprioritize those that may not be relevant to the current context.
This way, the sampled data will offer a more precise representation of the current state or trend.
For details on the theoretical background of generative designs and notation, please see our [introductory tutorial](SimpleGenerative.md) and an [applied tutorial](GenerativeDesigns.jl).
Here we will again assume that the generative process is based on sampling from a historical dataset, which gives measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
(with entities and features representing rows and columns, respectively).
Each experiment $e$ may yield measurements on some
subset of features $(X_{e}\subseteq X)$.
Given the current state, i.e., experimental evidence acquired thus far for the new entity, we assign probabilistic weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
$q(e_{S^{\prime}}|e_{S})$.
In the context of active sampling, we aim to further adjust the weights, $w_{j}$, calculated by the algorithm.
This adjustment can be accomplished by introducing a "prior", which is essentially a vector of weights that will multiply the computed weights, $w_{j}$, in an element-wise manner.
If we denote the "prior" weights as $p_{j}$, then the final weights assigned to the $j$-th row are computed as $w'_{j} = p_{j} * w_{j}$.
Alternatively, we can use "feature-wise" priors, which are considered when a readout for the specific feature is available for the new entity. # It is important to note here that the distance, which forms the basis of the probabilistic weights, is inherently computed only over the observed features.
To be more precise, for each experiment $e\in E$, we let $p^e_j$ denote the "prior" associated with that specific experiment.
If $S$ represents the set of experiments that have been performed for the new compound so far, we compute the reweighted probabilistic weight as $w'_{j} = \product_{e\in S} p^e_j \cdot w_j$.
We remark that this method can be used to filter out certain rows by setting their weight to zero.
Considering feature-wise priors can offer a more detailed and nuanced understanding of the data. These priors can be used to dynamically adjust the weight of historical observations, based on the specific readouts considered for the observation across different features.
For more information about active sampling, refer to the following articles.
- [Evolutionary Multiobjective Optimization via Efficient Sampling-Based Strategies](https://link.springer.com/article/10.1007/s40747-023-00990-z).
- [Sample-Efficient Multi-Objective Learning via Generalized Policy Improvement Prioritization](https://arxiv.org/abs/2301.07784).
- [Conditional gradient method for multiobjective optimization](https://link.springer.com/article/10.1007/s10589-020-00260-5)
- [A practical guide to multi-objective reinforcement learning and planning](https://link.springer.com/article/10.1007/s10458-022-09552-y)
## Synthetic Data Example
````@example ActiveSampling
using CEEDesigns, CEEDesigns.GenerativeDesigns
````
We create a synthetic dataset with continuous variables, `x1`, `x2`, and `y`. Both `x1` and `x2` are modeled as independent random variables that follow a normal distribution.
The target variable, `y`, is given as a weighted sum of `x1` and `x2`, with an additional noise component. The corrected version of your sentence should be: Consequently, if the value of `x2`, for example,
falls into a "sparse" region, we want the algorithm to avoid overfitting and focus its attention more on the other variable.
````@example ActiveSampling
using Random
using DataFrames
# Define the size of the dataset.
n = 1000;
# Generate `x1` and `x2` as independent random variables with normal distribution.
x1 = randn(n)
x2 = randn(n);
# Compute `y` as the sum of `x1`, `x2`, and the noise.
y = x1 .+ 0.2 * x2 .+ 0.1 * randn(n);
# Create a data frame.
data = DataFrame(; x1 = x1, x2 = x2, y = y);
data[1:10, :]
````
### Active Sampling
We again use the default method `DistanceBased` to assign the probabilistic weights across historical observations.
In addition, we will demonstrate the use of two additional keyword arguments of `DistanceBased`, related to active sampling:
- `importance_weights`: this is a dictionary of pairs `colname` with either `weights` or a function `x -> weight`, which will be applied to each element of the column to obtain the vector of weights. If data for a given column is available in the current state, the product of the corresponding weights is used to adjust the similarity vector.
For filtering out certain rows where the readouts fall outside a selected range, we can use the following keyword:
- `filter_range`: this is a dictionary of pairs `colname => (lower bound, upper bound)`. If there's data in the current state for a specific column specified in this list, only historical observations within the defined range for that column are considered.
In the current setup, we aim to adaptively filter out the values `x1` or `x2` that lie outside of one standard deviation from the mean.
````@example ActiveSampling
filter_range = Dict()
filter_range = Dict("x1" => (-1, 1), "x2" => (-1, 1))
````
We then call `DistanceBased` as follows:
````@example ActiveSampling
(sampler_active, uncertainty_active, weights_active) = DistanceBased(
data;
target = "y",
similarity = Exponential(; λ = 1),
filter_range = filter_range,
);
nothing #hide
````
To compare behavior with and without active sampling, we call `DistanceBased` again:
````@example ActiveSampling
(; sampler, uncertainty, weights) =
DistanceBased(data; target = "y", similarity = Exponential(; λ = 1));
nothing #hide
````
We plot the weights $w_j$ assigned to historical observations for both cases - with active sampling and without. The actual observation is shown in orange.
````@example ActiveSampling
evidence = Evidence("x1" => 5.0, "x2" => 0.5)
````
````@example ActiveSampling
using Plots
colors_active = max.(0.1, weights_active(evidence) ./ maximum(weights_active(evidence)))
p1 = scatter(
data[!, "x1"],
data[!, "x2"];
color = RGBA.(colorant"rgb(0,128,128)", colors_active),
title = "weights\n(active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p1,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p1
````
````@example ActiveSampling
colors = max.(0.1, weights(evidence) ./ maximum(weights(evidence)))
p2 = scatter(
data[!, "x1"],
data[!, "x2"];
color = RGBA.(colorant"rgb(0,128,128)", colors),
title = "weights\n(no active sampling)",
mscolor = nothing,
colorbar = false,
label = false,
)
scatter!(
p2,
[evidence["x1"]],
[evidence["x2"]];
color = :orange,
mscolor = nothing,
label = nothing,
)
p2
````
As it turns out, when active sampling was not used, the algorithm tended to overfit to the closest yet sparse points, which did not represent the true distribution accurately.
We can also compare the estimated uncertainty, which is computed as the variance of the posterior.
Without using active sampling, we obtain:
````@example ActiveSampling
round(uncertainty_active(evidence); digits = 1)
````
While for active sampling, we get:
````@example ActiveSampling
round(uncertainty(evidence); digits = 1)
````
#### Experimental Designs for Uncertainty Reduction
We compare the set of cost-efficient designs in cases where active sampling is used and where it is not.
We specify the experiments along with the associated features:
````@example ActiveSampling
experiments = Dict("x1" => 1.0, "x2" => 1.0, "y" => 6.0)
````
We specify the initial state.
````@example ActiveSampling
evidence = Evidence("x2" => 5.0)
````
Next we compute the set of efficient designs.
````@example ActiveSampling
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
designs_active = efficient_designs(
experiments;
sampler = sampler_active,
uncertainty = uncertainty_active,
thresholds = 5,
evidence,
mdp_options = (; max_parallel = 1),
);
nothing #hide
````
We can compare the fronts.
````@example ActiveSampling
p = scatter(
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
ylabel = "% uncertainty",
label = "efficient designs (no active sampling)",
title = "efficient front",
color = :blue,
mscolor = nothing,
)
scatter!(
p,
map(x -> x[1][1], designs_active),
map(x -> x[1][2], designs_active);
label = "efficient designs (active sampling)",
color = :teal,
mscolor = nothing,
)
p
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 11398 | ```@meta
EditURL = "GenerativeDesigns.jl"
```
# Heart Disease Triage Meets Generative Modeling
Consider again a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer; instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
For details on the theoretical background and notation, please see our tutorial on [generative experimental designs](SimpleGenerative.md). This tutorial
is a concrete application of the tools described in that document.
Importantly, we aim to design personalized adaptive policies for each patient. At the beginning of the triage process, we use a patient's prior data, such as sex, age, or type of chest pain, to project a range of cost-efficient experimental designs. Internally, while constructing these designs, we incorporate multiple-step-ahead lookups to model probable experimental outcomes and consider the subsequent decisions for each outcome. Then after choosing a specific decision policy from this set and acquiring additional experimental readouts, we adjust the continuation based on this evidence.
## Heart Disease Dataset
In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
````@example GenerativeDesigns
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
````
We provide appropriate scientific types of the features.
````@example GenerativeDesigns
using ScientificTypes
types = Dict(
:MaxHR => Continuous,
:Cholesterol => Continuous,
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
nothing #hide
````
## Generative Model for Outcomes Sampling
````@example GenerativeDesigns
using CEEDesigns, CEEDesigns.GenerativeDesigns
````
As previously discussed, we provide a dataset of historical records, the target variable, along with an information-theoretic measure to quantify the uncertainty about the target variable.
In what follows, we obtain three functions:
- `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator,
- `uncertainty`: this is a function of `evidence`,
- `weights`: this represents a function of `evidence` that distributes probabilistic weights across the rows in the dataset.
Note that internally, a state of the decision process is represented as a tuple `(evidence, costs)`.
You can specify the method for computing the distance using the `distance` keyword. By default, the Kronecker delta and quadratic distance will be utilised for categorical and continuous features, respectively.
````@example GenerativeDesigns
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
);
nothing #hide
````
Alternatively, you can provide a dictionary of `feature => distance` pairs. The implemented distance functionals are `DiscreteDistance(; λ)` and `QuadraticDistance(; λ, standardize=true)`. In that case, the specified distance will be applied to the respective feature, after which the distances will be collated across the range of features.
The above call is therefore equivalent to:
````@example GenerativeDesigns
numeric_feats = filter(c -> c <: Real, eltype.(eachcol(data)))
categorical_feats = setdiff(names(data), numeric_feats)
DistanceBased(
data;
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = merge(
Dict(c => DiscreteDistance() for c in categorical_feats),
Dict(c => QuadraticDistance() for c in numeric_feats),
),
);
nothing #hide
````
You can also use the squared Mahalanobis distance (`SquaredMahalanobisDistance(; diagonal)`). As the squared Mahalanobis distance only works with numeric features, we have to select a few, along with the target variable. For example, we could write:
````@example GenerativeDesigns
DistanceBased(
data[!, ["RestingBP", "MaxHR", "Cholesterol", "FastingBS", "HeartDisease"]];
target = "HeartDisease",
uncertainty = Entropy(),
similarity = Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 1),
);
nothing #hide
````
The package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
We specify the experiments along with the associated features:
````@example GenerativeDesigns
experiments = Dict(
# experiment => features
"BloodPressure" => 1.0 => ["RestingBP"],
"ECG" => 5.0 => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => 20.0 => ["Cholesterol"],
"BloodSugar" => 20.0 => ["FastingBS"],
"HeartDisease" => 100.0,
)
````
Let us inspect the distribution of belief for the following experimental evidence:
````@example GenerativeDesigns
evidence = Evidence("Age" => 55, "Sex" => "M")
````
````@example GenerativeDesigns
using StatsBase: countmap
using Plots
````
````@example GenerativeDesigns
target_belief = countmap(data[!, "HeartDisease"], weights(evidence))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
````
Let us next add an outcome of blood pressure measurement:
````@example GenerativeDesigns
evidence_with_bp = merge(evidence, Dict("RestingBP" => 190))
target_belief = countmap(data[!, "HeartDisease"], weights(evidence_with_bp))
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
color = :teal,
title = "unc: $(round(uncertainty(evidence_with_bp), digits=2))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["no disease", "disease"]);
p
````
## Cost-Efficient Experimental Designs for Uncertainty Reduction
In this experimental setup, our objective is to minimize the expected experimental cost while ensuring the uncertainty remains below a specified threshold.
We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs for various levels of uncertainty threshold. In the following example, we generate 6 thresholds spaces evenly between 0 and 1, inclusive.
Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl) is created, and the `POMDPs.solve` is called on the problem. Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
````@example GenerativeDesigns
# set seed for reproducibility
using Random: seed!
seed!(1)
````
````@example GenerativeDesigns
evidence = Evidence("Age" => 35, "Sex" => "M")
````
````@example GenerativeDesigns
# use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 20_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 1),
repetitions = 5,
);
nothing #hide
````
We plot the Pareto-efficient actions:
````@example GenerativeDesigns
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
````
We render the search tree for the second design, sorted in descending order based on the uncertainty threshold:
````@example GenerativeDesigns
using D3Trees
d3tree = D3Tree(designs[2][2].tree; init_expand = 2)
````
### Parallel Experiments
We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
````@example GenerativeDesigns
experiments = Dict(
# experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
"HeartDisease" => (100.0, 100.0),
)
````
We have to provide the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
````@example GenerativeDesigns
# minimize time, two concurrent experiments at maximum
seed!(1)
# use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(;
n_iterations = 2_000,
exploration_constant = 5.0,
tree_in_info = true,
)
designs = efficient_designs(
experiments;
sampler,
uncertainty,
thresholds = 6,
evidence,
solver,
mdp_options = (; max_parallel = 2, costs_tradeoff = (0, 1.0)),
repetitions = 5,
);
nothing #hide
````
We plot the Pareto-efficient actions:
````@example GenerativeDesigns
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
````
## Efficient Value Experimental Designs
In this experimental setup, we aim to maximize the value of experimental evidence, adjusted for the incurred experimental costs.
For this purpose, we need to specify a function that quantifies the "value" of decision-process making state, modeled as a tuple of experimental evidence and costs.
````@example GenerativeDesigns
value = function (evidence, (monetary_cost, execution_time))
return (1 - uncertainty(evidence)) - (0.005 * sum(monetary_cost))
end
````
Considering a discount factor $\lambda$, the total reward associated with the experimental state in an $n$-step decision process is given by $r = r_1 + \sum_{i=2}^n \lambda^{i-1} (r_i - r_{i-1})$, where $r_i$ is the value associated with the $i$-th state.
In the following example, we also limit the maximum rollout horizon to 4.
````@example GenerativeDesigns
seed!(1)
# use less number of iterations to speed up build process
solver = GenerativeDesigns.DPWSolver(; n_iterations = 2_000, depth = 4, tree_in_info = true)
design = efficient_value(
experiments;
sampler,
value,
evidence,
solver,
repetitions = 5,
mdp_options = (; discount = 0.8),
);
nothing #hide
````
````@example GenerativeDesigns
design[1] # optimized cost-adjusted value
````
````@example GenerativeDesigns
d3tree = D3Tree(design[2].tree; init_expand = 2)
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 26646 | ```@meta
EditURL = "SimpleGenerative.jl"
```
# Generative Experimental Designs
This document describes the theoretical background behind tools in CEEDesigns.jl for generative experimental designs
and demonstrates uses on synthetic data examples.
## Setting
Generative experimental designs differ from static designs in that the experimental design is specific for (or "personalized") to an incoming entity.
Personalized cost-efficient experimental designs for the new entity are made based on existing information (if any) about the new entity,
and from posterior distributions of unobserved features of that entity conditional on its observed features and historical data.
The entities may be patients, molecular compounds, or any other objects where one has a store of historical data
and seeks to find efficient experimental designs to learn more about a new arrival.
The personalized experimental designs are motivated by the fact that the value of information collected from an experiment
often differs across subsets of the population of entities.

In the context of static designs, we do not aspire to capture variation in information gain across different entities. Instead, we assume all entities come from a "Population" with a uniform information gain, in which case "Experiment C" would provide the maximum information value.
On the other hand, if we have the ability to discern if the entity belong to subpopulations "Population 1" or "Population 2," then we can tailor our
design to suggest either "Experiment A" or "Experiment B." Clearly, in the limit of a maximally heterogenous population, each
entity has its own "row." Our tools are able to handle the entire spectrum of such scenarios though distance based similarity,
described below.
## Theoretical Framework
### Historical Data
Like static designs, we consider a set $E$ of $n$ experiments, each with an associated tuple $(m_{e},t_{e})$ of monetary and
time costs (for more details on experiments and arrangements, see the tutorial on [static experimental designs](SimpleStatic.md)).
Additionally, consider a historical dataset giving measurements on $m$ features $X = \{x_1, \ldots, x_m\}$ for $l$ entities
(with entities and features representing rows and columns, respectively). Each experiment $e$ may yield measurements on some
subset of features $(X_{e}\subseteq X)$.
Furthermore there is an additional column $y$ which is a target variable we want to predict (CEEDesigns.jl may allow $y$
to be a vector, but we assume it is scalar here for ease of presentation).
Letting $m=3$, then the historical dataset may be visualized as the following table:

### New Entity
When a new entity arrives, it will have an unknown outcome $y$ and unknown values of some or all features $x_{i} \in X$.
We call the _state_ of the new entity the set of experiments conducted upon it so far (if any), along with the
measurements on any features produced by those experiments (if any), called _evidence_.
Consider the case where there are $n=3$ experiments, each of which yields a measurement on a single feature. Then
the state of a new entity arriving for which $e_{1}$ has already been performed will look like:

Letting $S$ denote the set of experiments which have been performed so far, then $S^{\prime}=E\S$ are unperformed experiments.
Then, _actions_ one can perform to learn more about the new entity are subsets of $S^{\prime}$. The size of subsets
is limited by the maximum number of parallel experiments.
In our running example, if the maximum number of parallel experiments is at least 2, then the available actions are:

### Posterior Distributions
Let $e_{S}$ be a random variable denoting the outcome of some experiments $S$ on the new entity. Then, there exists a
posterior distribution $q(e_{S^{\prime}}|e_{S})$ over outcomes of unperformed experiments $S^{\prime}$, conditioned on the current
state.
Furthermore, there also exists a posterior distribution over the unobserved target variable $q(y|e_{S})$. The information
value of the current state, derived from experimental evidence, can be defined as any statistical or information-theoretic
measure applied to $q(y|e_{S})$. This can include variance or entropy (among others). The information value
of the set of experiments performed in $S$ is analogous to $v_{S}$ defined in [static experimental designs](SimpleStatic.md).
### Similarity Weighting
There may be many ways to define these posterior distributions, but our approach uses distance-based similarity
scores to construct weights $w_{j}$ over historical entities which are similar to the new entity. These weights can be used to
weight the values of $y$ or features associated with $e_{S^{\prime}}$ to construct approximations of $q(y|e_{S})$ and
$q(e_{S^{\prime}}|e_{S})$.
If there is no evidence associated with a new entity, we assign $w_{j}$ according to some prior distribution (uniform by default).
Otherwise we use some particular distance and similarity metrics.
For each feature $x\in X$, we consider a function $\rho_x$, which measures the distance between two outputs. Please be aware that the "distances" discussed here do not conform to the mathematical definition of "metrics", even though they are functions derived from underlying metrics (i.e., a square of a metric). This is justified when considering how these "distances" are subsequently converted into probabilistic weights.
By default, we consider the following distances:
- Rescaled Kronecker delta (i.e., $\rho(x, y)=0$ only when $x=y$, and $\rho(x, y)= \lambda$ under any other circumstances, with $\lambda > 0$) for discrete features (i.e., features whose types are modeled as `MultiClass` type in [ScientificTypes.jl](https://github.com/JuliaAI/ScientificTypes.jl));
- Rescaled ("standardized", by default) squared distance $\rho(x, y) = λ \frac{(x - y)^2}{\sigma^2}$, where $\sigma^2$ is the variance of the feature column, estimated with respect to the prior for continuous features.
- Squared Mahalanobis distance $\rho(x,y) = (x-y)^{⊤}\Sigma^{-1}(x-y)$, where $\Sigma$ is the empirical covariance matrix of the historical data.
For distance metrics assuming independence of features (Kronecker delta and squared distance), given the new entity's experimental state with readouts over the feature set $F = \bigcup X_{e}$, where $e \in S$, we can calculate
the distance from the $j$-th historical entity as $d_j = \sum_{x\in F} \rho_x (\hat x, x_j)$, where $\hat x$ and $x_j$ denote the readout
for feature $x$ for the entity being tested and the entity recorded in $j$-th column.
The squared Mahalanobis distance directly takes in "rows", $\rho(\hat{x},x_{j})$.
Next, we convert distances $d_j$ into probabilistic weights $w_j$. By default, we use a rescaled exponential function, i.e.,
we put $w_j = \exp(-\lambda d_j)$ with $\lambda=0.5$. Notably, $\lambda$'s value determines how belief is distributed across the historical entities.
Larger values of $\lambda$ concentrate the belief tightly around the "closest" historical entities, while smaller values distribute more belief to more distant entities.
Note that by choosing the squared Mahalanobis distance and the exponential function with a factor of $\lambda=0.5$, the resulting weight effectively equals the density of a [multivariate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function) fitted to the historical data. A similar assertion applies when we use the sum of "standardized" squared distances instead. However, in this latter case, we "enforce" the independence of the features.
The proper choice of distance and similarity metrics depends on insight into the dataset at hand. Weights can then be used to construct
weighted histograms or density estimators for the posterior distributions of interest, or to directly resample historical rows.

### Policy Search
Given these parts, searching for optimal experimental designs (actions arranged in an efficient way) depends on what our objective sense is.
- The search may continue until the uncertainty about the posterior distribution of the target variable falls below a certain level. Our aim is to minimize the anticipated combined monetary cost and execution time of the search (considered as a "negative" reward). If all experiments are conducted without reaching below the required uncertainty level, or if the maximum number of experiments is exceeded, we penalize this scenario with an "infinitely negative" reward.
- We may aim to minimize the expected uncertainty while being constrained by the combined costs of the experiment.
- Alternatively, we could maximize the value of experimental evidence, adjusted for the incurred experimental costs.
Standard Markov decision process (MDP) algorithms can be used to solve this problem (offline learning) or construct the policy (online learning) for the sequential decision-making.
Our MDP's state space is finite-dimensional but generally continuous due to the allowance of continuous features, which complicates the problem and few algorithms specialize in this area.
We used the Double Progressive Widening Algorithm for this task as detailed in [A Comparison of Monte Carlo Tree Search and Mathematical Optimization for Large Scale Dynamic Resource Allocation](https://arxiv.org/abs/1405.5498).
In a nutshell, the Double Progressive Widening (DPW) algorithm is designed for online learning in complex environments, particularly those known as Continuous Finite-dimensional Markov Decision Processes where the state space is continuous. The key idea behind DPW is to progressively expand the search tree during the Monte Carlo Tree Search (MCTS) process. The algorithm does so by dynamically and selectively adding states and actions to the tree based on defined heuristics.
In the context of online learning, this algorithm addresses the complexity and challenges of real-time decision-making in domains with a large or infinite number of potential actions. As information is gathered in actual runtime, the algorithm explores and exploits this information to make optimal or near-optimal decisions. In other words, DPW permits the learning process to adapt on-the-fly as more data is made available, making it an effective tool for the dynamic and uncertain nature of online environments.
In particular, at the core of the Double Progressive Widening (DPW) algorithm are several key components, including expansion, search, and rollout.
The search component is where the algorithm sifts through the search tree to determine the most promising actions or states to explore next. By using exploration-exploitation strategies, it can effectively balance its efforts between investigating previously successful actions and venturing into unexplored territories.
The expansion phase is where the algorithm grows the search tree by adding new nodes, representing new state-action pairs, to the tree. This is done based on a predefined rule that dictates when and how much the tree should be expanded. This allows the algorithm to methodically discover and consider new potential actions without becoming overwhelmed with choices.
Lastly, the rollout stage, also known as a simulation stage, is where the algorithm plays out a series of actions to the end of a game or scenario using a specific policy (like a random policy). The results of these rollouts are then used to update the estimates of the values of state-action pairs, increasing the accuracy of future decisions.

In the above figure, nodes represent states of the decision process, while edges correspond to actions connecting these states.
A graphical summary of a single step of the overall search process to find the next best action, using our running example where a new entity
has had $e_{1}$ performed out of 3 possible experiments is below:

## Synthetic Data Example with Continuous $y$
We now present an example of finding cost-efficient generative designs on synthetic data using the CEEDesigns.jl package.
First we load necessary packages.
````@example SimpleGenerative
using CEEDesigns, CEEDesigns.GenerativeDesigns
using DataFrames
using ScientificTypes
import Distributions
using Copulas
using POMDPs, POMDPTools, MCTS
using Plots, StatsPlots, StatsBase
````
### Synthetic Data
We use the "Friedman #3" method to make synthetic data for a regression problem from [scikit-learn](https://scikit-learn.org/stable/datasets/sample_generators.html#generators-for-regression).
It considers $m=4$ features which predict a continuous $y$ via some nonlinear transformations. The marginal
distributions of each feature are given by the scikit-learn documentation. We additionally use a Gaussian copula
to induce a specified correlation structure on the features to illustrate the difference between Euclidean and Mahalanobis
distance metrics. We sample $l=1000$ rows of the historical data.
````@example SimpleGenerative
make_friedman3 = function (U, noise = 0, friedman3 = true)
size(U, 2) == 4 || error("input U must have 4 columns, has $(size(U,2))")
n = size(U, 1)
X = DataFrame(zeros(Float64, n, 4), :auto)
for i = 1:4
X[:, i] .= U[:, i]
end
ϵ = noise > 0 ? rand(Distributions.Normal(0, noise), size(X, 1)) : 0
if friedman3
X.y = @. atan((X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4])) / X[:, 1]) + ϵ
else
# Friedman #2
X.y = @. (X[:, 1]^2 + (X[:, 2] * X[:, 3] - 1 / (X[:, 2] * X[:, 4]))^2)^0.5 + ϵ
end
return X
end
ρ12, ρ13, ρ14, ρ23, ρ24, ρ34 = 0.8, 0.5, 0.3, 0.5, 0.25, 0.4
Σ = [
1 ρ12 ρ13 ρ14
ρ12 1 ρ23 ρ24
ρ13 ρ23 1 ρ34
ρ14 ρ24 ρ34 1
]
X1 = Distributions.Uniform(0, 100)
X2 = Distributions.Uniform(40 * π, 560 * π)
X3 = Distributions.Uniform(0, 1)
X4 = Distributions.Uniform(1, 11)
C = GaussianCopula(Σ)
D = SklarDist(C, (X1, X2, X3, X4))
X = rand(D, 1000)
data = make_friedman3(transpose(X), 0.01)
data[1:10, :]
````
We can check that the empirical correlation is roughly the same as the specified theoretical values:
````@example SimpleGenerative
cor(Matrix(data[:, Not(:y)]))
````
We ensure that our algorithms know that we have provided data of specified types.
````@example SimpleGenerative
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Continuous,
)
data = coerce(data, types);
nothing #hide
````
We may plot each feature $x_{i} \in X = {x_{1},x_{2},x_{3},x_{4}}$ against $y$.
````@example SimpleGenerative
p1 = scatter(data.x1, data.y; legend = false, xlab = "x1")
p2 = scatter(data.x2, data.y; legend = false, xlab = "x2")
p3 = scatter(data.x3, data.y; legend = false, xlab = "x3")
p4 = scatter(data.x4, data.y; legend = false, xlab = "x4")
plot(p1, p2, p3, p4; layout = (2, 2), legend = false)
````
### Distance-based Similarity
Given historical data, a target variable $y$, and metric to quantify uncertainty around
the posterior distribution on the target $q(y|e_{S})$, the function `DistanceBased`
returns three functions needed by CEEDesigns.jl:
- `sampler`: this is a function of `(evidence, features, rng)`, in which `evidence` denotes the current experimental evidence, `features` represent the set of features we want to sample from, and `rng` is a random number generator;
- `uncertainty`: this is a function of `evidence`,
- `weights`: this represents a function of `evidence` that generates probability weights $w_j$ to each row in the historical data.
By default, Euclidean distance is used as the distance metric. In the second
call to `DistanceBased`, we instead use the squared Mahalanobis distance.
It is possible to specify different distance metrics for each feature, see our
[heart disease generative modeling](GenerativeDesigns.md) tutorial for more information.
In both cases, the squared exponential function is used to convert distances
to weights.
````@example SimpleGenerative
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
(sampler_mh, uncertainty_mh, weights_mh) = DistanceBased(
data;
target = "y",
uncertainty = Variance(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
distance = SquaredMahalanobisDistance(; diagonal = 0),
);
nothing #hide
````
We can look at the uncertainty in $y$ for a state where a single
feature is "observed" at its mean value.
As we consider only a single non-missing entry, note that the probabilistic weights assigned by the squared Mahalanobis distance
are generally less "spread out." This is because the variant of the squared Mahalanobis distance, which we implemented for handling missing values,
effectively multiplies the other quadratic distance by a factor greater than one.
For more details, refer to page 285 of
[Multivariate outlier detection in incomplete survey data: The epidemic algorithm and transformed rank correlations](https://www.jstor.org/stable/3559861).
The interaction with uncertainties is more complex as the uncertainty depends on the values of the target variable that correspond to the rows in the historical data.
````@example SimpleGenerative
data_uncertainties =
[i => uncertainty(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
data_uncertainties_mh =
[i => uncertainty_mh(Evidence(i => mean(data[:, i]))) for i in names(data)[1:4]]
sort!(data_uncertainties_mh; by = x -> x[2], rev = true)
p1 = sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
title = "Uncertainty\n(Euclidean distance)",
)
p2 = sticks(
eachindex(data_uncertainties_mh),
[i[2] for i in data_uncertainties_mh];
xformatter = i -> data_uncertainties_mh[Int(i)][1],
label = false,
title = "Uncertainty\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
````
We can view the posterior distribution $q(y|e_{S})$ conditioned on a state (here arbitrarily set to $S = e_{3}$, giving evidence for $x_{3}$).
````@example SimpleGenerative
evidence = Evidence("x3" => mean(data.x3))
plot_weights = StatsBase.weights(weights(evidence))
plot_weights_mh = StatsBase.weights(weights_mh(evidence))
p1 = Plots.histogram(
data.y;
weights = plot_weights,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Euclidean distance)",
)
p2 = Plots.histogram(
data.y;
weights = plot_weights_mh,
legend = false,
ylabel = "Density",
title = "q(y|eₛ)\n(Mahalanobis distance)",
)
plot(p1, p2; layout = (1, 2), legend = false)
````
Like static designs, generative designs need to be provided a `DataFrame` assigning to each experiment
a tuple of monetary and time costs $(m_{e},t_{e})$, and what features each experiment provides observations of.
We'll set up the experimental costs such that experiments which have less marginal uncertainty are more costly
We finally add a very expensive "final" experiment which can directly observe the target variable.
````@example SimpleGenerative
observables_experiments = Dict(["x$i" => "e$i" for i = 1:4])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(data_uncertainties_mh)
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
````
### Find Cost-efficient Experimental Designs
We can now find cost-efficient experimental designs for a new entity that has no measurements (`Evidence()`).
Our objective sense is to minimize expected experimental combined cost while trying to reduce uncertainty to
a threshold value. We examine 7 different threshold levels of uncertainty, evenly spaced between 0 and 1, inclusive.
Additionally we set the `costs_tradeoff` such that equal weight is given to time and monetary cost when
constructing the combined costs of experiments.
Internally, for each choice of the uncertainty threshold, an instance of a Markov decision problem in [POMDPs.jl](https://github.com/JuliaPOMDP/POMDPs.jl)
is created, and the `POMDPs.solve` is called on the problem.
Afterwards, a number of simulations of the decision-making problem is run, all starting with the experimental `state`.
Note that we use the Euclidean distance, due to somewhat faster runtime.
````@example SimpleGenerative
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
nothing #hide
````
We plot the Pareto-efficient actions.
````@example SimpleGenerative
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
````
## Synthetic Data Example with Discrete $y$
### Synthetic Data
We use n-class classification problem generator from [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html#sklearn.datasets.make_classification)
We used parameters given below, for a total of $m=5$ features, with 4 of those informative and 1 redundant (linear combination of the other 4) feature.
The $y$ has 2 classes, with some added noise. We again sample $l=1000$ rows of historical entities.
The dataset can be approximately reproduced as below:
````@example SimpleGenerative
# using PyCall
# sklearn = PyCall.pyimport_conda("sklearn", "scikit-learn")
# py"""
# import sklearn as sk
# from sklearn.datasets import make_classification
# """
# X, y = py"make_classification(n_samples=1000,n_features=5,n_informative=4,n_redundant=1,n_repeated=0,n_classes=2,n_clusters_per_class=2,flip_y=0.1)"
# using DataFrames, CSV
# dat = DataFrame(X, :auto)
# dat.y = y
# CSV.write("./class.csv",dat)
using CSV
data = CSV.read("./data/class.csv", DataFrame)
types = Dict(
:x1 => ScientificTypes.Continuous,
:x2 => ScientificTypes.Continuous,
:x3 => ScientificTypes.Continuous,
:x4 => ScientificTypes.Continuous,
:y => ScientificTypes.Multiclass,
)
data = coerce(data, types);
nothing #hide
````
### Distance-based Similarity
We now set up the distance based similarity functions. We use `Entropy` as our metric of uncertainty this time,
which is more suitable for discrete $y$.
````@example SimpleGenerative
(; sampler, uncertainty, weights) = DistanceBased(
data;
target = "y",
uncertainty = Entropy(),
similarity = GenerativeDesigns.Exponential(; λ = 5),
);
nothing #hide
````
We may also look at the uncertainty from each marginal distribution of features.
This is a bit nonsensical as the data generating function will create multimodal clusters
so it will look artifically as if nothing is informative, but that is not the case.
````@example SimpleGenerative
data_uncertainties =
[i => uncertainty(Evidence(i => mode(data[:, i]))) for i in names(data)[1:end-1]]
sort!(data_uncertainties; by = x -> x[2], rev = true)
sticks(
eachindex(data_uncertainties),
[i[2] for i in data_uncertainties];
xformatter = i -> data_uncertainties[Int(i)][1],
label = false,
ylab = "Uncertainty",
)
````
We can view the posterior distribution $q(y|e_{S})$ when we consider the state as evidence a single measurement
of the first feature, set to the mean of that distribution.
````@example SimpleGenerative
evidence = Evidence("x1" => mean(data.x1))
plot_weights = StatsBase.weights(weights(evidence))
target_belief = countmap(data[!, "y"], plot_weights)
p = bar(
0:1,
[target_belief[0], target_belief[1]];
xrot = 40,
ylabel = "probability",
title = "unc: $(round(uncertainty(evidence), digits=1))",
kind = :bar,
legend = false,
);
xticks!(p, 0:1, ["0", "1"]);
p
````
Like previous examples, we'll set up the experimental costs such that experiments which have less marginal uncertainty
are more costly, add a final very expensive experiment directly on the target variable.
````@example SimpleGenerative
observables_experiments = Dict(["x$i" => "e$i" for i = 1:5])
experiments_costs = Dict([
observables_experiments[e[1]] => (i, i) => [e[1]] for
(i, e) in enumerate(sort(data_uncertainties; by = x -> x[2], rev = true))
])
experiments_costs["ey"] = (100, 100) => ["y"]
experiments_costs_df =
DataFrame(; experiment = String[], time = Int[], cost = Int[], measurement = String[]);
push!(
experiments_costs_df,
[
[
e,
experiments_costs[e][1][1],
experiments_costs[e][1][2],
only(experiments_costs[e][2]),
] for e in keys(experiments_costs)
]...,
);
experiments_costs_df
````
### Find Cost-efficient Experimental Designs
We can now find sets of cost-efficient experimental designs for a new entity with no measurements (`Evidence()`).
We use the same solver parameters as for the exaple with continuous $y$, and plot the resulting
Pareto front.
````@example SimpleGenerative
n_thresholds = 7
evidence = Evidence()
solver = GenerativeDesigns.DPWSolver(; n_iterations = 500, tree_in_info = true)
repetitions = 5
mdp_options = (;
max_parallel = length(experiments_costs),
discount = 1.0,
costs_tradeoff = (0.5, 0.5),
)
designs = efficient_designs(
experiments_costs;
sampler = sampler,
uncertainty = uncertainty,
thresholds = n_thresholds,
evidence = evidence,
solver = solver,
repetitions = repetitions,
mdp_options = mdp_options,
);
plot_front(designs; labels = make_labels(designs), ylabel = "% uncertainty")
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 9387 | ```@meta
EditURL = "SimpleStatic.jl"
```
# Static Experimental Designs
In this document we describe the theoretical background behind the tools in CEEDesigns.jl for producing optimal "static experimental designs," i.e.,
arrangements of experiments that exist along a Pareto-optimal tradeoff between cost and information gain.
We also show an example with synthetic data.
## Setting
Consider the following scenario. There exists a set of experiments, each of which, when performed, yields
measurements on one or more observables (features). Each subset of observables (and therefore each subset of experiments)
has some "information value," which is intentionally vaguely defined for generality, but for example, may be
a loss function if that subset is used to train some machine learning model. It is generally the value of acquiring that information.
Finally, each experiment has some monetary cost and execution time to perform the experiment, and
the user has some known tradeoff between overall execution time and cost.
CEEDesigns.jl provides tools to take these inputs and produce a set of optimal "arrangements" of experiments for each
subset of experiments that form a Pareto front along the tradeoff between information gain and total combined cost
(monetary and time). This allows informed decisions to be made, for example, regarding how to allocate scarce
resources to a set of experiments that attain some acceptable level of information (or, conversely, reduce
uncertainty below some level).
The arrangements produced by the tools introduced in this tutorial are called "static" because they inherently
assume that for each experiment, future data will deterministically yield the same information gain as the "historical" data did.
This information gain from the "historical" data is quantified based on certain aggregate statistics.
We can also consider "generative experimental designs," where the information gain is modeled as a random variable. This concept is detailed in another [tutorial](./SimpleGenerative.jl).
This tutorial introduces the theoretical framework behind static experimental designs with synthetic data.
For examples using real data, please see our other tutorials.
## Theoretical Framework
### Experiments
Let $E = \{ e_1, \ldots, e_n\}$ be a set of $n$ experiments (i.e., $|E|=n$). Each experiment $e \in E$ has an
associated tuple $(m_{e},t_{e})$, giving the monetary cost and time duration required to perform experiment $e$.

Consider $P(E)$, the power set of experiments (i.e., every possible subset of experiments). Each subset of
experiments $S\in P(E)$ has an associated value $v_{S}$, which is the value of the experiments contained in $S$.
This may be given by the loss function associated with a prediction task where the information yielded from $S$
is used as predictor variables, or some other notion of information value.

### Arrangements
If experiments within a subset $S$ can be performed simultaneously (in parallel), then each $S$ may be arranged
optimally with respect to time. An arrangement $O_{S}$ of $S$ is a partition of the experiments in $S$ such that
the size of each partition is not larger than the maximum number of experiments that may be done in parallel.
Let $l$ be the number of partitions, and $o_{i}$ a partition in $O_{S}$. Then the arrangement is a surjection from $S$
onto $O_{S}$. If no experiments can be done in parallel, then $l=|S|$. If all experiments are done in parallel, then
$l=1$. Other arrangements fall between these extremes.

### Optimal Arrangements
To find the optimal arrangement for each $S$ we need to know the cost of $O_{S}$. The monetary cost of $O_{S}$ is simply
the sum of the costs of each experiment: $m_{O_{S}}=\sum_{e\in S} m_{e}$.
The total time required is the sum of the maximum time *of each partition*. This is because while each partition in the
arrangement is done in serial, experiments within partitions are done in parallel. That is, $t_{O_{S}}=\sum_{i=1}^{l} \text{max} \{ t_{e}: e \in o_{i}\}$.
Given these costs and a parameter $\lambda$ which controls the tradeoff between monetary cost and time, the combined
cost of an arrangement is: $\lambda m_{O_{S}} + (1-\lambda) t_{O_{S}}$.
For instance, consider the experiments $S = \{e_{1},e_{2},e_{3},e_{4}\}$, with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$.
If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement
$O_{S} = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_{O_{S}} = 4$ and $t_{O_{S}} = 10$.
However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement
$O_{S} = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_{O_{S}} = 4$, and $t_{O_{S}} = 3 + 4 = 7$.
Continuing our example and assuming a maximum of two parallel experiments, the optimal arrangement is to conduct
$e_1$ in parallel with $e_2$, and $e_3$ with $e_4$. This results in an arrangement $O_{S} = (\{ e_1, e_2 \}, \{ e_3, e_4 \})$ with a total cost of $m_o = 4$ and $t_o = 2 + 4 = 6$.
In fact, it can be readily demonstrated that the optimal arrangement can be found by ordering the experiments in
S in descending order according to their execution times. Consequently, the experiments are grouped sequentially
into partitions whose size equals the maximum number of parallel experiments, except possibly for the final set,
if the maximum number of parallel experiments does not divide $S$ evenly.
## Synthetic Data Example
We now present an example of finding cost-efficient designs for synthetic data using the CEEDesigns.jl package.
First we load necessary packages.
````@example SimpleStatic
using CEEDesigns, CEEDesigns.StaticDesigns
using Combinatorics: powerset
using DataFrames
using POMDPs, POMDPTools, MCTS
````
We consider a situation where there are 3 experiments, and we draw a value of their "loss function"
or "entropy" from the uniform distribution on the unit interval for each.
For each $S\in P(E)$, we simulate the information value ($v_{S}$) of $S$ as the product of
the values for each individual experiment.
Therefore, because smaller values are better, any subset containing multiple experiments is guaranteed to be
more "valuable" than any component experiment.
````@example SimpleStatic
experiments = ["e1", "e2", "e3"];
experiments_val = Dict([e => rand() for e in experiments]);
experiments_evals = Dict(map(Set.(collect(powerset(experiments)))) do s
if length(s) > 0
s => prod([experiments_val[i] for i in s])
else
return s => 1.0
end
end);
nothing #hide
````
See our other tutorial on [heart disease triage](StaticDesigns.md) for an example of using CEEDesigns.jl's built-in
compatability with machine learning models from `MLJ.jl` to evalute performance of experiments using
predictive accuracy as information value.
Next we set up the costs $(m_{e},t_{e})$ for each experiment.
Better experiments are more costly, both in terms of time and monetary cost. We print
the data frame showing each experiment and its associated costs.
````@example SimpleStatic
experiments_costs = Dict(
sort(collect(keys(experiments_val)); by = k -> experiments_val[k], rev = true) .=>
tuple.(1:3, 1:3),
);
DataFrame(;
experiment = collect(keys(experiments_costs)),
time = getindex.(values(experiments_costs), 1),
cost = getindex.(values(experiments_costs), 2),
)
````
We can plot the experiments ordered by their information value.
````@example SimpleStatic
plot_evals(
experiments_evals;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "loss",
)
````
We print the data frame showing each subset of experiments and its overall information value.
````@example SimpleStatic
df_values = DataFrame(;
S = collect.(collect(keys(experiments_evals))),
value = collect(values(experiments_evals)),
)
sort(df_values, order(:value; rev = true))
````
Now we are ready to find the subsets of experiments giving an optimal tradeoff between information
value and combined cost. CEEDesigns exports a function `efficient_designs`
which formulates the problem of finding optimal arrangements as a Markov Decision Process and solves
optimal arrangements for each subset on the Pareto frontier.
We set $\lambda=0.5$, the parameter controlling the relative weight given to monetary versus time costs
with the tuple `tradeoff`.
````@example SimpleStatic
max_parallel = 2;
tradeoff = (0.5, 0.5);
designs = efficient_designs(
experiments_costs,
experiments_evals;
max_parallel = max_parallel,
tradeoff = tradeoff,
);
nothing #hide
````
Finally we may produce a plot of the set of cost-efficient experimental designs. The set of designs
is plotted along a Pareto frontier giving tradeoff between informatio value (y-axis) and combined cost (x-axis).
Note that because we set the maximum number of parallel experiments equal to 2, the efficient design for the complete set
of experiments groups the experiments with long execution times together (see plot legend; each group within a partition is
prefixed with a number).
````@example SimpleStatic
plot_front(designs; labels = make_labels(designs), ylabel = "loss")
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 7487 | ```@meta
EditURL = "StaticDesigns.jl"
```
# Heart Disease Triage
Consider a situation where a group of patients is tested for a specific disease. It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
For details on the theoretical background and notation, please see our tutorial on [static experimental designs](SimpleStatic.md), this tutorial
is a concrete application of the tools described in that document.
### Application to Predictive Modeling
Let's generalize the example from [static experimental designs](SimpleStatic.md) to the case where we want to compute the information value $v_{S}$ as the predictive
ability of a machine learning model which uses the measurements gained from experiments in $S$ to predict some $y$ of interest.
Let's introduce some formal notation.
Consider a dataset of historical readouts over $m$ features $X = \{x_1, \ldots, x_m\}$, and let $y$ denote the target variable that we want to predict.
Assume that each experiment $e \in E$ yields readouts over a subset $X_e \subseteq X$ of features.
Then, for each subset $S \subseteq E$ of experiments, we may model the value of information acquired by conducting the experiments in $S$ as the accuracy of a predictive model that predicts the value of $y$ based on readouts over features in $X_S = \bigcup_{e\in S} X_e$.
Then this accuracy is our information value $v_{S}$ of $S$.
## Heart Disease Dataset
In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
````@example StaticDesigns
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
````
## Predictive Accuracy
The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
We specify the experiments along with the associated features:
````@example StaticDesigns
experiments = Dict(
# experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
````
We may also provide additional zero-cost features, which are always available.
````@example StaticDesigns
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
````
And we specify the target for prediction.
````@example StaticDesigns
target = "HeartDisease"
````
### Classifier
We use [MLJ.jl](https://alan-turing-institute.github.io/MLJ.jl/dev/) to evaluate the predictive accuracy over subsets of experimental features.
````@example StaticDesigns
using MLJ
import BetaML, MLJModels
using Random: seed!
````
We provide appropriate scientific types of the features.
````@example StaticDesigns
types = Dict(
:ChestPainType => Multiclass,
:Oldpeak => Continuous,
:HeartDisease => Multiclass,
:Age => Continuous,
:ST_Slope => Multiclass,
:RestingECG => Multiclass,
:RestingBP => Continuous,
:Sex => Multiclass,
:FastingBS => Continuous,
:ExerciseAngina => Multiclass,
)
data = coerce(data, types);
nothing #hide
````
Next, we choose a particular predictive model that will evaluated in the sequel. We can list all models that are compatible with our dataset:
````@example StaticDesigns
models(matching(data, data[:, "HeartDisease"]))
````
Eventually, we fix `RandomForestClassifier` from [BetaML](https://github.com/sylvaticus/BetaML.jl)
````@example StaticDesigns
classifier = @load RandomForestClassifier pkg = BetaML verbosity = 3
model = classifier(; n_trees = 20, max_depth = 10)
````
### Performance Evaluation
We use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the predictive accuracy over subsets of experiments. We use `LogLoss` as a measure of accuracy. It is possible to provide additional keyword arguments, which will be passed to `MLJ.evaluate` (such as `measure`, shown below).
````@example StaticDesigns
using CEEDesigns, CEEDesigns.StaticDesigns
````
````@example StaticDesigns
seed!(1) # evaluation process generally is not deterministic
perf_eval = evaluate_experiments(
experiments,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
zero_cost_features,
measure = LogLoss(),
)
````
We plot performance measures evaluated for subsets of experiments, sorted by performance measure.
````@example StaticDesigns
plot_evals(
perf_eval;
f = x -> sort(collect(keys(x)); by = k -> x[k], rev = true),
ylabel = "logloss",
)
````
## Cost-Efficient Designs
We specify the cost associated with the execution of each experiment.
````@example StaticDesigns
costs = Dict(
# experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
````
We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs.
````@example StaticDesigns
designs = efficient_designs(costs, perf_eval)
````
````@example StaticDesigns
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
````
### Parallel Experiments
The previous example assumed that experiments had to be run sequentially. We can see how the optimal arrangement changes if we assume multiple experiments can be run in parallel. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
````@example StaticDesigns
experiments_costs = Dict(
# experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
````
We set the maximum number of concurrent experiments. Additionally, we can specify the tradeoff between monetary cost and execution time. In our case, we aim to minimize the execution time.
Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
````@example StaticDesigns
# Implicit, calculates accuracies automatically.
seed!(1) # evaluation process generally is not deterministic
designs = efficient_designs(
experiments_costs,
model,
data[!, Not("HeartDisease")],
data[!, "HeartDisease"];
eval_options = (; zero_cost_features, measure = LogLoss()),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
````
As we can see, the algorithm correctly suggests running experiments in parallel.
````@example StaticDesigns
plot_front(designs; labels = make_labels(designs), ylabel = "logloss")
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.3.7 | aab69b0a2ba41717d5d3c33c410cbe940d1fd58c | docs | 14578 | ```@meta
EditURL = "StaticDesignsFiltration.jl"
```
# Heart Disease Triage With Early Droupout
Consider again a situation where a group of patients is tested for a specific disease.
It may be costly to conduct an experiment yielding the definitive answer. Instead, we want to utilize various proxy experiments that provide partial information about the presence of the disease.
Moreover, we may assume that for some patients, the evidence gathered from proxy experiments can be considered 'conclusive'. Effectively, some patients may not need any additional triage; they might be deemed healthy or require immediate commencement of treatment. By doing so, we could save significant resources.
## Theoretical Framework
We take as a basis the setup and notation from the basic framework presented in the [static experimental designs tutorial](SimpleStatic.md).
We again have a set of experiments $E$, but now assume that a set of extrinsic decision-making rules is imposed on the experimental readouts.
If the experimental evidence acquired for a given entity satisfies a specific criterion, that entity is then removed from the triage.
However, other entities within the batch will generally continue in the experimental process.
In general, the process of establishing such rules is largely dependent on the specific problem and requires comprehensive understanding of the subject area.
We denote the expected fraction of entities that remain in the triage after conducting a set $S$ of experiments as the filtration rate, $f_S$. In the context of disease triage, this can be interpreted as the fraction of patients for whom the experimental evidence does not provide a 'conclusive' result.
As previously, each experiment $e$ incurs a cost $(m_e, t_e)$. Again, we let $O_{S}$ denote an arrangement of experiments in $S$.
Given a subset $S$ of experiments and their arrangement $O_{S}$, the total (discounted) monetary cost and execution time of the experimental design is given as $m_o = \sum_{i=1}^{l} r_{S_{i-1}}\sum_{e\in o_i} m_e$ and $t_o = \sum_{i=1}^{l} \max \{ t_e : e\in o_i\}$, respectively.
Importantly, the new factor $r_{S_{i-1}}$ models the fact that a set of entities may have dropped out in the previous experiments, hence saving the resources on running the subsequent experiments.
We note that these computations are based on the assumption that monetary cost is associated with the analysis of a single experimental entity, such as a patient. Therefore, the total monetary cost obtained for a specific arrangement is effectively the ["expected"](https://en.wikipedia.org/wiki/Expected_value) monetary cost, adjusted for a single entity. Conversely, we suppose that all entities can be concurrently examined in a specific experiment. As such, the total execution time is equivalent to the longest time until all experiments within an arrangement are finished or all entities have been eliminated (which ocurrs when the filtration rate the experiments conducted so far is zero). Importantly, this distinctly differs from calculating the 'expected lifespan' of an entity in the triage.
For instance, consider the experiments $e_1,\, e_2,\, e_3$, and $e_4$ with associated costs $(1, 1)$, $(1, 3)$, $(1, 2)$, and $(1, 4)$, and filtration rates $0.9,\,0.8,\,0.7$, and $0.6$. For subsets of experiments, we simply assume that the filtration rates multiply, thereby treating the experiments as independent binary discriminators. In other words, the filtration rate for a set $S=\{ e_1, e_3 \}$ would equal $f_S = 0.9 * 0.7 = 0.63$.
If we conduct experiments $e_1$ through $e_4$ in sequence, this would correspond to an arrangement $o = (\{ e_1 \}, \{ e_2 \}, \{ e_3 \}, \{ e_4 \})$ with a total cost of $m_o = 1 + 0.9 * 1 + 0.72 * 1 + 0.504 * 1 = 3.124$ and $t_o = 10$.
However, if we decide to conduct $e_1$ in parallel with $e_3$, and $e_2$ with $e_4$, we would obtain an arrangement $o = (\{ e_1, e_3 \}, \{ e_2, e_4 \})$ with a total cost of $m_o = 2 + 0.63 * 2 = 3.26$, and $t_o = 3 + 4 = 7$.
Given the constraint on the maximum number of parallel experiments, we construct an arrangement $o$ of experiments $S$ such that, for a fixed tradeoff $\lambda$ between monetary cost and execution time, the expected combined cost $c_{(o, \lambda)} = \lambda m_o + (1-\lambda) t_o$ is minimized. Significantly, our objective is to leverage the filtration rates within the experimental arrangement.
### A Note on Optimal Arrangements
In situations when experiments within a set $S$ are executed sequentially, i.e., one after the other, it can be demonstrated that the experiments should be arranged in ascending order by $\frac{\lambda m_e + (1-\lambda) t_e}{1-f_e}$.
Continuing our example and assuming that the experiments are conducted sequentially, the optimal arrangement $o$ would be to run experiments $e_4$ through $e_1$, yielding $m_o = 2.356$.
When we allow simultaneous execution of experiments, the problem turns more complicated, and we currently are not aware of an 'analytical' solution for it. Instead, we proposed approximating the 'optimal' arrangement as the 'optimal' policy found for a particular Markov decision process, in which:
- _state_ is the set of experiments that have been conducted thus far,
- _actions_ are subsets of experiments which have not been conducted yet; the size of these subsets is restricted by the maximum number of parallel experiments;
- _reward_ is a combined monetary cost and execution time, discounted by the filtration rate of previously conducted experiments.
Provided we know the information values $v_S$, filtration rates $r_S$, and experimental costs $c_S$ for each set of experiments $S$, we find a collection of Pareto-efficient experimental designs that balance both the implied value of information and the experimental cost.
## Heart Disease Dataset
In this tutorial, we consider a dataset that includes 11 clinical features along with a binary variable indicating the presence of heart disease in patients. The dataset can be found at [Kaggle: Heart Failure Prediction](https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction). It utilizes heart disease datasets from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/dataset/45/heart+disease).
````@example StaticDesignsFiltration
using CSV, DataFrames
data = CSV.File("data/heart_disease.csv") |> DataFrame
data[1:10, :]
````
In order to adapt the dataset to the current context, we can assume that, for every experiment, a medical specialist determined a range for 'conclusive' and 'inconclusive' outputs. This determination could be based on, say, optimizing the precision and recall factors of the resultant discriminative model. As an example, consider [A novel approach for heart disease prediction using strength scores with significant predictors](https://d-nb.info/1242792767/34) where rule mining for heart disease prediction is considered.\
It should be noted that the readout ranges defined below are entirely fictional.
````@example StaticDesignsFiltration
inconclusive_regions = Dict(
"ChestPainType" => ["NAP", "ASY"],
"RestingBP" => (50, 150),
"ExerciseAngina" => ["N"],
"FastingBS" => [0],
"RestingECG" => ["Normal"],
"MaxHR" => (50, 120),
"Cholesterol" => (0, 240),
"Oldpeak" => (-2.55, 2.55),
)
````
We apply the rules to derive a binary dataset where 'true' signifies that the readout was inconclusive, requiring them to remain in the triage.
````@example StaticDesignsFiltration
data_binary = DataFrame();
for colname in names(data[!, Not("HeartDisease")])
if haskey(inconclusive_regions, colname)
if inconclusive_regions[colname] isa Vector
data_binary[!, colname] =
map(x -> x ∈ inconclusive_regions[colname], data[!, colname])
else
lb, ub = inconclusive_regions[colname]
data_binary[!, colname] = map(x -> lb <= x <= ub, data[!, colname])
end
else
data_binary[!, colname] = trues(nrow(data))
end
end
data_binary[1:10, :]
````
## Discriminative Power and Filtration Rates
In this scenario, we model the value of information $v_S$ acquired by conducting a set of experiments as the ratio of patients for whom the results across the experiments in $S$ were 'inconclusive', i.e., $|\cap_{e\in S}\{ \text{patient} : \text{inconclusive in } e \}| / |\text{patients}|$. Essentially, the very same measure is used here to estimate the filtration rate.
The CEEDesigns.jl package offers an additional flexibility by allowing an experiment to yield readouts over multiple features at the same time. In our scenario, we can consider the features `RestingECG`, `Oldpeak`, `ST_Slope`, and `MaxHR` to be obtained from a single experiment `ECG`.
We specify the experiments along with the associated features:
````@example StaticDesignsFiltration
experiments = Dict(
# experiment => features
"BloodPressure" => ["RestingBP"],
"ECG" => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => ["Cholesterol"],
"BloodSugar" => ["FastingBS"],
)
````
We may also provide additional zero-cost features, which are always available.
````@example StaticDesignsFiltration
zero_cost_features = ["Age", "Sex", "ChestPainType", "ExerciseAngina"]
````
For binary datasets, we may use `evaluate_experiments` from `CEEDesigns.StaticDesigns` to evaluate the discriminative power of subsets of experiments.
````@example StaticDesignsFiltration
using CEEDesigns, CEEDesigns.StaticDesigns
````
````@example StaticDesignsFiltration
perf_eval = evaluate_experiments(experiments, data_binary; zero_cost_features)
````
Note that for each subset of experiments, the function returns a named tuple with fields `loss` and `filtration`.
We plot discriminative power evaluated for subsets of experiments.
````@example StaticDesignsFiltration
plot_evals(perf_eval; ylabel = "discriminative power")
````
## Cost-Efficient Designs
We specify the cost associated with the execution of each experiment.
````@example StaticDesignsFiltration
costs = Dict(
# experiment => cost
"BloodPressure" => 1,
"ECG" => 5,
"BloodCholesterol" => 20,
"BloodSugar" => 20,
)
````
We use the provided function `efficient_designs` to construct the set of cost-efficient experimental designs. Note that the filtration is enabled implicitly since we provided the filtration rates within `perf_eval`. Another form of `perf_eval` would be `subset of experiments => information measure`, in which case the filtration would equal one. That is, no dropout would be considered.
````@example StaticDesignsFiltration
designs = efficient_designs(costs, perf_eval)
````
````@example StaticDesignsFiltration
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
````
Let us compare the above with the efficient front with disabled filtration.
````@example StaticDesignsFiltration
# pass performance eval with discarded filtration rates (defaults to 1)
designs_no_filtration = efficient_designs(costs, Dict(k => v.loss for (k, v) in perf_eval))
````
````@example StaticDesignsFiltration
using Plots
p = scatter(
map(x -> x[1][1], designs_no_filtration),
map(x -> x[1][2], designs_no_filtration);
label = "designs with filtration disabled",
c = :blue,
mscolor = nothing,
fontsize = 16,
)
scatter!(
p,
map(x -> x[1][1], designs),
map(x -> x[1][2], designs);
xlabel = "combined cost",
ylabel = "discriminative power",
label = "designs with filtration enabled",
c = :teal,
mscolor = nothing,
fontsize = 16,
)
````
## Arrangement of a Set of Experiments
Importantly, the total execution cost of an experiment is generally not the sum of costs associated to each individual experiment. In fact, a non-zero dropout rate (`filtration < 1`) discounts the expected cost of subsequent experiments. As discussed previously, we are not aware of an 'analytical' solution to this problem.
Instead, we approximate the 'optimal' arrangement as the 'optimal' policy for a particular Markov decision process. This can be accomplished using, for instance, the [Monte Carlo Tree Search algorithm](https://github.com/JuliaPOMDP/MCTS.jl) as implemented in the [POMDPs.jl](http://juliapomdp.github.io/POMDPs.jl/latest/) package.
The following is a visualisation of the DPW search tree that was used to find an optimal arrangement for a set of experiments yielding the highest information value.
````@example StaticDesignsFiltration
using MCTS, D3Trees
experiments = Set(vcat.(designs[end][2].arrangement...)[1])
(; planner) = CEEDesigns.StaticDesigns.optimal_arrangement(
costs,
perf_eval,
experiments;
mdp_kwargs = (; tree_in_info = true),
)
_, info = action_info(planner, Set{String}())
t = D3Tree(info[:tree]; init_expand = 2)
````
````@example StaticDesignsFiltration
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
````
### Parallel Experiments
We may exploit parallelism in the experimental arrangement. To that end, we first specify the monetary cost and execution time for each experiment, respectively.
````@example StaticDesignsFiltration
experiments_costs = Dict(
# experiment => (monetary cost, execution time) => features
"BloodPressure" => (1.0, 1.0) => ["RestingBP"],
"ECG" => (5.0, 5.0) => ["RestingECG", "Oldpeak", "ST_Slope", "MaxHR"],
"BloodCholesterol" => (20.0, 20.0) => ["Cholesterol"],
"BloodSugar" => (20.0, 20.0) => ["FastingBS"],
)
````
We provide the maximum number of concurrent experiments. Additionally, we specify the tradeoff between monetary cost and execution time - in our case, we aim to minimize the execution time.
Below, we demonstrate the flexibility of `efficient_designs` as it can both evaluate the performance of experiments and generate efficient designs. Internally, `evaluate_experiments` is called first, followed by `efficient_designs`. Keyword arguments to the respective functions has to wrapped in `eval_options` and `arrangement_options` named tuples, respectively.
````@example StaticDesignsFiltration
# Implicit, calculates accuracies automatically
designs = efficient_designs(
experiments_costs,
data_binary;
eval_options = (; zero_cost_features),
arrangement_options = (; max_parallel = 2, tradeoff = (0.0, 1)),
)
````
As we can see, the algorithm correctly suggests running experiments in parallel.
````@example StaticDesignsFiltration
plot_front(designs; labels = make_labels(designs), ylabel = "discriminative power")
````
| CEEDesigns | https://github.com/Merck/CEEDesigns.jl.git |
|
[
"MIT"
] | 0.1.2 | 149f6f3325bc4703ff16372f7be26bc5171f6830 | code | 53382 | ### A Pluto.jl notebook ###
# v0.19.32
using Markdown
using InteractiveUtils
# ╔═╡ 6d0e158d-ba36-4100-86bf-44b878b30356
using AccessibleOptimization # reexport both AccessorsExtra and Optimization
# ╔═╡ 3fa1d138-6e8e-4e8b-bfac-71536628eeb8
using IntervalSets
# ╔═╡ c5915064-60e6-4180-a4e9-8e8a4e91b020
using StructArrays
# ╔═╡ a5db525e-1ee9-4451-a933-c3041166e38a
using StaticArrays
# ╔═╡ 4bdd0dcd-ca89-4102-bfa9-926683fee155
using DataManipulation
# ╔═╡ f03679e5-5d9e-41e5-bff2-c02822181d01
using FlexiMaps
# ╔═╡ 6115a5f1-6d34-4c10-985d-6abe36275978
using PyPlotUtils; pyplot_style!()
# ╔═╡ 58165c5e-b292-4b54-90a2-24b911095af7
using OptimizationOptimJL
# ╔═╡ 27ebaf90-bdc4-408b-9b7a-c951d3a64c8c
using OptimizationMetaheuristics
# ╔═╡ 63de3367-39e6-404a-ad7d-1597a7d1f446
using Kroki
# ╔═╡ 719aafc6-9a82-4b22-ae96-0ba843327c0a
using BenchmarkTools
# ╔═╡ 1d5d7187-fbac-4d4f-8a02-31f6251fcd72
using ProfileCanvas
# ╔═╡ 31766e3e-1d86-4d2a-8330-9838283d2f90
using StaticNumbers: static
# ╔═╡ acb4555e-969b-4ee7-a4af-7341a9eb5388
md"""
Import `AccessibleOptimization` and other useful packages:
"""
# ╔═╡ 0949c456-cd15-4d7a-a6f4-44d2fac82412
md"""
Load some optimization backends to use in the examples. Any backend works!
"""
# ╔═╡ 7800bdd6-8bcf-4424-a92f-91a1801db92a
HTML("""
<style>
pluto-output img {
max-width: 700px !important;
}
</style>
""")
# ╔═╡ 750e3462-cc5c-4e25-a888-6b9993aa3ad6
md"""
## Overview
"""
# ╔═╡ b893551a-fd2a-40fd-88db-9854cb872ff6
md"""
Here is a flowchart connecting the main working parts of `AccessibleOptimization`.
Here:
- bold arrows indicate actions performed by the user,
- regular arrows are for the main dataflow within the package,
- dashed arrows explain which part of the problem specification is used at which point,
Optics, their manipulation, `getall`, and `setall` come from `Accessors` and `AccessorsExtra` packages.
"""
# ╔═╡ b05afbf8-425f-427d-9171-3877db101fcb
Diagram(:mermaid, """
graph TD
subgraph Specification
SP
OA
F
OPS
end
subgraph AccessibleOptimization.jl
AOS
FLAT
OPTICS
CONSTRUCT
SCONSTRUCT
AOSOL
end
subgraph Optimization.jl
OS
Iterations
OSOL
end
subgraph Iterations
OVEC
OF
end
SP("Object O₀") ==> OPS
SP -.-> CONSTRUCT("Oᵢ = setall(O₀, optic, xᵢ)")
SP -.-> FLAT("x₀ = getall(O₀, optic)")
SP -.-> SCONSTRUCT("Oₛ = setall(O₀, optic, xₛ)")
OA(OptArgs definition) ==> OPS
OA -..-> OPTICS(Concat optics into one)
OPTICS -.-> FLAT
OPTICS -.-> CONSTRUCT
OPTICS -.-> SCONSTRUCT
F("Target f(object)") ==> OPS
F -.-> OF
OPS(OptProblemSpec) ==> AOS("solve(...)")
FLAT -- "Vector x₀" --> OS
AOS --> OS("solve(...)")
OS --> OVEC
OVEC("Vector xᵢ") --> CONSTRUCT
CONSTRUCT -- "Object Oᵢ" --> OF("Evaluate f(Oᵢ)")
OF --> OVEC
OF -- Finished? --> OSOL("Solution vector xₛ")
OSOL --> SCONSTRUCT
SCONSTRUCT ==> AOSOL("Solution object Oₛ")
style SP fill:#fdd
style OA fill:#dfd
style OPTICS fill:#dfd
style F fill:#ddf
linkStyle 0,1,2,3 stroke:#600
linkStyle 4,5,6,7,8 stroke:#060
linkStyle 9,10 stroke:#006
"""; options = Dict("flowchart_width" => "300px", "flowchart_use-width" => "300px", "flowchart_use-max-width" => "true"))
# ╔═╡ c7d1204a-8edf-4f36-b9f9-dc6e08477a0b
md"""
## Walkthrough
"""
# ╔═╡ 2651d2ed-1680-4fa4-93db-938958291afd
md"""
In this section, we walk through a concrete model fitting problem from start to end.
"""
# ╔═╡ e0ea9f28-bafc-4566-9b22-d00a2253d9e9
md"""
First, define a struct representing the model, along with a way to evaluate it.
This is standard Julia code, nothing specific to optimization or `Accessors`.
"""
# ╔═╡ 3f22a7ae-bd49-478c-8f74-391bb6cf11cc
begin
struct ExpModel{A,B}
scale::A
shift::B
end
struct SumModel{T <: Tuple}
comps::T
end
(m::ExpModel)(x) = m.scale * exp(-(x - m.shift)^2)
(m::SumModel)(x) = sum(c -> c(x), m.comps)
end
# ╔═╡ 3d0d0368-031d-4a04-b66c-2dc5e8be00a0
md"""
Generate or load an dataset, and define the loss function.
Again, this is plain Julia code. Here, we create the dataset from our model (`truemod`) with some noise.
"""
# ╔═╡ ea815f0c-8e7e-4b9d-a765-34baf0242140
truemod = SumModel((
ExpModel(2, 5),
ExpModel(0.5, 2),
ExpModel(0.5, 8),
))
# ╔═╡ 9257a65d-7dd1-41c3-8071-19ecf9115797
data = @p 0:0.2:10 |> StructArray(x=__, y=truemod.(__) .+ 0.03 .* randn.())
# ╔═╡ 63d598fa-02a6-4d36-94f4-43831a5de8d1
let
plt.figure()
plt.plot(data.x, data.y, ".-")
plt.gcf()
end
# ╔═╡ 8412b028-a559-4566-bd51-c4650a8edf73
loss(m, data) = @p sum(abs2(_.y - m(_.x)), data)
# ╔═╡ 25355d27-0766-468d-9c7c-edf0ee743711
md"Create an instance of the model struct. Some or all parameters would be optimized afterwards."
# ╔═╡ ff8ded6f-6f7d-41ac-93a0-11ff1f6f2a40
mod0 = SumModel((
ExpModel(1, 1),
ExpModel(1, 2),
ExpModel(1, 3),
))
# ╔═╡ 29faf78f-a44f-48cc-9e07-80cc70f6764c
md"""
It's only at this point where we encounter code specific to parameter optimization.
Let's define the parameters to be optimized. They are represented as `Accessors` optics and possible value bounds:
"""
# ╔═╡ 79ede060-9bf1-4a71-a92b-493b9d4fce8e
vars = OptArgs(
(@o _.comps[∗].shift) => 0..10.,
(@o _.comps[∗].scale) => 0.3..10.,
)
# ╔═╡ a53461db-00d3-48da-9a03-116311c10b5a
md"Optionally, define a set of constrains: each is a function of the model, and the interval of bounds."
# ╔═╡ 4a97d36d-81f6-447f-ba26-6f0ebb93217c
cons = OptCons(
((x, _) -> @p mean(_.shift, x.comps)) => 0.5..4,
)
# ╔═╡ ae16f334-e583-4fac-8c34-c5b4e60f248f
md"""
Create an optimization problem definition.
This step is equivalent to `OptimizationProblem(loss, ops, data)` in `Optimization.jl` itself, but here we can work with arbitrary structs and parameter definitions instead of vectors.
"""
# ╔═╡ 0340001b-8282-4fb7-94a1-cfec5c2ecfb6
# supported variants:
# ops = OptProblemSpec(MVector{<:Any, Float64}, mod0, vars)
# ops = OptProblemSpec(Tuple, mod0, vars)
# ops = OptProblemSpec(Vector{Float64}, mod0, vars)
# ops = OptProblemSpec(mod0, vars)
# ops = OptProblemSpec(Base.Fix2(loss, data), Vector, mod0, vars)
ops = OptProblemSpec(Base.Fix2(loss, data), SVector, mod0, vars)
# ops = OptProblemSpec(Base.Fix2(OptimizationFunction(loss, Optimization.AutoForwardDiff()), data), Vector{Float64}, mod0, vars, cons)
# equivalents in Optimization.jl itself:
# prob = OptimizationProblem(loss, ops, data)
# prob = OptimizationProblem(OptimizationFunction(loss, Optimization.AutoForwardDiff()), ops, data)
# ╔═╡ b923b0fd-f373-48b0-8689-0bdef2780c54
md"Finally, run `solve` on the problem. Same interface as in `Optimization` itself:"
# ╔═╡ 0e679fb7-1baf-4545-aef5-eb564e41db54
sol = solve(ops, ECA(), maxiters=300)
# sol = solve(prob, Optim.GradientDescent(), maxiters=300)
# sol = solve(ops, Optim.IPNewton(), maxiters=300)
# ╔═╡ eab52f13-6ff0-4fbc-80c9-782ef03b6e7a
md"""
`sol.u` is the resulting vector of parameters, directly provided by `Optimization`. All other solution properties are available as well.
"""
# ╔═╡ c4d2d970-c468-4d18-852f-846cb81a2d7a
sol.u
# ╔═╡ 17e4ff5b-ddd6-404f-a092-4c7c9b18cfed
md"While `sol.uobj` is the model object with its parameters optimized:"
# ╔═╡ 337a4039-2349-454e-b6dc-6a8d584b58a9
sol.uobj
# ╔═╡ 8a944bd7-befd-4e9e-999d-d1921053aa9c
md"""
## More examples
"""
# ╔═╡ 6c8f8970-4ff3-4b7a-b537-970cd6055e59
md"""
Further, we'll demonstrate fitting the same model, but with different parameters fixed/optimized.
Let's define convenience functions to fit and plot the results:
"""
# ╔═╡ b51f9964-1e19-4078-a2c6-6109e935a000
solmod_from_vars(vars) = @p let
OptProblemSpec(Base.Fix2(loss, data), mod0, vars)
solve(__, ECA(), maxiters=300)
__.uobj
end
# ╔═╡ 66acd240-f950-4c2a-bc06-1ac2c5929544
function plot_datamod(data, mod)
plt.figure()
plt.plot(data.x, data.y, ".-")
datamod = @set data.y = mod.(data.x)
plt.plot(datamod.x, datamod.y, ".-")
plt.gcf()
end
# ╔═╡ fd5c3705-a79e-4898-a94c-6ceb966a1334
md"Only optimize the first component shift, leaving everything else constant:"
# ╔═╡ bd06ef56-c099-4631-b895-0fa68da0f8ff
@p let
OptArgs(
(@o _.comps[1].shift) => 0..10.,
)
solmod_from_vars()
plot_datamod(data, __), __
end
# ╔═╡ 04c2526e-b991-43f0-aea3-ff816a2bc9de
md"Optimize scales and shifts of all components - specify them manually:"
# ╔═╡ 90757798-7aa5-46e8-8c7b-d7c66b47b865
@p let
OptArgs(
(@o _.comps[∗].scale) => 0..10.,
(@o _.comps[∗].shift) => 0..10.,
)
solmod_from_vars()
plot_datamod(data, __), __
end
# ╔═╡ 2c648777-a967-4129-8640-504fd523852f
md"""
Optimize scales and shifts of all components - specified via a recursive optic:
"""
# ╔═╡ 52baa97e-dcd4-4ba7-8492-6f1179522562
@p let
OptArgs(
RecursiveOfType(Number) => 0..10.,
)
solmod_from_vars()
plot_datamod(data, __), __
end
# ╔═╡ 4fe4e530-813d-4f8f-8a74-de08de26c3aa
md"Optimize scales and shifts of all components, while two scales (#2 and #3) are kept exactly the same:"
# ╔═╡ d741b31f-e947-4650-bcba-9d9b8f842726
@p let
OptArgs(
(@o _.comps[1].scale) => 0..10.,
(@o _.comps[2:3][∗].scale |> PartsOf() |> uniqueonly) => 0..1.,
(@o _.comps[∗].shift) => 0..10.,
)
solmod_from_vars()
plot_datamod(data, __), __
end
# ╔═╡ 3014244b-74f6-4c0f-a5f2-13c4091db1fc
md"""
Constrain the order, so that the largest component (by scale) is always the last:
"""
# ╔═╡ cbe06e5a-eece-41d4-9655-22e514e3cf83
@p let
OptArgs(
(@o _.comps[∗].scale |> PartsOf() |> onset(sort∘SVector) |> Elements()) => 0..10.,
(@o _.comps[∗].shift) => 0..10.,
)
solmod_from_vars()
plot_datamod(data, __), __
end
# ╔═╡ 96984d56-c0f2-423c-b457-cf2d826dd9c3
md"""
This example relies on the fact that `set`/`setall` is used to turn a parameter vector into a struct, see flowchart above. The `onset` wrapper modifies `set` on the `_.comps[∗].scale` optic so that the entries are sorted each time.
"""
# ╔═╡ dc57e188-20f6-4c7e-bef0-955547f2482f
md"""
## Etc
"""
# ╔═╡ 52735849-5810-46d6-bfa6-7fc67ba8c1c3
md"Some bechmarks to demonstrate little or no overhead:"
# ╔═╡ cdba5bb2-d52b-41d6-85ff-4011fc570a11
x0 = SumModel((
ExpModel(2, 0),
ExpModel(0, 0),
ExpModel(0, 0),
))
# ╔═╡ 7cafbcf6-57d4-4f07-87e7-74504e98d4f3
bvars = OptArgs(
(@o first(_.comps).shift) => 0..10.,
(@o _.comps[static(1:2)][∗].shift) => 0..10.,
(@o _.comps[static(2:3)][∗].scale |> PartsOf() |> uniqueonly) => 0..10.,
)
# ╔═╡ 67fc7546-e287-4001-a0cd-d5f74a94f3bc
bops = OptProblemSpec(Base.Fix2(loss, data), Vector, x0, bvars)
# bops = OptProblemSpec(Base.Fix2(loss, data), SVector, x0, bvars)
# ╔═╡ 30b8cec9-3c00-49ea-bf9f-76fe26fe5a87
u = @btime AccessibleOptimization.rawu($bops)
# ╔═╡ 15ca9bd4-8ced-462b-b34f-b781a041c1f1
@btime AccessibleOptimization.fromrawu($u, $bops)
# ╔═╡ f0ede4eb-1811-48e7-9a2b-49e7f67ae7a8
func = AccessibleOptimization.rawfunc(bops)
# ╔═╡ 708951df-5d62-4e06-9493-9886f95e426d
@btime loss($x0, $data)
# ╔═╡ 6e6eac98-7825-467a-bd59-ee33ec66c321
@btime func($u, $data)
# ╔═╡ 88801de8-abd8-4306-8504-04edbf2ee518
@btime AccessibleOptimization.rawbounds($bops)
# ╔═╡ 53f5d11d-7f29-48ad-a9be-d6ab67b763f0
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
AccessibleOptimization = "d88a00a0-4a21-4fe4-a515-e2123c37b885"
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
DataManipulation = "38052440-ad76-4236-8414-61389b2c5143"
FlexiMaps = "6394faf6-06db-4fa8-b750-35ccc60383f7"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
Kroki = "b3565e16-c1f2-4fe9-b4ab-221c88942068"
OptimizationMetaheuristics = "3aafef2f-86ae-4776-b337-85a36adf0b55"
OptimizationOptimJL = "36348300-93cb-4f02-beb5-3c3902f8871e"
ProfileCanvas = "efd6af41-a80b-495e-886c-e51b0c7d77a3"
PyPlotUtils = "5384e752-6c47-47b3-86ac-9d091b110b31"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StaticNumbers = "c5e4b96a-f99f-5557-8ed2-dc63ef9b5131"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
[compat]
AccessibleOptimization = "~0.1.1"
BenchmarkTools = "~1.3.2"
DataManipulation = "~0.1.14"
FlexiMaps = "~0.1.21"
IntervalSets = "~0.7.8"
Kroki = "~0.2.0"
OptimizationMetaheuristics = "~0.1.3"
OptimizationOptimJL = "~0.1.14"
ProfileCanvas = "~0.1.6"
PyPlotUtils = "~0.1.31"
StaticArrays = "~1.7.0"
StaticNumbers = "~0.4.0"
StructArrays = "~0.6.16"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.9.4"
manifest_format = "2.0"
project_hash = "64de9698c0aacc1c6543fd3272114f64086f8434"
[[deps.ADTypes]]
git-tree-sha1 = "332e5d7baeff8497b923b730b994fa480601efc7"
uuid = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
version = "0.2.5"
[[deps.AbstractTrees]]
git-tree-sha1 = "faa260e4cb5aba097a73fab382dd4b5819d8ec8c"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.4"
[[deps.AccessibleOptimization]]
deps = ["AccessorsExtra", "ConstructionBase", "DataPipes", "Optimization", "Reexport", "Statistics"]
git-tree-sha1 = "ddd0a1f18f7426b7d4ca365b70af5857338e0c52"
uuid = "d88a00a0-4a21-4fe4-a515-e2123c37b885"
version = "0.1.1"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "LinearAlgebra", "MacroTools", "Test"]
git-tree-sha1 = "a7055b939deae2455aa8a67491e034f735dd08d3"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.33"
[deps.Accessors.extensions]
AccessorsAxisKeysExt = "AxisKeys"
AccessorsIntervalSetsExt = "IntervalSets"
AccessorsStaticArraysExt = "StaticArrays"
AccessorsStructArraysExt = "StructArrays"
[deps.Accessors.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
Requires = "ae029012-a4dd-5104-9daa-d747884805df"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
[[deps.AccessorsExtra]]
deps = ["Accessors", "CompositionsBase", "ConstructionBase", "DataPipes", "InverseFunctions", "Reexport"]
git-tree-sha1 = "dd760656c4e27a443cc0a763ecf5865670e29947"
uuid = "33016aad-b69d-45be-9359-82a41f556fd4"
version = "0.1.60"
[deps.AccessorsExtra.extensions]
ColorTypesExt = "ColorTypes"
DictArraysExt = "DictArrays"
DictionariesExt = "Dictionaries"
DistributionsExt = "Distributions"
DomainSetsExt = "DomainSets"
FlexiMapsExt = "FlexiMaps"
LinearAlgebraExt = "LinearAlgebra"
StaticArraysExt = "StaticArrays"
StructArraysExt = "StructArrays"
TestExt = "Test"
URIsExt = "URIs"
[deps.AccessorsExtra.weakdeps]
ColorTypes = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
DictArrays = "e9958f2c-b184-4647-9c5a-224a61f6a14b"
Dictionaries = "85a47980-9c8c-11e8-2b9f-f7ca1fa99fb4"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf"
FlexiMaps = "6394faf6-06db-4fa8-b750-35ccc60383f7"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "02f731463748db57cc2ebfbd9fbc9ce8280d3433"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.7.1"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra", "Requires", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "247efbccf92448be332d154d6ca56b9fcdd93c31"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.6.1"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "d9a9701b899b30332bbcb3e1679c41cce81fb0e8"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.3.2"
[[deps.BitFlags]]
git-tree-sha1 = "2dc09997850d68179b69dafb58ae806167a32b1b"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.8"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "cd67fc487743b2f0fd4380d4cbd3a24660d0eec8"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.3"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.Combinatorics]]
git-tree-sha1 = "08c8b6831dc00bfea825826be0bc8336fc369860"
uuid = "861a8166-3701-5b0c-9a16-15d98fcdc6aa"
version = "1.0.2"
[[deps.CommonSolve]]
git-tree-sha1 = "0eee5eb66b1cf62cd6ad1b460238e60e4b09400c"
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
version = "0.2.4"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "8a62af3e248a8c4bad6b32cbbe663ae02275e32c"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.10.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.5+0"
[[deps.CompositeTypes]]
git-tree-sha1 = "02d2316b7ffceff992f3096ae48c7829a8aa0638"
uuid = "b152e2b5-7a66-4b01-a709-34e65c35f657"
version = "0.1.3"
[[deps.CompositionsBase]]
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.2"
weakdeps = ["InverseFunctions"]
[deps.CompositionsBase.extensions]
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
[[deps.ConcreteStructs]]
git-tree-sha1 = "f749037478283d372048690eb3b5f92a79432b34"
uuid = "2569d6c7-a4a2-43d3-a901-331e8e4be471"
version = "0.2.3"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "8cfa272e8bdedfa88b6aefbbca7c19f1befac519"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.3.0"
[[deps.Conda]]
deps = ["Downloads", "JSON", "VersionParsing"]
git-tree-sha1 = "51cab8e982c5b598eea9c8ceaced4b58d9dd37c9"
uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d"
version = "1.10.0"
[[deps.ConsoleProgressMonitor]]
deps = ["Logging", "ProgressMeter"]
git-tree-sha1 = "3ab7b2136722890b9af903859afcf457fa3059e8"
uuid = "88cd18e8-d9cc-4ea6-8889-5259c0d15c8b"
version = "0.1.2"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "c53fc348ca4d40d7b371e71fd52251839080cbc9"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.4"
weakdeps = ["IntervalSets", "StaticArrays"]
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseStaticArraysExt = "StaticArrays"
[[deps.DataAPI]]
git-tree-sha1 = "8da84edb865b0b5b0100c0666a9bc9a0b71c553c"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.15.0"
[[deps.DataManipulation]]
deps = ["Accessors", "AccessorsExtra", "DataPipes", "Dictionaries", "FlexiGroups", "FlexiMaps", "InverseFunctions", "Reexport", "Skipper"]
git-tree-sha1 = "ac171e5d322f3c33ee69cb784993a52c08127e86"
uuid = "38052440-ad76-4236-8414-61389b2c5143"
version = "0.1.14"
weakdeps = ["IntervalSets", "StructArrays"]
[deps.DataManipulation.extensions]
IntervalSetsExt = "IntervalSets"
StructArraysExt = "StructArrays"
[[deps.DataPipes]]
git-tree-sha1 = "bca470e22fb942e15707dc6f1e829c1b0f684bf4"
uuid = "02685ad9-2d12-40c3-9f73-c6aeda6a7ff5"
version = "0.3.13"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "3dbd312d370723b6bb43ba9d02fc36abade4518d"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.15"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.Dictionaries]]
deps = ["Indexing", "Random", "Serialization"]
git-tree-sha1 = "e82c3c97b5b4ec111f3c1b55228cebc7510525a2"
uuid = "85a47980-9c8c-11e8-2b9f-f7ca1fa99fb4"
version = "0.3.25"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "23163d55f885173722d1e4cf0f6110cdbaf7e272"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.15.1"
[[deps.DirectionalStatistics]]
deps = ["Accessors", "IntervalSets", "InverseFunctions", "LinearAlgebra", "Statistics", "StatsBase"]
git-tree-sha1 = "e067e4bfdb7a18ecca71ac8d59dd38c00c912b53"
uuid = "e814f24e-44b0-11e9-2fd5-aba2b6113d95"
version = "0.1.24"
[[deps.Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "5225c965635d8c21168e32a12954675e7bea1151"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.10"
[deps.Distances.extensions]
DistancesChainRulesCoreExt = "ChainRulesCore"
DistancesSparseArraysExt = "SparseArrays"
[deps.Distances.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.DomainSets]]
deps = ["CompositeTypes", "IntervalSets", "LinearAlgebra", "Random", "StaticArrays", "Statistics"]
git-tree-sha1 = "32c810efb5987bb4a5b6299525deaef8698d1919"
uuid = "5b8099bc-c8ec-5219-889f-1d9e522a28bf"
version = "0.7.1"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EnumX]]
git-tree-sha1 = "bdb1942cd4c45e3c678fd11569d5cccd80976237"
uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56"
version = "1.0.4"
[[deps.ExceptionUnwrapping]]
deps = ["Test"]
git-tree-sha1 = "e90caa41f5a86296e014e148ee061bd6c3edec96"
uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4"
version = "0.1.9"
[[deps.ExprTools]]
git-tree-sha1 = "27415f162e6028e81c72b82ef756bf321213b6ec"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.10"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random"]
git-tree-sha1 = "35f0c0f345bff2c6d636f95fdb136323b5a796ef"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "1.7.0"
weakdeps = ["SparseArrays", "Statistics"]
[deps.FillArrays.extensions]
FillArraysSparseArraysExt = "SparseArrays"
FillArraysStatisticsExt = "Statistics"
[[deps.FiniteDiff]]
deps = ["ArrayInterface", "LinearAlgebra", "Requires", "Setfield", "SparseArrays"]
git-tree-sha1 = "c6e4a1fbe73b31a3dea94b1da449503b8830c306"
uuid = "6a86dc24-6348-571c-b903-95158fe2bd41"
version = "2.21.1"
[deps.FiniteDiff.extensions]
FiniteDiffBandedMatricesExt = "BandedMatrices"
FiniteDiffBlockBandedMatricesExt = "BlockBandedMatrices"
FiniteDiffStaticArraysExt = "StaticArrays"
[deps.FiniteDiff.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.FlexiGroups]]
deps = ["AccessorsExtra", "Combinatorics", "DataPipes", "Dictionaries", "FlexiMaps"]
git-tree-sha1 = "f8d1a7d2eff2e7701e8827f88291583bc05f7ea7"
uuid = "1e56b746-2900-429a-8028-5ec1f00612ec"
version = "0.1.21"
[deps.FlexiGroups.extensions]
AxisKeysExt = "AxisKeys"
CategoricalArraysExt = "CategoricalArrays"
OffsetArraysExt = "OffsetArrays"
[deps.FlexiGroups.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
CategoricalArrays = "324d7699-5711-5eae-9e2f-1d82baa6b597"
OffsetArrays = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
[[deps.FlexiMaps]]
deps = ["Accessors", "DataPipes", "InverseFunctions"]
git-tree-sha1 = "7706ad2f68fbc12c0b2757ed45a8daff54366bf1"
uuid = "6394faf6-06db-4fa8-b750-35ccc60383f7"
version = "0.1.21"
weakdeps = ["Dictionaries", "StructArrays"]
[deps.FlexiMaps.extensions]
DictionariesExt = "Dictionaries"
StructArraysExt = "StructArrays"
[[deps.ForwardDiff]]
deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions"]
git-tree-sha1 = "cf0fe81336da9fb90944683b8c41984b08793dad"
uuid = "f6369f11-7733-5829-9624-2563aa707210"
version = "0.10.36"
weakdeps = ["StaticArrays"]
[deps.ForwardDiff.extensions]
ForwardDiffStaticArraysExt = "StaticArrays"
[[deps.FunctionWrappers]]
git-tree-sha1 = "d62485945ce5ae9c0c48f124a84998d755bae00e"
uuid = "069b7b12-0de2-55c6-9aab-29f3d0a68a2e"
version = "1.1.3"
[[deps.FunctionWrappersWrappers]]
deps = ["FunctionWrappers"]
git-tree-sha1 = "b104d487b34566608f8b4e1c39fb0b10aa279ff8"
uuid = "77dc65aa-8811-40c2-897b-53d922fa7daf"
version = "0.1.3"
[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[deps.GPUArraysCore]]
deps = ["Adapt"]
git-tree-sha1 = "2d6ca471a6c7b536127afccfa7564b5b39227fe0"
uuid = "46192b85-c4d5-4398-a991-12ede77f4527"
version = "0.1.5"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "5eab648309e2e060198b45820af1a37182de3cce"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.10.0"
[[deps.Indexing]]
git-tree-sha1 = "ce1566720fd6b19ff3411404d4b977acd4814f9f"
uuid = "313cdc1a-70c2-5d6a-ae34-0150d3930a38"
version = "1.1.1"
[[deps.IntegerMathUtils]]
git-tree-sha1 = "b8ffb903da9f7b8cf695a8bead8e01814aa24b30"
uuid = "18e54dd8-cb9d-406c-a71d-865a43cbb235"
version = "0.1.2"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.IntervalSets]]
deps = ["Dates", "Random"]
git-tree-sha1 = "3d8866c029dd6b16e69e0d4a939c4dfcb98fac47"
uuid = "8197267c-284f-5f27-9208-e0e47529a953"
version = "0.7.8"
weakdeps = ["Statistics"]
[deps.IntervalSets.extensions]
IntervalSetsStatisticsExt = "Statistics"
[[deps.InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "68772f49f54b479fa88ace904f6127f0a3bb2e46"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.12"
[[deps.IrrationalConstants]]
git-tree-sha1 = "630b497eafcc20001bba38a4651b327dcfc491d2"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.2.2"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLLWrappers]]
deps = ["Artifacts", "Preferences"]
git-tree-sha1 = "7e5d6779a1e09a36db2a7b6cff50942a0a7d0fca"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.5.0"
[[deps.JMcDM]]
deps = ["Requires"]
git-tree-sha1 = "3e61354940109772a01efd25fc0818dd7d411109"
uuid = "358108f5-d052-4d0a-8344-d5384e00c0e5"
version = "0.7.10"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.4"
[[deps.Kroki]]
deps = ["Base64", "CodecZlib", "DocStringExtensions", "HTTP", "JSON", "Markdown", "Reexport"]
git-tree-sha1 = "a3235f9ff60923658084df500cdbc0442ced3274"
uuid = "b3565e16-c1f2-4fe9-b4ab-221c88942068"
version = "0.2.0"
[[deps.LaTeXStrings]]
git-tree-sha1 = "50901ebc375ed41dbf8058da26f9de442febbbec"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.1"
[[deps.LatticeRules]]
deps = ["Random"]
git-tree-sha1 = "7f5b02258a3ca0221a6a9710b0a0a2e8fb4957fe"
uuid = "73f95e8e-ec14-4e6a-8b18-0d2e271c4e55"
version = "0.0.1"
[[deps.Lazy]]
deps = ["MacroTools"]
git-tree-sha1 = "1370f8202dac30758f3c345f9909b97f53d87d3f"
uuid = "50d2b5c4-7a5e-59d5-8109-a42b560f39c0"
version = "0.15.1"
[[deps.LeftChildRightSiblingTrees]]
deps = ["AbstractTrees"]
git-tree-sha1 = "fb6803dafae4a5d62ea5cab204b1e657d9737e7f"
uuid = "1d6d02ad-be62-4b6b-8a6d-2f90e265016e"
version = "0.2.0"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.4"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "8.4.0+0"
[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.11.0+1"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.LineSearches]]
deps = ["LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "Printf"]
git-tree-sha1 = "7bbea35cec17305fc70a0e5b4641477dc0789d9d"
uuid = "d3d80556-e9d4-5f37-9878-2ab0fcc64255"
version = "7.2.0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LogExpFunctions]]
deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "7d6dd4e9212aebaeed356de34ccf262a3cd415aa"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.26"
[deps.LogExpFunctions.extensions]
LogExpFunctionsChainRulesCoreExt = "ChainRulesCore"
LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables"
LogExpFunctionsInverseFunctionsExt = "InverseFunctions"
[deps.LogExpFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.LoggingExtras]]
deps = ["Dates", "Logging"]
git-tree-sha1 = "c1dd6d7978c12545b4179fb6153b9250c96b0075"
uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36"
version = "1.0.3"
[[deps.MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "9ee1618cbf5240e6d4e0371d6f24065083f60c48"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.11"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"]
git-tree-sha1 = "c067a280ddc25f196b5e7df3877c6b226d390aaf"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.1.9"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.2+0"
[[deps.Metaheuristics]]
deps = ["Distances", "JMcDM", "LinearAlgebra", "Pkg", "Printf", "Random", "Reexport", "Requires", "SearchSpaces", "SnoopPrecompile", "Statistics"]
git-tree-sha1 = "fda08e881de2665d0a4cfbaf98dd6d24b9439142"
uuid = "bcdb8e00-2c21-11e9-3065-2b553b22f898"
version = "3.3.3"
[[deps.Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "f66bdc5de519e8f8ae43bdc598782d35a25b1272"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.1.0"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2022.10.11"
[[deps.NLSolversBase]]
deps = ["DiffResults", "Distributed", "FiniteDiff", "ForwardDiff"]
git-tree-sha1 = "a0b464d183da839699f4c79e7606d9d186ec172c"
uuid = "d41bc354-129a-5804-8e4c-c37616107c6c"
version = "7.8.3"
[[deps.NaNMath]]
deps = ["OpenLibm_jll"]
git-tree-sha1 = "0877504529a3e5c3343c6f8b4c0381e57e4387e4"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "1.0.2"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.NonNegLeastSquares]]
deps = ["Distributed", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "1271344271ffae97e2855b0287356e6ea5c221cc"
uuid = "b7351bd1-99d9-5c5d-8786-f205a815c4d7"
version = "0.4.0"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.21+4"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+0"
[[deps.OpenSSL]]
deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "OpenSSL_jll", "Sockets"]
git-tree-sha1 = "51901a49222b09e3743c65b8847687ae5fc78eb2"
uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c"
version = "1.4.1"
[[deps.OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "cc6e1927ac521b659af340e0ca45828a3ffc748f"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "3.0.12+0"
[[deps.OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[deps.Optim]]
deps = ["Compat", "FillArrays", "ForwardDiff", "LineSearches", "LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "PositiveFactorizations", "Printf", "SparseArrays", "StatsBase"]
git-tree-sha1 = "01f85d9269b13fedc61e63cc72ee2213565f7a72"
uuid = "429524aa-4258-5aef-a3af-852621145aeb"
version = "1.7.8"
[[deps.Optimization]]
deps = ["ADTypes", "ArrayInterface", "ConsoleProgressMonitor", "DocStringExtensions", "LinearAlgebra", "Logging", "LoggingExtras", "Pkg", "Printf", "ProgressLogging", "Reexport", "Requires", "SciMLBase", "SparseArrays", "TerminalLoggers"]
git-tree-sha1 = "1aa7ffea6e171167e9cae620d749e16d5874414a"
uuid = "7f7a1694-90dd-40f0-9382-eb1efda571ba"
version = "3.19.3"
[deps.Optimization.extensions]
OptimizationEnzymeExt = "Enzyme"
OptimizationFiniteDiffExt = "FiniteDiff"
OptimizationForwardDiffExt = "ForwardDiff"
OptimizationMTKExt = "ModelingToolkit"
OptimizationReverseDiffExt = "ReverseDiff"
OptimizationSparseDiffExt = ["SparseDiffTools", "Symbolics", "ReverseDiff"]
OptimizationTrackerExt = "Tracker"
OptimizationZygoteExt = "Zygote"
[deps.Optimization.weakdeps]
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
FiniteDiff = "6a86dc24-6348-571c-b903-95158fe2bd41"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
SparseDiffTools = "47a9eef4-7e08-11e9-0b38-333d64bd3804"
Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.OptimizationMetaheuristics]]
deps = ["Metaheuristics", "Optimization", "Reexport"]
git-tree-sha1 = "287f529435e4950470857b16e866a682fe6e7893"
uuid = "3aafef2f-86ae-4776-b337-85a36adf0b55"
version = "0.1.3"
[[deps.OptimizationOptimJL]]
deps = ["Optim", "Optimization", "Reexport", "SparseArrays"]
git-tree-sha1 = "bea24fb320d58cb639e3cbc63f8eedde6c667bd3"
uuid = "36348300-93cb-4f02-beb5-3c3902f8871e"
version = "0.1.14"
[[deps.OrderedCollections]]
git-tree-sha1 = "dfdf5519f235516220579f949664f1bf44e741c5"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.6.3"
[[deps.Parameters]]
deps = ["OrderedCollections", "UnPack"]
git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe"
uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a"
version = "0.12.3"
[[deps.Parsers]]
deps = ["Dates", "PrecompileTools", "UUIDs"]
git-tree-sha1 = "a935806434c9d4c506ba941871b327b96d41f2bf"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.8.0"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.9.2"
[[deps.PositiveFactorizations]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "17275485f373e6673f7e7f97051f703ed5b15b20"
uuid = "85a6dd25-e78a-55b7-8502-1745935b8125"
version = "0.2.4"
[[deps.PrecompileTools]]
deps = ["Preferences"]
git-tree-sha1 = "03b4c25b43cb84cee5c90aa9b5ea0a78fd848d2f"
uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
version = "1.2.0"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00805cd429dcb4870060ff49ef443486c262e38e"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.4.1"
[[deps.Primes]]
deps = ["IntegerMathUtils"]
git-tree-sha1 = "1d05623b5952aed1307bf8b43bec8b8d1ef94b6e"
uuid = "27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae"
version = "0.5.5"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.Profile]]
deps = ["Printf"]
uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79"
[[deps.ProfileCanvas]]
deps = ["Base64", "JSON", "Pkg", "Profile", "REPL"]
git-tree-sha1 = "e42571ce9a614c2fbebcaa8aab23bbf8865c624e"
uuid = "efd6af41-a80b-495e-886c-e51b0c7d77a3"
version = "0.1.6"
[[deps.ProgressLogging]]
deps = ["Logging", "SHA", "UUIDs"]
git-tree-sha1 = "80d919dee55b9c50e8d9e2da5eeafff3fe58b539"
uuid = "33c8b6b6-d38a-422a-b730-caa89a2f386c"
version = "0.1.4"
[[deps.ProgressMeter]]
deps = ["Distributed", "Printf"]
git-tree-sha1 = "00099623ffee15972c16111bcf84c58a0051257c"
uuid = "92933f4c-e287-5a05-a399-4b506db050ca"
version = "1.9.0"
[[deps.PyCall]]
deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"]
git-tree-sha1 = "1cb97fa63a3629c6d892af4f76fcc4ad8191837c"
uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
version = "1.96.2"
[[deps.PyPlot]]
deps = ["Colors", "LaTeXStrings", "PyCall", "Sockets", "Test", "VersionParsing"]
git-tree-sha1 = "9220a9dae0369f431168d60adab635f88aca7857"
uuid = "d330b81b-6aea-500a-939a-2ce795aea3ee"
version = "2.11.2"
[[deps.PyPlotUtils]]
deps = ["Accessors", "ColorTypes", "DataPipes", "DirectionalStatistics", "DomainSets", "FlexiMaps", "IntervalSets", "LinearAlgebra", "NonNegLeastSquares", "PyCall", "PyPlot", "Statistics", "StatsBase"]
git-tree-sha1 = "b6c3add9b602520fe779597302c983dbae7e6e5d"
uuid = "5384e752-6c47-47b3-86ac-9d091b110b31"
version = "0.1.31"
[deps.PyPlotUtils.extensions]
AxisKeysExt = "AxisKeys"
AxisKeysUnitfulExt = ["AxisKeys", "Unitful"]
UnitfulExt = "Unitful"
[deps.PyPlotUtils.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.QuasiMonteCarlo]]
deps = ["Accessors", "ConcreteStructs", "LatticeRules", "LinearAlgebra", "Primes", "Random", "Requires", "Sobol", "StatsBase"]
git-tree-sha1 = "cc086f8485bce77b6187141e1413c3b55f9a4341"
uuid = "8a4e6c94-4038-4cdc-81c3-7e6ffdb2a71b"
version = "0.3.3"
[deps.QuasiMonteCarlo.extensions]
QuasiMonteCarloDistributionsExt = "Distributions"
[deps.QuasiMonteCarlo.weakdeps]
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.RecipesBase]]
deps = ["PrecompileTools"]
git-tree-sha1 = "5c3d09cc4f31f5fc6af001c250bf1278733100ff"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.3.4"
[[deps.RecursiveArrayTools]]
deps = ["Adapt", "ArrayInterface", "DocStringExtensions", "GPUArraysCore", "IteratorInterfaceExtensions", "LinearAlgebra", "RecipesBase", "Requires", "StaticArraysCore", "Statistics", "SymbolicIndexingInterface", "Tables"]
git-tree-sha1 = "d7087c013e8a496ff396bae843b1e16d9a30ede8"
uuid = "731186ca-8d62-57ce-b412-fbd966d074cd"
version = "2.38.10"
[deps.RecursiveArrayTools.extensions]
RecursiveArrayToolsMeasurementsExt = "Measurements"
RecursiveArrayToolsMonteCarloMeasurementsExt = "MonteCarloMeasurements"
RecursiveArrayToolsTrackerExt = "Tracker"
RecursiveArrayToolsZygoteExt = "Zygote"
[deps.RecursiveArrayTools.weakdeps]
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
MonteCarloMeasurements = "0987c9cc-fe09-11e8-30f0-b96dd679fdca"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.RuntimeGeneratedFunctions]]
deps = ["ExprTools", "SHA", "Serialization"]
git-tree-sha1 = "6aacc5eefe8415f47b3e34214c1d79d2674a0ba2"
uuid = "7e49a35a-f44a-4d26-94aa-eba1b4ca6b47"
version = "0.5.12"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.SciMLBase]]
deps = ["ADTypes", "ArrayInterface", "CommonSolve", "ConstructionBase", "Distributed", "DocStringExtensions", "EnumX", "FillArrays", "FunctionWrappersWrappers", "IteratorInterfaceExtensions", "LinearAlgebra", "Logging", "Markdown", "PrecompileTools", "Preferences", "Printf", "QuasiMonteCarlo", "RecipesBase", "RecursiveArrayTools", "Reexport", "RuntimeGeneratedFunctions", "SciMLOperators", "StaticArraysCore", "Statistics", "SymbolicIndexingInterface", "Tables", "TruncatedStacktraces"]
git-tree-sha1 = "164773badb9ee8c62af2ff1a7778fd4867142a07"
uuid = "0bca4576-84f4-4d90-8ffe-ffa030f20462"
version = "2.9.0"
[deps.SciMLBase.extensions]
SciMLBaseChainRulesCoreExt = "ChainRulesCore"
SciMLBasePartialFunctionsExt = "PartialFunctions"
SciMLBasePyCallExt = "PyCall"
SciMLBasePythonCallExt = "PythonCall"
SciMLBaseRCallExt = "RCall"
SciMLBaseZygoteExt = "Zygote"
[deps.SciMLBase.weakdeps]
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
PartialFunctions = "570af359-4316-4cb7-8c74-252c00c2016b"
PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"
RCall = "6f49c342-dc21-5d91-9882-a32aef131414"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[[deps.SciMLOperators]]
deps = ["ArrayInterface", "DocStringExtensions", "Lazy", "LinearAlgebra", "Setfield", "SparseArrays", "StaticArraysCore", "Tricks"]
git-tree-sha1 = "51ae235ff058a64815e0a2c34b1db7578a06813d"
uuid = "c0aeaf25-5076-4817-a8d5-81caf7dfa961"
version = "0.3.7"
[[deps.SearchSpaces]]
deps = ["Combinatorics", "Random"]
git-tree-sha1 = "2662fd537048fb12ff34fabb5249bf50e06f445b"
uuid = "eb7571c6-2196-4f03-99b8-52a5a35b3163"
version = "0.2.0"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.Setfield]]
deps = ["ConstructionBase", "Future", "MacroTools", "StaticArraysCore"]
git-tree-sha1 = "e2cc6d8c88613c05e1defb55170bf5ff211fbeac"
uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46"
version = "1.1.1"
[[deps.SimpleBufferStream]]
git-tree-sha1 = "874e8867b33a00e784c8a7e4b60afe9e037b74e1"
uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7"
version = "1.1.0"
[[deps.Skipper]]
git-tree-sha1 = "f1407f6a7c3c2df3a534106fa931a08f3fea12e4"
uuid = "fc65d762-6112-4b1c-b428-ad0792653d81"
version = "0.1.10"
weakdeps = ["Accessors", "Dictionaries"]
[deps.Skipper.extensions]
AccessorsExt = "Accessors"
DictionariesExt = "Dictionaries"
[[deps.SnoopPrecompile]]
deps = ["Preferences"]
git-tree-sha1 = "e760a70afdcd461cf01a575947738d359234665c"
uuid = "66db9d55-30c0-4569-8b51-7e840670fc0c"
version = "1.0.3"
[[deps.Sobol]]
deps = ["DelimitedFiles", "Random"]
git-tree-sha1 = "5a74ac22a9daef23705f010f72c81d6925b19df8"
uuid = "ed01d8cd-4d21-5b2a-85b4-cc3bdc58bad4"
version = "1.5.0"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "5165dfb9fd131cf0c6957a3a7605dede376e7b63"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.2.0"
[[deps.SparseArrays]]
deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.SpecialFunctions]]
deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "e2cfc4012a19088254b3950b85c3c1d8882d864d"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "2.3.1"
[deps.SpecialFunctions.extensions]
SpecialFunctionsChainRulesCoreExt = "ChainRulesCore"
[deps.SpecialFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
[[deps.StaticArrays]]
deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"]
git-tree-sha1 = "5ef59aea6f18c25168842bded46b16662141ab87"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.7.0"
weakdeps = ["Statistics"]
[deps.StaticArrays.extensions]
StaticArraysStatisticsExt = "Statistics"
[[deps.StaticArraysCore]]
git-tree-sha1 = "36b3d696ce6366023a0ea192b4cd442268995a0d"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.2"
[[deps.StaticNumbers]]
git-tree-sha1 = "b54bf9e3b0914394584270460284692720071d64"
uuid = "c5e4b96a-f99f-5557-8ed2-dc63ef9b5131"
version = "0.4.0"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
version = "1.9.0"
[[deps.StatsAPI]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1ff449ad350c9c4cbc756624d6f8a8c3ef56d3ed"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.7.0"
[[deps.StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "1d77abd07f617c4868c33d4f5b9e1dbb2643c9cf"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.34.2"
[[deps.StructArrays]]
deps = ["Adapt", "ConstructionBase", "DataAPI", "GPUArraysCore", "StaticArraysCore", "Tables"]
git-tree-sha1 = "0a3db38e4cce3c54fe7a71f831cd7b6194a54213"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.16"
[[deps.SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[deps.SuiteSparse_jll]]
deps = ["Artifacts", "Libdl", "Pkg", "libblastrampoline_jll"]
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
version = "5.10.1+6"
[[deps.SymbolicIndexingInterface]]
deps = ["DocStringExtensions"]
git-tree-sha1 = "f8ab052bfcbdb9b48fad2c80c873aa0d0344dfe5"
uuid = "2efcf032-c050-4f8e-a9bb-153293bab1f5"
version = "0.2.2"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.3"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits"]
git-tree-sha1 = "cb76cf677714c095e535e3501ac7954732aeea2d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.11.1"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.0"
[[deps.TerminalLoggers]]
deps = ["LeftChildRightSiblingTrees", "Logging", "Markdown", "Printf", "ProgressLogging", "UUIDs"]
git-tree-sha1 = "f133fab380933d042f6796eda4e130272ba520ca"
uuid = "5d786b92-1e48-4d6f-9151-6b4477ca9bed"
version = "0.1.7"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.TranscodingStreams]]
git-tree-sha1 = "1fbeaaca45801b4ba17c251dd8603ef24801dd84"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.10.2"
weakdeps = ["Random", "Test"]
[deps.TranscodingStreams.extensions]
TestExt = ["Test", "Random"]
[[deps.Tricks]]
git-tree-sha1 = "eae1bb484cd63b36999ee58be2de6c178105112f"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.8"
[[deps.TruncatedStacktraces]]
deps = ["InteractiveUtils", "MacroTools", "Preferences"]
git-tree-sha1 = "ea3e54c2bdde39062abf5a9758a23735558705e1"
uuid = "781d530d-4396-4725-bb49-402e4bee1e77"
version = "1.4.0"
[[deps.URIs]]
git-tree-sha1 = "67db6cc7b3821e19ebe75791a9dd19c9b1188f2b"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.5.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.UnPack]]
git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b"
uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed"
version = "1.0.2"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.VersionParsing]]
git-tree-sha1 = "58d6e80b4ee071f5efd07fda82cb9fbe17200868"
uuid = "81def892-9a0e-5fdd-b105-ffc91e053289"
version = "1.3.0"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.13+0"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.8.0+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.52.0+1"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+0"
"""
# ╔═╡ Cell order:
# ╟─acb4555e-969b-4ee7-a4af-7341a9eb5388
# ╠═6d0e158d-ba36-4100-86bf-44b878b30356
# ╠═3fa1d138-6e8e-4e8b-bfac-71536628eeb8
# ╠═c5915064-60e6-4180-a4e9-8e8a4e91b020
# ╠═a5db525e-1ee9-4451-a933-c3041166e38a
# ╠═4bdd0dcd-ca89-4102-bfa9-926683fee155
# ╠═f03679e5-5d9e-41e5-bff2-c02822181d01
# ╠═6115a5f1-6d34-4c10-985d-6abe36275978
# ╟─0949c456-cd15-4d7a-a6f4-44d2fac82412
# ╠═58165c5e-b292-4b54-90a2-24b911095af7
# ╠═27ebaf90-bdc4-408b-9b7a-c951d3a64c8c
# ╟─63de3367-39e6-404a-ad7d-1597a7d1f446
# ╟─7800bdd6-8bcf-4424-a92f-91a1801db92a
# ╟─750e3462-cc5c-4e25-a888-6b9993aa3ad6
# ╟─b893551a-fd2a-40fd-88db-9854cb872ff6
# ╟─b05afbf8-425f-427d-9171-3877db101fcb
# ╟─c7d1204a-8edf-4f36-b9f9-dc6e08477a0b
# ╟─2651d2ed-1680-4fa4-93db-938958291afd
# ╟─e0ea9f28-bafc-4566-9b22-d00a2253d9e9
# ╠═3f22a7ae-bd49-478c-8f74-391bb6cf11cc
# ╟─3d0d0368-031d-4a04-b66c-2dc5e8be00a0
# ╠═ea815f0c-8e7e-4b9d-a765-34baf0242140
# ╠═9257a65d-7dd1-41c3-8071-19ecf9115797
# ╠═63d598fa-02a6-4d36-94f4-43831a5de8d1
# ╠═8412b028-a559-4566-bd51-c4650a8edf73
# ╟─25355d27-0766-468d-9c7c-edf0ee743711
# ╠═ff8ded6f-6f7d-41ac-93a0-11ff1f6f2a40
# ╟─29faf78f-a44f-48cc-9e07-80cc70f6764c
# ╠═79ede060-9bf1-4a71-a92b-493b9d4fce8e
# ╟─a53461db-00d3-48da-9a03-116311c10b5a
# ╠═4a97d36d-81f6-447f-ba26-6f0ebb93217c
# ╟─ae16f334-e583-4fac-8c34-c5b4e60f248f
# ╠═0340001b-8282-4fb7-94a1-cfec5c2ecfb6
# ╟─b923b0fd-f373-48b0-8689-0bdef2780c54
# ╠═0e679fb7-1baf-4545-aef5-eb564e41db54
# ╟─eab52f13-6ff0-4fbc-80c9-782ef03b6e7a
# ╠═c4d2d970-c468-4d18-852f-846cb81a2d7a
# ╟─17e4ff5b-ddd6-404f-a092-4c7c9b18cfed
# ╠═337a4039-2349-454e-b6dc-6a8d584b58a9
# ╟─8a944bd7-befd-4e9e-999d-d1921053aa9c
# ╟─6c8f8970-4ff3-4b7a-b537-970cd6055e59
# ╠═b51f9964-1e19-4078-a2c6-6109e935a000
# ╠═66acd240-f950-4c2a-bc06-1ac2c5929544
# ╟─fd5c3705-a79e-4898-a94c-6ceb966a1334
# ╠═bd06ef56-c099-4631-b895-0fa68da0f8ff
# ╟─04c2526e-b991-43f0-aea3-ff816a2bc9de
# ╠═90757798-7aa5-46e8-8c7b-d7c66b47b865
# ╟─2c648777-a967-4129-8640-504fd523852f
# ╠═52baa97e-dcd4-4ba7-8492-6f1179522562
# ╟─4fe4e530-813d-4f8f-8a74-de08de26c3aa
# ╠═d741b31f-e947-4650-bcba-9d9b8f842726
# ╟─3014244b-74f6-4c0f-a5f2-13c4091db1fc
# ╠═cbe06e5a-eece-41d4-9655-22e514e3cf83
# ╟─96984d56-c0f2-423c-b457-cf2d826dd9c3
# ╟─dc57e188-20f6-4c7e-bef0-955547f2482f
# ╟─52735849-5810-46d6-bfa6-7fc67ba8c1c3
# ╠═719aafc6-9a82-4b22-ae96-0ba843327c0a
# ╠═1d5d7187-fbac-4d4f-8a02-31f6251fcd72
# ╠═31766e3e-1d86-4d2a-8330-9838283d2f90
# ╠═cdba5bb2-d52b-41d6-85ff-4011fc570a11
# ╠═7cafbcf6-57d4-4f07-87e7-74504e98d4f3
# ╠═67fc7546-e287-4001-a0cd-d5f74a94f3bc
# ╠═30b8cec9-3c00-49ea-bf9f-76fe26fe5a87
# ╠═15ca9bd4-8ced-462b-b34f-b781a041c1f1
# ╠═f0ede4eb-1811-48e7-9a2b-49e7f67ae7a8
# ╠═708951df-5d62-4e06-9493-9886f95e426d
# ╠═6e6eac98-7825-467a-bd59-ee33ec66c321
# ╠═88801de8-abd8-4306-8504-04edbf2ee518
# ╠═53f5d11d-7f29-48ad-a9be-d6ab67b763f0
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| AccessibleOptimization | https://github.com/JuliaAPlavin/AccessibleOptimization.jl.git |
|
[
"MIT"
] | 0.1.2 | 149f6f3325bc4703ff16372f7be26bc5171f6830 | code | 5971 | module AccessibleOptimization
using Reexport
@reexport using Optimization
@reexport using AccessorsExtra
using DataPipes
using ConstructionBase
using Statistics: mean
export OptArgs, OptCons, OptProblemSpec, solobj
ConstructionBase.constructorof(::Type{<:OptimizationFunction{x}}) where {x} =
function(args...)
kwargs = NamedTuple{fieldnames(OptimizationFunction)}(args)
OptimizationFunction{x}(kwargs.f, kwargs.adtype; @delete(kwargs[(:f, :adtype)])...)
end
struct OptArgs{TS}
specs::TS
OptArgs(specs...) = new{typeof(specs)}(specs)
end
_optic((o, i)::Pair) = o
_optic(o) = o
_intbound((o, i)::Pair) = i
_intbound(o) = nothing
optic(v::OptArgs) = AccessorsExtra.ConcatOptics(map(_optic, v.specs))
rawu(x0, v::OptArgs) = getall(x0, optic(v))
fromrawu(u, x0, v::OptArgs) = setall(x0, optic(v), u)
rawfunc(f, x0, v::OptArgs) = (u, p) -> f(fromrawu(u, x0, v), p)
rawbounds(x0, v::OptArgs, AT=nothing) =
if @p v.specs |> any(isnothing(_intbound(_)))
@assert @p v.specs |> all(isnothing(_intbound(_)))
return ()
else
@p let
v.specs
map(fill(_intbound(_), length(getall(x0, _optic(_)))))
reduce(vcat)
(lb=_convert(AT, minimum.(__)), ub=_convert(AT, maximum.(__)))
end
end
rawu(x0::Type, v::OptArgs) = @p v.specs |> map(_intbound) |> map(mean)
fromrawu(u, x0::Type, v::OptArgs) = @p map(_optic(_1) => _2, v.specs, u) |> construct(x0, __...)
rawbounds(x0::Type, v::OptArgs, AT=nothing) =
if @p v.specs |> any(isnothing(_intbound(_)))
@assert @p v.specs |> all(isnothing(_intbound(_)))
return ()
else
@p let
v.specs
map(_intbound(_))
(lb=_convert(AT, minimum.(__)), ub=_convert(AT, maximum.(__)))
end
end
struct OptCons{TC,TS}
ctype::TC
specs::TS
OptCons(CT::Union{Type,Nothing}, specs...) = new{typeof(CT), typeof(specs)}(CT, specs)
OptCons(specs...) = OptCons(nothing, specs...)
end
ConstructionBase.constructorof(::Type{<:OptCons}) = (ctype, specs) -> OptCons(ctype, specs...)
rawconsbounds(c::OptCons) = @p let
c.specs
map(_[2])
(lcons=_convert(c.ctype, minimum.(__)), ucons=_convert(c.ctype, maximum.(__)))
end
# rawcons(cons::OptCons, x0, v::OptArgs) = function(u, p)
# x = fromrawu(u, x0, v)
# map(cons.specs) do (consfunc, consint)
# consfunc(x, p)
# end |> cons.ctype
# end
_apply(f, args...) = f(args...)
rawcons(cons::OptCons, x0, v::OptArgs) = function(res, u, p)
x = fromrawu(u, x0, v)
res .= _apply.(first.(cons.specs), (x,), (p,))
end
Base.summary(cons::OptCons, x, p) = @p let
cons.specs
map(enumerate(__)) do (i, (f, int))
v = f(x, p)
"cons #$i: $v $(v ∈ int ? '∈' : '∉') $int"
end
join(__, '\n')
Text
end
struct OptProblemSpec{F,D,U,X0,VS<:OptArgs,CS<:Union{OptCons,Nothing}}
func::F
data::D
utype::U
x0::X0
vars::VS
cons::CS
end
function OptProblemSpec(f::Base.Fix2, utype::Type, x0, vars::OptArgs, cons::OptCons)
cons = @set cons.ctype = something(cons.ctype, utype)
OptProblemSpec(f.f, f.x, utype, x0, vars, cons)
end
OptProblemSpec(f::Base.Fix2, utype::Union{Type,Nothing}, x0, vars::OptArgs, cons::Union{OptCons,Nothing}) = OptProblemSpec(f.f, f.x, utype, x0, vars, cons)
OptProblemSpec(f::Base.Fix2, utype::Union{Type,Nothing}, x0, vars::OptArgs) = OptProblemSpec(f, utype, x0, vars, nothing)
OptProblemSpec(f::Base.Fix2, x0, vars::OptArgs) = OptProblemSpec(f, nothing, x0, vars)
OptProblemSpec(f::Base.Fix2, x0, vars::OptArgs, cons::Union{OptCons,Nothing}) = OptProblemSpec(f, nothing, x0, vars, cons)
rawfunc(s::OptProblemSpec) = rawfunc(s.func, s.x0, s.vars)
rawfunc(s::OptProblemSpec{<:OptimizationFunction}) = rawfunc(s.func.f, s.x0, s.vars)
rawdata(s::OptProblemSpec) = s.data
rawu(s::OptProblemSpec) = _convert(s.utype, rawu(s.x0, s.vars))
rawbounds(s::OptProblemSpec) = rawbounds(s.x0, s.vars, s.utype)
rawconsbounds(s::OptProblemSpec) = rawconsbounds(s.cons)
rawcons(s::OptProblemSpec) = rawcons(s.cons, s.x0, s.vars)
fromrawu(u, s::OptProblemSpec) = fromrawu(u, s.x0, s.vars)
solobj(sol, s) = fromrawu(sol.u, s)
struct OptSolution{S<:SciMLBase.OptimizationSolution, O<:OptProblemSpec}
sol::S
ops::O
end
Base.propertynames(os::OptSolution) = (propertynames(os.sol)..., :uobj)
Base.getproperty(os::OptSolution, s::Symbol) =
s == :uobj ? solobj(os.sol, os.ops) :
s == :sol ? getfield(os, s) :
s == :ops ? getfield(os, s) :
getproperty(os.sol, s)
SciMLBase.solve(s::OptProblemSpec, args...; kwargs...) =
OptSolution(solve(OptimizationProblem(s), args...; kwargs...), s)
SciMLBase.OptimizationProblem(s::OptProblemSpec, args...; kwargs...) =
if isnothing(s.cons)
OptimizationProblem(rawfunc(s), rawu(s), rawdata(s), args...; rawbounds(s)..., kwargs...)
else
OptimizationProblem(OptimizationFunction(rawfunc(s), cons=rawcons(s)), rawu(s), rawdata(s), args...; rawbounds(s)..., rawconsbounds(s)..., kwargs...)
end
SciMLBase.OptimizationProblem(s::OptProblemSpec{<:OptimizationFunction}, args...; kwargs...) =
if isnothing(s.cons)
f = @p s.func |>
@set(__.f = rawfunc(s))
OptimizationProblem(f, rawu(s), rawdata(s), args...; rawbounds(s)..., kwargs...)
else
f = @p s.func |>
@set(__.f = rawfunc(s)) |>
@set __.cons = rawcons(s)
OptimizationProblem(f, rawu(s), rawdata(s), args...; rawbounds(s)..., rawconsbounds(s)..., kwargs...)
end
_convert(::Nothing, x) = x
_convert(T::Type{<:Tuple}, x::Tuple) = convert(T, x)
_convert(T::Type{<:Vector}, x::Tuple) = convert(T, collect(x))
_convert(T::Type{<:AbstractVector}, x::Tuple) = convert(T, x) # SVector, MVector
_convert(T::Type{<:Tuple}, x::AbstractVector) = T(x...)
_convert(T::Type{<:Vector}, x::AbstractVector) = convert(T, x)
_convert(T::Type{<:AbstractVector}, x::AbstractVector) = T(x...) # SVector, MVector
end
| AccessibleOptimization | https://github.com/JuliaAPlavin/AccessibleOptimization.jl.git |
|
[
"MIT"
] | 0.1.2 | 149f6f3325bc4703ff16372f7be26bc5171f6830 | code | 5666 | using TestItems
using TestItemRunner
@run_package_tests
@testitem "constructorof" begin
of = OptimizationFunction(+, Optimization.AutoForwardDiff())
@test constructorof(typeof(of))(Accessors.getfields(of)...) === of
end
@testitem "Optimization" begin
using IntervalSets
using StructArrays
using StaticArrays
using OptimizationOptimJL, OptimizationMetaheuristics
using ReverseDiff
struct ExpModel{A,B}
scale::A
shift::B
end
struct SumModel{T <: Tuple}
comps::T
end
(m::ExpModel)(x) = m.scale * exp(-(x - m.shift)^2)
(m::SumModel)(x) = sum(c -> c(x), m.comps)
loss(m, data) = sum(r -> abs2(r.y - m(r.x)), data)
truemod = SumModel((
ExpModel(2, 5),
ExpModel(0.5, 2),
ExpModel(0.5, 8),
))
data = let x = 0:0.2:10
StructArray(; x, y=truemod.(x) .+ range(-0.01, 0.01, length=length(x)))
end
mod0 = SumModel((
ExpModel(1, 1),
ExpModel(1, 2),
ExpModel(1, 3),
))
vars = OptArgs(
@optic(_.comps[∗].shift) => 0..10.,
@optic(_.comps[∗].scale) => 0.3..10.,
)
prob = OptProblemSpec(Base.Fix2(loss, data), mod0, vars)
sol = solve(prob, ECA(), maxiters=300)
@test sol.u isa Vector{Float64}
@test sol.uobj isa SumModel
@test getall(sol.uobj, @optic _.comps[∗].shift) |> collect |> sort ≈ [2, 5, 8] rtol=1e-2
@testset "no autodiff" begin
@testset "OptProblemSpec(utype=$(prob.utype))" for prob in (
OptProblemSpec(Base.Fix2(loss, data), mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), Vector, mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), Vector{Float64}, mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), SVector, mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), SVector{<:Any, Float64}, mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), MVector, mod0, vars),
OptProblemSpec(Base.Fix2(loss, data), MVector{<:Any, Float64}, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), Vector, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), Vector{Float64}, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), SVector, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), SVector{<:Any, Float64}, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), MVector, mod0, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), MVector{<:Any, Float64}, mod0, vars),
)
sol = solve(prob, ECA(), maxiters=10)
@test sol.u isa Vector{Float64}
@test sol.uobj isa SumModel
end
end
@testset "construct" begin
vars = OptArgs(
@optic(_.scale) => 0.3..10.,
@optic(_.shift) => 0..10.,
)
@testset "OptProblemSpec(utype=$(prob.utype))" for prob in (
OptProblemSpec(Base.Fix2(loss, data), Vector, ExpModel, vars),
OptProblemSpec(Base.Fix2(loss, data), Vector{Float64}, ExpModel, vars),
OptProblemSpec(Base.Fix2(loss, data), SVector, ExpModel, vars),
OptProblemSpec(Base.Fix2(loss, data), SVector{<:Any, Float64}, ExpModel, vars),
OptProblemSpec(Base.Fix2(loss, data), MVector, ExpModel, vars),
OptProblemSpec(Base.Fix2(loss, data), MVector{<:Any, Float64}, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), Vector, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), Vector{Float64}, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), SVector, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), SVector{<:Any, Float64}, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), MVector, ExpModel, vars),
OptProblemSpec(Base.Fix2(OptimizationFunction{false}(loss), data), MVector{<:Any, Float64}, ExpModel, vars),
)
sol = solve(prob, ECA(), maxiters=10)
@test sol.u isa Vector{Float64}
@test sol.uobj isa ExpModel
end
end
@testset "autodiff, cons" begin
vars = OptArgs(
@optic(_.comps[∗].shift) => 0..10.,
@optic(_.comps[∗].scale) => 0.3..10.,
)
cons = OptCons(
((x, _) -> sum(c -> c.shift, x.comps) / length(x.comps)) => 0.5..4,
)
prob = OptProblemSpec(Base.Fix2(OptimizationFunction(loss, Optimization.AutoForwardDiff()), data), Vector{Float64}, mod0, vars, cons)
sol = solve(prob, Optim.IPNewton(), maxiters=10)
@test sol.u isa Vector{Float64}
@test sol.uobj isa SumModel
for (f, int) in cons.specs
@test f(sol.uobj, data) ∈ int
end
end
@testset "autodiff, no box" begin
vars = OptArgs(
@optic(_.comps[∗].shift),
@optic(_.comps[∗].scale),
)
prob = OptProblemSpec(Base.Fix2(OptimizationFunction(loss, Optimization.AutoForwardDiff()), data), Vector{Float64}, mod0, vars)
sol = solve(prob, Optim.Newton(), maxiters=10)
@test sol.u isa Vector{Float64}
@test sol.uobj isa SumModel
end
end
@testitem "_" begin
import CompatHelperLocal as CHL
CHL.@check()
using Aqua
Aqua.test_all(AccessorsExtra, piracies=false, ambiguities=false)
end
| AccessibleOptimization | https://github.com/JuliaAPlavin/AccessibleOptimization.jl.git |
|
[
"MIT"
] | 0.1.2 | 149f6f3325bc4703ff16372f7be26bc5171f6830 | docs | 3461 | # AccessibleOptimization.jl
Combining `Accessors.jl` + `Optimization.jl` to enable function optimization with arbitrary structs. Vary struct parameters, combinations and transformations of them. Uniform and composable, zero overhead.
Defining features of `AccessibleOptimization`:
- No need to deal with raw vectors of optimized parameters: their values are automatically put into model structs
- Can use arbitrary structs as model definitions, no requirements or limitations on their content, types, or methods
- Can flexibly specify the list of parameters to optimize, as well as their bounds and constrains - independently of the model struct/object creation
- Everything is type-stable and performant
# Usage
Suppose you want to fit a model to data. Here, our model is a sum of squared exponentials.
First, define your model and a way to evaluate it. Regular Julia code, no special types or functions. This is not `Accessors`/`Optimization` specific at all, you may have model definitions already!
```julia
struct ExpModel{A,B}
scale::A
shift::B
end
struct SumModel{T <: Tuple}
comps::T
end
(m::ExpModel)(x) = m.scale * exp(-(x - m.shift)^2)
(m::SumModel)(x) = sum(c -> c(x), m.comps)
loss(m, data) = @p data |> sum(abs2(_.y - m(_.x)))
```
Then, load `AccessibleOptimization`, define optimization parameters, and perform optimization:
```julia
using AccessibleOptimization
# which parameters to optimize, what are their bouds?
vars = OptArgs(
(@o _.comps[∗].shift) => 0..10., # shifts of both components: values from 0..10
(@o log10(_.comps[∗].scale)) => -1..1, # component scales: positive-only (using log10 transformation), from 10^-1 to 10^1
)
# create and solve the optimization problem, interface very similar to Optimization.jl
ops = OptProblemSpec(Base.Fix2(loss, data), mod0, vars)
sol = solve(ops, ECA(), maxiters=300)
sol.uobj::SumModel # the optimal model
```
We use [Accessors.jl](https://github.com/JuliaObjects/Accessors.jl) and [AccessorsExtra.jl](https://gitlab.com/aplavin/AccessorsExtra.jl) optics to specify parameters to vary during optimization. Basic `@optic` syntax demonstrated in the above example includes property and index access (`_.prop`, `_[1]`) and selecting all elements of a collection with `_[∗]` (type with `\ast<tab>`). Refer to the `Accessors[Extra]` documentation for more details.
See a Pluto notebook with [a walkthrough, more examples and explanations](https://aplavin.github.io/AccessibleOptimization.jl/examples/notebook.html).
# Related packages
`AccessibleOptimization` gains its composability and generality powers (and half its name!) from `Accessors` and `AccessorsExtra` packages.
The optimization part is directly delegated to `Optimization`. Other backends are possible, but best to add them as methods to `Optimization` proper and use from `AccessibleOptimization`.
These packages have generally similar goals, but neither provides all features `AccessibleOptimization` or `Accessors` do:
- [Functors.jl](https://github.com/FluxML/Functors.jl)
- [FlexibleFunctors.jl](https://github.com/Metalenz/FlexibleFunctors.jl)
- [GModelFit.jl](https://github.com/gcalderone/GModelFit.jl)
- [ModelParameters.jl](https://github.com/rafaqz/ModelParameters.jl)
- [ParameterHandling.jl](https://github.com/JuliaGaussianProcesses/ParameterHandling.jl)
- [TransformVariables.jl](https://github.com/tpapp/TransformVariables.jl)
- [ValueShapes.jl](https://github.com/oschulz/ValueShapes.jl)
| AccessibleOptimization | https://github.com/JuliaAPlavin/AccessibleOptimization.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 340 | using Documenter
using EffectSizes
makedocs(;
modules=[EffectSizes],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
],
repo="https://github.com/harryscholes/EffectSizes.jl/blob/{commit}{path}#L{line}",
sitename="EffectSizes.jl",
)
deploydocs(;
repo="github.com/harryscholes/EffectSizes.jl",
)
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 927 | module EffectSizes
using Statistics
using Distributions
using StatsBase
using SpecialFunctions
import Distributions: quantile
import StatsBase: confint
export
AbstractEffectSize,
EffectSize,
CohenD,
HedgeG,
GlassΔ,
effectsize,
confint,
quantile,
AbstractConfidenceInterval,
ConfidenceInterval,
BootstrapConfidenceInterval,
lower,
upper
"""
_update_module_doc()
This function updates the module docs and is called before running the doctests.
This way, the docs in README.md are also tested.
"""
function _update_module_doc()
path = pkgdir(EffectSizes, "README.md")
text = read(path, String)
# The code blocks in the README.md should be julia blocks the syntax highlighter.
text = replace(text, "```julia" => "```jldoctest")
@doc text EffectSizes
end
_update_module_doc()
include("confidence_interval.jl")
include("effect_size.jl")
end # module
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 4124 | bootstrapsample(xs::AbstractVector) = @views xs[rand(1:length(xs), length(xs))]
function twotailedquantile(quantile::AbstractFloat)
0. ≤ quantile ≤ 1. || throw(DomainError(quantile))
lq = (1 - quantile) / 2
uq = quantile + lq
return lq, uq
end
"""
AbstractConfidenceInterval{T<:Real}
A type representing a confidence interval.
Subtypes implement:
Method | Description
:--- | :---
`confint` | returns the lower and upper bounds
`quantile` | returns the quantile
"""
abstract type AbstractConfidenceInterval{T<:Real} end
"""
quantile(ci::AbstractConfidenceInterval) -> Float64
Returns the quantile of a confidence interval.
"""
quantile(::T) where T<:AbstractConfidenceInterval =
throw(ArgumentError("`quantile` is not implemented for $(string(T))"))
"""
confint(ci::AbstractConfidenceInterval{T}) -> Tuple{T,T}
Return the lower and upper bounds of a confidence interval.
"""
confint(::T) where T<:AbstractConfidenceInterval =
throw(ArgumentError("`confint` is not implemented for $(string(T))"))
"""
lower(ci::AbstractConfidenceInterval{T}) -> T
Return the lower bound of a confidence interval.
"""
lower(ci::AbstractConfidenceInterval) = confint(ci)[1]
"""
upper(ci::AbstractConfidenceInterval{T}) -> T
Return the upper bound of a confidence interval.
"""
upper(ci::AbstractConfidenceInterval) = confint(ci)[2]
"""
ConfidenceInterval(lower, upper, quantile)
A type representing the `lower` and `upper` bounds of an effect size confidence
interval at a specified `quantile`.
ConfidenceInterval(xs, ys, es; quantile)
Calculate a confidence interval for the effect size `es` between two vectors `xs` and `ys`
at a specified `quantile`.
"""
struct ConfidenceInterval{T<:Real} <: AbstractConfidenceInterval{T}
ci::Tuple{T,T}
quantile::Float64
function ConfidenceInterval(l::T, u::T, q::Float64) where T<:Real
l ≤ u || throw(ArgumentError("l > u"))
0. ≤ q ≤ 1. || throw(DomainError(q))
new{T}((l, u), q)
end
end
function ConfidenceInterval(
xs::AbstractVector{T},
ys::AbstractVector{T},
es::Real;
quantile::AbstractFloat,
) where T<:Real
0. ≤ quantile ≤ 1. || throw(DomainError(quantile))
nx = length(xs)
ny = length(ys)
σ² = (nx + ny) / (nx * ny) + es^2 / 2(nx + ny)
_, uq = twotailedquantile(quantile)
z = Distributions.quantile(Normal(), uq)
ci = z * √σ²
return ConfidenceInterval(
es - ci,
es + ci,
quantile,
)
end
confint(ci::ConfidenceInterval) = ci.ci
quantile(ci::ConfidenceInterval) = ci.quantile
"""
BootstrapConfidenceInterval(lower, upper, quantile, bootstrap)
A type representing the `lower` and `upper` bounds of an effect size confidence
interval at a specified `quantile` with `bootstrap` resamples.
BootstrapConfidenceInterval(f, xs, ys, bootstrap; quantile)
Calculate a bootstrap confidence interval between two vectors `xs` and `ys` at a specified
`quantile` by applying `f` to `bootstrap` resamples of `xs` and `ys`.
"""
struct BootstrapConfidenceInterval{T<:Real} <: AbstractConfidenceInterval{T}
ci::Tuple{T,T}
quantile::Float64
bootstrap::Int64
function BootstrapConfidenceInterval(l::T, u::T, q::Float64, b::Int64) where T<:Real
l ≤ u || throw(ArgumentError("l > u"))
0. ≤ q ≤ 1. || throw(DomainError(q))
b > 1 || throw(DomainError(b))
new{T}((l, u), q, b)
end
end
function BootstrapConfidenceInterval(
f::Function,
xs::AbstractVector{T},
ys::AbstractVector{T},
bootstrap::Integer = 1000;
quantile::AbstractFloat,
) where T<:Real
0. ≤ quantile ≤ 1. || throw(DomainError(quantile))
bootstrap > 1 || throw(DomainError(bootstrap))
es = map(_->f(bootstrapsample(xs), bootstrapsample(ys)), 1:bootstrap)
lq, uq = twotailedquantile(quantile)
return BootstrapConfidenceInterval(
Distributions.quantile(es, lq),
Distributions.quantile(es, uq),
quantile,
bootstrap,
)
end
confint(ci::BootstrapConfidenceInterval) = ci.ci
quantile(ci::BootstrapConfidenceInterval) = ci.quantile
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 5771 | """
AbstractEffectSize
An abstract type to represent an effect size.
Effect | Effect size
:---|---:
Small | 0.2
Medium | 0.5
Large | 0.8
Subtypes implement:
Method | Description
:--- | :---
`effectsize` | returns the effect size index
`confint` | returns the confidence interval
"""
abstract type AbstractEffectSize end
"""
effectsize(es::AbstractEffectSize)
Return the effect size index.
"""
effectsize(::T) where T<:AbstractEffectSize =
throw(ArgumentError("`effectsize` is not implemented for $(string(T))"))
"""
confint(es::AbstractEffectSize) -> ConfidenceInterval
Return the confidence interval of an effect size as a `ConfidenceInterval` object.
"""
confint(::T) where T<:AbstractEffectSize =
throw(ArgumentError("`confint` is not implemented for $(string(T))"))
"""
quantile(es::AbstractEffectSize) -> Float64
Returns the quantile of a confidence interval.
"""
quantile(es::AbstractEffectSize) = quantile(confint(es))
# Used by: CohenD
function pooledstd(xs::AbstractVector{T}, ys::AbstractVector{T}) where T<:Real
nx = length(xs)
ny = length(ys)
return √(((nx - 1) * var(xs) + (ny - 1) * var(ys)) / (nx + ny - 2))
end
function correction(n::Integer)
n > 1 || throw(DomainError(n))
m = n - 2
if n < 40
corrfact = gamma(m / 2) / (√(m / 2) * gamma((m - 1) / 2))
else
corrfact = 1 − (3 / (4 * m − 9))
end
return corrfact
end
_effectsize(μx::T, μy::T, σ::T) where T<:Real = ((μx - μy) / σ)
_effectsize(μx::T, μy::T, σ::T, n::Integer) where T<:Real = ((μx - μy) / σ) * correction(n)
"""
CohenD(xs, ys[, bootstrap]; [quantile=0.95])
Calculate Cohen's ``d`` effect size index between two vectors `xs` and `ys`.
A confidence interval for the effect size is calculated at the `quantile` quantile. If
`bootstrap` is provided, the confidence interval is calculated by resampling from `xs`
and `ys` `bootstrap` times.
```math
d = \\frac{m_A - m_B}{s}
```
where ``m`` is the mean and ``s`` is the pooled standard deviation:
```math
s = \\sqrt{\\frac{(n_A - 1) s_A^2 + (n_B - 1) s_B^2}{n_A + n_B - 2}}
```
If ``m_A`` > ``m_B``, ``d`` will be positive and if ``m_A`` < ``m_B``, ``d`` will be negative.
!!! note
`HedgeG` outperforms `CohenD` when sample sizes are < 20.
# Examples
```julia
xs = randn(100000)
ys = randn(100000) .+ 0.01
using EffectSizes
CohenD(xs, ys)
using HypothesisTests
EqualVarianceTTest(xs, ys)
```
"""
struct CohenD{T<:Real,CI<:AbstractConfidenceInterval{T}} <: AbstractEffectSize
d::T
ci::CI
end
function cohend(xs::AbstractVector{T}, ys::AbstractVector{T}) where T<:Real
return _effectsize(
mean(xs),
mean(ys),
pooledstd(xs, ys),
)
end
effectsize(es::CohenD) = es.d
confint(es::CohenD) = es.ci
"""
const EffectSize = CohenD
See [`CohenD`](@ref).
"""
const EffectSize = CohenD
"""
HedgeG(xs, ys[, bootstrap]; [quantile=0.95])
Calculate Hedge's ``g`` effect size index between two vectors `xs` and `ys`.
A confidence interval for the effect size is calculated at the `quantile` quantile. If
`bootstrap` is provided, the confidence interval is calculated by resampling from `xs`
and `ys` `bootstrap` times.
```math
g = \\frac{m_A - m_B}{s}
```
where ``m`` is the mean and ``s`` is the pooled standard deviation:
```math
s = \\sqrt{\\frac{(n_A - 1) s_A^2 + (n_B - 1) s_B^2}{n_A + n_B}}
```
If ``m_A`` > ``m_B``, ``g`` will be positive and if ``m_A`` < ``m_B``, ``g`` will be
negative.
!!! note
`HedgeG` outperforms `CohenD` when sample sizes are < 20.
"""
struct HedgeG{T<:Real,CI<:AbstractConfidenceInterval{T}} <: AbstractEffectSize
g::T
ci::CI
end
function hedgeg(xs::AbstractVector{T}, ys::AbstractVector{T}) where T<:Real
return _effectsize(
mean(xs),
mean(ys),
pooledstd(xs, ys),
length(xs) + length(ys),
)
end
effectsize(es::HedgeG) = es.g
confint(es::HedgeG) = es.ci
"""
GlassΔ(treatment, control[, bootstrap]; [quantile=0.95])
Calculate Glass's ``Δ`` effect size index between two vectors `treatment` and `control`.
A confidence interval for the effect size is calculated at the `quantile` quantile. If
`bootstrap` is provided, the confidence interval is calculated by resampling from `xs`
and `ys` `bootstrap` times.
```math
Δ = \\frac{m_T - m_C}{s_C}
```
where ``m`` is the mean, ``s`` is the standard deviation, ``T`` is the treatment group and
``C`` is the control group.
If ``m_T`` > ``m_C``, ``Δ`` will be positive and if ``m_T`` < ``m_C``, ``Δ`` will be negative.
!!! note
`GlassΔ` should be used when the standard deviations between the two groups are very
different.
"""
struct GlassΔ{T<:Real,CI<:AbstractConfidenceInterval{T}} <: AbstractEffectSize
Δ::T
ci::CI
end
function glassΔ(xs::AbstractVector{T}, ys::AbstractVector{T}) where T<:Real
return _effectsize(
mean(xs),
mean(ys),
std(ys),
)
end
effectsize(es::GlassΔ) = es.Δ
confint(es::GlassΔ) = es.ci
# constructors
for (T, f) = [(:CohenD, cohend), (:GlassΔ, glassΔ), (:HedgeG, hedgeg)]
@eval begin
# Normal CI
function $T(
xs::AbstractVector{T},
ys::AbstractVector{T};
quantile::Float64=0.95,
) where T<:Real
es = $f(xs, ys)
ci = ConfidenceInterval(xs, ys, es; quantile=quantile)
$T(es, ci)
end
# Bootstrap CI
function $T(
xs::AbstractVector{T},
ys::AbstractVector{T},
bootstrap::Integer;
quantile::Float64=0.95,
) where T<:Real
es = $f(xs, ys)
ci = BootstrapConfidenceInterval($f, xs, ys, bootstrap; quantile=quantile)
$T(es, ci)
end
end
end
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 454 | using Documenter
using EffectSizes
using Test
DocMeta.setdocmeta!(
EffectSizes,
:DocTestSetup,
:(using EffectSizes);
recursive=true
)
# Only test one Julia version to avoid differences due to changes in printing.
if v"1.6" ≤ VERSION
EffectSizes._update_module_doc()
doctest(EffectSizes)
else
@warn "Skipping doctests"
end
@testset "EffectSizes.jl" begin
include("test_confint.jl")
include("test_effectsize.jl")
end
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 3408 | using EffectSizes
using Test
using EffectSizes: bootstrapsample, twotailedquantile, AbstractConfidenceInterval,
ConfidenceInterval, BootstrapConfidenceInterval
@testset "AbstractConfidenceInterval" begin
l = .1
u = .9
q = .95
ci = ConfidenceInterval(l, u, q)
@test confint(ci) == (l, u)
@test lower(ci) == l
@test upper(ci) == u
@test quantile(ci) == q
@test_throws ArgumentError ConfidenceInterval(1, -1, .95)
@test_throws ArgumentError ConfidenceInterval(1., 0.999, .95)
@testset "ConfidenceInterval" begin
l = .1
u = .9
q = .95
ci = ConfidenceInterval(l, u, q)
@test confint(ci) == (l, u)
@test lower(ci) == l
@test upper(ci) == u
@test quantile(ci) == q
@test_throws ArgumentError ConfidenceInterval(1, -1, .95)
@test_throws ArgumentError ConfidenceInterval(1., 0.999, .95)
@test_throws DomainError ConfidenceInterval(l, u, -0.1)
@test_throws DomainError ConfidenceInterval(l, u, 1.1)
xs = randn(90)
ys = randn(110)
es = 0.2
q = 0.9
ci = ConfidenceInterval(xs, ys, es, quantile=q)
@test ci isa AbstractConfidenceInterval
@test quantile(ci) == q
@test lower(ci) < upper(ci)
@test ci == ConfidenceInterval(xs, ys, es, quantile=q)
ci2 = ConfidenceInterval(xs, ys, es, quantile=0.8)
@test ci !== ci2
@test lower(ci2) > lower(ci)
@test upper(ci2) < upper(ci)
@test_throws DomainError ConfidenceInterval(xs, ys, es, quantile=1.1)
end
@testset "BootstrapConfidenceInterval" begin
l = .1
u = .9
q = .95
b = 10^4
ci = BootstrapConfidenceInterval(l, u, q, b)
@test confint(ci) == (l, u)
@test lower(ci) == l
@test upper(ci) == u
@test quantile(ci) == q
@test ci.bootstrap == b
@test_throws ArgumentError BootstrapConfidenceInterval(1, -1, q, b)
@test_throws ArgumentError BootstrapConfidenceInterval(1., 0.999, q, b)
@test_throws DomainError BootstrapConfidenceInterval(l, u, -0.1, b)
@test_throws DomainError BootstrapConfidenceInterval(l, u, 1.1, b)
@test_throws DomainError BootstrapConfidenceInterval(l, u, q, -1)
xs = randn(90)
ys = randn(110)
q = 0.8
f(xs, ys) = sum([sum(xs), sum(ys)] ./ 1000)
ci = BootstrapConfidenceInterval(f, xs, ys, 100, quantile=q)
@test ci isa AbstractConfidenceInterval
@test quantile(ci) == q
@test lower(ci) < upper(ci)
@test_throws DomainError BootstrapConfidenceInterval(f, xs, ys, 100, quantile=1.1)
@test_throws DomainError BootstrapConfidenceInterval(f, xs, ys, -1, quantile=q)
end
end
@testset "bootstrapsample" begin
for _ = 1:100
xs = rand(100)
ys = bootstrapsample(xs)
@test length(ys) == length(xs)
@test Set(ys) ≤ Set(xs)
end
end
@testset "twotailedquantile" begin
l, u = twotailedquantile(.95)
@test l ≈ 0.025
@test u ≈ 0.975
@test l + u == 1
l, u = twotailedquantile(.9)
@test l ≈ 0.05
@test u ≈ 0.95
@test l + u == 1
for q = rand(100)
l, u = twotailedquantile(q)
@test l + u == 1
end
@test_throws DomainError twotailedquantile(-.1)
@test_throws DomainError twotailedquantile(1.1)
end
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | code | 2267 | using EffectSizes, Statistics
using Test
using EffectSizes: AbstractEffectSize, correction, pooledstd, _effectsize
@testset "$T constructor" for (T, v) = [(EffectSize, :d), (CohenD, :d), (HedgeG, :g),
(GlassΔ, :Δ)]
e = 0.
l = -1.
u = 1.
q = .95
es = T(e, ConfidenceInterval(l, u, q))
@test es isa AbstractEffectSize
@test effectsize(es) == getfield(es, v)
@test confint(es) == es.ci
@test quantile(es) == es.ci.quantile
@test lower(es.ci) == es.ci.ci[1]
@test upper(es.ci) == es.ci.ci[2]
xs = randn(90)
ys = randn(110)
@test effectsize(T(xs .+ 1, xs)) > 0
@test effectsize(T(xs, xs .+ 1)) < 0
@testset "constructors" begin
# Normal
es = T(xs, ys)
@test quantile(es) == 0.95
@test typeof(effectsize(es)) == eltype(xs)
@test es == T(xs, ys)
@test effectsize(T(xs, xs)) == 0
es2 = T(xs, ys, quantile=0.8)
@test lower(confint(es2)) > lower(confint(es))
@test upper(confint(es2)) < upper(confint(es))
@test quantile(es2) == 0.8
@test effectsize(es2) == effectsize(es)
# bootstrap
es3 = T(xs, ys, 100)
@test effectsize(es3) == effectsize(es)
@test quantile(es3) == 0.95
es4 = T(xs, ys, 100, quantile=0.1)
@test quantile(es4) == 0.1
@test lower(confint(es3)) < lower(confint(es4))
@test upper(confint(es3)) > upper(confint(es4))
@test effectsize(T(xs, xs, 100)) == 0
end
@testset "Integers" begin
# Smoke tests for `Int`s.
xs = round.(Int, randn(90) .* 10)
ys = round.(Int, randn(110) .* 10)
T(xs, ys, quantile=0.95)
end
end
@testset "correction" begin
@test_throws DomainError correction(1)
@test correction(2) == -Inf
@test correction(20) > .9
@test correction(10^9) ≈ 1
end
@testset "_effectsize" begin
# from http://staff.bath.ac.uk/pssiw/stats2/page2/page14/page14.html
@test round(_effectsize(20., 24., 4.53), digits=3) == -0.883
xs = 10:110
ys = 1:100
mx = mean(xs)
my = mean(ys)
s = pooledstd(xs, ys)
@test _effectsize(mx, my, s, 100) > _effectsize(mx, my, s, 50) > _effectsize(mx, my, s, 10)
end
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | docs | 1694 | # EffectSizes.jl
[](https://harryscholes.github.io/EffectSizes.jl/stable)
[](https://harryscholes.github.io/EffectSizes.jl/dev)
[](https://github.com/harryscholes/EffectSizes.jl/actions)
EffectSizes.jl is a Julia package for effect size measures. Confidence intervals are
assigned to effect sizes using the Normal distribution or by bootstrap resampling.
The package implements types for the following measures:
**Measure** | **Type**
---|---
Cohen's *d* | `CohenD`
Hedge's *g* | `HedgeG`
Glass's *Δ* | `GlassΔ`
## Installation
```jl
julia> import Pkg; Pkg.add("EffectSizes");
```
## Examples
```julia
julia> using Random, EffectSizes; Random.seed!(1);
julia> xs = randn(10^3);
julia> ys = randn(10^3) .+ 0.5;
julia> es = CohenD(xs, ys, quantile=0.95); # normal CI (idealised distribution)
julia> typeof(es)
CohenD{Float64, ConfidenceInterval{Float64}}
julia> effectsize(es)
-0.5035709742336323
julia> quantile(es)
0.95
julia> ci = confint(es);
julia> typeof(ci)
ConfidenceInterval{Float64}
julia> confint(ci)
(-0.5926015897640895, -0.41454035870317507)
julia> es = CohenD(xs, ys, 10^4, quantile=0.95); # bootstrap CI (empirical distribution)
julia> effectsize(es) # effect size is the same
-0.5035709742336323
julia> typeof(es)
CohenD{Float64, BootstrapConfidenceInterval{Float64}}
julia> ci = confint(es); # confidence interval is different
julia> lower(ci)
-0.5919535584593746
julia> upper(ci)
-0.4155997394380884
```
## Contributing
Ideas and PRs are very welcome.
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | docs | 83 | # docs/src
This folder is required by Documenter.jl even if we only run doctests.
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 1.0.1 | 451749b3cc4beb81a00a90943197e00ccb344d75 | docs | 1550 | # EffectSizes.jl
EffectSizes.jl is a Julia package for effect size measures. Confidence intervals are
assigned to effect sizes using either the normal distribution or by bootstrap resampling.
The package implements types for the following measures:
**Measure** | **Type**
---|---
Cohen's *d* | `CohenD`
Hedge's *g* | `HedgeG`
Glass's *Δ* | `GlassΔ`
## Installation
```julia
] add https://github.com/harryscholes/EffectSizes.jl
```
## Examples
```julia
julia> using Random, EffectSizes; Random.seed!(1);
julia> xs = randn(10^3);
julia> ys = randn(10^3) .+ 0.5;
julia> es = CohenD(xs, ys, quantile=0.95); # normal CI (idealised distribution)
julia> typeof(es)
CohenD{Float64,ConfidenceInterval{Float64}}
julia> effectsize(es)
-0.503…
julia> quantile(es)
0.95
julia> ci = confint(es);
julia> typeof(ci)
ConfidenceInterval{Float64}
julia> confint(ci)
(-0.592…, -0.414…)
julia> es = CohenD(xs, ys, 10^4, quantile=0.95); # bootstrap CI (empirical distribution)
julia> effectsize(es) # effect size is the same
-0.503…
julia> typeof(es)
CohenD{Float64,BootstrapConfidenceInterval{Float64}}
julia> ci = confint(es); # confidence interval is different
julia> lower(ci)
-0.591…
julia> upper(ci)
-0.415…
```
## Index
```@index
```
## API
```@docs
AbstractEffectSize
EffectSize
CohenD
HedgeG
GlassΔ
effectsize
confint(::AbstractEffectSize)
quantile(::AbstractEffectSize)
AbstractConfidenceInterval
ConfidenceInterval
BootstrapConfidenceInterval
confint(::AbstractConfidenceInterval)
lower
upper
quantile(::AbstractConfidenceInterval)
```
| EffectSizes | https://github.com/harryscholes/EffectSizes.jl.git |
|
[
"MIT"
] | 0.2.0 | aa8a8a140729fbca8c8d960ab488e0bf6b87feed | code | 2657 | __precompile__(true)
module UnitfulUS
import Unitful
using Unitful: @unit
export @us_str
# Survey lengths
@unit sinch_us "inˢ" USSurveyInch (100//3937)*Unitful.m false
@unit sft_us "ftˢ" USSurveyFoot 12sinch_us false
@unit sli_us "liˢ" USSurveyLink (33//50)sft_us false
@unit syd_us "ydˢ" USSurveyYard 3sft_us false
@unit srd_us "rdˢ" USSurveyRod 25sli_us false
@unit sch_us "chˢ" USSurveyChain 4srd_us false
@unit sfur_us "furˢ" USSurveyFurlong 10sch_us false
@unit smi_us "miˢ" USSurveyMile 8sfur_us false
@unit slea_us "leaˢ" USSurveyLeague 3smi_us false
# Survey areas
@unit sac_us "acˢ" USSurveyAcre 43560sft_us^2 false
@unit town_us "township" USSurveyTownship 36smi_us^2 false
# Dry volumes
# Exact but the fraction is awful; will fix later
@unit drypt_us "dryptᵘˢ" USDryPint 550.6104713575*Unitful.ml false
@unit dryqt_us "dryqtᵘˢ" USDryQuart 2drypt_us false
@unit pk_us "pkᵘˢ" USPeck 8dryqt_us false
@unit bushel_us "buᵘˢ" USBushel 4pk_us false
# Liquid volumes
@unit gal_us "galᵘˢ" USGallon 231*(Unitful.inch)^3 false
@unit qt_us "qtᵘˢ" USQuart gal_us//4 false
@unit pt_us "ptᵘˢ" USPint qt_us//2 false
@unit cup_us "cupᵘˢ" USCup pt_us//2 false
@unit gill_us "gillᵘˢ" USGill cup_us//2 false
@unit floz_us "fl ozᵘˢ" USFluidOunce pt_us//16 false
@unit tbsp_us "tbspᵘˢ" USTablespoon floz_us//2 false
@unit tsp_us "tspᵘˢ" USTeaspoon tbsp_us//3 false
@unit fldr_us "fl drᵘˢ" USFluidDram floz_us//8 false
@unit minim_us "minimᵘˢ" USMinim fldr_us//60 false
# Mass
@unit cwt_us "cwtᵘˢ" USHundredweight 100*Unitful.lb false
@unit ton_us "tonᵘˢ" USTon 2000*Unitful.lb false
include("usmacro.jl")
# Some gymnastics required here because if we precompile, we cannot add to
# Unitful.basefactors at compile time and expect the changes to persist to runtime.
const localunits = Unitful.basefactors
function __init__()
merge!(Unitful.basefactors, localunits)
Unitful.register(UnitfulUS)
end
end # module
| UnitfulUS | https://github.com/PainterQubits/UnitfulUS.jl.git |
|
[
"MIT"
] | 0.2.0 | aa8a8a140729fbca8c8d960ab488e0bf6b87feed | code | 1983 | """
macro us_str(unit)
String macro to easily recall U.S. customary units located in the `UnitfulUS`
package. Although all unit symbols in that package are suffixed with `_us`,
the suffix should not be used when using this macro.
Note that what goes inside must be parsable as a valid Julia expression.
Examples:
```jldoctest
julia> 1.0us"tbsp"
1.0 m s^-1
julia> 1.0us"syd" - 1.0u"yd"
1.0 m N
```
"""
macro us_str(unit)
ex = Meta.parse(unit)
esc(replace_value(ex))
end
const allowed_funcs = [:*, :/, :^, :sqrt, :√, :+, :-, ://]
function replace_value(ex::Expr)
if ex.head == :call
ex.args[1] in allowed_funcs ||
error("""$(ex.args[1]) is not a valid function call when parsing a unit.
Only the following functions are allowed: $allowed_funcs""")
for i=2:length(ex.args)
if typeof(ex.args[i])==Symbol || typeof(ex.args[i])==Expr
ex.args[i]=replace_value(ex.args[i])
end
end
return Core.eval(@__MODULE__, ex)
elseif ex.head == :tuple
for i=1:length(ex.args)
if typeof(ex.args[i])==Symbol
ex.args[i]=replace_value(ex.args[i])
else
error("only use symbols inside the tuple.")
end
end
return Core.eval(@__MODULE__, ex)
else
error("Expr head $(ex.head) must equal :call or :tuple")
end
end
dottify(s, t, u...) = dottify(Expr(:(.), s, QuoteNode(t)), u...)
dottify(s) = s
function replace_value(sym::Symbol)
s = Symbol(sym, :_us)
if !(isdefined(UnitfulUS, s) && ustrcheck_bool(getfield(UnitfulUS, s)))
error("Symbol $s could not be found in UnitfulUS.")
end
return getfield(UnitfulUS, s)
end
replace_value(literal::Number) = literal
ustrcheck_bool(x::Unitful.Number) = true
ustrcheck_bool(x::Unitful.Unitlike) = true
ustrcheck_bool(x::Unitful.Quantity) = true
ustrcheck_bool(x::Unitful.MixedUnits) = true
ustrcheck_bool(x) = false
| UnitfulUS | https://github.com/PainterQubits/UnitfulUS.jl.git |
|
[
"MIT"
] | 0.2.0 | aa8a8a140729fbca8c8d960ab488e0bf6b87feed | code | 678 | using UnitfulUS
using Test
@testset "US string macro" begin
@test @macroexpand(us"gal") == UnitfulUS.gal_us
@test @macroexpand(us"1.0") == 1.0
@test @macroexpand(us"ton/gal") == UnitfulUS.ton_us / UnitfulUS.gal_us
@test @macroexpand(us"1.0gal") == 1.0 * UnitfulUS.gal_us
@test @macroexpand(us"gal^-1") == UnitfulUS.gal_us ^ -1
@test_throws LoadError @macroexpand(us"ton gal")
# Disallowed functions
@test_throws LoadError @macroexpand(us"abs(2)")
# Units not found
@test_throws LoadError @macroexpand(us"kg")
# test ustrcheck(x) fallback to catch non-units / quantities
@test_throws LoadError @macroexpand(us"ustrcheck")
end
| UnitfulUS | https://github.com/PainterQubits/UnitfulUS.jl.git |
|
[
"MIT"
] | 0.2.0 | aa8a8a140729fbca8c8d960ab488e0bf6b87feed | docs | 2277 | # UnitfulUS
[](https://travis-ci.org/PainterQubits/UnitfulUS.jl)
[](https://coveralls.io/github/PainterQubits/UnitfulUS.jl?branch=master)
[](http://codecov.io/github/PainterQubits/UnitfulUS.jl?branch=master)
A supplemental units package for [Unitful.jl](https://github.com/PainterQubits/Unitful.jl.git).
## Defined units
All units defined are suffixed with `_us`.
- U.S. survey units (length) are also prefixed by `s`:
`sinch_us` (inch), `sft_us` (foot), `sli_us` (link), `syd_us`
(yard), `srd_us` (rod), `sch_us` (chain), `sfur_us` (furlong), `smi_us`
(statute mile), `slea_us` (league).
- U.S. survey units (area) are prefixed by `s` where ambiguous:
`sac_us` (acre), `town_us` (township).
- U.S. dry volumes: `drypt_us` (dry pint), `dryqt_us` (dry quart), `pk_us` (dry
peck), `bushel_us` (bushel).
- U.S. liquid volumes: `gal_us` (gallon), `qt_us` (quart), `pt_us` (pint),
`cup_us` (cup), `gill_us` (gill / half cup), `floz_us` (fluid ounce),
`tbsp_us` (culinary tablespoon), `tsp_us` (culinary teaspoon),
`fldr_us` (fluid dram), `minim_us` (minim)
- U.S. mass units: `cwt_us` (hundredweight), `ton_us` (ton)
## Special features
This package defines a string macro `@us_str` that only searches for units from
this package. `@u_str` is the only exported symbol from the package. When using
the string macro, omit the `_us` suffix from units, as the macro will append it
for you.
Usage examples:
```jl
julia> using Unitful.DefaultSymbols, UnitfulUS
julia> us"gal" == UnitfulUS.gal_us
true
julia> 1us"gal" |> m^3
473176473//125000000000 m^3
```
As can be seen, the `us` string macro aids in the distinction of U.S. gallons from
other possible definitions of the gallon (Imperial gallon). Note that because
this package registers with the `@u_str` macro, you can mix units from this
package and the Unitful defaults so long as you include the `_us` suffix on units
from this package:
```jl
julia> using Unitful, UnitfulUS
julia> 1.0u"kg/gal_us"
1.0 kg galᵘˢ
```
| UnitfulUS | https://github.com/PainterQubits/UnitfulUS.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 975 | module RecordArraysBenchmarks
using BenchmarkTools: Benchmark, BenchmarkGroup
include("utils.jl")
include("bench_increments.jl")
include("bench_random_increments.jl")
function setup()
suite = BenchmarkGroup()
suite["Increments"] = BenchIncrements.setup()
suite["RandomIncrements"] = BenchRandomIncrements.setup()
return suite
end
function set_smoke_params!(bench)
bench.params.seconds = 0.001
bench.params.evals = 1
bench.params.samples = 1
bench.params.gctrial = false
bench.params.gcsample = false
return bench
end
foreach_benchmark(f!, bench::Benchmark) = f!(bench)
function foreach_benchmark(f!, group::BenchmarkGroup)
for x in values(group)
foreach_benchmark(f!, x)
end
end
function setup_smoke()
suite = setup()
foreach_benchmark(set_smoke_params!, suite)
return suite
end
function clear()
BenchIncrements.clear()
BenchRandomIncrements.clear()
end
end # module RecordArraysBenchmarks
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 871 | module BenchIncrements
using BenchmarkTools
using RecordArrays
using ..Utils: clobber
@inline function unsafe_inc!(xs::RecordArray)
@inbounds xs.a[end] += 1
end
@inline function unsafe_inc!(xs)
x = @inbounds xs[end]
x = merge(x, (; a = x.a + 1))
@inbounds xs[end] = x
end
@noinline function repeat_inc!(xs, n = 2^10)
isempty(xs) && return
for _ in 1:n
unsafe_inc!(xs)
clobber()
end
end
function setup()
suite = BenchmarkGroup()
suite["base"] = @benchmarkable(
repeat_inc!(xs),
setup = begin
xs = fill((a = 0, b = 0, c = 0, d = 0), 10)
end,
)
suite["rec"] = @benchmarkable(
repeat_inc!(xs),
setup = begin
xs = RecordArrays.fill((a = 0, b = 0, c = 0, d = 0), 10)
end,
)
return suite
end
function clear() end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 1381 | module BenchRandomIncrements
using BenchmarkTools
using RecordArrays
const CACHE = Ref{Any}()
@inline function unsafe_inc!(counters::RecordArray, i)
@inbounds counters.a[i] += 1
end
@inline function unsafe_inc!(counters, i)
x = @inbounds counters[end]
x = merge(x, (; a = x.a + 1))
@inbounds counters[i] = x
end
@noinline function inc!(counters, indices)
for i in indices
unsafe_inc!(counters, i)
end
end
function generate(nindices = 2^10, ncounters = 10)
return (
counters_base = fill((a = 0, b = 0, c = 0, d = 0), ncounters),
counters_rec = RecordArrays.fill((a = 0, b = 0, c = 0, d = 0), ncounters),
indices = rand(1:ncounters, nindices),
)
end
function setup()
CACHE[] = generate()
suite = BenchmarkGroup()
suite["base"] = @benchmarkable(
inc!(counters, indices),
setup = begin
counters = CACHE[].counters_base::$(typeof(CACHE[].counters_base))
indices = CACHE[].indices::$(typeof(CACHE[].indices))
end,
)
suite["rec"] = @benchmarkable(
inc!(counters, indices),
setup = begin
counters = CACHE[].counters_rec::$(typeof(CACHE[].counters_rec))
indices = CACHE[].indices::$(typeof(CACHE[].indices))
end,
)
return suite
end
function clear()
CACHE[] = nothing
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 247 | module Utils
using Base: llvmcall
# https://github.com/JuliaCI/BenchmarkTools.jl/pull/92
@inline function clobber()
llvmcall("""
call void asm sideeffect "", "~{memory}"()
ret void
""", Cvoid, Tuple{})
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 1109 | baremodule RecordArrays
export
#
FieldArray,
FieldVector,
RecordArray,
RecordVector
import Base
abstract type _AbstractRecordArray{T,N} <: Base.AbstractArray{T,N} end
struct RecordArray{T,N,Buffer,Storage,Step} <: _AbstractRecordArray{T,N}
buffer::Buffer
pointer::Base.Ptr{Storage}
eltype::Base.Val{T}
size::NTuple{N,Int}
step::Base.Val{Step}
end
const RecordVector{T} = RecordArray{T,1}
struct FieldArray{Field,T,N,Buffer,Storage,Step} <: _AbstractRecordArray{T,N}
buffer::Buffer
pointer::Base.Ptr{Storage}
eltype::Base.Val{T}
size::NTuple{N,Int}
step::Base.Val{Step}
field::Base.Val{Field}
end
const FieldVector{Field,T} = FieldArray{Field,T,1}
function fill end
function unsafe_zeros end
module Implementations
using Base: @propagate_inbounds
using ..RecordArrays:
#
FieldArray,
RecordArray,
RecordArrays,
_AbstractRecordArray
include("utils.jl")
include("common.jl")
include("records.jl")
include("fields.jl")
end # module Implementations
Implementations.define_docstrings()
end # baremodule RecordArrays
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 1658 | Base.size(A::_AbstractRecordArray) = getfield(A, :size)
_buffer(A) = getfield(A, :buffer)
_step(A) = getfield(A, :step)
stepof(A) = valueof(_step(A))
Base.parent(A::_AbstractRecordArray) = _buffer(A)::AbstractArray
@inline Base.pointer(A::_AbstractRecordArray) = getfield(A, :pointer)
@inline Base.pointer(A::_AbstractRecordArray, i::Integer) = pointer(A) + (i - 1) * stepof(A)
@inline Base.getindex(A::_AbstractRecordArray{<:Any,0}) = A[1]
@inline Base.setindex!(A::_AbstractRecordArray{<:Any,0}, x) = A[1] = x
@inline function Base.getindex(A::_AbstractRecordArray, i::Int)
@boundscheck checkbounds(A, i)
buf = _buffer(A)
GC.@preserve buf begin
return unwrap_union_value(unsafe_load(pointer(A, i)))
end
end
@inline function Base.setindex!(A::_AbstractRecordArray, x, i::Int)
@boundscheck checkbounds(A, i)
buf = _buffer(A)
v = field_convert(eltype(A), x)
GC.@preserve buf begin
unsafe_store!(pointer(A, i), v)
end
end
@propagate_inbounds Base.getindex(A::_AbstractRecordArray, I::Int...) =
A[LinearIndices(A)[I...]]
@propagate_inbounds Base.setindex!(A::_AbstractRecordArray, v, I::Int...) =
A[LinearIndices(A)[I...]] = v
function check_eltype(::Type{T}) where {T}
if T isa Union
check_eltype(T.a)
check_eltype(T.b)
return
end
ismutabletype(T) && noinline() do
error("mutable types are not supported; got: $T")
end
isconcretetype(T) || noinline() do
error("a concrete type is required; got: $T")
end
Base.datatype_pointerfree(T) || noinline() do
error("containing GC-managed object: $T")
end
return
end
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 1290 | """
FieldArray{Field}(A::RecordArray)
A.\$Field
Create a view to a field of elements in a `RecordArray`.
```jldoctest
julia> using RecordArrays
julia> xs = RecordArrays.fill((a = 1, b = 2), 3);
julia> xs.a
3-element FieldArray{:a,Int64,1,…}:
1
1
1
````
"""
function RecordArrays.FieldArray{Field}(A::RecordArray) where {Field}
T = fieldtype(eltype(A), Field)
check_eltype(eltype(A))
check_eltype(T)
offset = fieldoffset(eltype(A), fieldindex(eltype(A), Val(Field)))
ptr = Ptr{wrap_union_type(T)}(pointer(A) + offset)
buf = _buffer(A)
return FieldArray(buf, ptr, Val(T), size(A), _step(A), Val(Field))
end
function Base.summary(
io::IO,
A::FieldArray{Field,T,N,Vector{UInt8},Storage},
) where {Field,T,N,Storage}
@nospecialize A
is_standard = T isa Type
is_standard &= N isa Int
is_standard &= Field isa Union{Symbol,Integer}
is_standard &= if T isa Union
Storage === UnionValue{T}
else
T === Storage
end
is_standard || return invoke(summary, Tuple{IO,AbstractArray}, io, A)
print(io, length(A), "-element ")
print(io, FieldArray)
print(io, '{')
show(io, Field)
print(io, ',')
show(io, T)
print(io, ',')
show(io, N)
print(io, ",…")
print(io, '}')
end
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 3854 | """
RecordArray{T,N}(undef, dims; [align])
RecordVector{T}(undef, length; [align])
Create an array with array-of-structures memory layout.
Optionally accept alignment `align` of each element (i.e.,
`pointer(A:;RecordArray, i)` is divisible by `align` for all `i in
eachindex(A)`).
See also [`RecordArrays.fill`](@ref) and [`RecordArrays.unsafe_zeros`](@ref).
```jldoctest
julia> using RecordArrays
julia> xs = RecordArray{@NamedTuple{a::Float64, b::Char}}(undef, 3);
julia> xs.a .= 1:3;
julia> xs.b .= 'a':'c';
julia> xs
3-element RecordArray{NamedTuple{(:a, :b), Tuple{Float64, Char}},1,…}:
(a = 1.0, b = 'a')
(a = 2.0, b = 'b')
(a = 3.0, b = 'c')
````
"""
(RecordArrays.RecordArray, RecordArrays.RecordVector)
function RecordArrays.RecordArray{T,N}(
::UndefInitializer,
dims::NTuple{N,Integer};
align = nothing,
) where {T,N}
check_eltype(T)
Storage = wrap_union_type(T)
if align === nothing
elseif sizeof(Storage) <= Int(align)
else
noinline() do
error("`align = $align` smaller than `sizeof($Storage) = $(sizeof(Storage))`")
end
end
step = Int(something(align, sizeof(T)))
buffer = Vector{UInt8}(undef, *(step, dims...) + something(align, 0))
ptr = Ptr{Storage}(alignto(pointer(buffer), align))
return RecordArray(buffer, ptr, Val(T), dims, Val(step))
end
RecordArrays.RecordArray{T,N}(
undef::UndefInitializer,
dims::Vararg{Integer,N};
kwargs...,
) where {T,N} = RecordArray{T,N}(undef, dims; kwargs...)
RecordArrays.RecordArray{T}(
undef::UndefInitializer,
dims::NTuple{N,Integer};
kwargs...,
) where {T,N} = RecordArray{T,N}(undef, dims; kwargs...)
RecordArrays.RecordArray{T}(
undef::UndefInitializer,
dims::Vararg{Integer,N};
kwargs...,
) where {T,N} = RecordArray{T,N}(undef, dims; kwargs...)
Base.getproperty(A::RecordArray, name::Symbol) = FieldArray{name}(A)
Base.propertynames(A::RecordArray) = fieldnames(eltype(A))
@noinline function Base.setproperty!(A::RecordArray, name::Symbol, _)
error(
"$(ndims(A))-dim `RecordArray` does not support `setproperty!`;",
" use, e.g., `A.$name .= array` instead",
)
end
function _view_scalar(A, i)
ptr = pointer(A, i)
return RecordArray(_buffer(A), ptr, Val(eltype(A)), (), _step(A))
end
Base.view(A::RecordArray, i::Integer) = _view_scalar(A, i)
Base.view(A::RecordArray{T,N}, I::Vararg{Integer,N}) where {T,N} =
_view_scalar(A, LinearIndices(A)[I...])
"""
RecordArrays.fill(x::T, dims::NTuple{N,Integer}) -> A::RecordArray{T,N}
Create a `RecordArray` filled with `x`.
"""
RecordArrays.fill
RecordArrays.fill(x, dims::Integer...; kwargs...) = RecordArrays.fill(x, dims; kwargs...)
function RecordArrays.fill(x, dims::Tuple; kwargs...)
A = RecordArray{typeof(x)}(undef, dims; kwargs...)
fill!(A, x)
return A
end
"""
RecordArrays.unsafe_zeros(T, dims::NTuple{N,Integer}) -> A::RecordArray{T,N}
Create a `RecordArray` filled with zeros for all elements and all fields.
"""
RecordArrays.unsafe_zeros
RecordArrays.unsafe_zeros(T::Type, dims::Integer...; kwargs...) =
RecordArrays.unsafe_zeros(T, dims; kwargs...)
function RecordArrays.unsafe_zeros(T::Type, dims::Tuple; kwargs...)
A = RecordArray{T}(undef, dims; kwargs...)
fill!(_buffer(A), 0)
return A
end
function Base.summary(io::IO, A::RecordArray{T,N,Vector{UInt8},Storage}) where {T,N,Storage}
@nospecialize A
is_standard = T isa Type
is_standard &= N isa Int
is_standard &= if T isa Union
Storage === UnionValue{T}
else
T === Storage
end
is_standard || return invoke(summary, Tuple{IO,AbstractArray}, io, A)
print(io, length(A), "-element ")
print(io, RecordArray)
print(io, '{')
show(io, T)
print(io, ',')
show(io, N)
print(io, ",…")
print(io, '}')
end
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 1995 | valueof(::Val{x}) where {x} = x
# @inline fieldindex(::T, field::Val) where {T} = fieldindex(T, field)
@generated function fieldindex(::Type{T}, ::Val{field}) where {T,field}
field isa Symbol || return :(error("`field` must be a symbol; given: $field"))
return findfirst(n -> n === field, fieldnames(T))
end
if !isdefined(Base, :ismutabletype)
function ismutabletype(@nospecialize(t::Type))
t = Base.unwrap_unionall(t)
# TODO: what to do for `Union`?
return isa(t, DataType) && t.mutable
end
end
function noinline(f)
@noinline wrapper() = f()
wrapper()
end
alignto(ptr, ::Nothing) = ptr
function alignto(ptr, align)
ispow2(align) || noinline() do
error("not a power of 2: `align = $align`")
end
# return ptr + (align - mod(UInt(ptr), align))
return ptr + (align - (UInt(ptr) & (align - 1)))
end
struct UnionValue{T}
value::T
end
unwrap_union_value(x) = x
unwrap_union_value(x::UnionValue) = x.value
function wrap_union_type(::Type{T}) where {T}
if T isa Union
return UnionValue{T}
else
return T
end
end
@inline function field_convert(::Type{T}, x) where {T}
if T isa Union
return UnionValue{T}(convert(T, x))
else
return convert(T, x)
end
end
function define_docstrings()
docstrings = [:RecordArrays => joinpath(dirname(@__DIR__), "README.md")]
#=
docsdir = joinpath(@__DIR__, "docs")
for filename in readdir(docsdir)
stem, ext = splitext(filename)
ext == ".md" || continue
name = Symbol(stem)
name in names(RecordArrays, all=true) || continue
push!(docstrings, name => joinpath(docsdir, filename))
end
=#
for (name, path) in docstrings
include_dependency(path)
doc = read(path, String)
doc = replace(doc, r"^```julia"m => "```jldoctest $name")
doc = replace(doc, "<kbd>TAB</kbd>" => "_TAB_")
@eval RecordArrays $Base.@doc $doc $name
end
end
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 258 | try
using RecordArraysBenchmarks
true
catch
false
end || begin
let path = joinpath(@__DIR__, "../benchmark/RecordArraysBenchmarks/Project.toml")
path in LOAD_PATH || push!(LOAD_PATH, path)
end
using RecordArraysBenchmarks
end
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 312 | using Test
macro test_error(ex)
@gensym err
quote
let $err = nothing
$Test.@test try
$ex
false
catch _err
$err = _err
true
end
$err
end
end |> esc
end
const ⊏ = occursin
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 540 | module TestRecordArrays
using Test
include("load.jl")
@testset "$file" for file in sort([
file for file in readdir(@__DIR__) if match(r"^test_.*\.jl$", file) !== nothing
])
if file == "test_doctest.jl"
if lowercase(get(ENV, "JULIA_PKGEVAL", "false")) == "true"
@info "Skipping doctests on PkgEval."
continue
elseif VERSION < v"1.6" || VERSION >= v"1.7-"
@info "Skipping doctests on Julia $VERSION."
continue
end
end
include(file)
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 285 | module TestBenchSmoke
using Test
using RecordArraysBenchmarks: clear, setup_smoke
@testset "smoke test benchmarks" begin
try
local suite
@test (suite = setup_smoke()) isa Any
@test run(suite) isa Any
finally
clear()
end
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 783 | module TestCommon
include("preamble.jl")
using RecordArrays.Implementations: check_eltype
struct Node{T}
head::T
tail::Union{Nothing,Node{T}}
end
@testset "check_eltype" begin
@test check_eltype(Some{Int}) === nothing
@test check_eltype(typeof((a = 1, b = 2))) === nothing
@testset "Ref" begin
err = @test_error check_eltype(typeof(Ref(0))) === nothing
@test "mutable type" ⊏ sprint(showerror, err)
end
@testset "Integer" begin
err = @test_error check_eltype(Integer) === nothing
@test "concrete type is required" ⊏ sprint(showerror, err)
end
@testset "Node{Int}" begin
err = @test_error check_eltype(Node{Int}) === nothing
@test "GC-managed" ⊏ sprint(showerror, err)
end
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 164 | module TestDoctest
import RecordArrays
using Documenter: doctest
using Test
@testset "doctest" begin
doctest(RecordArrays; manual = false)
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 578 | module TestFill
using Test
using RecordArrays
rawdata = """
fill((a = 1, b = 2))
fill((a = 1, b = 2), 10)
fill((a = 1, b = 2), 2, 3)
fill((a = 1, b = 2), 2, 3, 4)
fill(Some(0))
fill(Some(0), 10)
fill(Some(0), 2, 3)
fill(Some{Union{Int,Missing}}(0))
fill(Some{Union{Int,Missing}}(0), 10)
fill(Some{Union{Int,Missing}}(0), 2, 3)
""" |> x -> split(x, "\n", keepempty = false)
@testset "$code" for code in rawdata
base = Base.include_string(@__MODULE__, code)
rec = Base.include_string(@__MODULE__, "RecordArrays.$code")
@test collect(rec) == base
end
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | code | 2019 | module TestRecords
using RecordArrays
using Test
@testset "fill((a = 1, b = 2), 10)" begin
@testset "$(sprint(show, align))" for align in [nothing, 64]
A = RecordArrays.fill((a = 1, b = 2), 10; align = align)
@test A.a == fill(1, 10)
@test A.b == fill(2, 10)
A.a .= 1:10
A.b .= reverse(1:10)
@test A[1] == (a = 1, b = 10)
@test A[2] == (a = 2, b = 9)
@test A.a == 1:10
@test A.b == 10:-1:1
end
end
struct OneValue{T}
value::T
end
@testset "fill(OneValue{Union{Nothing,Int}}, 10)" begin
Eltype = OneValue{Union{Nothing,Int}}
@testset "$(sprint(show, align))" for align in [nothing, 64]
A = RecordArrays.fill(Eltype(0), 10; align = align)
@test A[1] === Eltype(0)
@test A.value[1] === 0
A[2] = Eltype(2)
A[3] = Eltype(nothing)
@test A[2] === Eltype(2)
@test A[3] === Eltype(nothing)
@test A.value[2] === 2
@test A.value[3] === nothing
A.value[4] = 4
A.value[5] = nothing
@test A[4] === Eltype(4)
@test A[5] === Eltype(nothing)
@test A.value[4] === 4
@test A.value[5] === nothing
vals = [[0, 2, nothing, 4, nothing]; fill(0, 5)]
@test collect(A) == Eltype.(vals)
@test collect(A.value) == vals
end
end
# Maybe stop using `Vector{UInt8}` and use padding objects, so that we can put
# GC-managed objects in the array?
#=
struct Node{T}
head::T
tail::Union{Nothing,Node{T}}
end
list() = nothing
list(x, xs...) = Node(x, list(xs...))
@testset "fill(Node{Int}(...), 10)" begin
@testset "$(sprint(show, align))" for align in [nothing, 64]
A = RecordArrays.fill(list(1, 2), 10; align = align)
@test A[1] === list(1, 2)
@test A.head[1] === 1
@test A.tail[1] === list(2)
A[1] = list(1, 2, 3)
@test A[1] === list(1, 2, 3)
@test A.tail[1] === list(2, 3)
@test A[2] === list(1, 2)
end
end
=#
end # module
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 0.1.0 | 256a843a570e2f6605bcada25c5df0527ac3fc60 | docs | 2374 | # RecordArrays.jl: flexible Array-of-Structures representation for Julia
**NOTE**: [StructArrays.jl](https://github.com/JuliaArrays/StructArrays.jl)
provides the abstract array interface for Structure-of-Arrays representation
which is much more appropriate for many performance-oriented programs.
RecordArrays.jl is a package for using Array-of-Structures representation with
more control than `Array{T}`. For example, it can be used for creating
task-local state aligned to cache line. Updating a single field at single
index does not mutate other fields.
## Usage
```julia
julia> using RecordArrays
julia> xs = RecordArrays.fill((a = 1, b = 2), 5; align = 64)
5-element RecordArray{NamedTuple{(:a, :b), Tuple{Int64, Int64}},1,…}:
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
julia> all(i -> mod(UInt(pointer(xs, i)), 64) == 0, eachindex(xs))
true
julia> xs[1] = (a = 111, b = 222);
julia> xs
5-element RecordArray{NamedTuple{(:a, :b), Tuple{Int64, Int64}},1,…}:
(a = 111, b = 222)
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
julia> xs.a
5-element FieldArray{:a,Int64,1,…}:
111
1
1
1
1
julia> xs.a[2] = 11111;
julia> xs
5-element RecordArray{NamedTuple{(:a, :b), Tuple{Int64, Int64}},1,…}:
(a = 111, b = 222)
(a = 11111, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
julia> x3 = view(xs, 3) # acts like a `NamedTuple` of `Ref`s
1-element RecordArray{NamedTuple{(:a, :b), Tuple{Int64, Int64}},0,…}:
(a = 1, b = 2)
julia> x3.a[]
1
julia> x3.a[] = 333;
julia> xs
5-element RecordArray{NamedTuple{(:a, :b), Tuple{Int64, Int64}},1,…}:
(a = 111, b = 222)
(a = 11111, b = 2)
(a = 333, b = 2)
(a = 1, b = 2)
(a = 1, b = 2)
```
Use `RecordArray{T}(undef, dims)` to allocate a new uninitialized array:
```julia
julia> using RecordArrays
julia> xs = RecordArray{Some{Union{Nothing,Int}}}(undef, 3);
julia> xs .= Some.(1:3)
3-element RecordArray{Some{Union{Nothing, Int64}},1,…}:
1
2
3
```
Another way to allocate a new array is to use `RecordArrays.unsafe_zeros`:
```julia
julia> using RecordArrays
julia> xs = RecordArrays.unsafe_zeros(NTuple{5, UInt8}, 3)
3-element RecordArray{NTuple{5, UInt8},1,…}:
(0x00, 0x00, 0x00, 0x00, 0x00)
(0x00, 0x00, 0x00, 0x00, 0x00)
(0x00, 0x00, 0x00, 0x00, 0x00)
```
## See also
* https://github.com/Vitaliy-Yakovchuk/StructViews.jl
| RecordArrays | https://github.com/tkf/RecordArrays.jl.git |
|
[
"MIT"
] | 1.1.0 | c0dfa5a35710a193d83f03124356eef3386688fc | code | 2198 | module DefaultApplication
import InteractiveUtils
# based on https://stackoverflow.com/questions/38086185/
const _is_wsl = Sys.islinux() &&
let osrelease = "/proc/sys/kernel/osrelease"
isfile(osrelease) && occursin(r"microsoft|wsl"i, read(osrelease, String))
end
"""
DefaultApplication.open(filename; wait = false)
Open a file with the default application determined by the OS.
The argument `wait` is passed to `run`.
"""
function open(filename; wait = false)
@static if Sys.isapple()
run(`open $(filename)`; wait = wait)
elseif _is_wsl
# Powershell can open *relative* paths in WSL, hence using relpath
# Could use wslview instead, but powershell is more universally available.
# Could use cmd + wslpath instead, but cmd complains about the working directory.
# Quotes around the filename are to deal with spaces.
relfile = relpath(filename)
cmd = `powershell.exe -NoProfile -NonInteractive -Command start \"$(relfile)\"`
run(cmd; wait = wait)
elseif Sys.islinux() || Sys.isbsd()
run(`xdg-open $(filename)`; wait = wait)
elseif Sys.iswindows()
cmd = get(ENV, "COMSPEC", "cmd.exe")
run(`$(cmd) /c start $(filename)`; wait = wait)
else
@warn("Opening files the default application is not supported on this OS.",
KERNEL = Sys.KERNEL)
end
end
"""
DefaultApplication.test()
Helper function that creates text file, attempts to open it with the OS-specific
default application, and prints information that helps with debugging.
"""
function test()
path = tempname() * ".txt"
write(path, "some text, should be opened in a text editor")
@info("opening text file with the default application",
path = path)
@info("""
If the file was not opened, please copy the output and open an issue at
https://github.com/tpapp/DefaultApplication.jl/issues
""")
InteractiveUtils.versioninfo(stdout; verbose = true)
if Sys.iswindows()
@info("Version information for windows",
windows_version = Sys.windows_version())
end
DefaultApplication.open(path)
end
end # module
| DefaultApplication | https://github.com/tpapp/DefaultApplication.jl.git |
|
[
"MIT"
] | 1.1.0 | c0dfa5a35710a193d83f03124356eef3386688fc | code | 826 | using Test
import DefaultApplication
CI = get(ENV, "CI", "false") == "true"
if Sys.islinux()
if CI
# ensure clean slate
sentinel = "/tmp/saved-argument"
rm(sentinel; force = true)
# set up test file
testfile = "/tmp/test.txt"
write(testfile, "test text")
## uncomment lines below for debug information
@info("environment",
XDGMIMETYPE = chomp(read(`xdg-mime query filetype $(testfile)`, String)),
XDGMIMEDEFAULT = chomp(read(`xdg-mime query default text/plain`, String)))
@info "opening $(testfile)"
DefaultApplication.open(testfile)
sleep(1)
@info "test that file was opened"
@test chomp(read(sentinel, String)) == testfile
else
@warn "Tests are only ran in CI."
end
end
| DefaultApplication | https://github.com/tpapp/DefaultApplication.jl.git |
|
[
"MIT"
] | 1.1.0 | c0dfa5a35710a193d83f03124356eef3386688fc | docs | 4265 | # DefaultApplication.jl

[](https://github.com/tpapp/DefaultApplication.jl/actions?query=workflow%3ACI)
[](http://codecov.io/github/tpapp/DefaultApplication.jl?branch=master)
Julia library for opening a file with the default application determined by the OS.
## Motivation
Many packages implement variations on the same short code snippet. This package maintains a version that can be shared or tested.
This package intends to be very lightweight, and has no dependencies outside the standard libraries. Nevertheless, if you still don't want to use this as a dependency, you can of course also copy the code of `DefaultApplication.open()` to another package, but then you will have to repeat this to keep up with bugfixes and developments.
## Usage
```julia
import DefaultApplication
DefaultApplication.open("/some/file.png")
```
`open` is not exported from the package, because it would clash with `Base.open`.
## Status
| OS | version | status |
|:--------|:-------------|:------- |
| Linux | Ubuntu 19.10 | `✅` |
| Linux | Ubuntu 19.04 | `✅` |
| Linux | Ubuntu 18.04 | `✅` |
| Linux | Ubuntu 16.04 | `✅` (CI) |
| Linux | Debian 8.0 | `✅` |
| OS X | Darwin 17.7 | `✅` |
| Windows | 10 | `✅` |
If your OS/version is missing, please test as described below and open an issue with the information so that this table can be extended.
## Testing
Currently there are only partial unit tests, since the functionality of this package is difficult to test without a desktop environment. Testing, bug reports, feature requests and PRs are welcome.
There is a utility function `DefaultApplication.test()` for testing, which prints information for bug reports:
```julia
julia> import DefaultApplication
julia> DefaultApplication.test()
┌ Info: opening text file with the default application
└ path = "/tmp/jl_ISgu7A.txt"
┌ Info: If the file was not opened, please copy the output and open an issue at
└ https://github.com/tpapp/DefaultApplication.jl/issues
Julia Version 1.4.0-rc1.0
Commit b0c33b0cf5 (2020-01-23 17:23 UTC)
Platform Info:
OS: Linux (x86_64-linux-gnu)
Ubuntu 19.10
uname: Linux 5.3.0-29-generic #31-Ubuntu SMP Fri Jan 17 17:27:26 UTC 2020 x86_64 x86_64
CPU: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz:
speed user nice sys idle irq
#1 3014 MHz 312924 s 452 s 102521 s 4773911 s 0 s
#2 3005 MHz 392192 s 374 s 79742 s 1121314 s 0 s
#3 3028 MHz 417948 s 275 s 80886 s 1122523 s 0 s
#4 2984 MHz 400951 s 386 s 84294 s 1115707 s 0 s
#5 2909 MHz 411316 s 613 s 82936 s 1120208 s 0 s
#6 2878 MHz 386572 s 368 s 82815 s 1116943 s 0 s
#7 3011 MHz 366070 s 673 s 92152 s 1123035 s 0 s
#8 2997 MHz 383230 s 544 s 82892 s 1124208 s 0 s
Memory: 15.518669128417969 GB (5564.16796875 MB free)
Uptime: 86757.0 sec
Load Avg: 0.58447265625 0.50439453125 0.505859375
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-8.0.1 (ORCJIT, skylake)
Environment:
JULIA_NUM_THREADS = 1
HOME = /home/tamas
XDG_SEAT_PATH = /org/freedesktop/DisplayManager/Seat0
MANDATORY_PATH = /usr/share/gconf/xubuntu.mandatory.path
DEFAULTS_PATH = /usr/share/gconf/xubuntu.default.path
TERM = eterm-color
PATH = /home/tamas/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
XDG_SESSION_PATH = /org/freedesktop/DisplayManager/Session0
JULIA_CMDSTAN_HOME = /home/tamas/src/cmdstan/
Process(`xdg-open /tmp/jl_ISgu7A.txt`, ProcessRunning)
```
## Related documentation
- [`COMSPEC`](https://en.wikipedia.org/wiki/COMSPEC) (Windows)
- [`xdg-open`](https://linux.die.net/man/1/xdg-open) (Linux)
- [`open`](https://ss64.com/osx/open.html) (OS X)
| DefaultApplication | https://github.com/tpapp/DefaultApplication.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.