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"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 4115 | @testset "featuredgraph" begin
V = 4
E = 5
vdim = 3
edim = 5
gdim = 7
pdim = 11
nf = rand(vdim, V)
ef = rand(edim, E)
gf = rand(gdim)
pf = rand(pdim, V)
@testset "features" begin
adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
fg = FeaturedGraph(adjm; nf=nf, ef=ef ,gf=gf, pf=pf)
@test has_graph(fg)
@test has_node_feature(fg)
@test has_edge_feature(fg)
@test has_global_feature(fg)
@test has_positional_feature(fg)
@test graph(fg).S == adjm
@test node_feature(fg) == nf
@test edge_feature(fg) == ef
@test global_feature(fg) == gf
@test positional_feature(fg) == pf
@test GraphSignals.nf_dims_repr(fg.nf) == vdim
@test GraphSignals.ef_dims_repr(fg.ef) == edim
@test GraphSignals.gf_dims_repr(fg.gf) == gdim
@test GraphSignals.pf_dims_repr(fg.pf) == pdim
fg2 = FeaturedGraph(fg)
@test GraphSignals.adjacency_matrix(fg2) == adjm
@test node_feature(fg2) == nf
@test edge_feature(fg2) == ef
@test global_feature(fg2) == gf
new_nf = rand(vdim, V)
new_fg = ConcreteFeaturedGraph(fg, nf=new_nf)
@test node_feature(new_fg) == new_nf
@test edge_feature(new_fg) == ef
@test global_feature(new_fg) == gf
@test positional_feature(new_fg) == pf
# Test with transposed features
nf_t = rand(V, vdim)'
fg = FeaturedGraph(adjm; nf=nf_t)
@test has_graph(fg)
@test has_node_feature(fg)
@test !has_edge_feature(fg)
@test !has_global_feature(fg)
@test !has_positional_feature(fg)
@test graph(fg).S == adjm
@test node_feature(fg) == nf_t
@test isnothing(edge_feature(fg))
@test isnothing(global_feature(fg))
@test isnothing(positional_feature(fg))
end
@testset "setting properties" begin
adjm1 = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
adjm2 = [0 1 0 1;
1 0 1 1;
0 1 0 1;
1 1 1 0]
fg = FeaturedGraph(adjm1; nf=nf, ef=ef, gf=gf, pf=pf)
fg.graph.S .= adjm2
@test fg.graph.S == adjm2
@test_throws DimensionMismatch fg.graph = [0 1; 0 1]
nf_ = rand(10, V)
fg.nf = nf_
@test node_feature(fg) == nf_
@test_throws DimensionMismatch fg.nf = rand(10, 11)
ef_ = rand(10, E)
fg.ef = ef_
@test edge_feature(fg) == ef_
@test_throws DimensionMismatch fg.ef = rand(10, 11)
pf_ = rand(10, V)
fg.pf = pf_
@test positional_feature(fg) == pf_
@test_throws DimensionMismatch fg.pf = rand(10, 11)
end
@testset "graph properties" begin
adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
fg = FeaturedGraph(adjm)
@test vertices(fg) == 1:V
@test edges(fg) isa GraphSignals.EdgeIter
@test neighbors(fg) == [2, 3, 4, 1, 3, 1, 2, 4, 1, 3]
@test incident_edges(fg) == fg |> graph |> GraphSignals.edgevals
el = GraphSignals.to_namedtuple(fg)
@test el.N == V
@test el.E == E
@test el.es == [1, 2, 4, 1, 3, 2, 3, 5, 4, 5]
@test el.nbrs == [2, 3, 4, 1, 3, 1, 2, 4, 1, 3]
@test el.xs == [1, 1, 1, 2, 2, 3, 3, 3, 4, 4]
end
@testset "generate coordinates" begin
adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
fg = FeaturedGraph(adjm; nf=nf, pf=:auto)
@test size(positional_feature(fg)) == (1, V)
end
@testset "random subgraph" begin
adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
fg = FeaturedGraph(adjm)
rand_subgraph = sample(fg, 3)
@test rand_subgraph isa FeaturedSubgraph
@test length(rand_subgraph.nodes) == 3
@test_throws ErrorException sample(fg, 5)
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 3155 | @testset "graph" begin
V = 6
@testset "undirected graph" begin
E = 7
adjm = [0 1 0 1 0 1;
1 0 1 0 0 0;
0 1 0 1 1 0;
1 0 1 0 0 0;
0 0 1 0 1 0;
1 0 0 0 0 0]
adjl = [
[2, 4, 6],
[1, 3],
[2, 4, 5],
[1, 3],
[3, 5],
[1],
]
@testset "constructor" begin
ug = SimpleGraph(V)
add_edge!(ug, 1, 2); add_edge!(ug, 1, 4); add_edge!(ug, 1, 6)
add_edge!(ug, 2, 3); add_edge!(ug, 3, 4); add_edge!(ug, 3, 5)
add_edge!(ug, 5, 5)
wug = SimpleWeightedGraph(V)
add_edge!(wug, 1, 2, 2); add_edge!(wug, 1, 4, 2); add_edge!(wug, 1, 6, 1)
add_edge!(wug, 2, 3, 5); add_edge!(wug, 3, 4, 2); add_edge!(wug, 3, 5, 2)
add_edge!(wug, 5, 5, 3)
for g in [adjm, adjl, ug, wug]
fg = FeaturedGraph(g)
@test adjacency_list(fg) == adjl
@test nv(fg) == V
@test ne(fg) == E
@test !is_directed(fg)
@test has_edge(fg, 1, 2)
@test neighbors(fg, 1) == adjl[1]
end
end
@testset "conversions" begin
for g in [adjm, adjl]
@test adjacency_list(g) == adjl
@test nv(g) == V
@test ne(g) == E
@test !is_directed(g)
end
end
end
@testset "directed graph" begin
E = 6
adjm = [0 0 0 0 0 0; # asymmetric
0 0 0 0 0 0;
1 1 0 0 0 0;
0 0 1 0 0 0;
0 1 1 0 0 0;
1 0 0 0 0 0]
adjl = Vector{Int64}[
[3, 6],
[3, 5],
[4, 5],
[],
[],
[]
]
@testset "constructor" begin
dg = SimpleDiGraph(V)
add_edge!(dg, 1, 3); add_edge!(dg, 2, 3); add_edge!(dg, 1, 6)
add_edge!(dg, 2, 5); add_edge!(dg, 3, 4); add_edge!(dg, 3, 5)
wdg = SimpleWeightedDiGraph(V)
add_edge!(wdg, 1, 3, 2); add_edge!(wdg, 2, 3, 2); add_edge!(wdg, 1, 6, 1)
add_edge!(wdg, 2, 5, -2); add_edge!(wdg, 3, 4, -2); add_edge!(wdg, 3, 5, -1)
for g in [adjm, adjl, dg, wdg]
fg = FeaturedGraph(g)
@test adjacency_list(fg) == adjl
@test nv(fg) == V
@test ne(fg) == E
@test is_directed(fg)
@test has_edge(fg, 1, 3)
@test neighbors(fg, 1) == adjl[1]
end
end
end
@testset "remove self loops" begin
adjl = [
[1, 2, 3],
[2, 3],
[1, 2],
]
adjl_noselfloops = [
[2, 3],
[3],
[1, 2],
]
new_adjl = GraphSignals.remove_self_loops(adjl)
@test new_adjl == adjl_noselfloops
GraphSignals.remove_self_loops!(adjl)
@test adjl == adjl_noselfloops
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 551 | @testset "graphdomains" begin
T = Float32
d = GraphSignals.NullDomain()
@test isnothing(GraphSignals.domain(d))
@test isnothing(positional_feature(d))
@test !has_positional_feature(d)
@test GraphSignals.pf_dims_repr(d) == 0
GraphSignals.check_num_nodes(0, d)
pf = rand(T, 2, 3, 4)
d = GraphSignals.NodeDomain(pf)
@test GraphSignals.domain(d) == pf
@test positional_feature(d) == pf
@test has_positional_feature(d)
@test GraphSignals.pf_dims_repr(d) == 2
GraphSignals.check_num_nodes(3, d)
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 1432 | @testset "graphsignals" begin
T = Float32
dim = 2
num = 3
batch_size = 4
s = GraphSignals.NullGraphSignal()
@test isnothing(GraphSignals.signal(s))
@test isnothing(node_feature(s))
@test isnothing(node_feature(s))
@test isnothing(node_feature(s))
@test !has_node_feature(s)
@test !has_edge_feature(s)
@test !has_global_feature(s)
@test GraphSignals.nf_dims_repr(s) == 0
@test GraphSignals.ef_dims_repr(s) == 0
@test GraphSignals.gf_dims_repr(s) == 0
GraphSignals.check_num_nodes(0, s)
GraphSignals.check_num_edges(0, s)
nf = rand(T, dim, num, batch_size)
s = GraphSignals.NodeSignal(nf)
@test GraphSignals.signal(s) == nf
@test node_feature(s) == nf
@test has_node_feature(s)
@test GraphSignals.nf_dims_repr(s) == dim
GraphSignals.check_num_nodes(3, s)
# permutation equivariant
ef = rand(T, dim, num, batch_size)
s = GraphSignals.EdgeSignal(ef)
@test GraphSignals.signal(s) == ef
@test edge_feature(s) == ef
@test has_edge_feature(s)
@test GraphSignals.ef_dims_repr(s) == dim
GraphSignals.check_num_edges(3, s)
# permutation equivariant
gf = rand(T, dim, batch_size)
s = GraphSignals.GlobalSignal(gf)
@test GraphSignals.signal(s) == gf
@test global_feature(s) == gf
@test has_global_feature(s)
@test GraphSignals.gf_dims_repr(s) == dim
# permutation invariant
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 9604 | @testset "linalg" begin
in_channel = 3
out_channel = 5
N = 6
adjs = Dict(
:simple => [0. 1. 1. 0. 0. 0.;
1. 0. 1. 0. 1. 0.;
1. 1. 0. 1. 0. 1.;
0. 0. 1. 0. 0. 0.;
0. 1. 0. 0. 0. 0.;
0. 0. 1. 0. 0. 0.],
:weight => [0. 2. 2. 0. 0. 0.;
2. 0. 1. 0. 2. 0.;
2. 1. 0. 5. 0. 2.;
0. 0. 5. 0. 0. 0.;
0. 2. 0. 0. 0. 0.;
0. 0. 2. 0. 0. 0.],
)
degs = Dict(
:simple => [2. 0. 0. 0. 0. 0.;
0. 3. 0. 0. 0. 0.;
0. 0. 4. 0. 0. 0.;
0. 0. 0. 1. 0. 0.;
0. 0. 0. 0. 1. 0.;
0. 0. 0. 0. 0. 1.],
:weight => [4. 0. 0. 0. 0. 0.;
0. 5. 0. 0. 0. 0.;
0. 0. 10. 0. 0. 0.;
0. 0. 0. 5. 0. 0.;
0. 0. 0. 0. 2. 0.;
0. 0. 0. 0. 0. 2.]
)
laps = Dict(
:simple => [2. -1. -1. 0. 0. 0.;
-1. 3. -1. 0. -1. 0.;
-1. -1. 4. -1. 0. -1.;
0. 0. -1. 1. 0. 0.;
0. -1. 0. 0. 1. 0.;
0. 0. -1. 0. 0. 1.],
:weight => [4. -2. -2. 0. 0. 0.;
-2. 5. -1. 0. -2. 0.;
-2. -1. 10. -5. 0. -2.;
0. 0. -5. 5. 0. 0.;
0. -2. 0. 0. 2. 0.;
0. 0. -2. 0. 0. 2.],
)
norm_laps = Dict(
:simple => [1. -1/sqrt(2*3) -1/sqrt(2*4) 0. 0. 0.;
-1/sqrt(2*3) 1. -1/sqrt(3*4) 0. -1/sqrt(3) 0.;
-1/sqrt(2*4) -1/sqrt(3*4) 1. -1/2 0. -1/2;
0. 0. -1/2 1. 0. 0.;
0. -1/sqrt(3) 0. 0. 1. 0.;
0. 0. -1/2 0. 0. 1.],
:weight => [1. -2/sqrt(4*5) -2/sqrt(4*10) 0. 0. 0.;
-2/sqrt(4*5) 1. -1/sqrt(5*10) 0. -2/sqrt(2*5) 0.;
-2/sqrt(4*10) -1/sqrt(5*10) 1. -5/sqrt(5*10) 0. -2/sqrt(2*10);
0. 0. -5/sqrt(5*10) 1. 0. 0.;
0. -2/sqrt(2*5) 0. 0. 1. 0.;
0. 0. -2/sqrt(2*10) 0. 0. 1.]
)
@testset "undirected graph" begin
adjm = [0 1 0 1;
1 0 1 0;
0 1 0 1;
1 0 1 0]
deg = [2 0 0 0;
0 2 0 0;
0 0 2 0;
0 0 0 2]
isd = [√2, √2, √2, √2]
lap = [2 -1 0 -1;
-1 2 -1 0;
0 -1 2 -1;
-1 0 -1 2]
norm_lap = [1. -.5 0. -.5;
-.5 1. -.5 0.;
0. -.5 1. -.5;
-.5 0. -.5 1.]
scaled_lap = [0 -0.5 0 -0.5;
-0.5 0 -0.5 -0;
0 -0.5 0 -0.5;
-0.5 0 -0.5 0]
rw_lap = [1 -.5 0 -.5;
-.5 1 -.5 0;
0 -.5 1 -.5;
-.5 0 -.5 1]
ugs = Dict(
:simple => SimpleGraph(N),
:weight => SimpleWeightedGraph(N),
)
add_edge!(ugs[:simple], 1, 2); add_edge!(ugs[:simple], 1, 3);
add_edge!(ugs[:simple], 2, 3); add_edge!(ugs[:simple], 3, 4)
add_edge!(ugs[:simple], 2, 5); add_edge!(ugs[:simple], 3, 6)
add_edge!(ugs[:weight], 1, 2, 2); add_edge!(ugs[:weight], 1, 3, 2)
add_edge!(ugs[:weight], 2, 3, 1); add_edge!(ugs[:weight], 3, 4, 5)
add_edge!(ugs[:weight], 2, 5, 2); add_edge!(ugs[:weight], 3, 6, 2)
fg = FeaturedGraph(adjm)
@test matrixtype(fg) == :adjm
@test repr(fg) == "FeaturedGraph:\n\tUndirected graph with (#V=4, #E=4) in adjacency matrix"
@test GraphSignals.adjacency_matrix(adjm, Int64) === adjm
for T in [Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64]
for g in [adjm, sparse(adjm), fg]
@test GraphSignals.degrees(g; dir=:both) == [2, 2, 2, 2]
D = GraphSignals.degree_matrix(g, T, dir=:out)
@test D == T.(deg)
@test GraphSignals.degree_matrix(g, T; dir=:in) == D
@test GraphSignals.degree_matrix(g, T; dir=:both) == D
@test eltype(D) == T
@test GraphSignals.adjacency_matrix(g) == adjm
L = Graphs.laplacian_matrix(g, T)
@test L == T.(lap)
@test eltype(L) == T
end
for kind in [:simple, :weight]
@test GraphSignals.degrees(ugs[kind], T, dir=:out) == T.(diag(degs[kind]))
D = GraphSignals.degree_matrix(ugs[kind], T, dir=:out)
@test D == T.(degs[kind])
@test GraphSignals.degree_matrix(ugs[kind], T; dir=:in) == D
@test GraphSignals.degree_matrix(ugs[kind], T; dir=:both) == D
@test eltype(D) == T
@test Graphs.laplacian_matrix(ugs[kind], T) == T.(laps[kind])
end
for g in [adjm, sparse(adjm)]
SL = GraphSignals.signless_laplacian(g, T)
@test SL == T.(adjm + deg)
@test eltype(SL) == T
end
end
fg = FeaturedGraph(Float64.(adjm))
@test matrixtype(fg) == :adjm
for T in [Float16, Float32, Float64]
for g in [adjm, sparse(adjm), fg]
NA = GraphSignals.normalized_adjacency_matrix(g, T)
@test NA ≈ T.(I - norm_lap)
@test eltype(NA) == T
NA = GraphSignals.normalized_adjacency_matrix(g, T, selfloop=true)
@test eltype(NA) == T
NL = GraphSignals.normalized_laplacian(g, T)
@test NL ≈ T.(norm_lap)
@test eltype(NL) == T
SL = GraphSignals.scaled_laplacian(g, T)
@test SL ≈ T.(scaled_lap)
@test eltype(SL) == T
end
for kind in [:simple, :weight]
NA = GraphSignals.normalized_adjacency_matrix(ugs[kind], T)
@test NA ≈ T.(I - norm_laps[kind])
@test eltype(NA) == T
NL = normalized_laplacian(ugs[kind], T)
@test NL ≈ T.(norm_laps[kind])
@test eltype(NL) == T
end
RW = GraphSignals.random_walk_laplacian(adjm, T)
@test RW == T.(rw_lap)
@test eltype(RW) == T
RW = GraphSignals.random_walk_laplacian(sparse(adjm), T)
@test RW == T.(rw_lap)
@test eltype(RW) == T
end
end
@testset "directed" begin
adjm = [0 2 0 3;
0 0 4 0;
2 0 0 1;
0 0 0 0]
degs = Dict(
:out => diagm(0=>[2, 2, 4, 4]),
:in => diagm(0=>[5, 4, 3, 0]),
:both => diagm(0=>[7, 6, 7, 4]),
)
laps = Dict(
:out => degs[:out] - adjm,
:in => degs[:in] - adjm,
:both => degs[:both] - adjm,
)
norm_laps = Dict(
:out => I - diagm(0=>[1/2, 1/2, 1/4, 1/4])*adjm,
:in => I - diagm(0=>[1/5, 1/4, 1/3, 0])*adjm,
)
sig_laps = Dict(
:out => degs[:out] + adjm,
:in => degs[:in] + adjm,
:both => degs[:both] + adjm,
)
rw_laps = Dict(
:out => I - diagm(0=>[1/2, 1/2, 1/4, 1/4]) * adjm,
:in => I - diagm(0=>[1/5, 1/4, 1/3, 0]) * adjm,
:both => I - diagm(0=>[1/7, 1/6, 1/7, 1/4]) * adjm,
)
dgs = Dict(
:simple => SimpleDiGraph(N),
:weight => SimpleWeightedDiGraph(N),
)
add_edge!(dgs[:simple], 1, 3); add_edge!(dgs[:simple], 2, 3)
add_edge!(dgs[:simple], 1, 6); add_edge!(dgs[:simple], 2, 5)
add_edge!(dgs[:simple], 3, 4); add_edge!(dgs[:simple], 3, 5)
add_edge!(dgs[:weight], 1, 3, 2); add_edge!(dgs[:weight], 2, 3, 2)
add_edge!(dgs[:weight], 1, 6, 1); add_edge!(dgs[:weight], 2, 5, -2)
add_edge!(dgs[:weight], 3, 4, -2); add_edge!(dgs[:weight], 3, 5, -1)
for T in [Int8, Int16, Int32, Int64, Int128, Float16, Float32, Float64]
for g in [adjm, sparse(adjm)]
for dir in [:out, :in, :both]
D = GraphSignals.degree_matrix(g, T, dir=dir)
@test D == T.(degs[dir])
@test eltype(D) == T
L = Graphs.laplacian_matrix(g, T, dir=dir)
@test L == T.(laps[dir])
@test eltype(L) == T
SL = GraphSignals.signless_laplacian(g, T, dir=dir)
@test SL == T.(sig_laps[dir])
@test eltype(SL) == T
end
@test_throws ArgumentError GraphSignals.degree_matrix(g, dir=:other)
end
end
for T in [Float32, Float64]
for g in [adjm, sparse(adjm)]
for dir in [:out, :in]
L = normalized_laplacian(g, T, dir=dir)
@test L == T.(norm_laps[dir])
@test eltype(L) == T
end
for dir in [:out, :in, :both]
RW = GraphSignals.random_walk_laplacian(g, T, dir=dir)
@test collect(RW) ≈ T.(rw_laps[dir])
@test eltype(RW) == T
end
end
end
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 1224 | @testset "neighbor_graphs" begin
T = Float32
V = 100
vdim = 10
batch_size = 10
k = 5
@testset "Euclidean distance" begin
nf = rand(T, vdim, V)
fg = kneighbors_graph(nf, k; include_self=false)
@test fg isa FeaturedGraph
@test nv(fg) == V
@test ne(fg) == V*k
@test node_feature(fg) == nf
end
@testset "Minkowski distance" begin
nf = rand(T, vdim, V)
fg = kneighbors_graph(nf, k, Minkowski(3); include_self=true)
@test fg isa FeaturedGraph
@test nv(fg) == V
@test ne(fg) == V*k
@test node_feature(fg) == nf
end
@testset "Jaccard distance" begin
nf = rand(T[0, 1], vdim, V)
fg = kneighbors_graph(nf, k, Jaccard(); include_self=true)
@test fg isa FeaturedGraph
@test nv(fg) == V
@test ne(fg) == V*k
@test node_feature(fg) == nf
end
@testset "batch" begin
nf = rand(T, vdim, V, batch_size)
fg = kneighbors_graph(nf, k; include_self=false)
@test fg isa FeaturedGraph
@test nv(fg) == V
@test ne(fg) == V*k
@test node_feature(fg) == reshape(mean(nf, dims=3), size(nf)[1:2]...)
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 286 | @testset "positional" begin
dims = (3, 4, 5)
N = length(dims)
A = rand(dims...)
coord = GraphSignals.generate_grid(A)
@test size(coord) == (N, dims...)
coord = GraphSignals.generate_grid(A, with_batch=true)
@test size(coord) == (N-1, dims[1:end-1]...)
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 752 | @testset "random" begin
adjm = [0 1 0 1 1; # symmetric
1 0 0 0 0;
0 0 1 0 0;
1 0 0 0 1;
1 0 0 1 0]
start = 1
fg = FeaturedGraph(adjm)
@test random_walk(adjm, start) ⊆ [2, 4, 5]
@test random_walk(fg, start) ⊆ [2, 4, 5]
@test random_walk(adjm[:, start]) ⊆ [2, 4, 5]
markov_chain = random_walk(fg, start, 5)
@test length(markov_chain) == 5
@test Set(markov_chain) ⊆ collect(1:5)
@test neighbor_sample(adjm, start) ⊆ [2, 4, 5]
@test neighbor_sample(fg, start) ⊆ [2, 4, 5]
@test neighbor_sample(adjm[:, start]) ⊆ [2, 4, 5]
neighbors = neighbor_sample(fg, start, 5, replace=true)
@test length(neighbors) == 5
@test Set(neighbors) ⊆ [2, 4, 5]
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 765 | using GraphSignals
using CUDA
using Distances
using Flux
using FillArrays
using Graphs
using LinearAlgebra
using MLUtils
using NNlib
using SimpleWeightedGraphs
using SparseArrays
using StatsBase
using Test
CUDA.allowscalar(false)
include("test_utils.jl")
cuda_tests = [
"cuda/linalg",
"cuda/featuredgraph",
"cuda/sparsematrix",
"cuda/sparsegraph",
"cuda/graphdomain",
]
tests = [
"positional",
"graph",
"linalg",
"sparsegraph",
"graphdomain",
"graphsignal",
"featuredgraph",
"subgraph",
"random",
"neighbor_graphs",
"dataloader",
"tokenizer",
]
if CUDA.functional()
append!(tests, cuda_tests)
end
@testset "GraphSignals.jl" begin
for t in tests
include("$(t).jl")
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 7822 | @testset "SparseGraph" begin
T = Float32
@testset "undirected graph" begin
# undirected graph with self loop
V = 5
E = 5
adjm = [0 1 0 1 1;
1 0 0 0 0;
0 0 1 0 0;
1 0 0 0 1;
1 0 0 1 0]
adjl = Vector{Int64}[
[2, 4, 5],
[1],
[3],
[1, 5],
[1, 4]
]
@testset "constructor" begin
ug = SimpleGraph(V)
add_edge!(ug, 1, 2); add_edge!(ug, 1, 4); add_edge!(ug, 1, 5)
add_edge!(ug, 3, 3); add_edge!(ug, 4, 5)
wug = SimpleWeightedGraph(V)
add_edge!(wug, 1, 2, 2); add_edge!(wug, 1, 4, 2); add_edge!(wug, 1, 5, 1)
add_edge!(wug, 3, 3, 5); add_edge!(wug, 4, 5, 2)
for g in [adjm, adjl, ug, wug]
sg = SparseGraph(g, false, T)
@test (sg.S .!= 0) == adjm
@test sg.edges == [1, 3, 4, 1, 2, 3, 5, 4, 5]
@test sg.E == E
@test eltype(sg) == T
end
end
@testset "conversions" begin
sg = SparseGraph(adjm, false, T)
@test GraphSignals.adjacency_matrix(sg) == adjm
@test collect(sg) == adjm
@test SparseArrays.sparse(sg) == adjm
@test adjacency_list(sg) == adjl
end
sg = SparseGraph(adjm, false, T)
@test nv(sg) == V
@test ne(sg) == E
@test !Graphs.is_directed(sg)
@test !Graphs.is_directed(typeof(sg))
@test repr(sg) == "SparseGraph{Float32}(#V=5, #E=5)"
@test Graphs.has_self_loops(sg)
@test !Graphs.has_self_loops(SparseGraph([0 1; 1 0], false, T))
@test !GraphSignals.has_all_self_loops(sg)
@test GraphSignals.has_all_self_loops(SparseGraph([1 1; 1 1], false, T))
@test sg == SparseGraph(adjm, false, T)
@test graph(sg) == sg
@test Graphs.has_vertex(sg, 3)
@test Graphs.vertices(sg) == 1:V
@test Graphs.edgetype(sg) == typeof((1, 5))
@test Graphs.has_edge(sg, 1, 5)
@test edge_index(sg, 1, 5) == 4
@test sg[1, 5] == 1
@test sg[CartesianIndex((1, 5))] == 1
@test length(edges(sg)) == 9
el = GraphSignals.to_namedtuple(sg)
@test el.N == V
@test el.E == E
@test el.es == [1, 3, 4, 1, 2, 3, 5, 4, 5]
@test el.nbrs == [2, 4, 5, 1, 3, 1, 5, 1, 4]
@test el.xs == [1, 1, 1, 2, 3, 4, 4, 5, 5]
@test GraphSignals.edgevals(sg) == sg.edges
@test GraphSignals.edgevals(sg, 1) == sg.edges[1:3]
@test GraphSignals.edgevals(sg, 1:2) == sg.edges[1:4]
# graph without edges
sg_no_edge = SparseGraph(zeros(V, V), false, T)
es, nbrs, xs = collect(edges(sg_no_edge))
@test es == []
@test nbrs == []
@test xs == []
@test Graphs.neighbors(sg, 1) == adjl[1]
@test Graphs.neighbors(sg, 3) == adjl[3]
@test incident_edges(sg, 1) == [1, 3, 4]
@test incident_edges(sg, 3) == [2]
@test GraphSignals.dsts(sg) == [1, 3, 1, 1, 4]
@test GraphSignals.srcs(sg) == [2, 3, 4, 5, 5]
@test outneighbors(sg) == [[2, 4, 5], [1], [3], [1, 5], [1, 4]]
@test inneighbors(sg) == [[2, 4, 5], [1], [3], [1, 5], [1, 4]]
@testset "subgraph" begin
nodes = [1, 2, 4, 5]
ss = subgraph(sg, nodes)
@test nv(ss) == length(nodes)
@test_skip ne(ss) == 4
@test !Graphs.is_directed(ss)
@test !Graphs.is_directed(typeof(ss))
@test eltype(sg) == T
@test repr(ss) == "subgraph of SparseGraph{Float32}(#V=5, #E=5) with nodes=[1, 2, 4, 5]"
@test !Graphs.has_self_loops(ss)
@test !GraphSignals.has_all_self_loops(ss)
@test sparse(ss) == [0 1 1 1;
1 0 0 0;
1 0 0 1;
1 0 1 0]
@test !Graphs.has_vertex(ss, 3)
@test Graphs.vertices(ss) == nodes
@test Graphs.edgetype(ss) == typeof((1, 5))
@test Graphs.has_edge(ss, 1, 5)
@test_skip edge_index(ss, 1, 5) == 4
@test_skip ss[1, 5] == 1
@test_skip ss[CartesianIndex((1, 5))] == 1
@test subgraph(ss, [1, 4, 5]) == subgraph(sg, [1, 4, 5])
end
end
@testset "directed graph" begin
# directed graph with self loop
V = 5
E = 7
adjm = [0 0 1 0 1;
1 0 0 0 0;
0 0 0 0 0;
0 0 1 1 1;
1 0 0 0 0]
adjl = Vector{Int64}[
[2, 5],
[],
[1, 4],
[4],
[1, 4],
]
@testset "constructor" begin
dg = SimpleDiGraph(V)
add_edge!(dg, 1, 2); add_edge!(dg, 1, 5); add_edge!(dg, 3, 1)
add_edge!(dg, 3, 4); add_edge!(dg, 4, 4); add_edge!(dg, 5, 1)
add_edge!(dg, 5, 4)
wdg = SimpleWeightedDiGraph(V)
add_edge!(wdg, 1, 2, 2); add_edge!(wdg, 1, 5, 2); add_edge!(wdg, 3, 1, 1)
add_edge!(wdg, 3, 4, 5); add_edge!(wdg, 4, 4, 2); add_edge!(wdg, 5, 1, 2)
add_edge!(wdg, 5, 4, 4)
for g in [adjm, adjl, dg, wdg]
sg = SparseGraph(g, true, T)
@test (sg.S .!= 0) == adjm
@test sg.edges == collect(1:7)
@test sg.E == E
@test eltype(sg) == T
end
end
@testset "conversions" begin
sg = SparseGraph(adjm, true, T)
@test GraphSignals.adjacency_matrix(sg) == adjm
@test collect(sg) == adjm
@test SparseArrays.sparse(sg) == adjm
@test adjacency_list(sg) == adjl
end
sg = SparseGraph(adjm, true, T)
@test nv(sg) == V
@test ne(sg) == E
@test Graphs.is_directed(sg)
@test Graphs.is_directed(typeof(sg))
@test repr(sg) == "SparseGraph{Float32}(#V=5, #E=7)"
@test Graphs.has_self_loops(sg)
@test !GraphSignals.has_all_self_loops(sg)
@test sg == SparseGraph(adjm, true, T)
@test Graphs.has_vertex(sg, 3)
@test Graphs.vertices(sg) == 1:V
@test Graphs.edgetype(sg) == typeof((3, 1))
@test Graphs.has_edge(sg, 3, 1)
@test edge_index(sg, 3, 1) == 3
@test sg[1, 3] == 1
@test sg[CartesianIndex((1, 3))] == 1
@test length(edges(sg)) == E
es, nbrs, xs = collect(edges(sg))
@test es == collect(1:7)
@test nbrs == [2, 5, 1, 4, 4, 1, 4]
@test xs == [1, 1, 3, 3, 4, 5, 5]
@test GraphSignals.edgevals(sg) == sg.edges
@test GraphSignals.edgevals(sg, 1) == sg.edges[1:2]
@test GraphSignals.edgevals(sg, 1:2) == sg.edges[1:2]
# graph without edges
sg_no_edge = SparseGraph(zeros(V, V), true, T)
es, nbrs, xs = collect(edges(sg_no_edge))
@test es == []
@test nbrs == []
@test xs == []
@test Graphs.neighbors(sg, 1) == adjl[1]
@test Graphs.neighbors(sg, 2) == adjl[2]
@test_throws ArgumentError Graphs.neighbors(sg, 2, dir=:none)
@test incident_edges(sg, 1, dir=:out) == [1, 2]
@test incident_edges(sg, 1, dir=:in) == [3, 6]
@test sort!(incident_edges(sg, 1, dir=:both)) == [1, 2, 3, 6]
@test_throws ArgumentError incident_edges(sg, 2, dir=:none)
@test GraphSignals.dsts(sg) == [2, 5, 1, 4, 4, 1, 4]
@test GraphSignals.srcs(sg) == [1, 1, 3, 3, 4, 5, 5]
@test outneighbors(sg) == [[2, 5], [], [1, 4], [4], [1, 4]]
@test inneighbors(sg) == [[3, 5], [1], [], [3, 4, 5], [1]]
end
end | GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 4683 | @testset "subgraph" begin
T = Float64
V = 5
vdim = 3
nf = rand(vdim, V)
gf = rand(7)
nodes = [1,2,3,5]
@testset "undirected graph" begin
E = 5
ef = rand(5, E)
adjm = T[0 1 0 1 0; # symmetric
1 0 1 0 0;
0 1 0 1 0;
1 0 1 0 0;
0 0 0 0 1]
fg = FeaturedGraph(adjm, nf=nf, ef=ef, gf=gf)
subg = FeaturedSubgraph(fg, nodes)
@test graph(subg) === graph(fg)
@test subgraph(fg, nodes) == subg
@test is_directed(subg) == is_directed(fg)
@test adjacency_matrix(subg) == view(adjm, nodes, nodes)
@test adjacency_matrix(subg) isa SubArray
@test node_feature(subg) == nf
@test edge_feature(subg) == ef
@test global_feature(subg) == gf
new_nf = rand(vdim, V)
new_subg = ConcreteFeaturedGraph(subg, nf=new_nf)
@test node_feature(new_subg) == new_nf
@test edge_feature(new_subg) == ef
@test global_feature(new_subg) == gf
@test vertices(subg) == nodes
@test edges(subg) == [1,2,5]
@test neighbors(subg) == [2, 4, 1, 3, 2, 4, 5]
@test incident_edges(subg) == [1, 3, 1, 2, 2, 4, 5]
@test GraphSignals.degrees(subg) == [2, 2, 2, 1]
@test GraphSignals.degree_matrix(subg) == diagm([2, 2, 2, 1])
@test GraphSignals.normalized_adjacency_matrix(subg) ≈ [0 .5 0 0;
.5 0 .5 0;
0 .5 0 0;
0 0 0 1]
@test GraphSignals.laplacian_matrix(subg) == [2 -1 0 0;
-1 2 -1 0;
0 -1 2 0;
0 0 0 0]
@test GraphSignals.normalized_laplacian(subg) ≈ [1 -.5 0 0;
-.5 1 -.5 0;
0 -.5 1 0;
0 0 0 0]
@test GraphSignals.scaled_laplacian(subg) ≈ [0 -.5 0 0;
-.5 0 -.5 0;
0 -.5 0 0;
0 0 0 -1]
rand_subgraph = sample(subg, 3)
@test rand_subgraph isa FeaturedSubgraph
@test length(rand_subgraph.nodes) == 3
@test rand_subgraph.nodes ⊆ subg.nodes
end
@testset "directed graph" begin
E = 16
ef = rand(5, E)
adjm = [1 1 0 1 0; # asymmetric
1 1 1 0 0;
0 1 1 1 1;
1 0 1 1 0;
1 0 1 0 1]
fg = FeaturedGraph(adjm, nf=nf, ef=ef, gf=gf)
subg = FeaturedSubgraph(fg, nodes)
@test graph(subg) === graph(fg)
@test subgraph(fg, nodes) == subg
@test is_directed(subg) == is_directed(fg)
@test adjacency_matrix(subg) == view(adjm, nodes, nodes)
@test adjacency_matrix(subg) isa SubArray
@test node_feature(subg) == nf
@test edge_feature(subg) == ef
@test global_feature(subg) == gf
@test vertices(subg) == nodes
@test edges(subg) == [1,2,4,5,6,7,8,9,11,15,16]
@test neighbors(subg) == [1, 2, 4, 5, 1, 2, 3, 2, 3, 4, 5, 3, 5]
@test incident_edges(subg) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16]
rand_subgraph = sample(subg, 3)
@test rand_subgraph isa FeaturedSubgraph
@test length(rand_subgraph.nodes) == 3
@test rand_subgraph.nodes ⊆ subg.nodes
end
@testset "mask" begin
adj1 = [0 1 0 1; # symmetric
1 0 1 0;
0 1 0 1;
1 0 1 0]
adj2 = [1 1 0 1 0; # asymmetric
1 1 1 0 0;
0 1 1 1 1;
1 0 1 1 0;
1 0 1 0 1]
mask1 = [2, 3, 4]
mask2 = [1, 2, 3, 4]
fg1 = FeaturedGraph(adj1)
fg2 = FeaturedGraph(adj2)
gm1 = mask(fg1, mask1)
gm2 = mask(fg2, mask2)
@test subgraph(fg1, mask1) == gm1
@test subgraph(fg2, mask2) == gm2
@test adjacency_matrix(gm1) == [0 1 0;
1 0 1;
0 1 0]
@test adjacency_matrix(gm2) == [1 1 0 1;
1 1 1 0;
0 1 1 1;
1 0 1 1]
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 1504 | # From FluxML/NNlib.jl/test/test_utils.jl
using ChainRulesTestUtils
using FiniteDifferences
using Zygote
function gradtest(f, xs...; atol=1e-6, rtol=1e-6, fkwargs=NamedTuple(),
check_rrule=false,
fdm=:central,
check_broadcast=false,
skip=false, broken=false)
# TODO: revamp when https://github.com/JuliaDiff/ChainRulesTestUtils.jl/pull/166
# is merged
if check_rrule
test_rrule(f, xs...; fkwargs=fkwargs)
end
if check_broadcast
length(fkwargs) > 0 && @warn("CHECK_BROADCAST: dropping keywords args")
h = (xs...) -> sum(sin.(f.(xs...)))
else
h = (xs...) -> sum(sin.(f(xs...; fkwargs...)))
end
y_true = h(xs...)
if fdm == :central
fdm_obj = FiniteDifferences.central_fdm(5, 1)
elseif fdm == :forward
fdm_obj = FiniteDifferences.forward_fdm(5, 1)
elseif fdm == :backward
fdm_obj = FiniteDifferences.backward_fdm(5, 1)
end
# @show fdm fdm_obj
gs_fd = FiniteDifferences.grad(fdm_obj, h, xs...)
y_ad, pull = Zygote.pullback(h, xs...)
gs_ad = pull(one(y_ad))
@test y_true ≈ y_ad atol=atol rtol=rtol
for (g_ad, g_fd) in zip(gs_ad, gs_fd)
if skip
@test_skip g_ad ≈ g_fd atol=atol rtol=rtol
elseif broken
@test_broken g_ad ≈ g_fd atol=atol rtol=rtol
else
@test g_ad ≈ g_fd atol=atol rtol=rtol
end
end
return true
end | GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 1088 | @testset "tokenizer" begin
V, E = 4, 5
batch_size = 10
adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0]
orthonormal = repeat(Matrix{Float64}(I(V)), outer=(1, 1, batch_size))
orf = GraphSignals.orthogonal_random_features(V, batch_size)
@test NNlib.batched_mul(NNlib.batched_transpose(orf), orf) ≈ orthonormal
orf = GraphSignals.orthogonal_random_features(adjm, batch_size)
@test NNlib.batched_mul(NNlib.batched_transpose(orf), orf) ≈ orthonormal
node_id = node_identifier(adjm, batch_size; method=GraphSignals.orthogonal_random_features)
@test NNlib.batched_mul(NNlib.batched_transpose(node_id), node_id) ≈ orthonormal
node_id = node_identifier(adjm, batch_size; method=GraphSignals.laplacian_matrix)
@test NNlib.batched_mul(NNlib.batched_transpose(node_id), node_id) ≈ orthonormal
@test GraphSignals.laplacian_matrix(adjm, batch_size) == node_id
node_id, edge_id = identifiers(adjm, batch_size)
@test size(node_id) == (2V, V, batch_size)
@test size(edge_id) == (2V, 2E, batch_size)
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 1192 | T = Float32
@testset "cuda/featuredgraph" begin
@testset "undirected graph" begin
# undirected graph with self loop
V = 5
E = 5
nf = rand(10, V)
adjm = T[0 1 0 1 1;
1 0 0 0 0;
0 0 1 0 0;
1 0 0 0 1;
1 0 0 1 0]
fg = FeaturedGraph(adjm; directed=:undirected, nf=nf) |> gpu
@test has_graph(fg)
@test has_node_feature(fg)
@test !has_edge_feature(fg)
@test !has_global_feature(fg)
@test graph(fg) isa SparseGraph
@test node_feature(fg) isa CuMatrix{T}
end
@testset "directed graph" begin
# directed graph with self loop
V = 5
E = 7
nf = rand(10, V)
adjm = T[0 0 1 0 1;
1 0 0 0 0;
0 0 0 0 0;
0 0 1 1 1;
1 0 0 0 0]
fg = FeaturedGraph(adjm; directed=:directed, nf=nf) |> gpu
@test has_graph(fg)
@test has_node_feature(fg)
@test !has_edge_feature(fg)
@test !has_global_feature(fg)
@test graph(fg) isa SparseGraph
@test node_feature(fg) isa CuMatrix{T}
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 780 | T = Float32
@testset "cuda/graphdomains" begin
d = GraphSignals.NullDomain() |> gpu
@test isnothing(GraphSignals.domain(d))
@test isnothing(positional_feature(d))
@test !has_positional_feature(d)
pf = rand(T, 2, 3, 4)
d = GraphSignals.NodeDomain(pf) |> gpu
@test collect(GraphSignals.domain(d)) == pf
@test collect(positional_feature(d)) == pf
@test has_positional_feature(d)
V = 5
nf = rand(10, V)
pf = rand(10, V)
adjm = T[0 1 0 1 1;
1 0 0 0 0;
0 0 1 0 0;
1 0 0 0 1;
1 0 0 1 0]
fg = FeaturedGraph(adjm; nf=nf, pf=pf) |> gpu
gs = gradient(x -> sum(positional_feature(FeaturedGraph(x))), fg)[1]
@test :domain in keys(gs.pf)
@test gs.pf.domain isa CuArray
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 6633 | T = Float32
@testset "cuda/linalg" begin
in_channel = 3
out_channel = 5
N = 6
adjs = Dict(
:simple => [0. 1. 1. 0. 0. 0.;
1. 0. 1. 0. 1. 0.;
1. 1. 0. 1. 0. 1.;
0. 0. 1. 0. 0. 0.;
0. 1. 0. 0. 0. 0.;
0. 0. 1. 0. 0. 0.],
:weight => [0. 2. 2. 0. 0. 0.;
2. 0. 1. 0. 2. 0.;
2. 1. 0. 5. 0. 2.;
0. 0. 5. 0. 0. 0.;
0. 2. 0. 0. 0. 0.;
0. 0. 2. 0. 0. 0.],
)
degs = Dict(
:simple => [2. 0. 0. 0. 0. 0.;
0. 3. 0. 0. 0. 0.;
0. 0. 4. 0. 0. 0.;
0. 0. 0. 1. 0. 0.;
0. 0. 0. 0. 1. 0.;
0. 0. 0. 0. 0. 1.],
:weight => [4. 0. 0. 0. 0. 0.;
0. 5. 0. 0. 0. 0.;
0. 0. 10. 0. 0. 0.;
0. 0. 0. 5. 0. 0.;
0. 0. 0. 0. 2. 0.;
0. 0. 0. 0. 0. 2.]
)
laps = Dict(
:simple => [2. -1. -1. 0. 0. 0.;
-1. 3. -1. 0. -1. 0.;
-1. -1. 4. -1. 0. -1.;
0. 0. -1. 1. 0. 0.;
0. -1. 0. 0. 1. 0.;
0. 0. -1. 0. 0. 1.],
:weight => [4. -2. -2. 0. 0. 0.;
-2. 5. -1. 0. -2. 0.;
-2. -1. 10. -5. 0. -2.;
0. 0. -5. 5. 0. 0.;
0. -2. 0. 0. 2. 0.;
0. 0. -2. 0. 0. 2.],
)
norm_laps = Dict(
:simple => [1. -1/sqrt(2*3) -1/sqrt(2*4) 0. 0. 0.;
-1/sqrt(2*3) 1. -1/sqrt(3*4) 0. -1/sqrt(3) 0.;
-1/sqrt(2*4) -1/sqrt(3*4) 1. -1/2 0. -1/2;
0. 0. -1/2 1. 0. 0.;
0. -1/sqrt(3) 0. 0. 1. 0.;
0. 0. -1/2 0. 0. 1.],
:weight => [1. -2/sqrt(4*5) -2/sqrt(4*10) 0. 0. 0.;
-2/sqrt(4*5) 1. -1/sqrt(5*10) 0. -2/sqrt(2*5) 0.;
-2/sqrt(4*10) -1/sqrt(5*10) 1. -5/sqrt(5*10) 0. -2/sqrt(2*10);
0. 0. -5/sqrt(5*10) 1. 0. 0.;
0. -2/sqrt(2*5) 0. 0. 1. 0.;
0. 0. -2/sqrt(2*10) 0. 0. 1.]
)
@testset "undirected graph" begin
adjm = [0 1 0 1;
1 0 1 0;
0 1 0 1;
1 0 1 0]
deg = [2 0 0 0;
0 2 0 0;
0 0 2 0;
0 0 0 2]
isd = [√2, √2, √2, √2]
lap = [2 -1 0 -1;
-1 2 -1 0;
0 -1 2 -1;
-1 0 -1 2]
norm_lap = [1. -.5 0. -.5;
-.5 1. -.5 0.;
0. -.5 1. -.5;
-.5 0. -.5 1.]
scaled_lap = [0 -0.5 0 -0.5;
-0.5 0 -0.5 -0;
0 -0.5 0 -0.5;
-0.5 0 -0.5 0]
rw_lap = [1 -.5 0 -.5;
-.5 1 -.5 0;
0 -.5 1 -.5;
-.5 0 -.5 1]
@test GraphSignals.adjacency_matrix(adjm |> gpu, Int32) isa CuMatrix{Int32}
@test GraphSignals.adjacency_matrix(adjm |> gpu) isa CuMatrix{Int64}
fg = FeaturedGraph(T.(adjm)) |> gpu
@test collect(GraphSignals.adjacency_matrix(fg)) == adjm
@test collect(GraphSignals.degrees(fg; dir=:both)) == [2, 2, 2, 2]
D = GraphSignals.degree_matrix(fg, T, dir=:out)
@test collect(D) == T.(deg)
@test GraphSignals.degree_matrix(fg, T; dir=:in) == D
@test GraphSignals.degree_matrix(fg, T; dir=:both) == D
@test eltype(D) == T
L = Graphs.laplacian_matrix(fg, T)
@test collect(L) == T.(lap)
@test eltype(L) == T
NA = GraphSignals.normalized_adjacency_matrix(fg, T)
@test collect(NA) ≈ T.(I - norm_lap)
@test eltype(NA) == T
NA = GraphSignals.normalized_adjacency_matrix(fg, T, selfloop=true)
@test eltype(NA) == T
NL = GraphSignals.normalized_laplacian(fg, T)
@test collect(NL) ≈ T.(norm_lap)
@test eltype(NL) == T
SL = GraphSignals.scaled_laplacian(fg, T)
@test SL isa CuMatrix{T}
@test collect(SL) ≈ T.(scaled_lap)
@test eltype(SL) == T
# RW = GraphSignals.random_walk_laplacian(fg, T)
# @test RW == T.(rw_lap)
# @test eltype(RW) == T
end
# @testset "directed" begin
# adjm = [0 2 0 3;
# 0 0 4 0;
# 2 0 0 1;
# 0 0 0 0]
# degs = Dict(
# :out => diagm(0=>[2, 2, 4, 4]),
# :in => diagm(0=>[5, 4, 3, 0]),
# :both => diagm(0=>[7, 6, 7, 4]),
# )
# laps = Dict(
# :out => degs[:out] - adjm,
# :in => degs[:in] - adjm,
# :both => degs[:both] - adjm,
# )
# norm_laps = Dict(
# :out => I - diagm(0=>[1/2, 1/2, 1/4, 1/4])*adjm,
# :in => I - diagm(0=>[1/5, 1/4, 1/3, 0])*adjm,
# )
# sig_laps = Dict(
# :out => degs[:out] + adjm,
# :in => degs[:in] + adjm,
# :both => degs[:both] + adjm,
# )
# rw_laps = Dict(
# :out => I - diagm(0=>[1/2, 1/2, 1/4, 1/4]) * adjm,
# :in => I - diagm(0=>[1/5, 1/4, 1/3, 0]) * adjm,
# :both => I - diagm(0=>[1/7, 1/6, 1/7, 1/4]) * adjm,
# )
# for g in [adjm, sparse(adjm)]
# for dir in [:out, :in, :both]
# D = GraphSignals.degree_matrix(g, T, dir=dir)
# @test D == T.(degs[dir])
# @test eltype(D) == T
# L = Graphs.laplacian_matrix(g, T, dir=dir)
# @test L == T.(laps[dir])
# @test eltype(L) == T
# SL = GraphSignals.signless_laplacian(g, T, dir=dir)
# @test SL == T.(sig_laps[dir])
# @test eltype(SL) == T
# end
# @test_throws DomainError GraphSignals.degree_matrix(g, dir=:other)
# end
# for g in [adjm, sparse(adjm)]
# for dir in [:out, :in]
# L = normalized_laplacian(g, T, dir=dir)
# @test L == T.(norm_laps[dir])
# @test eltype(L) == T
# end
# for dir in [:out, :in, :both]
# RW = GraphSignals.random_walk_laplacian(g, T, dir=dir)
# @test RW == T.(rw_laps[dir])
# @test eltype(RW) == T
# end
# end
# end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 2225 | T = Float32
@testset "cuda/sparsegraph" begin
@testset "undirected graph" begin
# undirected graph with self loop
V = 5
E = 5
ef = cu(rand(10, E))
adjm = T[0 1 0 1 1;
1 0 0 0 0;
0 0 1 0 0;
1 0 0 0 1;
1 0 0 1 0]
adjl = Vector{T}[
[2, 4, 5],
[1],
[3],
[1, 5],
[1, 4]
]
sg = SparseGraph(adjm, false) |> gpu
@test (collect(sg.S) .!= 0) == adjm
@test sg.S isa CUSPARSE.CuSparseMatrixCSC{T}
@test collect(sg.edges) == [1, 3, 4, 1, 2, 3, 5, 4, 5]
@test sg.edges isa CuVector
@test sg.E == E
@test nv(sg) == V
@test ne(sg) == E
@test collect(neighbors(sg, 1)) == adjl[1]
@test collect(neighbors(sg, 2)) == adjl[2]
@test collect(GraphSignals.dsts(sg)) == [1, 3, 1, 1, 4]
@test collect(GraphSignals.srcs(sg)) == [2, 3, 4, 5, 5]
@test_throws ArgumentError GraphSignals.aggregate_index(sg, :edge, :in)
@test random_walk(sg, 1) ⊆ [2, 4, 5]
@test neighbor_sample(sg, 1) ⊆ [2, 4, 5]
end
@testset "directed graph" begin
# directed graph with self loop
V = 5
E = 7
ef = cu(rand(10, E))
adjm = T[0 0 1 0 1;
1 0 0 0 0;
0 0 0 0 0;
0 0 1 1 1;
1 0 0 0 0]
adjl = Vector{T}[
[2, 5],
[],
[1, 4],
[4],
[1, 4],
]
sg = SparseGraph(adjm, true) |> gpu
@test (collect(sg.S) .!= 0) == adjm
@test sg.S isa CUSPARSE.CuSparseMatrixCSC{T}
@test collect(sg.edges) == collect(1:7)
@test sg.edges isa CuVector
@test sg.E == E
@test nv(sg) == V
@test ne(sg) == E
@test collect(neighbors(sg, 1)) == adjl[1]
@test collect(neighbors(sg, 3)) == adjl[3]
@test Array(GraphSignals.dsts(sg)) == [2, 5, 1, 4, 4, 1, 4]
@test Array(GraphSignals.srcs(sg)) == [1, 1, 3, 3, 4, 5, 5]
@test random_walk(sg, 1) ⊆ [2, 5]
@test neighbor_sample(sg, 1) ⊆ [2, 5]
end
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | code | 245 | T = Float32
@testset "cuda/sparsematrix" begin
adjm = cu(sparse(
T[0 1 0 1;
1 0 1 0;
0 1 0 1;
1 0 1 0]))
@test collect(rowvals(adjm, 2)) == [1, 3]
@test collect(nonzeros(adjm, 2)) == [1, 1]
end
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | docs | 5163 | # Changelog
All notable changes to this project will be documented in this file.
## [0.9.2]
- update dependencies
## [0.9.1]
- fix `GraphSignals.scaled_laplacian` on `CuArray`
## [0.9.0]
- compatible to NNlib v0.9
- support Julia equals or greater than v1.9
## [0.8.6]
- update compat
## [0.8.5]
- refactor and drop Adapt dependency
## [0.8.4]
- improve performance on `orthogonal_random_features` by not collecting `qr.Q`
## [0.8.3]
- update compat
## [0.8.2]
- replace `tokenize` with `identifier`
## [0.8.1]
- update docs
## [0.8.0]
- support facilities for TokenGT: `node_identifier`, `tokenize`
## [0.7.3]
- update doc
## [0.7.2]
- fix naming issue
## [0.7.1]
- fix check number functions
## [0.7.0]
- add `NodeSignal`, `EdgeSignal` and `GlobalSignal`
- drop inplace operations for `FeaturedGraph`
- drop `parent`
- drop `NullGraph` support
## [0.6.10]
- fix gradient wrt `NodeDomain` for cuarray
## [0.6.9]
- `FeaturedSubgraph` supports `DataLoader`
## [0.6.8]
- update doc
## [0.6.7]
- fix failed gradient while `FeaturedGraph` passed to cuda
## [0.6.6]
- fix `getobs`
## [0.6.5]
- `FeaturedGraph` supports `DataLoader`, `shuffleobs` and `splitobs`
## [0.6.4]
- change `generate_coordinates` to `generate_grid`
## [0.6.3]
- move `to_namedtuple` from GeometricFlux
## [0.6.2]
- support positional encoding for `FeaturedGraph`
- add `NodeDomain` and `NullDomain`
## [0.6.1]
- support Functors v0.3
## [0.6.0]
- add positional features
## [0.5.2]
- make `kneighbors_graph` non-differentiable and enable batch learning
## [0.5.1]
- fix invalid `setfield!` for `CuSparseMatrixCSC`
## [0.5.0]
- add `kneighbors_graph`
- fix doc test and some bug
## [0.4.3]
- Resolve conflict with StatsBase
## [0.4.2]
- support `collect(edges(g))` for graph without edges
## [0.4.1]
- add `has_all_self_loops` and `isneighbors`
## [0.4.0]
- add `SparseSubgraph`
- relax `FeaturedGraph`
- drop support of `edge_scatter`, `neighbor_scatter`, `repeat_nodes` and `promote_graph`
## [0.3.13]
- fix collect for edges
## [0.3.12]
- update docs
## [0.3.11]
- inplace normalized adjacency matrix
- specify type for `FeaturedGraph`
## [0.3.10]
- add `FeaturedSubgraph` for subgraphing `FeaturedGraph`
## [0.3.9]
- add sample for generate random subgraph for `FeaturedGraph` and `FeaturedSubgraph`
- drop `cpu_neighbors` and `cpu_incident_edges`
- add `neighbors`, `incident_edges`, `repeat_nodes` for `FeaturedGraph` and `FeaturedSubgraph`
- add `parent` for `FeaturedGraph` and `FeaturedSubgraph`
- access features in `FeaturedSubgraph` change to `FeaturedGraph`
## [0.3.8]
- bug fix for message-passing network
## [0.3.7]
- correct edge direction for `has_edge` and `edge_index`
- add `has_edge` for `FeaturedGraph`
## [0.3.6]
- add random walk and neighbor sampling on graph
- add `edges` and `neighbors` as API for `FeaturedGraph`
- add `cpu_neighbors`
- add `collect` and `sparse` for `SparseGraph`
## [0.3.5]
- fix normalized_adjacency_matrix for FeaturedGraph
## [0.3.4]
- correct degree_matrix with CuSparseMatrixCSC input
- correct normalized adjacency matrix with self-loop
- adjacency_matrix returns dense arrays
## [0.3.3]
- add normalized adjacency matrix
- migrate GraphLaplacians
- migrate LightGraphs to Graphs
## [0.3.2]
- migrate LightGraphs to Graphs
## [0.3.1]
- change function name `check_num_node`, `check_num_edge` into `check_num_nodes`, `check_num_edges`
## [0.3.0]
- `FeaturedGraph` use `SparseGraph` as core graph structure
- `SparseGraph` support cuda for undirected graph and directed graph
- make `FeaturedGraph` idempotent
- make `FeaturedGraph` can be pass to gpu
- add scatter for FeaturedGraph
- update manual
- drop `fetch_graph`
## [0.2.3]
- Support gradient for neighbor_scatter and edge_scatter
- Support CUDA up to v3.3
## [0.2.2]
- EdgeIndex support adjacency matrix and juliagraphs
- add `neighbor_scatter` for scatter across neighbors
## [0.2.1]
- Support CUDA up to v3.2
- FeaturedGraph checks feature dimensions in constructors and before setting property
- add Base.show for FeaturedGraph
- add EdgeIndex and edge_scatter for providing an indexing strucutre to message-passing
- add GraphMask for masking FeaturedGraph
## [0.2.0]
- Support Julia v1.6 and CUDA v2.6 only
## [0.1.13]
- Support CUDA v2.6
- Support FillArrays v0.11
- Support Zygote v0.6
## [0.1.12]
- Dimension check should be done in layer but previous to computation
## [0.1.11]
- Refactor checking feature dimensions
- Support Julia v1.6
- Fix CuArray promotion
## [0.1.10]
- Bug fix
## [0.1.9]
- Add feature dimension check on constructor
- Refactor FeaturedGraph constructor
## [0.1.8]
- Accept transposed matrix as node feature
- Refactor
## [0.1.7]
- Support ne for adjacency list
## [0.1.6]
- Support is_directed for FeaturedGraph
- Fix test case
- Bug fix
## [0.1.5]
- Add ne for adjacency list
## [0.1.4]
- Take off dimension check
## [0.1.3]
- Bug fix
## [0.1.2]
- Laplacian matrix can be contained in FeaturedGraph
- Add dimensional check among graph, node and edge feature
- Add ne for matrix
- Add mask for FeaturedGraph
- Add fetch_graph
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | docs | 2330 | # GraphSignals.jl
[](https://yuehhua.github.io/GraphSignals.jl/stable)
[](https://yuehhua.github.io/GraphSignals.jl/dev)
[](https://travis-ci.org/yuehhua/GraphSignals.jl)
[](https://gitlab.com/JuliaGPU/GraphSignals.jl/commits/master)
A generic graph representation for combining graph signals (or features) and graph topology (or graph structure). It supports the graph structure defined in JuliaGraphs packages (i.e. LightGraphs and SimpleWeightedGraphs) and compatible with APIs in JuliaGraphs packages. Graph signals are usually features, including node feautres, edge features and graph features. Features are contained in arrays and CuArrays are supported via CUDA.jl.
## Example
```julia
julia> using GraphSignals, LightGraphs
julia> N = 4
4
julia> ug = SimpleGraph(N)
{4, 0} undirected simple Int64 graph
julia> add_edge!(ug, 1, 2); add_edge!(ug, 1, 3); add_edge!(ug, 1, 4);
julia> add_edge!(ug, 2, 3); add_edge!(ug, 3, 4);
julia> fg = FeaturedGraph(ug)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
)
julia> N = 4
4
julia> E = 5
5
julia> nf = rand(3, N);
julia> ef = rand(5, E);
julia> gf = rand(7);
julia> fg = FeaturedGraph(ug, nf=nf, ef=ef, gf=gf)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
Node feature: ℝ^3 <Matrix{Float64}>,
Edge feature: ℝ^5 <Matrix{Float64}>,
Global feature: ℝ^7 <Vector{Float64}>,
)
julia> nf = rand(3, 7);
julia> fg = FeaturedGraph(ug, nf=nf)
ERROR: DimensionMismatch("number of nodes must match between graph (4) and node features (7)")
...
```
## APIs
### Graph-related APIs
* `graph`
* `node_feature`
* `edge_feature`
* `global_feature`
* `mask`
* `has_graph`
* `has_node_feature`
* `has_edge_feature`
* `has_global_feature`
* `nv`
* `ne`
* `adjacency_list`
* `is_directed`
* `fetch_graph`
### Linear algebraic APIs
* `adjacency_matrix`
* `degrees`
* `degree_matrix`
* `inv_sqrt_degree_matrix`
* `laplacian_matrix`, `laplacian_matrix!`
* `normalized_laplacian`, `normalized_laplacian!`
* `scaled_laplacian`, `scaled_laplacian!`
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | docs | 2655 | ```@meta
CurrentModule = GraphSignals
```
# GraphSignals
GraphSignals is aim to provide a general data structure, which is composed of a graph and graph signals, in order to support a graph neural network library, specifically, GeometricFlux.jl. The concept of graph is used ubiquitously in several fields, including computer science, social science, biological science and neural science. GraphSignals provides graph signals attached to a graph as a whole for training or inference a graph neural network. Some characteristics of this package are listed:
- Graph signals can be node features, edge features or global features, which are all general arrays.
- Graph Laplacian and related matrices are supported to calculated from a general data structure.
- Support graph representations from JuliaGraphs.
## Example
`FeaturedGraph` supports various graph representations.
It supports graph in adjacency matrix.
```julia
julia> adjm = [0 1 1 1;
1 0 1 0;
1 1 0 1;
1 0 1 0];
julia> fg = FeaturedGraph(adjm)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
)
```
It also supports graph in adjacency list.
```julia
julia> adjl = [
[2, 3, 4],
[1, 3],
[1, 2, 4],
[1, 3]
];
julia> fg = FeaturedGraph(adjl)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
)
```
It supports `SimpleGraph` from LightGraphs and convert adjacency matrix into a Laplacian matrix as well.
```julia
julia> using LightGraphs
julia> N = 4
4
julia> ug = SimpleGraph(N)
{4, 0} undirected simple Int64 graph
julia> add_edge!(ug, 1, 2); add_edge!(ug, 1, 3); add_edge!(ug, 1, 4);
julia> add_edge!(ug, 2, 3); add_edge!(ug, 3, 4);
julia> fg = FeaturedGraph(ug)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
)
julia> laplacian_matrix!(fg)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in Laplacian matrix,
)
```
Features can be attached to it.
```julia
julia> N = 4
4
julia> E = 5
5
julia> nf = rand(3, N);
julia> ef = rand(5, E);
julia> gf = rand(7);
julia> fg = FeaturedGraph(ug, nf=nf, ef=ef, gf=gf)
FeaturedGraph(
Undirected graph with (#V=4, #E=5) in adjacency matrix,
Node feature: ℝ^3 <Matrix{Float64}>,
Edge feature: ℝ^5 <Matrix{Float64}>,
Global feature: ℝ^7 <Vector{Float64}>,
)
```
If there are mismatched node features attached to it, a `DimensionMismatch` is throw out and hint user.
```julia
julia> nf = rand(3, 7);
julia> fg = FeaturedGraph(ug, nf=nf)
ERROR: DimensionMismatch("number of nodes must match between graph (4) and node features (7)")
```
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | docs | 4795 | # FeaturedGraph
## Construct a FeaturedGraph and graph representations
A `FeaturedGraph` is aimed to represent a composition of graph representation and graph signals. A graph representation is required to construct a `FeaturedGraph` object. Graph representation can be accepted in several forms: adjacency matrix, adjacency list or graph representation provided from JuliaGraphs.
```julia
julia> adj = [0 1 1;
1 0 1;
1 1 0]
3×3 Matrix{Int64}:
0 1 1
1 0 1
1 1 0
julia> FeaturedGraph(adj)
FeaturedGraph(
Undirected graph with (#V=3, #E=3) in adjacency matrix,
)
```
Currently, `SimpleGraph` and `SimpleDiGraph` from LightGraphs.jl, `SimpleWeightedGraph` and `SimpleWeightedDiGraph` from SimpleWeightedGraphs.jl, as well as `MetaGraph` and `MetaDiGraph` from MetaGraphs.jl are supported.
If a graph representation is not given, a `FeaturedGraph` object will be regarded as a `NullGraph`. A `NullGraph` object is just used as a special case of `FeaturedGraph` to represent a null object.
```julia
julia> FeaturedGraph()
NullGraph()
```
### FeaturedGraph constructors
```@docs
NullGraph()
```
```@docs
FeaturedGraph
```
## Graph Signals
Graph signals is a collection of any signals defined on a graph. Graph signals can be the signals related to vertex, edges or graph itself. If a vertex signal is given, it is recorded as a node feature in `FeaturedGraph`. A node feature is stored as the form of generic array, of which type is `AbstractArray`. A node feature can be indexed by the node index, which is the same index for given graph.
Node features can be optionally given in construction of a `FeaturedGraph`.
```julia
julia> fg = FeaturedGraph(adj, nf=rand(5, 3))
FeaturedGraph(
Undirected graph with (#V=3, #E=3) in adjacency matrix,
Node feature: ℝ^5 <Matrix{Float64}>,
)
julia> has_node_feature(fg)
true
julia> node_feature(fg)
5×3 Matrix{Float64}:
0.534928 0.719566 0.952673
0.395465 0.268515 0.335446
0.79428 0.18623 0.454377
0.530675 0.402474 0.00920068
0.642556 0.719674 0.772497
```
Users check node/edge/graph features are available by `has_node_feature`, `has_edge_feature` and `has_global_feature`, respectively, and fetch these features by `node_feature`, `edge_feature` and `global_feature`.
### Getter methods
```@docs
graph
```
```@docs
node_feature
```
```@docs
edge_feature
```
```@docs
global_feature
```
### Check methods
```@docs
has_graph
```
```@docs
has_node_feature
```
```@docs
has_edge_feature
```
```@docs
has_global_feature
```
## Graph properties
`FeaturedGraph` is itself a graph, so we can query some graph properties from a `FeaturedGraph`.
```
julia> nv(fg)
3
julia> ne(fg)
3
julia> is_directed(fg)
false
```
Users can query number of vertex and number of edge by `nv` and `ne`, respectively. `is_directed` checks if the underlying graph is a directed graph or not.
### Graph-related APIs
```@docs
nv
```
```@docs
ne
```
```@docs
is_directed
```
## Pass `FeaturedGraph` to CUDA
Passing a `FeaturedGraph` to CUDA is easy. Just pipe a `FeaturedGraph` object to `gpu` provided by Flux.
```
julia> using Flux
julia> fg = fg |> gpu
FeaturedGraph(
Undirected graph with (#V=3, #E=3) in adjacency matrix,
Node feature: ℝ^5 <CuArray{Float32, 2, CUDA.Mem.DeviceBuffer}>,
)
```
## Linear algebra for `FeaturedGraph`
`FeaturedGraph` supports the calculation of graph Laplacian matrix in inplace manner.
```
julia> fg = FeaturedGraph(adj, nf=rand(5, 3))
FeaturedGraph(
Undirected graph with (#V=3, #E=3) in adjacency matrix,
Node feature: ℝ^5 <Matrix{Float64}>,
)
julia> laplacian_matrix!(fg)
FeaturedGraph(
Undirected graph with (#V=3, #E=3) in Laplacian matrix,
Node feature: ℝ^5 <Matrix{Float64}>,
)
julia> laplacian_matrix(fg)
3×3 SparseArrays.SparseMatrixCSC{Int64, Int64} with 9 stored entries:
-2 1 1
1 -2 1
1 1 -2
```
`laplacian_matrix!` mutates the adjacency matrix into a Laplacian matrix in a `FeaturedGraph` object and the Laplacian matrix can be fetched by `laplacian_matrix`. The Laplacian matrix is cached in a `FeaturedGraph` object and can be passed to a graph neural network model for training or inference. This way reduces the calculation overhead for Laplacian matrix during the training process.
`FeaturedGraph` supports not only Laplacian matrix, but also normalized Laplacian matrix and scaled Laplacian matrix calculation.
### Inplaced linear algebraic APIs
```@docs
laplacian_matrix!
```
```@docs
normalized_laplacian!
```
```@docs
scaled_laplacian!
```
### Linear algebraic APIs
Non-inplaced APIs returns a vector or a matrix directly.
```@docs
adjacency_matrix
```
```@docs
degrees
```
```@docs
degree_matrix
```
```@docs
laplacian_matrix
```
```@docs
normalized_laplacian
```
```@docs
scaled_laplacian
```
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.9.2 | 6108a8e889648f0d3951d40b2eb47e9d79fb4516 | docs | 6645 | # Sparse graph Strucutre
## The need of graph structure
Graph convolution can be classified into spectral-based graph convolution and spatial-based graph convolution. Spectral-based graph convolution relys on the algebaric operations, including `+`, `-`, `*`, which are applied to features with graph structure. Spatial-based graph convolution relys on the indexing operations, since spatial-based graph convolution always indexes the neighbors of vertex. A graph structure can be use under two view point of a part of algebaric operations or an indexing structure.
Message-passing neural network requires to access neighbor information for each vertex. Messages are passed from a vertex's neighbors to itself. A efficient indexing data structure is required to access incident edges or neighbor vertices from a specific vertex.
## `SparseGraph`
SparseGraph is implemented with sparse matrix. It is built on top of built-in sparse matrix, `SparseMatrixCSC`. `SparseMatrixCSC` can be used as a regular matrix and performs algebaric operations with matrix or vectors.
To benefit message-passing scheme, making a graph structure as an indexing structure is important. A well-designed indexing structure is made to leverage the sparse format of `SparseMatrixCSC`, which is in CSC format. CSC format stores sparse matrix in a highly compressed manner. Comparing to traditional COO format, CSC format compresses the column indices into column pointers. All values are stored in single vector. If we want to index the sparse matrix `A`, the row indices can be fetched by `rowvals[colptr[j]:(colptr[j+1]-1)]` and the non-zero values can be indexed by `nzvals[colptr[j]:(colptr[j+1]-1)]`. The edge indices are designed in the same manner `edges[colptr[j]:(colptr[j+1]-1)]`. This way matches the need of indexing neighbors of vertex. This makes neighbor indices or values close together. It takes ``O(1)`` to get negihbor indices, instead of searching neighbor in ``O(N)``. Thus, `SparseGraph` takes both advantages of both algebaric operations and indexing operations.
## Create `SparseGraph`
`SparseGraph` accepts adjacency matrix, adjacency list, and almost all graphs defined in JuliaGraphs.
```julia
julia> using GraphSignals, LightGraphs
julia> ug = SimpleGraph(4)
{4, 0} undirected simple Int64 graph
julia> add_edge!(ug, 1, 2); add_edge!(ug, 1, 3); add_edge!(ug, 1, 4);
julia> add_edge!(ug, 2, 3); add_edge!(ug, 3, 4);
julia> sg = SparseGraph(ug)
SparseGraph(#V=4, #E=5)
```
The indexed adjacency list is a list of list strucutre. The inner list consists of a series of tuples containing a vertex index and a edge index, respectively.
## Operate `SparseGraph` as graph
It supports basic graph APIs for querying graph information, including number of vertices `nv` and number of edges `ne`.
```julia
julia> is_directed(sg)
false
julia> nv(sg)
4
julia> ne(sg)
5
julia> eltype(sg)
Int64
julia> has_vertex(sg, 3)
true
julia> has_edge(sg, 1, 2)
true
```
We can compare two graph structure if they are equivalent or not.
```julia
julia> adjm = [0 1 1 1; 1 0 1 0; 1 1 0 1; 1 0 1 0]
4×4 Matrix{Int64}:
0 1 1 1
1 0 1 0
1 1 0 1
1 0 1 0
julia> sg2 = SparseGraph(adjm, false)
SparseGraph(#V=4, #E=5)
julia> sg == sg2
true
```
We can also iterate over edges.
```julia
julia> for (i, e) in edges(sg)
println("edge index: ", i, ", edge: ", e)
end
edge index: 1, edge: (2, 1)
edge index: 2, edge: (3, 1)
edge index: 3, edge: (3, 2)
edge index: 4, edge: (4, 1)
edge index: 5, edge: (4, 3)
```
Edge index is the index for each edge. It is used to index edge features.
## Indexing operations
To get neighbors of a specified vertex, `neighbors` is used by passing a `SparseGraph` object and a vertex index. A vector of neighbor vertex index is returned.
```julia
julia> neighbors(sg, 1)
3-element view(::Vector{Int64}, 1:3) with eltype Int64:
2
3
4
```
To get incident edges of a specified vertex, `incident_edges` can be used and it will return edge indices.
```julia
julia> incident_edges(sg, 1)
3-element view(::Vector{Int64}, 1:3) with eltype Int64:
1
2
4
```
An edge index can be fetched by querying an edge, for example, edge `(1, 2)` and edge `(2, 1)` refers to the same edge with index `1`.
```julia
julia> edge_index(sg, 1, 2)
1
julia> edge_index(sg, 2, 1)
1
```
One can have the opportunity to index the underlying sparse matrix.
```julia
julia> sg[1, 2]
1
julia> sg[2, 1]
1
```
## Aggregate over neighbors
In message-passing scheme, it is always to aggregate node features or edge feature from neighbors. For convention, `edge_scatter` and `neighbor_scatter` are used to apply aggregate operations over edge features or neighbor vertex features. The actual aggregation is supported by `scatter` operations.
```julia
julia> nf = rand(10, 4);
julia> neighbor_scatter(+, nf, sg)
10×4 Matrix{Float64}:
1.54937 1.03974 1.72926 1.03974
1.38554 0.775991 1.34106 0.775991
1.13192 0.424888 1.34657 0.424888
2.23452 1.63226 2.436 1.63226
0.815662 0.718865 1.25237 0.718865
2.35763 1.42174 2.26442 1.42174
1.94051 1.44812 1.71694 1.44812
1.83641 1.89104 1.80857 1.89104
2.43027 1.92217 2.37003 1.92217
1.58177 1.16149 1.87467 1.16149
```
For example, `neighbor_scatter` aggregates node features `nf` via neighbors in graph `sg` by `+` operation.
```julia
julia> ef = rand(9, 5);
julia> edge_scatter(+, ef, sg)
9×4 Matrix{Float64}:
2.22577 0.967172 1.92781 1.92628
1.4842 1.20605 2.30014 0.849819
2.20728 1.01527 0.899094 1.35062
1.09119 0.589925 1.62597 1.51175
1.42288 1.63764 1.23445 0.693258
1.57561 0.926591 1.72599 0.690108
1.68402 0.544808 1.58687 1.70676
1.10908 1.0898 1.05256 0.508157
2.33764 1.26419 1.87927 1.11151
```
Or, `edge_scatter` aggregates edge features `ef` via incident edges in graph `sg` by `+` operation.
## `SparseGraph` APIs
```@docs
SparseGraph
GraphSignals.neighbors
incident_edges
neighbor_scatter
edge_scatter
```
## Internals
In the design of `SparseGraph`, it resolve the problem of indexing edge features. For a graph, edge is represented in `(i, j)` and edge features are considered as a matrix `ef` with edge number in its column. The problem is to unifiedly fetch corresponding edge feature `ef[:, k]` for edge `(i, j)` over directed and undirected graph. To resolve this issue, edge index is set to be the unique index for each edge. Further, `aggregate_index` is designed to generate indices for aggregating from neighbor nodes or incident edges. Conclusively, it provides the core operations needed in message-passing scheme.
| GraphSignals | https://github.com/yuehhua/GraphSignals.jl.git |
|
[
"MIT"
] | 0.2.2 | 080ffb5dfb8237913a618a5b11bab85f3ef159d7 | code | 3239 | module EndpointRanges
import Base: +, -, *, /, ÷, %
using Base: ViewIndex, tail, axes1
export ibegin, iend
abstract type Endpoint end
struct IBegin <: Endpoint end
struct IEnd <: Endpoint end
const ibegin = IBegin()
const iend = IEnd()
(::IBegin)(b::Integer, e::Integer) = b
(::IEnd )(b::Integer, e::Integer) = e
(::IBegin)(r::AbstractRange) = first(r)
(::IEnd )(r::AbstractRange) = last(r)
struct IndexFunction{F<:Function} <: Endpoint
index::F
end
(f::IndexFunction)(r::AbstractRange) = f.index(r)
for op in (:+, :-)
@eval $op(x::Endpoint) = IndexFunction(r->x(r))
end
for op in (:+, :-, :*, :/, :÷, :%)
@eval $op(x::Endpoint, y::Endpoint) = IndexFunction(r->$op(x(r), y(r)))
@eval $op(x::Endpoint, y::Number) = IndexFunction(r->$op(x(r), y))
@eval $op(x::Number, y::Endpoint) = IndexFunction(r->$op(x, y(r)))
end
# deliberately not <: AbstractUnitRange{Int}
abstract type EndpointRange{T} end
struct EndpointUnitRange{F<:Union{Int,Endpoint},L<:Union{Int,Endpoint}} <: EndpointRange{Int}
start::F
stop::L
end
struct EndpointStepRange{F<:Union{Int,Endpoint},L<:Union{Int,Endpoint}} <: EndpointRange{Int}
start::F
step::Int
stop::L
end
(r::EndpointUnitRange)(s::AbstractRange) = r.start(s):r.stop(s)
(r::EndpointUnitRange{Int,E})(s::AbstractRange) where {E<:Endpoint} = r.start:r.stop(s)
(r::EndpointUnitRange{E,Int})(s::AbstractRange) where {E<:Endpoint} = r.start(s):r.stop
(r::EndpointStepRange)(s::AbstractRange) = r.start(s):r.step:r.stop(s)
(r::EndpointStepRange{Int,E})(s::AbstractRange) where {E<:Endpoint} = r.start:r.step:r.stop(s)
(r::EndpointStepRange{E,Int})(s::AbstractRange) where {E<:Endpoint} = r.start(s):r.step:r.stop
(::Colon)(start::Endpoint, stop::Endpoint) = EndpointUnitRange(start, stop)
(::Colon)(start::Endpoint, stop::Int) = EndpointUnitRange(start, stop)
(::Colon)(start::Int, stop::Endpoint) = EndpointUnitRange(start, stop)
(::Colon)(start::Endpoint, step::Int, stop::Endpoint) = EndpointStepRange(start, step, stop)
(::Colon)(start::Endpoint, step::Int, stop::Int) = EndpointStepRange(start, step, stop)
(::Colon)(start::Int, step::Int, stop::Endpoint) = EndpointStepRange(start, step, stop)
function Base.getindex(r::UnitRange, s::EndpointRange)
getindex(r, newindex(axes1(r), s))
end
function Base.getindex(r::AbstractUnitRange, s::EndpointRange)
getindex(r, newindex(axes1(r), s))
end
function Base.getindex(r::StepRange, s::EndpointRange)
getindex(r, newindex(axes1(r), s))
end
function Base.getindex(r::StepRangeLen, s::EndpointRange)
getindex(r, newindex(axes1(r), s))
end
function Base.getindex(r::LinRange, s::EndpointRange)
getindex(r, newindex(axes1(r), s))
end
@inline function Base.to_indices(A, inds, I::Tuple{Union{Endpoint, EndpointRange}, Vararg{Any}})
(newindex(inds[1], I[1]), to_indices(A, inds[2:end], Base.tail(I))...)
end
@inline newindices(indsA, inds) = (newindex(indsA[1], inds[1]), newindices(tail(indsA), tail(inds))...)
newindices(::Tuple{}, ::Tuple{}) = ()
newindex(indA, i::Union{Real, AbstractArray, Colon}) = i
newindex(indA, i::EndpointRange) = i(indA)
newindex(indA, i::IBegin) = first(indA)
newindex(indA, i::IEnd) = last(indA)
newindex(indA, i::Endpoint) = i(indA)
end # module
| EndpointRanges | https://github.com/JuliaArrays/EndpointRanges.jl.git |
|
[
"MIT"
] | 0.2.2 | 080ffb5dfb8237913a618a5b11bab85f3ef159d7 | code | 1523 | using EndpointRanges
using Test
@testset "One dimensional" begin
r1 = -3:7
r2 = 2:5
@test ibegin(r1) == -3
@test ibegin(r2) == 2
@test iend(r1) == 7
@test iend(r2) == 5
@test (ibegin+3)(r1) == 0
@test (ibegin+2)(r2) == 4
@test (iend+3)(r1) == 10
@test (iend-2)(r2) == 3
for a in (1:20,
range(1,step=2,length=20),
1.0:2.0:39.0,
range(1,stop=100,length=20),
collect(1:20),
view(0:21, 2:21))
@test a[ibegin] == a[1]
@test a[iend] == a[end]
@test a[ibegin+1] == a[2]
@test a[iend-1] == a[end-1]
@test_throws BoundsError a[ibegin-1]
@test_throws BoundsError a[iend+1]
@test a[ibegin:20] == a[1:20]
@test a[1:iend] == a[1:20]
@test a[ibegin+2:iend-3] == a[3:17]
@test a[ibegin+2:iend÷2] == a[3:10]
@test a[2*ibegin+1:iend÷2] == a[3:10]
@test a[1:(ibegin+iend)÷2] == a[1:10]
@test view(a, 1:(ibegin+iend)÷2) == view(a, 1:10)
@test view(a, ibegin+2:iend-3) == view(a, 3:17)
end
# issue #8
a = 1:9
@test a[ibegin] == 1
@test a[iend] == 9
# issue #10
@test a[ibegin:3:iend] == 1:3:7
end
@testset "Multidimensional" begin
# issue #3
A = reshape(1:12, (3, 4))
@test A[ibegin:2, 2:iend] == A[1:2, 2:4]
A = reshape(1:20, 4, 5)
@test A[2,ibegin] == 2
@test A[2,ibegin+1] == 6
@test A[3,iend-1] == 15
@test A[ibegin+1,iend-1] == 14
end
| EndpointRanges | https://github.com/JuliaArrays/EndpointRanges.jl.git |
|
[
"MIT"
] | 0.2.2 | 080ffb5dfb8237913a618a5b11bab85f3ef159d7 | docs | 869 | # EndpointRanges
[](https://travis-ci.org/JuliaArrays/EndpointRanges.jl)
[](http://codecov.io/github/JuliaArrays/EndpointRanges.jl?branch=master)
This Julia package makes it easier to index "unconventional" arrays
(ones for which indexing does not necessarily start at 1), by defining
constants `ibegin` and `iend` that stand for the beginning and end,
respectively, of the indices range along any given dimension.
# Usage
```jl
using EndpointRanges
a = 1:20
a[ibegin:iend] == a
a[ibegin+3:iend-2] == a[4:18]
a[1:(ibegin+iend)÷2] == a[1:10]
```
Note that, unlike `3:end` you can also pass such indices as arguments to a function:
```
view(a, ibegin+2:iend-3) == view(a, 3:17)
```
| EndpointRanges | https://github.com/JuliaArrays/EndpointRanges.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 964 | module MeshCatMechanisms
export MechanismVisualizer,
animate,
MeshCatSink,
setelement!,
manipulate!
# Re-export from MeshCat.jl
export render,
Triad,
setanimation!
# Re-export from MechanismGeometries.jl
export VisualElement,
Skeleton,
URDFVisuals,
visual_elements
# Re-export from RigidBodyDynamics.jl
export set_configuration!,
Point3D
using MeshCat
using CoordinateTransformations
using RigidBodyDynamics
const rbd = RigidBodyDynamics
using RigidBodyDynamics.Graphs: ancestors, edge_to_parent, source, vertices, root
using Interpolations: interpolate, Gridded, Linear
using LoopThrottle: @throttle
using MechanismGeometries: visual_elements, VisualElement, Skeleton, URDFVisuals, AbstractGeometrySource, MeshFile
using GeometryBasics: HyperSphere, Point
include("visualizer.jl")
include("animate.jl")
include("ode_callback.jl")
include("manipulate.jl")
using .Manipulate
end # module
| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 2938 | """
animate(vis::MechanismVisualizer,
times::Vector{Float64},
configurations::Vector{Vector{Float64}};
fps::Float64=60, realtimerate::Float64=1.)
Animate the given mechanism passing through a time-coded series of
configurations by linearly interpolating the configuration vectors.
"""
function animate(vis::MechanismVisualizer,
times::Vector{Float64},
configurations::AbstractVector{<:AbstractVector{Float64}};
fps::Float64 = 60., realtimerate::Float64 = 1.)
@assert fps > 0
@assert 0 < realtimerate < Inf
state = vis.state
interpolated_configurations = interpolate((times,), configurations, Gridded(Linear()))
t0, tf = first(times), last(times)
framenum = 0
walltime0 = time()
@throttle framenum while true
t = min(tf, t0 + (time() - walltime0) * realtimerate)
q = interpolated_configurations(t)
set_configuration!(state, q)
rbd.normalize_configuration!(state)
_render_state!(vis)
framenum += 1
t == tf && break
end max_rate = fps
end
function MeshCat.Animation(mvis::MechanismVisualizer,
times::AbstractVector{<:Real},
configurations::AbstractVector{<:AbstractVector{<:Real}};
fps::Integer=30)
@assert axes(times) == axes(configurations)
interpolated_configurations = interpolate((times,), configurations, Gridded(Linear()))
animation = Animation()
num_frames = floor(Int, (times[end] - first(times)) * fps)
for frame in 0 : num_frames
time = first(times) + frame / fps
let mvis = mvis, interpolated_configurations = interpolated_configurations, time=time
atframe(animation, frame) do
set_configuration!(mvis, interpolated_configurations(time))
end
end
end
return animation
end
MeshCat.setanimation!(mvis::MechanismVisualizer, args...; kw...) =
setanimation!(visualizer(mvis), args...; kw...)
function MeshCat.setanimation!(mvis::MechanismVisualizer,
times::AbstractVector{<:Real},
configurations::AbstractVector{<:AbstractVector{<:Real}};
fps::Integer=30,
play::Bool=true,
repetitions::Integer=1)
Base.depwarn("""
`setanimation!(mvis, times, configurations; ..)` is deprecated. Instead, you can construct an `Animation` and then call `setanimation!` with the result.
For example, if you previously did:
```
setanimation!(mvis, times, configurations, fps=30, play=true)
```
You should now do:
```
animation = Animation(mvis, times, configurations, fps=25)
setanimation!(mvis, animation, play=true)
```
""", :setanimation_t_q)
animation = Animation(mvis, times, configurations, fps=fps)
setanimation!(mvis, animation, play=play, repetitions=repetitions)
end
| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 2913 | module Manipulate
export manipulate!
using MeshCatMechanisms
using RigidBodyDynamics
using RigidBodyDynamics: Bounds, position_bounds, lower, upper
using InteractBase: slider, Widget, observe, vbox
using OrderedCollections: OrderedDict
function remove_infs(b::Bounds, default=Float64(π))
Bounds(isfinite(lower(b)) ? lower(b) : -default,
isfinite(upper(b)) ? upper(b) : default)
end
slider_range(joint::Joint) = remove_infs.(position_bounds(joint))
function slider_range(joint::Joint{T, <: QuaternionFloating}) where {T}
defaults = [1., 1, 1, 1, 10, 10, 10]
remove_infs.(position_bounds(joint), defaults)
end
slider_labels(joint::Joint) = [string("q", i) for i in 1:num_positions(joint)]
slider_labels(joint::Joint{T, <:QuaternionFloating}) where {T} = ["rw", "rx", "ry", "rz", "x", "y", "z"]
function sliders(joint::Joint, values=clamp.(zeros(num_positions(joint)), position_bounds(joint));
bounds=slider_range(joint),
labels=slider_labels(joint),
resolution=0.01, prefix="")
map(bounds, labels, values) do b, label, value
num_steps = ceil(Int, (upper(b) - lower(b)) / resolution)
r = range(lower(b), stop=upper(b), length=num_steps)
slider(range(lower(b), stop=upper(b), length=num_steps),
value=clamp(value, first(r), last(r)),
label=string(prefix, label))
end
end
function combined_observable(joint::Joint, sliders::AbstractVector)
map(observe.(sliders)...) do args...
q = vcat(args...)
normalize_configuration!(q, joint)
q
end
end
function widget(joint::Joint{T, <:Fixed}, args...) where T
Widget{:rbd_joint}()
end
function widget(joint::Joint, initial_value=clamp.(zeros(num_positions(joint)), position_bounds(joint)); prefix=string(joint, '.'))
s = sliders(joint, initial_value, prefix=prefix)
keys = Symbol.(slider_labels(joint))
w = Widget{:rbd_joint}(OrderedDict(zip(keys, s)))
w.output = combined_observable(joint, s)
w.layout = x -> vbox(s...)
w
end
function manipulate!(callback::Function, state::MechanismState)
joint_list = joints(state.mechanism)
widgets = widget.(joint_list, configuration.(state, joint_list))
keys = Symbol.(joint_list)
w = Widget{:rbd_manipulator}(OrderedDict(zip(keys, widgets)))
w.output = map(observe.(widgets)...) do signals...
for i in 1:length(joint_list)
if num_positions(joint_list[i]) > 0
set_configuration!(state, joint_list[i], signals[i])
end
end
callback(state)
end
w.layout = x -> vbox(widgets...)
w
end
function manipulate!(callback::Function, vis::MechanismVisualizer)
manipulate!(vis.state) do x
set_configuration!(vis, configuration(x))
callback(x)
end
end
manipulate!(vis::MechanismVisualizer) = manipulate!(x -> nothing, vis)
end | MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 770 | mutable struct MeshCatSink{M <: MechanismState} <: rbd.OdeIntegrators.OdeResultsSink
vis::MechanismVisualizer{M}
min_wall_Δt::Float64
last_update_wall_time::Float64
function MeshCatSink(vis::MechanismVisualizer{M}; max_fps::Float64 = 60.) where {M <: MechanismState}
new{M}(vis, 1 / max_fps, -Inf)
end
end
function rbd.OdeIntegrators.initialize(sink::MeshCatSink, t, state)
sink.last_update_wall_time = -Inf
rbd.OdeIntegrators.process(sink, t, state)
end
function rbd.OdeIntegrators.process(sink::MeshCatSink, t, state)
wall_Δt = time() - sink.last_update_wall_time
if wall_Δt > sink.min_wall_Δt
set_configuration!(sink.vis, configuration(state))
sink.last_update_wall_time = time()
end
nothing
end
| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 7342 | struct MechanismVisualizer{M <: MechanismState, V <: AbstractVisualizer}
state::M
visualizer::V
modcount::Int
function MechanismVisualizer(state::M, vis::V) where {M <: MechanismState, V <: AbstractVisualizer}
new{M, V}(state, vis, rbd.modcount(state.mechanism))
end
end
function MechanismVisualizer(state::MechanismState, source::AbstractGeometrySource=Skeleton(), vis::AbstractVisualizer=Visualizer())
vis = MechanismVisualizer(state, vis)
setelement!(vis, source)
vis
end
function setelement!(vis::MechanismVisualizer, source::AbstractGeometrySource)
elements = visual_elements(mechanism(vis), source)
_set_mechanism!(vis, elements)
_render_state!(vis)
end
MechanismVisualizer(m::Mechanism, args...) = MechanismVisualizer(MechanismState{Float64}(m), args...)
state(mvis::MechanismVisualizer) = mvis.state
mechanism(mvis::MechanismVisualizer) = mvis.state.mechanism
visualizer(mvis::MechanismVisualizer) = mvis.visualizer
to_affine_map(tform::Transform3D) = AffineMap(rotation(tform), translation(tform))
function _set_mechanism!(mvis::MechanismVisualizer, elements::AbstractVector{<:VisualElement})
for (i, element) in enumerate(elements)
setelement!(mvis, element, "geometry_$i")
end
end
Base.getindex(mvis::MechanismVisualizer, x...) = getindex(mvis.visualizer, x...)
# TODO: much of this information can be cached if this
# method becomes a performance bottleneck.
# We can probably just put `@memoize` from Memoize.jl right here.
function Base.getindex(mvis::MechanismVisualizer, frame::CartesianFrame3D)
body = rbd.body_fixed_frame_to_body(mechanism(mvis), frame)
mvis[body][string(frame)]
end
function Base.getindex(mvis::MechanismVisualizer, body::RigidBody)
path = _path(mechanism(mvis), body)
mvis[path...]
end
"""
setelement!(mvis::MechanismVisualizer, element::VisualElement, name::AbstractString="<element>")
Attach the given visual element to the visualizer.
The element's frame will determine how its geometry is attached to the scene
tree, so that any other geometries attached to the same body will all move together.
"""
function setelement!(mvis::MechanismVisualizer, element::VisualElement, name::AbstractString="<element>")
setelement!(mvis, element.frame, element.geometry, MeshLambertMaterial(color=element.color), name)
settransform!(mvis[element.frame][name], element.transform)
end
"""
setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, object::AbstractObject, name::AbstractString="<element>")
Attach the given geometric object (geometry + material) to the visualizer at the given frame
"""
function setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, object::AbstractObject, name::AbstractString="<element>")
body = rbd.body_fixed_frame_to_body(mechanism(mvis), frame)
definition = rbd.frame_definition(body, frame)
frame_vis = mvis[frame]
settransform!(frame_vis, to_affine_map(definition))
setobject!(frame_vis[name], object)
end
"""
setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, geometry::GeometryLike, name::AbstractString="<element>")
Attach the given geometry to the visualizer at the given frame, using its default material.
"""
function setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, geometry::GeometryLike, name::AbstractString="<element>")
setelement!(mvis, frame, Object(geometry), name)
end
"""
setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, geometry::GeometryLike, material::AbstractMaterial, name::AbstractString="<element>")
Construct an object with the given geometry and material and attach it to the visualizer
"""
function setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, geometry::GeometryLike, material::AbstractMaterial, name::AbstractString="<element>")
setelement!(mvis, frame, Object(geometry, material), name)
end
function setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, geometry::MeshFile, material::AbstractMaterial, name::AbstractString="<element>")
ext = lowercase(splitext(geometry.filename)[2])
# We load .dae files as MeshFileObject so that threejs can handle loading
# their built-in primitives, materials, and textures. All other meshes are
# loaded as MeshFileGeometry which uses MeshIO to load the mesh geometry in
# Julia (but does not currently handle any materials or textures).
if ext == ".dae"
obj = MeshFileObject(geometry.filename)
else
obj = Object(MeshFileGeometry(geometry.filename), material)
end
setelement!(mvis, frame, obj, name)
end
# Special cases for visualizing frames and points
"""
setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, scale::Real=0.5, name::AbstractString="<element>")
Add a Triad geometry with the given scale to the visualizer at the specified frame
"""
function setelement!(mvis::MechanismVisualizer, frame::CartesianFrame3D, scale::Real=0.5, name::AbstractString="<element>")
setelement!(mvis, frame, Triad(scale), name)
end
"""
setelement!(mvis::MechanismVisualizer, point::Point3D, radius::Real=0.05, name::AbstractString="<element>")
Add a HyperSphere geometry with the given radius to the visualizer at the given point
"""
function setelement!(mvis::MechanismVisualizer, point::Point3D, radius::Real=0.05, name::AbstractString="<element>")
setelement!(mvis, point.frame, HyperSphere(Point(point.v[1], point.v[2], point.v[3]), convert(eltype(point.v), radius)), name)
end
function _path(mechanism, body)
body_ancestors = ancestors(body, mechanism.tree)
path = string.(reverse(body_ancestors))
end
function _render_state!(mvis::MechanismVisualizer, state::MechanismState=mvis.state)
@assert mvis.state.mechanism === state.mechanism
if rbd.modcount(state.mechanism) != mvis.modcount
error("Mechanism has been modified after creating the visualizer. Please create a new MechanismVisualizer")
end
vis = mvis.visualizer
tree = mechanism(mvis).tree # TODO: tree accessor?
for body in vertices(tree)
if body == root(tree)
continue
else
parent = source(edge_to_parent(body, tree), tree)
tform = relative_transform(state, default_frame(body), default_frame(parent))
settransform!(mvis[body], to_affine_map(tform))
end
end
end
"""
set_configuration!(mvis::MechanismVisualizer, args...)
Set the configuration of the mechanism visualizer and re-render it.
# Examples
```julia-repl
julia> set_configuration!(vis, [1., 2., 3.])
```
```julia-repl
julia> set_configuration!(vis, findjoint(robot, "shoulder"), 1.0)
```
"""
function rbd.set_configuration!(mvis::MechanismVisualizer, args...)
set_configuration!(mvis.state, args...)
_render_state!(mvis)
end
rbd.configuration(mvis::MechanismVisualizer, args...) = configuration(mvis.state, args...)
MeshCat.render(mvis::MechanismVisualizer, args...; kw...) = MeshCat.render(mvis.visualizer, args...; kw...)
Base.open(mvis::MechanismVisualizer, args...; kw...) = open(mvis.visualizer, args...; kw...)
Base.wait(mvis::MechanismVisualizer) = wait(mvis.visualizer)
function Base.copyto!(mvis::MechanismVisualizer, state::Union{MechanismState, AbstractVector})
copyto!(mvis.state, state)
_render_state!(mvis)
end
| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | code | 4735 | using Test
using MeshCat
using MeshCatMechanisms
using RigidBodyDynamics
using RigidBodyDynamics.OdeIntegrators
using CoordinateTransformations: Translation
using ValkyrieRobot
using NBInclude
using StaticArrays
vis = Visualizer()
@testset "MeshCatMechanisms" begin
@testset "URDF mechanism" begin
urdf = joinpath(@__DIR__, "urdf", "Acrobot.urdf")
robot = parse_urdf(urdf, remove_fixed_tree_joints=false)
mvis = MechanismVisualizer(robot, URDFVisuals(urdf), vis)
if !haskey(ENV, "CI")
open(mvis)
wait(mvis)
end
set_configuration!(mvis, [0, -0.5])
set_configuration!(mvis, findjoint(robot, "shoulder"), 1.0)
@test configuration(mvis) == [1.0, -0.5]
@test configuration(mvis, findjoint(robot, "shoulder")) == [1.0]
copyto!(mvis, [0.1, -0.6, 0.0, 0.0])
@test configuration(mvis) == [0.1, -0.6]
setelement!(mvis, default_frame(bodies(robot)[end]))
setelement!(mvis, Point3D(default_frame(bodies(robot)[3]), 0.2, 0.2, 0.2))
@testset "simulation and animation" begin
state = MechanismState(robot, randn(2), randn(2))
t, q, v = simulate(state, 5.0);
animate(mvis, t, q)
animation = Animation(mvis, t, q)
setanimation!(mvis, animation)
end
@testset "deprecated `setanimation!`" begin
state = MechanismState(robot, randn(2), randn(2))
t, q, v = simulate(state, 5.0);
animate(mvis, t, q)
setanimation!(mvis, t, q)
end
end
@testset "URDF with fixed joints" begin
urdf = joinpath(@__DIR__, "urdf", "Acrobot_fixed.urdf")
robot = parse_urdf(urdf)
delete!(vis)
mvis = MechanismVisualizer(robot, URDFVisuals(urdf), vis)
set_configuration!(mvis, [0.5])
@testset "simulation and animation" begin
state = MechanismState(robot, randn(1), randn(1))
t, q, v = simulate(state, 5.0);
animate(mvis, t, q)
setanimation!(mvis, Animation(mvis, t, q))
end
end
@testset "Valkyrie" begin
val = Valkyrie();
delete!(vis)
mvis = MechanismVisualizer(
val.mechanism,
URDFVisuals(ValkyrieRobot.urdfpath(), package_path=[ValkyrieRobot.packagepath()]),
vis[:val_urdf])
end
@testset "valkyrie inertias" begin
val = Valkyrie();
mvis = MechanismVisualizer(
val.mechanism,
Skeleton(),
vis[:val_inertia])
settransform!(vis[:val_inertia], Translation(0, 2, 0))
end
@testset "visualization during simulation" begin
urdf = joinpath(@__DIR__, "urdf", "Acrobot.urdf")
robot = parse_urdf(urdf, remove_fixed_tree_joints=false)
mvis = MechanismVisualizer(robot, URDFVisuals(urdf), vis[:acrobot][:robot])
settransform!(vis[:acrobot], Translation(0, -2, 0))
result = DynamicsResult{Float64}(robot)
function damped_dynamics!(vd::AbstractArray, sd::AbstractArray, t, state)
damping = 2.
τ = -damping * velocity(state)
dynamics!(result, state, τ)
copyto!(vd, result.v̇)
copyto!(sd, result.ṡ)
nothing
end
state = MechanismState(robot, randn(2), randn(2))
integrator = MuntheKaasIntegrator(state, damped_dynamics!, runge_kutta_4(Float64), MeshCatSink(mvis))
integrate(integrator, 10., 1e-3, max_realtime_rate = 1.)
end
@testset "position bounds resolution" begin
j = Joint("foo", Revolute(SVector(1., 0, 0)))
RigidBodyDynamics.position_bounds(j) .= RigidBodyDynamics.Bounds(-1.234, 0.0)
MeshCatMechanisms.Manipulate.sliders(j)
MeshCatMechanisms.Manipulate.widget(j)
end
@testset "manipulation" begin
delete!(vis)
mechanism = rand_chain_mechanism(Float64, [QuaternionFloating{Float64}; [Revolute{Float64} for i = 1:5]]...)
mvis = MechanismVisualizer(mechanism)
widget = manipulate!(mvis)
end
@testset "manipulation - negative bounds issue" begin
mechanism = rand_chain_mechanism(Float64, Revolute{Float64})
joint = first(joints(mechanism))
joint.position_bounds .= RigidBodyDynamics.Bounds(-2.0, -1.0)
mvis = MechanismVisualizer(mechanism)
widget = manipulate!(mvis)
end
@testset "examples" begin
dir = joinpath(@__DIR__, "..", "examples")
for file in readdir(dir)
base, ext = splitext(file)
if ext == ".jl"
@info "Running $file"
include(joinpath(dir, file))
end
end
end
end
| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.9.0 | b766636d31175340e542c833cff1895c2f3f41cc | docs | 1774 | # MeshCatMechanisms
[](https://github.com/JuliaRobotics/MeshCatMechanisms.jl/actions?query=workflow%3ACI)
[](http://codecov.io/github/JuliaRobotics/MeshCatMechanisms.jl?branch=master)
MeshCatMechanisms.jl adds support for visualizing mechanisms and robots from [RigidBodyDynamics.jl](https://github.com/tkoolen/RigidBodyDynamics.jl) with [MeshCat.jl](https://github.com/rdeits/MeshCat.jl). All geometries are constructed using [MechanismGeometries.jl](https://github.com/rdeits/MechanismGeometries.jl).
Features:
* Parsing geometry directly from URDF files
* Animation of robot trajectories from RigidBodyDynamics.jl simulations
* Live rendering of simulation progress using the `OdeIntegrators.OdeResultsSink` interface
* Interactive manipulation of the mechanism configuration using [InteractBase.jl](https://github.com/piever/InteractBase.jl)
## Related Projects
MeshCatMechanisms.jl provides similar functionality to [RigidBodyTreeInspector.jl](https://github.com/rdeits/RigidBodyTreeInspector.jl), but is built on top of the lighter-weight MeshCat viewer instead of [DrakeVisualizer.jl](https://github.com/rdeits/DrakeVisualizer.jl).
# Installation
Stable release:
```julia
Pkg.add("MeshCatMechanisms")
```
Latest and greatest:
```julia
Pkg.add("MeshCatMechanisms")
Pkg.clone("https://github.com/rdeits/MechanismGeometries.jl")
Pkg.checkout("MeshCatMechanisms")
Pkg.checkout("MeshCat")
```
# Usage
See [examples/demo.ipynb](examples/demo.ipynb)
# Examples

| MeshCatMechanisms | https://github.com/JuliaRobotics/MeshCatMechanisms.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 814 | const _pkg_root = dirname(dirname(@__FILE__))
const _pkg_deps = joinpath(_pkg_root,"deps")
const _pkg_assets = joinpath(_pkg_root,"assets")
!isdir(_pkg_assets) && mkdir(_pkg_assets)
deps = [
"https://use.fontawesome.com/releases/v5.0.7/js/all.js",
"https://cdn.jsdelivr.net/gh/piever/[email protected]/highlight/prism.css",
"https://cdn.jsdelivr.net/gh/piever/[email protected]/highlight/prism.js",
"https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/11.1.0/nouislider.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/11.1.0/nouislider.min.css",
"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css"
]
for dep in deps
download(dep, joinpath(_pkg_assets, splitdir(dep)[2]))
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 2514 | module InteractBase
using WebIO, OrderedCollections, Observables, CSSUtil, Colors, JSExpr
import Observables: ObservablePair, AbstractObservable
import JSExpr: JSString
using Random
using Dates
using Base64: stringmime
using JSON
using Knockout
using Knockout: js_lambda
using Widgets
import Widgets:
observe,
AbstractWidget,
div,
Widget,
widget,
widgettype,
@layout!,
components,
input,
spinbox,
textbox,
textarea,
autocomplete,
datepicker,
timepicker,
colorpicker,
checkbox,
toggle,
filepicker,
opendialog,
savedialog,
slider,
rangeslider,
rangepicker,
button,
dropdown,
radiobuttons,
checkboxes,
toggles,
togglebuttons,
tabs,
entry,
latex,
alert,
highlight,
notifications,
confirm,
togglecontent,
tabulator,
accordion,
mask,
tooltip!,
wdglabel,
slap_design!,
@manipulate,
manipulatelayout,
triggeredby,
onchange
import Observables: throttle
export observe, Widget, widget
export @manipulate
export filepicker, opendialog, savedialog, datepicker, timepicker, colorpicker, spinbox
export autocomplete, input, dropdown, checkbox, textbox, textarea, button, toggle, togglecontent
export slider, rangeslider, rangepicker
export radiobuttons, togglebuttons, tabs, checkboxes, toggles
export latex, alert, confirm, highlight, notifications, accordion, tabulator, mask
export onchange
export settheme!, resettheme!, gettheme, availablethemes, NativeHTML
export slap_design!
abstract type WidgetTheme<:Widgets.AbstractBackend; end
struct NativeHTML<:WidgetTheme; end
const font_awesome = joinpath(@__DIR__, "..", "assets", "all.js")
const prism_js = joinpath(@__DIR__, "..", "assets", "prism.js")
const prism_css = joinpath(@__DIR__, "..", "assets", "prism.css")
const highlight_css = joinpath(@__DIR__, "..", "assets", "highlight.css")
const nouislider_min_js = joinpath(@__DIR__, "..", "assets", "nouislider.min.js")
const nouislider_min_css = joinpath(@__DIR__, "..", "assets", "nouislider.min.css")
const style_css = joinpath(@__DIR__, "..", "assets", "style.css")
include("classes.jl")
include("backends.jl")
include("utils.jl")
include("input.jl")
include("slider.jl")
include("optioninput.jl")
include("layout.jl")
include("output.jl")
include("modifiers.jl")
function __init__()
if Widgets.get_backend() === Widgets.DummyBackend()
Widgets.set_backend!(NativeHTML())
end
end
end # module
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 915 | libraries(::WidgetTheme) = [style_css]
Base.@deprecate_binding backend Widgets.backends
const themes = OrderedDict{Symbol, WidgetTheme}(:nativehtml => NativeHTML())
registertheme!(key::Union{Symbol, AbstractString}, val::WidgetTheme) = setindex!(themes, val, Symbol(key))
"""
`settheme!(s::Union{Symbol, AbstractString})`
Set theme of Interact globally. See `availablethemes()` to know what themes are currently available.
"""
function settheme!(s::Union{Symbol, AbstractString})
theme = get(themes, Symbol(s)) do
error("Theme $s is not available.")
end
settheme!(theme)
end
settheme!(b::WidgetTheme) = isa(Widgets.get_backend(), WidgetTheme) && Widgets.set_backend!(b)
gettheme() = isa(Widgets.get_backend(), WidgetTheme) ? Widgets.get_backend() : nothing
availablethemes() = sort(collect(keys(themes)))
resettheme!() = isa(Widgets.get_backend(), WidgetTheme) && Widgets.reset_backend!()
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 1942 | mergeclasses(args...) = join(args, ' ')
getclass(args...) = getclass(gettheme(), args...)
function getclass(T::WidgetTheme, arg, typ...)
length(typ) > 0 && last(typ) == "label" && return ""
if arg == :input
typ==() && return "input"
typ[1] in ["checkbox", "radio"] && return "is-checkradio"
typ[1]=="toggle" && return "switch"
typ==("range",) && return "slider"
typ==("range", "fullwidth") && return "slider is-fullwidth"
typ==("rangeslider", "horizontal",) && return "rangeslider rangeslider-horizontal"
typ==("rangeslider", "vertical",) && return "rangeslider rangeslider-vertical"
if typ[1]=="file"
typ[2:end]==() && return "file"
typ[2:end]==("span",) && return "file-cta"
typ[2:end]==("span", "icon") && return "file-icon"
typ[2:end]==("span","label") && return "file-label"
typ[2:end]==("icon",) && return "fas fa-upload"
typ[2:end]==("label",) && return "file-label"
typ[2:end]==("name",) && return "file-name"
end
return "input"
elseif arg == :dropdown
return typ == (true,) ? "select is-multiple" : "select"
elseif arg == :button
typ==("primary",) && return "is-primary"
typ==("active",) && return "is-primary is-selected"
typ==("fullwidth",) && return "is-fullwidth"
return "is-medium button"
elseif arg==:tab
typ==("active",) && return "is-active"
return "not-active"
elseif arg == :textarea
return "textarea"
elseif arg==:wdglabel
return "interact"
elseif arg==:div
return "field"
elseif arg==:togglebuttons
return "buttons has-addons is-centered"
elseif arg==:tabs
return "tabs"
elseif arg==:radiobuttons
return "field"
elseif arg==:ijulia
return "interactbulma"
else
return ""
end
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 16517 | _basename(v::AbstractArray) = basename.(v)
_basename(::Nothing) = nothing
_basename(v) = basename(v)
"""
`filepicker(label="Choose a file..."; multiple=false, accept="*")`
Create a widget to select files.
If `multiple=true` the observable will hold an array containing the paths of all
selected files. Use `accept` to only accept some formats, e.g. `accept=".csv"`
"""
function filepicker(theme::WidgetTheme, lbl="Choose a file..."; attributes=PropDict(),
label=lbl, className="", multiple=false, value=multiple ? String[] : "", kwargs...)
(value isa AbstractObservable) || (value = Observable{Any}(value))
filename = Observable{Any}(_basename(value[]))
if multiple
onFileUpload = js"""function (data, e){
var files = e.target.files;
var fileArray = Array.from(files);
this.filename(fileArray.map(function (el) {return el.name;}));
return this.path(fileArray.map(function (el) {return el.path;}));
}
"""
else
onFileUpload = js"""function(data, e) {
var files = e.target.files;
this.filename(files[0].name);
return this.path(files[0].path);
}
"""
end
multiple && (attributes=merge(attributes, PropDict(:multiple => true)))
attributes = merge(attributes, PropDict(:type => "file", :style => "display: none;",
Symbol("data-bind") => "event: {change: onFileUpload}"))
className = mergeclasses(getclass(theme, :input, "file"), className)
template = dom"div[style=display:flex; align-items:center;]"(
node(:label, className=getclass(theme, :input, "file", "label"))(
node(:input; className=className, attributes=attributes, kwargs...),
node(:span,
node(:span, (node(:i, className = getclass(theme, :input, "file", "icon"))), className=getclass(theme, :input, "file", "span", "icon")),
node(:span, label, className=getclass(theme, :input, "file", "span", "label")),
className=getclass(theme, :input, "file", "span"))
),
node(:span, attributes = Dict("data-bind" => " text: filename() == '' ? 'No file chosen' : filename()"),
className = getclass(theme, :input, "file", "name"))
)
observs = ["path" => value, "filename" => filename]
ui = knockout(template, observs, methods = ["onFileUpload" => onFileUpload])
slap_design!(ui, theme)
Widget{:filepicker}(observs, scope = ui, output = ui["path"], layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
"""
`opendialog(; value = String[], label = "Open", icon = "far fa-folder-open", options...)`
Creates an [Electron openDialog](https://electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options-callback).
`value` is the list of selected files or folders. `options` (given as keyword arguments) correspond to
`options` of the Electron dialog. This widget will not work in the browser but only in an Electron window.
## Examples
```jldoctest
julia> ui = InteractBase.opendialog(; properties = ["showHiddenFiles", "multiSelections"], filters = [(; name = "Text", extensions = ["txt", "md"])]);
julia> ui[]
0-element Array{String,1}
```
"""
opendialog(theme::WidgetTheme; value = String[], label = "Open", icon = "far fa-folder-open", kwargs...) =
dialog(theme, js"showOpenDialog"; value = value, label = label, icon = icon, kwargs...)
"""
`savedialog(; value = String[], label = "Open", icon = "far fa-folder-open", options...)`
Create an [Electron saveDialog](https://electronjs.org/docs/api/dialog#dialogshowsavedialogbrowserwindow-options-callback).
`value` is the list of selected files or folders. `options` (given as keyword arguments) correspond to
`options` of the Electron dialog. This widget will not work in the browser but only in an Electron window.
## Examples
```jldoctest
julia> ui = InteractBase.savedialog(; properties = ["showHiddenFiles"], filters = [(; name = "Text", extensions = ["txt", "md"])]);
julia> ui[]
""
```
"""
savedialog(theme::WidgetTheme; value = "", label = "Save", icon = "far fa-save", kwargs...) =
dialog(theme, js"showSaveDialog"; value = value, label = label, icon = icon, kwargs...)
function dialog(theme::WidgetTheme, dialogtype; value, className = "", label = "dialog", icon = nothing, options...)
(value isa AbstractObservable) || (value = Observable(value))
scp = Scope()
setobservable!(scp, "output", value)
clicks = Observable(scp, "clicks", 0)
callback = @js function (val)
$value[] = val
end
onimport(scp, js"""
function () {
const { dialog } = require('electron').remote;
this.dialog = dialog;
}
""")
onjs(clicks, js"""
function (val) {
console.log(this.dialog.$dialogtype($options, $callback));
}
""")
className = mergeclasses(getclass(theme, :button), className)
content = if icon === nothing
(label,)
else
iconNode = node(:span, node(:i, className = icon), className = "icon")
(iconNode, node(:span, label))
end
btn = node(:button, content...,
events=Dict("click" => @js event -> ($clicks[] = $clicks[] + 1)),
className = className)
scp.dom = btn
slap_design!(scp, theme)
Widget{:dialog}([]; output = value, scope = scp, layout = Widgets.scope)
end
_parse(::Type{S}, x) where{S} = parse(S, x)
function _parse(::Type{Dates.Time}, x)
segments = split(x, ':')
length(segments) >= 2 && all(!isempty, segments) || return nothing
h, m = parse.(Int, segments)
Dates.Time(h, m)
end
function _string(x::Dates.Time)
h = Dates.hour(x)
m = Dates.minute(x)
string(lpad(h, 2, "0"), ":", lpad(m, 2, "0"))
end
_string(x::Dates.Date) = string(x)
"""
`datepicker(value::Union{Dates.Date, Observable, Nothing}=nothing)`
Create a widget to select dates.
"""
function datepicker end
"""
`timepicker(value::Union{Dates.Time, Observable, Nothing}=nothing)`
Create a widget to select times.
"""
function timepicker end
for (func, typ, str, unit) in [(:timepicker, :(Dates.Time), "time", Dates.Second), (:datepicker, :(Dates.Date), "date", Dates.Day) ]
@eval begin
function $func(theme::WidgetTheme, val=nothing; value=val, kwargs...)
(value isa AbstractObservable) || (value = Observable{Union{$typ, Nothing}}(value))
f = x -> x === nothing ? "" : _string(x)
g = t -> _parse($typ, t)
pair = ObservablePair(value, f=f, g=g)
ui = input(theme, pair.second; typ=$str, kwargs...)
Widget{$(Expr(:quote, func))}(ui, output = value)
end
function $func(theme::WidgetTheme, vals::AbstractRange, val=medianelement(vals); value=val, kwargs...)
f = x -> x === nothing ? "" : _string(x)
fs = x -> x === nothing ? "" : split(string(convert($unit, x)), ' ')[1]
min, max = extrema(vals)
$func(theme; value=value, min=f(min), max=f(max), step=fs(step(vals)), kwargs...)
end
end
end
"""
`colorpicker(value::Union{Color, Observable}=colorant"#000000")`
Create a widget to select colors.
"""
function colorpicker(theme::WidgetTheme, val=colorant"#000000"; value=val, kwargs...)
(value isa AbstractObservable) || (value = Observable{Color}(value))
f = t -> "#"*hex(t)
g = t -> parse(Colorant,t)
pair = ObservablePair(value, f=f, g=g)
ui = input(theme, pair.second; typ="color", kwargs...)
Widget{:colorpicker}(ui, output = value)
end
"""
`spinbox([range,] label=""; value=nothing)`
Create a widget to select numbers with placeholder `label`. An optional `range` first argument
specifies maximum and minimum value accepted as well as the step. Use `step="any"` to allow all
decimal numbers.
"""
function spinbox(theme::WidgetTheme, label=""; value=nothing, placeholder=label, isinteger=nothing, kwargs...)
isinteger === nothing || @warn "`isinteger` is deprecated"
if !isa(value, AbstractObservable)
T = something(isinteger, isa(value, Integer)) ? Int : Float64
value = Observable{Union{T, Nothing}}(value)
end
ui = input(theme, value; isnumeric=true, placeholder=placeholder, typ="number", kwargs...)
Widget{:spinbox}(ui; output = value)
end
spinbox(theme::WidgetTheme, vals::AbstractRange, args...; value=first(vals), kwargs...) =
spinbox(theme, args...; value=value, min=minimum(vals), max=maximum(vals), step=step(vals), kwargs...)
"""
`autocomplete(options, label=""; value="")`
Create a textbox input with autocomplete options specified by `options`, with `value`
as initial value and `label` as label.
"""
function autocomplete(::WidgetTheme, options, args...; attributes=PropDict(), kwargs...)
(options isa AbstractObservable) || (options = Observable{Any}(options))
option_array = _js_array(options)
s = gensym()
attributes = merge(attributes, PropDict(:list => s))
t = textbox(args...; extra_obs=["options_js" => option_array], attributes=attributes, kwargs...)
Widgets.scope(t).dom = node(:div,
Widgets.scope(t).dom,
node(:datalist, node(:option, attributes=Dict("data-bind"=>"value : key"));
attributes = Dict("data-bind" => "foreach : options_js", "id" => s))
)
w = Widget{:autocomplete}(t)
w[:options] = options
w
end
"""
`input(o; typ="text")`
Create an HTML5 input element of type `type` (e.g. "text", "color", "number", "date") with `o`
as initial value.
"""
@noinline function input(theme::WidgetTheme, o; extra_js=js"", extra_obs=[], label=nothing, typ="text", wdgtyp=typ,
className="", style=Dict(), isnumeric=Knockout.isnumeric(o),
computed=[], attributes=Dict(), bind="value", bindto="value", valueUpdate="input", changes=0, kwargs...)
(o isa AbstractObservable) || (o = Observable(o))
(changes isa AbstractObservable) || (changes = Observable(changes))
data = Pair{String, Any}["changes" => changes, bindto => o]
if isnumeric && bind == "value"
bind = "numericValue"
end
append!(data, (string(key) => val for (key, val) in extra_obs))
countChanges = js_lambda("this.changes(this.changes()+1)")
attrDict = merge(
attributes,
Dict(:type => typ,
Symbol("data-bind") => "$bind: $bindto, valueUpdate: '$valueUpdate', event: {change: $countChanges}"
)
)
className = mergeclasses(getclass(theme, :input, wdgtyp), className)
template = node(:input; className=className, attributes=attrDict, style=style, kwargs...)()
ui = knockout(template, data, extra_js; computed=computed)
(label != nothing) && (ui.dom = flex_row(wdglabel(theme, label), ui.dom))
slap_design!(ui, theme)
Widget{:input}(data, scope = ui, output = ui[bindto], layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
@noinline function input(theme::WidgetTheme; typ="text", kwargs...)
if typ in ["checkbox", "radio"]
o = false
elseif typ in ["number", "range"]
o = 0.0
else
o = ""
end
input(theme, o; typ=typ, kwargs...)
end
"""
`button(content... = "Press me!"; value=0)`
A button. `content` goes inside the button.
Note the button `content` supports a special `clicks` variable, that gets incremented by `1`
with each click e.g.: `button("clicked {{clicks}} times")`.
The `clicks` variable is initialized at `value=0`. Given a button `b`, `b["is-loading"]` defines
whether the button is in a loading state (spinning wheel). Use `b["is-loading"][]=true` or
`b["is-loading"][]=false` respectively to display or take away the spinner.
"""
function button(theme::WidgetTheme, content...; label = "Press me!", value = 0, style = Dict{String, Any}(),
className = getclass(theme, :button, "primary"), attributes=Dict(), kwargs...)
isempty(content) && (content = (label,))
(value isa AbstractObservable) || (value = Observable(value))
loading = Observable(false)
className = "delete" in split(className, ' ') ? className : mergeclasses(getclass(theme, :button), className)
countClicks = js_lambda("this.clicks(this.clicks()+1)")
attrdict = merge(
Dict("data-bind"=>"click: $countClicks, css: {'is-loading' : loading}"),
attributes
)
template = node(:button, content...; className=className, attributes=attrdict, style=style, kwargs...)
button = knockout(template, ["clicks" => value, "loading" => loading])
slap_design!(button, theme)
Widget{:button}(["is-loading" => loading], scope = button, output = value,
layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
for wdg in [:toggle, :checkbox]
@eval begin
$wdg(theme::WidgetTheme, value, lbl::AbstractString=""; label=lbl, kwargs...) =
$wdg(theme; value=value, label=label, kwargs...)
$wdg(theme::WidgetTheme, label::AbstractString, val=false; value=val, kwargs...) =
$wdg(theme; value=value, label=label, kwargs...)
$wdg(theme::WidgetTheme, value::AbstractString, label::AbstractString; kwargs...) =
error("value cannot be a string")
function $wdg(theme::WidgetTheme; bind="checked", valueUpdate="change", value=false, label="", labelclass="", kwargs...)
s = gensym() |> string
(label isa Tuple) || (label = (label,))
widgettype = $(Expr(:quote, wdg))
wdgtyp = string(widgettype)
labelclass = mergeclasses(getclass(theme, :input, wdgtyp, "label"), labelclass)
ui = input(theme, value; bind=bind, typ="checkbox", valueUpdate="change", wdgtyp=wdgtyp, id=s, kwargs...)
Widgets.scope(ui).dom = node(:div, className = "field interact-widget")(Widgets.scope(ui).dom, dom"label[className=$labelclass, for=$s]"(label...))
Widget{widgettype}(ui)
end
end
end
"""
`checkbox(value::Union{Bool, AbstractObservable}=false; label)`
A checkbox.
e.g. `checkbox(label="be my friend?")`
"""
function checkbox end
"""
`toggle(value::Union{Bool, AbstractObservable}=false; label)`
A toggle switch.
e.g. `toggle(label="be my friend?")`
"""
function toggle end
"""
`textbox(hint=""; value="")`
Create a text input area with an optional placeholder `hint`
e.g. `textbox("enter number:")`. Use `typ=...` to specify the type of text. For example
`typ="email"` or `typ="password"`. Use `multiline=true` to display a `textarea` spanning
several lines.
"""
function textbox(theme::WidgetTheme, hint=""; multiline=false, placeholder=hint, value="", typ="text", kwargs...)
multiline && return textarea(theme; placeholder=placeholder, value=value, kwargs...)
Widget{:textbox}(input(theme, value; typ=typ, placeholder=placeholder, kwargs...))
end
"""
`textarea(hint=""; value="")`
Create a textarea with an optional placeholder `hint`
e.g. `textarea("enter number:")`. Use `rows=...` to specify how many rows to display
"""
function textarea(theme::WidgetTheme, hint=""; label=nothing, className="",
placeholder=hint, value="", attributes=Dict(), style=Dict(), bind="value", valueUpdate = "input", kwargs...)
(value isa AbstractObservable) || (value = Observable(value))
attrdict = convert(PropDict, attributes)
attrdict[:placeholder] = placeholder
attrdict["data-bind"] = "$bind: value, valueUpdate: '$valueUpdate'"
className = mergeclasses(getclass(theme, :textarea), className)
template = node(:textarea; className=className, attributes=attrdict, style=style, kwargs...)
ui = knockout(template, ["value" => value])
(label != nothing) && (ui.dom = flex_row(wdglabel(theme, label), ui.dom))
slap_design!(ui, theme)
Widget{:textarea}(scope = ui, output = ui["value"], layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
function wdglabel(theme::WidgetTheme, text; padt=5, padr=10, padb=0, padl=10,
className="", style = Dict(), kwargs...)
className = mergeclasses(getclass(theme, :wdglabel), className)
padding = Dict(:padding=>"$(padt)px $(padr)px $(padb)px $(padl)px")
node(:label, text; className=className, style = merge(padding, style), kwargs...)
end
function flex_row(a,b,c=dom"div"())
node(
:div,
node(:div, a, className = "interact-flex-row-left"),
node(:div, b, className = "interact-flex-row-center"),
node(:div, c, className = "interact-flex-row-right"),
className = "interact-flex-row interact-widget"
)
end
flex_row(a) = node(:div, a, className = "interact-flex-row interact-widget")
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 426 | center(w) = flex_row(w)
center(w::Widget) = w
center(w::Widget{:toggle}) = flex_row(w)
manipulatelayout(::WidgetTheme) = t -> node(:div, map(center, values(components(t)))..., map(center, t.output))
function widget(::WidgetTheme, x::Observable; label = nothing)
if label === nothing
x
else
Widget{:observable}(["label" => label], output = x, layout = t -> flex_row(t["label"], t.output))
end
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 655 | """
`tooltip!(wdg::AbstractWidget, tooltip; className = "")`
Experimental. Add a tooltip to widget wdg. `tooltip` is the text that will be shown and `className`
can be used to customize the tooltip, for example `is-tooltip-bottom` or `is-tooltip-danger`.
"""
function tooltip!(wdg::AbstractWidget, args...; kwargs...)
tooltip!(node(wdg)::Node, args...; kwargs...)
return wdg
end
function tooltip!(n::Node, tooltip; className = "")
d = props(n)
get!(d, :attributes, Dict{String, Any})
get!(d, :className, "")
d[:attributes]["data-tooltip"] = tooltip
d[:className] = mergeclasses(d[:className], className, "tooltip")
n
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 15797 | struct Automatic; end
const automatic = Automatic()
function _js_array(x::AbstractDict; process=string, placeholder=nothing)
v = OrderedDict[OrderedDict("key" => key, "val" => i, "id" => "id"*randstring()) for (i, (key, val)) in enumerate(x)]
placeholder !== nothing && pushfirst!(v, OrderedDict("key" => placeholder, "val" => 0, "id" => "id"*randstring()))
return v
end
function _js_array(x::AbstractArray; process=string, placeholder=nothing)
v = OrderedDict[OrderedDict("key" => process(val), "val" => i, "id" => "id"*randstring()) for (i, val) in enumerate(x)]
placeholder !== nothing && pushfirst!(v, OrderedDict("key" => placeholder, "val" => 0, "id" => "id"*randstring()))
return v
end
function _js_array(o::AbstractObservable; process=string, placeholder=nothing)
map(t -> _js_array(t; process=process, placeholder=placeholder), o)
end
struct Vals2Idxs{T} <: AbstractVector{T}
vals::Vector{T}
vals2idxs::Dict{T, Int}
function Vals2Idxs(v::AbstractArray{T}) where {T}
vals = convert(Vector{T}, v)
idxs = 1:length(vals)
vals2idxs = Dict{T, Int}(zip(vals, idxs))
new{T}(vals, vals2idxs)
end
end
Vals2Idxs(v::AbstractDict) = Vals2Idxs(collect(values(v)))
Base.parent(d::Vals2Idxs) = d.vals
Base.get(d::Vals2Idxs, key, default = 0) = get(d.vals2idxs, key, default)
Base.get(d::Vals2Idxs, key::Integer, default = 0) = get(d.vals2idxs, key, default)
getmany(d::Vals2Idxs{T}, key::AbstractArray{<:T}, default = 0) where {T} =
filter(t -> t!= 0, map(x -> get(d, x), key))
Base.getindex(d::Vals2Idxs, x::Int) = get(d.vals, x, nothing)
Base.size(d::Vals2Idxs) = size(d.vals)
function valueindexpair(value, vals2idxs, args...; multiple = false, rev = false)
_get = multiple ? getmany : get
f = x -> _get(vals2idxs[], x)
g = x -> getindex(vals2idxs[], x)
p = ObservablePair(value, args..., f=f, g=g)
on(vals2idxs) do x
p.links[rev+1].f(p[rev+1][])
end
p
end
function initvalueindex(value, index, vals2idxs;
multiple = false, default = multiple ? eltype(vals2idxs[])[] : first(vals2idxs[]), rev = false)
if value === automatic
value = (index === nothing) ? default : vals2idxs[][Observables.to_value(index)]
end
(value isa AbstractObservable) || (value = Observable{Any}(value))
if index === nothing
p = valueindexpair(value, vals2idxs; multiple = multiple, rev = rev)
index = p.second
else
(index isa AbstractObservable) || (index = Observable{Any}(index))
p = valueindexpair(value, vals2idxs, index; multiple = multiple, rev = rev)
end
return p
end
"""
```
dropdown(options::AbstractDict;
value = first(values(options)),
label = nothing,
multiple = false)
```
A dropdown menu whose item labels are the keys of options.
If `multiple=true` the observable will hold an array containing the values
of all selected items
e.g. `dropdown(OrderedDict("good"=>1, "better"=>2, "amazing"=>9001))`
`dropdown(values::AbstractArray; kwargs...)`
`dropdown` with labels `string.(values)`
see `dropdown(options::AbstractDict; ...)` for more details
"""
dropdown(T::WidgetTheme, options; kwargs...) =
dropdown(T::WidgetTheme, Observable{Any}(options); kwargs...)
"""
```
dropdown(options::AbstractObservable;
value = first(values(options[])),
label = nothing,
multiple = false)
```
A dropdown menu whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = dropdown(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
function dropdown(theme::WidgetTheme, options::AbstractObservable;
attributes=PropDict(),
placeholder = nothing,
label = nothing,
multiple = false,
value = automatic,
index = nothing,
className = "",
style = PropDict(),
div_select = nothing,
kwargs...)
div_select !== nothing && warn("`div_select` keyword is deprecated", once=true)
multiple && (attributes[:multiple] = true)
vals2idxs = map(Vals2Idxs, options)
p = initvalueindex(value, index, vals2idxs, multiple = multiple)
value, index = p.first, p.second
bind = multiple ? "selectedOptions" : "value"
option_array = _js_array(options, placeholder=placeholder)
disablePlaceholder =
js"""
function(option, item) {
ko.applyBindingsToNode(option, {disable: item.val == 0}, item);
}
"""
attrDict = merge(
Dict(Symbol("data-bind") => "options : options_js, $bind : index, optionsText: 'key', optionsValue: 'val', valueAllowUnset: true, optionsAfterRender: disablePlaceholder"),
attributes
)
className = mergeclasses(getclass(theme, :dropdown, multiple), className)
div_select === nothing && (div_select = node(:div, className = className))
template = node(:select; attributes = attrDict, kwargs...)() |> div_select
label != nothing && (template = vbox(label, template))
ui = knockout(template, ["index" => index, "options_js" => option_array];
methods = ["disablePlaceholder" => disablePlaceholder])
slap_design!(ui, theme)
Widget{:dropdown}(["options"=>options, "index" => ui["index"]], scope = ui, output = value, layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
multiselect(theme::WidgetTheme, options; kwargs...) =
multiselect(theme, Observable{Any}(options); kwargs...)
function multiselect(theme::WidgetTheme, options::AbstractObservable; container=node(:div, className=:field), wrap=identity,
label = nothing, typ="radio", wdgtyp=typ, stack=true, skip=1em, hskip=skip, vskip=skip,
value = automatic, index = nothing, kwargs...)
vals2idxs = map(Vals2Idxs, options)
p = initvalueindex(value, index, vals2idxs, multiple = (typ != "radio"))
value, index = p.first, p.second
s = gensym()
option_array = _js_array(options)
entry = wrap(InteractBase.entry(s; typ=typ, wdgtyp=wdgtyp, stack=stack, kwargs...))
(entry isa Tuple )|| (entry = (entry,))
template = container(attributes = Dict("data-bind" => "foreach : options_js"))(
entry...
)
ui = knockout(template, ["index" => index, "options_js" => option_array])
if (label != nothing)
ui.dom = stack ? vbox(label, CSSUtil.vskip(vskip), ui.dom) : hbox(label, CSSUtil.hskip(hskip), ui.dom)
end
slap_design!(ui, theme)
Widget{:radiobuttons}(["options"=>options, "index" => ui["index"]], scope = ui, output = value, layout = node(:div, className = "field interact-widget")∘Widgets.scope)
end
function entry(theme::WidgetTheme, s; className="", typ="radio", wdgtyp=typ, stack=(typ!="radio"), kwargs...)
className = mergeclasses(getclass(theme, :input, wdgtyp), className)
f = stack ? node(:div, className="field") : tuple
f(
node(:input, className = className, attributes = Dict("name" => s, "type" => typ, "data-bind" => "checked : \$root.index, checkedValue: val, attr : {id : id}"))(),
node(:label, attributes = Dict("data-bind" => "text : key, attr : {for : id}"))
)
end
"""
```
radiobuttons(options::AbstractDict;
value::Union{T, Observable} = first(values(options)))
```
e.g. `radiobuttons(OrderedDict("good"=>1, "better"=>2, "amazing"=>9001))`
`radiobuttons(values::AbstractArray; kwargs...)`
`radiobuttons` with labels `string.(values)`
see `radiobuttons(options::AbstractDict; ...)` for more details
```
radiobuttons(options::AbstractObservable; kwargs...)
```
Radio buttons whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = radiobuttons(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
radiobuttons(theme::WidgetTheme, vals; kwargs...) = multiselect(theme, vals; kwargs...)
"""
```
checkboxes(options::AbstractDict;
value = valtype(options)[]
```
A list of checkboxes whose item labels are the keys of options.
The observable will hold an array containing the values
of all selected items,
e.g. `checkboxes(OrderedDict("good"=>1, "better"=>2, "amazing"=>9001))`
`checkboxes(values::AbstractArray; kwargs...)`
`checkboxes` with labels `string.(values)`
see `checkboxes(options::AbstractDict; ...)` for more details
```
checkboxes(options::AbstractObservable; kwargs...)
```
Checkboxes whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = checkboxes(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
To create checkboxes that are already checked off when shown, one can use the `value` keyword:
```julia
options = ["a", "b", "c"]
value = ["a", "c"]
checkboxes(options, value = value)
```
The boxes "a" and "c" will be checked off when the checkboxes widget is shown.
Both `options` and `value` can be Observables.
"""
checkboxes(theme::WidgetTheme, options; kwargs...) =
Widget{:checkboxes}(multiselect(theme, options; typ="checkbox", kwargs...))
"""
```
toggles(options::AbstractDict;
value = first(values(options)))
```
A list of toggle switches whose item labels are the keys of options.
Tthe observable will hold an array containing the values
of all selected items,
e.g. `toggles(OrderedDict("good"=>1, "better"=>2, "amazing"=>9001))`
`toggles(values::AbstractArray; kwargs...)`
`toggles` with labels `string.(values)`
see `toggles(options::AbstractDict; ...)` for more details
```
toggles(options::AbstractObservable; kwargs...)
```
Toggles whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = toggles(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
toggles(theme::WidgetTheme, options; kwargs...) =
Widget{:toggles}(multiselect(theme, options; typ="checkbox", wdgtyp="toggle", kwargs...))
for wdg in [:togglebuttons, :tabs]
@eval $wdg(theme::WidgetTheme, options; kwargs...) = $wdg(theme, Observable(options); kwargs...)
end
"""
`togglebuttons(options::AbstractDict; value::Union{T, Observable}, multiple=false)`
Creates a set of toggle buttons whose labels are the keys of options. Set `multiple=true`
to allow multiple (or zero) active buttons at the same time.
`togglebuttons(values::AbstractArray; kwargs...)`
`togglebuttons` with labels `string.(values)`
see `togglebuttons(options::AbstractDict; ...)` for more details
```
togglebuttons(options::AbstractObservable; kwargs...)
```
Togglebuttons whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = togglebuttons(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
function togglebuttons(theme::WidgetTheme, options::AbstractObservable;
className = "",
activeclass = getclass(theme, :button, "active"),
multiple = false,
index = nothing, value = automatic,
container = node(:div, className = getclass(theme, :togglebuttons)), wrap=identity,
label = nothing, readout = false, vskip = 1em, kwargs...)
vals2idxs = map(Vals2Idxs, options)
p = initvalueindex(value, index, vals2idxs; multiple = multiple)
value, index = p.first, p.second
className = mergeclasses("interact-widget", getclass(theme, :button), className)
updateMethod = multiple ? js"""
function (val) {
var id = this.index.indexOf(val);
id > -1 ? this.index.splice(id, 1) : this.index.push(val);
}
""" : js"function (val) {this.index(val)}"
active = multiple ? "\$root.index().includes(val)" : "\$root.index() == val"
updateSelected = js_lambda("\$root.update(val)")
btn = node(:span,
node(:label, attributes = Dict("data-bind" => "text : key")),
attributes=Dict("data-bind"=>
"click: $updateSelected, css: {'$activeclass' : $active, '$className' : true}"),
)
option_array = _js_array(options)
template = container(attributes = "data-bind" => "foreach : options_js")(wrap(btn))
label != nothing && (template = flex_row(wdglabel(theme, label), template))
ui = knockout(template, ["index" => index, "options_js" => option_array], methods = Dict("update" => updateMethod))
slap_design!(ui, theme)
w = Widget{:togglebuttons}(["options"=>options, "index" => ui["index"], "vals2idxs" => vals2idxs];
scope = ui,
output = value,
layout = t -> div(Widgets.scope(t), className = "interact-widget"))
if readout
w[:display] = mask(map(parent, vals2idxs); index = index)
w.layout = t -> div(Widgets.scope(t), CSSUtil.vskip(vskip), t[:display], className = "interact-widget")
end
w
end
"""
`tabs(options::AbstractDict; value::Union{T, Observable})`
Creates a set of tabs whose labels are the keys of options. The label can be a link.
`tabs(values::AbstractArray; kwargs...)`
`tabs` with labels `values`
see `tabs(options::AbstractDict; ...)` for more details
```
tabs(options::AbstractObservable; kwargs...)
```
Tabs whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = tabs(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
function tabs(theme::WidgetTheme, options::AbstractObservable;
className = "",
activeclass = getclass(theme, :tab, "active"),
index = nothing, value = automatic,
container=node(:div, className = getclass(theme, :tabs)), wrap=identity,
label = nothing, readout = false, vskip = 1em, kwargs...)
vals2idxs = map(Vals2Idxs, options)
p = initvalueindex(value, index, vals2idxs; default = first(vals2idxs[]))
value, index = p.first, p.second
className = mergeclasses("interact-widget", getclass(theme, :tab), className)
updateSelected = js_lambda("\$root.index(val)")
tab = node(:li,
wrap(node(:a, attributes = Dict("data-bind" => "text: key"))),
attributes=Dict("data-bind"=>
"click: $updateSelected, css: {'$activeclass' : \$root.index() == val, '$className' : true}"),
)
option_array = _js_array(options)
template = container(
node(:ul, attributes = "data-bind" => "foreach : options_js")(tab)
)
label != nothing && (template = flex_row(wdglabel(theme, label), template))
ui = knockout(template, ["index" => index, "options_js" => option_array])
slap_design!(ui, theme)
w = Widget{:tabs}(["options"=>options, "index" => ui["index"], "vals2idxs" => vals2idxs];
scope = ui, output = value, layout = t -> div(Widgets.scope(t), className = "interact-widget"))
if readout
w[:display] = mask(map(parent, vals2idxs); index = index)
w.layout = t -> div(Widgets.scope(t), CSSUtil.vskip(vskip), t[:display], className = "interact-widget")
end
w
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 12103 | using WebIO, JSExpr
const katex_min_js = joinpath(@__DIR__, "..", "assets", "katex.min.js")
const katex_min_css = joinpath(@__DIR__, "..", "assets", "katex.min.css")
"""
`latex(txt)`
Render `txt` in LaTeX using KaTeX. Backslashes need to be escaped:
`latex("\\\\sum_{i=1}^{\\\\infty} e^i")`
"""
function latex(theme::WidgetTheme, txt)
(txt isa AbstractObservable) || (txt = Observable(txt))
w = Scope(imports=[
katex_min_js,
katex_min_css
])
w["value"] = txt
onimport(w, @js function (k)
this.k = k
this.container = this.dom.querySelector("#container")
k.render($(txt[]), this.container)
end)
onjs(w["value"], @js (txt) -> this.k.render(txt, this.container))
w.dom = dom"div#container"()
Widget{:latex}(scope = w, output = w["value"], layout = node(:div, className = "interact-widget")∘Widgets.scope)
end
"""
`alert(text="")`
Creates a `Widget{:alert}`. To cause it to trigger an alert, do:
```julia
wdg = alert("Error!")
wdg()
```
Calling `wdg` with a string will set the alert message to that string before triggering the alert:
```julia
wdg = alert("Error!")
wdg("New error message!")
```
For the javascript to work, the widget needs to be part of the UI, even though it is not visible.
"""
function alert(theme::WidgetTheme, text = ""; value = text)
value isa AbstractObservable || (value = Observable(value))
scp = WebIO.Scope()
setobservable!(scp, "text", value)
onjs(
scp["text"],
js"""function (value) {
alert(value);
}"""
)
Widget{:alert}(["text" => value]; scope = scp,
layout = t -> node(:div, Widgets.scope(t), style = Dict("display" => "none")))
end
(wdg::Widget{:alert})(text = wdg["text"][]) = (wdg["text"][] = text; return)
"""
`confirm([f,] text="")`
Creates a `Widget{:confirm}`. To cause it to trigger a confirmation dialogue, do:
```julia
wdg = confirm([f,] "Are you sure you want to unsubscribe?")
wdg()
```
`observe(wdg)` is a `Observable{Bool}` and is set to `true` if the user clicks on "OK" in the dialogue,
or to false if the user closes the dialogue or clicks on "Cancel". When `observe(wdg)` is set, the function `f`
will be called with that value.
Calling `wdg` with a string and/or a function will set the confirmation message and/or the callback function:
```julia
wdg = confirm("Are you sure you want to unsubscribe?")
wdg("File exists, overwrite?") do x
x ? print("Overwriting") : print("Aborting")
end
```
For the javascript to work, the widget needs to be part of the UI, even though it is not visible.
"""
function confirm(theme::WidgetTheme, fct::Function = x -> nothing, text::AbstractString = "")
text isa AbstractObservable || (text = Observable(text))
scp = WebIO.Scope()
setobservable!(scp, "text", text)
value = Observable(scp, "value", false)
onjs(
scp["text"],
@js function (txt)
$value[] = confirm(txt)
end
)
wdg = Widget{:confirm}(["text" => text, "function" => fct]; scope = scp, output = value,
layout = t -> node(:div, Widgets.scope(t), style = Dict("visible" => false)))
on(x -> wdg["function"](x), value)
wdg
end
confirm(theme::WidgetTheme, text::AbstractString, fct::Function = x -> nothing) = confirm(theme, fct, text)
function (wdg::Widget{:confirm})(fct::Function = wdg["function"], text::AbstractString = wdg["text"][])
wdg["function"] = fct
wdg["text"][] = text
return
end
(wdg::Widget{:confirm})(text::AbstractString, fct::Function = wdg["function"]) = wdg(fct, text)
"""
`highlight(txt; language = "julia")`
`language` syntax highlighting for `txt`.
"""
function highlight(theme::WidgetTheme, txt; language = "julia")
(txt isa AbstractObservable) || (txt = Observable(txt))
s = "code"*randstring(16)
w = Scope(imports = [
highlight_css,
prism_js,
prism_css,
])
w["value"] = txt
w.dom = node(
:div,
node(
:pre,
node(:code, className = "language-$language", attributes = Dict("id"=>s))
),
className = "content"
)
onimport(w, js"""
function (p) {
var code = document.getElementById($s);
code.innerHTML = $(txt[]);
Prism.highlightElement(code);
}
"""
)
onjs(w["value"], js"""
function (val){
var code = document.getElementById($s);
code.innerHTML = val
Prism.highlightElement(code)
}
""")
Widget{:highlight}(scope = w, output = w["value"], layout = node(:div, className = "interact-widget")∘Widgets.scope)
end
"""
`notifications(v=[]; layout = node(:div))`
Display elements of `v` inside notification boxes that can be closed with a close button.
The elements are laid out according to `layout`.
`observe` on this widget returns the observable of the list of elements that have not been deleted.
"""
function notifications(theme::WidgetTheme, v=[]; container = node(:div),
wrap = identity,
layout = (v...)->container((wrap(el) for el in v)...),
className = "")
scope = Scope()
output = Observable{Any}(v)
to_delete = Observable(scope, "to_delete", 0)
on(to_delete) do ind
v = output[]
deleteat!(v, ind)
output[] = v
end
className = mergeclasses(className, "notification")
list = map(output) do t
function create_item(ind, el)
btn = node(:button, className = "delete", events = Dict("click" =>
@js event -> $to_delete[] = $ind))
node(:div, btn, el, className = className)
end
[create_item(ind, el) for (ind, el) in enumerate(t)]
end
scope.dom = map(v -> layout(v...), list)
slap_design!(scope, theme)
Widget{:notifications}([:list => list]; output = output, scope = scope,
layout = _ -> node(:div, scope, className="interact-widget"))
end
"""
`accordion(options; multiple = true)`
Display `options` in an `accordion` menu. `options` is an `AbstractDict` whose
keys represent the labels and whose values represent what is shown in each entry.
`options` can be an `Observable`, in which case the `accordion` updates as soon as
`options` changes.
"""
function accordion(theme::WidgetTheme, options::Observable;
multiple = true, value = nothing, index = value, key = automatic)
vals2idxs = map(Vals2Idxs∘collect∘_keys, options)
p = initvalueindex(key, index, vals2idxs, rev = true, multiple = multiple)
key, index = p.first, p.second
option_array = map(x -> [OrderedDict("label" => key, "i" => i, "content" => stringmime(MIME"text/html"(), WebIO.render(val))) for (i, (key, val)) in enumerate(x)], options)
onClick = multiple ? js"function (i) {this.index.indexOf(i) > -1 ? this.index.remove(i) : this.index.push(i)}" :
js"function (i) {this.index(i)}"
isactive = multiple ? "\$root.index.indexOf(i) > -1" : "\$root.index() == i"
updateSelected = js_lambda("\$root.onClick(i)")
template = dom"section.accordions"(attributes = Dict("data-bind" => "foreach: options_js"),
node(:article, className="accordion", attributes = Dict("data-bind" => "css: {'is-active' : $isactive}", ))(
dom"div.accordion-header.toggle"(dom"p"(attributes = Dict("data-bind" => "html: label")), attributes = Dict("data-bind" => "click: $updateSelected")),
dom"div.accordion-body"(dom"div.accordion-content"(attributes = Dict("data-bind" => "html: content")))
)
)
scp = knockout(template, ["index" => index, "options_js" => option_array], methods = Dict("onClick" => onClick))
slap_design!(scp, theme)
Widget{:accordion}(["index" => index, "key" => key, "options" => options]; scope = scp, output = index, layout = node(:div, className = "interact-widget")∘Widgets.scope)
end
accordion(theme::WidgetTheme, options; kwargs...) = accordion(theme, Observable{Any}(options); kwargs...)
"""
`togglecontent(content, value::Union{Bool, Observable}=false; label)`
A toggle switch that, when activated, displays `content`
e.g. `togglecontent(checkbox("Yes, I am sure"), false, label="Are you sure?")`
"""
function togglecontent(theme::WidgetTheme, content, args...; skip = 0em, vskip = skip, kwargs...)
btn = toggle(theme, args...; kwargs...)
Widgets.scope(btn).dom = node(:div,
Widgets.scope(btn).dom,
node(:div,
content,
attributes = Dict("data-bind" => "visible: value")
),
className = "interact-widget",
style = Dict("display" => "flex", "flex-direction"=>"column")
)
Widget{:togglecontent}(btn)
end
"""
`mask(options; index, key)`
Only display the `index`-th element of `options`. If `options` is a `AbstractDict`, it is possible to specify
which option to show using `key`. `options` can be a `Observable`, in which case `mask` updates automatically.
Use `index=0` or `key = nothing` to not have any selected option.
## Examples
```julia
wdg = mask(OrderedDict("plot" => plot(rand(10)), "scatter" => scatter(rand(10))), index = 1)
wdg = mask(OrderedDict("plot" => plot(rand(10)), "scatter" => scatter(rand(10))), key = "plot")
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
function mask(theme::WidgetTheme, options; value = nothing, index = value, key = automatic, multiple = false)
options isa AbstractObservable || (options = Observable{Any}(options))
vals2idxs = map(Vals2Idxs∘collect∘_keys, options)
p = initvalueindex(key, index, vals2idxs, rev = true, multiple = multiple)
key, index = p.first, p.second
ui = map(options) do val
v = _values(val)
nodes = (node(:div, el, attributes = Dict("data-bind" => "visible: index() == $i")) for (i, el) in enumerate(v))
knockout(node(:div, nodes...), ["index" => index])
end
Widget{:mask}(["index" => index, "key" => key, "options" => options];
output = index, layout = t -> ui)
end
"""
`tabulator(options::AbstractDict; index, key)`
Creates a set of toggle buttons whose labels are the keys of options. Displays the value of the selected option underneath.
Use `index::Int` to select which should be the index of the initial option, or `key::String`.
The output is the selected `index`. Use `index=0` to not have any selected option.
## Examples
```julia
tabulator(OrderedDict("plot" => plot(rand(10)), "scatter" => scatter(rand(10))), index = 1)
tabulator(OrderedDict("plot" => plot(rand(10)), "scatter" => scatter(rand(10))), key = "plot")
```
`tabulator(values::AbstractArray; kwargs...)`
`tabulator` with labels `values`
see `tabulator(options::AbstractDict; ...)` for more details
```
tabulator(options::Observable; navbar=tabs, kwargs...)
```
Tabulator whose `options` are a given `Observable`. Set the `Observable` to some other
value to update the options in real time. Defaults to `navbar=tabs`: use `navbar=togglebuttons`
to have buttons instead of tabs.
## Examples
```julia
options = Observable(["a", "b", "c"])
wdg = tabulator(options)
options[] = ["c", "d", "e"]
```
Note that the `options` can be modified from the widget directly:
```julia
wdg[:options][] = ["c", "d", "e"]
```
"""
function tabulator(theme::WidgetTheme, options; navbar = tabs, skip = 1em, vskip = skip, value = nothing, index = value, key = automatic, kwargs...)
options isa AbstractObservable || (options = Observable{Any}(options))
vals2idxs = map(Vals2Idxs∘collect∘_keys, options)
p = initvalueindex(key, index, vals2idxs, rev = true)
key, index = p.first, p.second
d = map(t -> OrderedDict(zip(parent(t), 1:length(parent(t)))), vals2idxs)
buttons = navbar(theme, d; index = index, readout = false, kwargs...)
content = mask(theme, options; index = index)
layout = t -> div(t[:navbar], CSSUtil.vskip(vskip), t[:content], className = "interact-widget")
Widget{:tabulator}(["index" => index, "key" => key, "navbar" => buttons, "content" => content, "options" => options];
output = index, layout = layout)
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 8578 | _length(v::AbstractArray) = length(v)
_length(::Any) = 1
_map(f, v::AbstractArray) = map(f, v)
_map(f, v) = f(v)
function _searchsortedfirst(vals, t)
rev = first(vals) > last(vals)
searchsortedfirst(vals, t, rev = rev)
end
function format(x)
io = IOBuffer()
show(IOContext(io, :compact => true), x)
String(take!(io))
end
for func in [:rangeslider, :slider]
@eval begin
function $func(theme::WidgetTheme, vals::AbstractArray, formatted_vals = format.(vec(vals)); value = medianelement(vals), kwargs...)
T = Observables.to_value(value) isa Vector ? Vector{eltype(vals)} : eltype(vals)
value isa AbstractObservable || (value = Observable{T}(value))
vals = vec(vals)
indices = axes(vals)[1]
f = x -> _map(t -> _searchsortedfirst(vals, t), x)
g = x -> vals[Int.(x)]
index = ObservablePair(value, f = f, g = g).second
wdg = Widget($func(theme, indices, formatted_vals; value = index, kwargs...), output = value)
wdg["value"] = value
wdg
end
end
end
"""
```
function slider(vals::AbstractArray;
value=medianelement(vals),
label=nothing, readout=true, kwargs...)
```
Creates a slider widget which can take on the values in `vals`, and updates
observable `value` when the slider is changed.
"""
function slider(theme::WidgetTheme, vals::AbstractUnitRange{<:Integer}, formatted_vals = format.(vals);
className=getclass(theme, :input, "range", "fullwidth"),
readout=true, label=nothing, value=medianelement(vals), orientation = "horizontal", attributes = Dict(), kwargs...)
min, max = extrema(vals)
orientation = string(orientation)
attributes = merge(attributes, Dict("orient" => orientation))
(value isa AbstractObservable) || (value = convert(eltype(vals), value))
format = js"""
function(){
return this.formatted_vals()[parseInt(this.index())-($min)];
}
"""
ui = input(theme, value; bindto="index", attributes=attributes, extra_obs = ["formatted_vals" => formatted_vals], computed = ["formatted_val" => format],
typ="range", min=min, max=max, step=1, className=className, kwargs...)
if (label != nothing) || readout
if orientation != "vertical"
Widgets.scope(ui).dom = readout ?
flex_row(wdglabel(theme, label), Widgets.scope(ui).dom, node(:p, attributes = Dict("data-bind" => "text: formatted_val"))) :
flex_row(wdglabel(theme, label), Widgets.scope(ui).dom)
else
readout && (label = vbox(label, node(:p, attributes = Dict("data-bind" => "text: formatted_val"))))
Widgets.scope(ui).dom = hbox(wdglabel(theme, label), dom"div[style=flex-shrink:1]"(Widgets.scope(ui).dom))
end
end
Widget{:slider}(ui)
end
"""
```
function rangeslider(vals::AbstractArray;
value=medianelement(vals),
label=nothing, readout=true,
orientation="horizontal",
direction="ltr", kwargs...)
```
Creates a slider widget which can take on the values in `vals` and accepts several "handles".
Pass a vector to `value` with two values if you want to select a range.
Use the `orientation="vertical"` keyword argument to create a vertical slider.
By default the slider is top-to-botom and left-to-right,
but this can be changed using the `direction="rtl"` keyword argument.
"""
function rangeslider(theme::WidgetTheme, vals::AbstractUnitRange{<:Integer}, formatted_vals = format.(vals);
style = Dict(), label = nothing, value = medianelement(vals), orientation = "horizontal", readout = true,
className = "is-primary", direction="ltr")
T = Observables.to_value(value) isa Vector ? Vector{eltype(vals)} : eltype(vals)
value isa AbstractObservable || (value = Observable{T}(value))
index = value
orientation = string(orientation)
direction = string(direction)
preprocess = T<:Vector ? js"unencoded.map(Math.round)" : js"Math.round(unencoded[0])"
scp = Scope(imports = vcat([nouislider_min_js, nouislider_min_css], libraries(theme)))
setobservable!(scp, "index", index)
fromJS = Observable(scp, "fromJS", false)
changes = Observable(scp, "changes", 0)
connect = _length(index[]) > 1 ? js"true" : js"[true, false]"
min, max = extrema(vals)
s = step(vals)
id = "slider"*randstring()
start = JSExpr.@js $index[]
updateValue = JSExpr.@js function updateValue(values, handle, unencoded, tap, positions)
$fromJS[] = true
$index[] = $preprocess
end
updateCount = JSExpr.@js function updateCount(values, handle, unencoded, tap, positions)
$changes[] = $changes[]+1
end
tooltips = JSString("[" * join(fill(readout, _length(value[])), ", ") * "]")
onimport(scp, js"""
function (noUiSlider) {
var vals = JSON.parse($(JSON.json(formatted_vals)));
$updateValue
$updateCount
var slider = document.getElementById($id);
noUiSlider.create(slider, {
start: $start,
step: 1,
tooltips: $tooltips,
connect: $connect,
orientation: $orientation,
direction: $direction,
format: {
to: function ( value ) {
var ind = Math.round(value-($min));
return ind + 1 > vals.length ? vals[vals.length - 1] : vals[ind];
},
from: function ( value ) {
return parseInt(value);
}
},
range: {
'min': ($min),
'max': ($max)
},})
slider.noUiSlider.on("slide", updateValue);
slider.noUiSlider.on("change", updateCount);
}
""")
slap_design!(scp, theme)
onjs(index, @js function (val)
if !$fromJS[]
document.getElementById($id).noUiSlider.set(Array.isArray(val) ? val : [val])
end
$fromJS[] = false
end)
style = Dict{String, Any}(string(key) => val for (key, val) in style)
haskey(style, "flex-grow") || (style["flex-grow"] = "1")
!haskey(style, "height") && orientation == "vertical" && (style["height"] = "20em")
scp.dom = node(:div, style = style, attributes = Dict("id" => id))
layout = function (t)
if orientation != "vertical"
sld = t.scope
sld = label !== nothing ? flex_row(label, sld) : sld
sld = readout ? vbox(vskip(3em), sld) : sld
sld = div(sld, className = "field rangeslider rangeslider-horizontal interact-widget $className")
else
sld = t.scope
sld = readout ? hbox(hskip(6em), sld) : sld
sld = label !== nothing ? vbox(label, sld) : sld
sld = div(sld, className = "field rangeslider rangeslider-vertical interact-widget $className")
end
sld
end
Widget{:rangeslider}(["index" => index, "changes" => changes];
scope = scp, output = value, layout = layout)
end
"""
```
function rangepicker(vals::AbstractArray;
value=[extrema(vals)...],
label=nothing, readout=true, kwargs...)
```
A multihandle slider with a set of spinboxes, one per handle.
"""
function rangepicker(theme::WidgetTheme, vals::AbstractRange{S}; value = [extrema(vals)...], readout = false, className = "is-primary") where {S}
T = Observables.to_value(value) isa Vector ? Vector{eltype(vals)} : eltype(vals)
value isa AbstractObservable || (value = Observable{T}(value))
wdg = Widget{:rangepicker}(output = value)
if !(T<:Vector)
wdg["input"] = input(S, theme, vals, value=value)
else
function newinput(i)
f = t -> t[i]
g = t -> (s = copy(value[]); s[i] = t; s)
new_val = ObservablePair(value, f=f, g=g).second
input(S, theme, vals, value = new_val)
end
for i in eachindex(value[])
wdg["input$i"] = newinput(i)
end
end
inputs = t -> (val for (key, val) in components(t) if occursin(r"slider|input", string(key)))
wdg.layout = t -> div(inputs(t)..., className = "interact-widget")
wdg["slider"] = rangeslider(theme, vals; value = value, readout = readout, className = className)
wdg["changes"] = map(+, (val["changes"] for val in inputs(wdg))...)
return wdg
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 1121 | import WebIO: camel2kebab
# Get median elements of ranges, used for initialising sliders.
# Differs from median(r) in that it always returns an element of the range
medianidx(r) = (1+length(r)) ÷ 2
medianelement(r::AbstractArray) = r[medianidx(r)]
medianval(r::AbstractDict) = medianelement(collect(values(r)))
medianelement(r::AbstractDict) = medianval(r)
_values(r::AbstractArray) = r
_values(r::AbstractDict) = values(r)
_keys(r::AbstractArray) = 1:length(r)
_keys(r::AbstractDict) = keys(r)
inverse_dict(d::AbstractDict) = Dict(zip(values(d), keys(d)))
const Propkey = Union{Symbol, String}
const PropDict = Dict{Propkey, Any}
function slap_design!(w::Scope, args)
for arg in args
import!(w, arg)
end
w
end
slap_design!(w::Scope, args::AbstractString...) = slap_design!(w::Scope, args)
slap_design!(w::Scope, args::WidgetTheme = gettheme()) =
slap_design!(w::Scope, libraries(args))
slap_design!(n::Node, args...) = slap_design!(Scope()(n), args...)
slap_design!(w::Widget, args...) = (slap_design!(scope(w), args...); w)
isijulia() = isdefined(Main, :IJulia) && Main.IJulia.inited
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 293 | using Random
using InteractBase, Observables, OrderedCollections, Colors, WebIO, CSSUtil
using Widgets
using Dates
import InteractBase: widgettype
import Widgets: components
using Test
include("test_observables.jl")
include("test_theme.jl")
include("test_deps.jl")
include("test_dialog.jl")
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 706 | font_awesome = joinpath(@__DIR__, "..", "assets", "all.js")
prism_js = joinpath(@__DIR__, "..", "assets", "prism.js")
prism_css = joinpath(@__DIR__, "..", "assets", "prism.css")
highlight_css = joinpath(@__DIR__, "..", "assets", "highlight.css")
nouislider_min_js = joinpath(@__DIR__, "..", "assets", "nouislider.min.js")
nouislider_min_css = joinpath(@__DIR__, "..", "assets", "nouislider.min.css")
style_css = joinpath(@__DIR__, "..", "assets", "style.css")
@testset "deps" begin
@test isfile(font_awesome)
@test isfile(prism_js)
@test isfile(prism_css)
@test isfile(highlight_css)
@test isfile(nouislider_min_js)
@test isfile(nouislider_min_css)
@test isfile(style_css)
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 153 | using InteractBase
using Test
@testset "Dialog" begin
@test InteractBase.opendialog() isa Widget
@test InteractBase.savedialog() isa Widget
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 10576 | @testset "input" begin
a = InteractBase.input()
@test widgettype(a) == :input
@test observe(a)[] == ""
a = InteractBase.input(typ = "number");
@test observe(a)[] == 0
s = Observable{Any}(12)
a = InteractBase.input(s, typ = "number");
@test observe(a)[] == s[]
@test widgettype(input(Bool)) == :toggle
@test widgettype(input(Dates.Date)) == :datepicker
@test widgettype(input(Dates.Time)) == :timepicker
@test widgettype(input(Color)) == :colorpicker
@test widgettype(input(String)) == :textbox
@test widgettype(input(Int)) == :spinbox
@test widgettype(widget(true)) == :toggle
@test widgettype(widget(Dates.Date(Dates.now()))) == :datepicker
@test widgettype(widget(Dates.Time(Dates.now()))) == :timepicker
@test widgettype(widget(colorant"red")) == :colorpicker
@test widgettype(widget("")) == :textbox
@test widgettype(widget(1)) == :spinbox
@test widgettype(widget(1:100)) == :slider
@test widgettype(widget(["a", "b", "c"])) == :togglebuttons
end
@testset "input widgets" begin
a = filepicker()
@test widgettype(a) == :filepicker
@test a["filename"][] == ""
@test a["path"][] == ""
a["path"][] = "/home/Jack/documents/test.csv"
@test a["path"][] == observe(a)[] == "/home/Jack/documents/test.csv"
a = datepicker(value = Dates.Date(01,01,01))
b = datepicker(Dates.Date(01,01,01))
@test observe(a)[] == observe(b)[] == Dates.Date(01,01,01)
@test widgettype(a) == :datepicker
a = colorpicker(value = colorant"red")
b = colorpicker(colorant"red")
@test observe(a)[] == observe(b)[] == colorant"red"
@test widgettype(a) == :colorpicker
a = spinbox(label = "")
@test widgettype(a) == :spinbox
@test observe(a)[] == nothing
a = textbox();
@test widgettype(a) == :textbox
@test observe(a)[] == ""
s = "asd"
a = textbox(value = s);
@test observe(a)[] == "asd"
a = textarea(label = "test");
@test widgettype(a) == :textarea
@test observe(a)[] == ""
s = "asd"
a = textarea(value = s);
@test observe(a)[] == "asd"
a = autocomplete(["aa", "bb", "cc"], value = "a");
@test widgettype(a) == :autocomplete
@test observe(a)[] == "a"
a = button("Press me!", value = 12)
@test widgettype(a) == :button
@test observe(a)[] == 12
a = toggle(label = "Agreed")
@test widgettype(a) == :toggle
@test observe(a)[] == false
s = Observable(true)
a = toggle(s, label = "Agreed")
@test observe(a)[] == true
a = togglecontent(checkbox("Yes, I am sure"), "Are you sure?")
@test widgettype(a) == :togglecontent
@test observe(a)[] == false
s = Observable(true)
a = togglecontent(checkbox("Yes, I am sure"), "Are you sure?", value = s)
@test observe(a)[] == true
v = slider([0, 12, 22], value = 12)
@test widgettype(v) == :slider
@test observe(v)[] == 12
@test v["index"][] == 2
# v["internalvalue"][] = 3
# @test observe(v)[] == 22
end
@testset "slider" begin
@test isfile(InteractBase.nouislider_min_js)
@test isfile(InteractBase.nouislider_min_css)
w = Dates.Date("2000-11-11") : Day(1) : Dates.Date("2000-12-12")
s = InteractBase.rangeslider(w, value = [w[10], w[20]])
@test observe(s)[] == [w[10], w[20]]
@test observe(s["index"])[] == [10, 20]
observe(s["index"])[] = [13, 14]
sleep(0.1)
@test observe(s)[] == [w[13], w[14]]
w = 1:5:500
s = InteractBase.rangepicker(w, value = [w[10], w[20]])
@test collect(keys(components(s))) == [:input1, :input2, :slider, :changes]
@test observe(s)[] == [w[10], w[20]] == observe(s["slider"])[]
@test observe(s["slider"])[] == [w[10], w[20]]
observe(s["slider"])[] = [w[13], w[14]]
sleep(0.1)
@test observe(s)[] == [w[13], w[14]]
@test observe(s["input1"])[] == w[13]
@test observe(s["input2"])[] == w[14]
end
@testset "options" begin
a = dropdown(["a", "b", "c"])
@test widgettype(a) == :dropdown
@test observe(a)[] == "a"
a = dropdown(OrderedDict("a" => 1, "b" => 2, "c" => 3))
@test observe(a)[] == 1
a = dropdown(OrderedDict("a" => 1, "b" => 3, "c" => 4), value = 3)
@test observe(a)[] == 3
@test observe(a, "index")[] == 2
v = [0.1, 0.2, 1.2]
a = dropdown(OrderedDict("a" => 1, "b" => 3, "c" => v), value = v)
@test observe(a)[] == v
@test observe(a, "index")[] == 3
v = [0.1, 0.2, 1.2]
a = dropdown(OrderedDict("a" => 1, "b" => 3, "c" => v), value = [3, v], multiple = true)
@test observe(a)[] == [3, v]
@test observe(a, "index")[] == [2, 3]
a = togglebuttons(["a", "b", "c"])
@test widgettype(a) == :togglebuttons
@test observe(a)[] == "a"
a = togglebuttons(OrderedDict("a" => 1, "b" => 2, "c"=>3))
@test observe(a)[] == 1
a = togglebuttons(OrderedDict("a" => 1, "b" => 2, "c" => 4), value = 4)
@test observe(a)[] == 4
a = radiobuttons(["a", "b", "c"])
@test widgettype(a) == :radiobuttons
@test observe(a)[] == "a"
a = radiobuttons(OrderedDict("a" => 1, "b" => 2, "c" => 3))
@test observe(a)[] == 1
a = radiobuttons(OrderedDict("a" => 1, "b" => 2, "c" => 3), value = 3, label = "Test")
@test observe(a)[] == 3
end
@testset "ijulia" begin
@test !InteractBase.isijulia()
end
@testset "widget" begin
s = slider(1:100, value = 12)
w = InteractBase.Widget{:test}(components(s), scope = Widgets.scope(s), output = Observable(1))
@test observe(w)[] == 1
@test widgettype(s) == :slider
@test widgettype(w) == :test
@test w["index"][] == 12
w = Widget(w, output = scope(s)["index"])
@test observe(w)[] == 12
w = InteractBase.widget(Observable(1))
@test w isa Observable
end
@testset "manipulate" begin
ui = @manipulate for r = 0:.05:1, g = 0:.05:1, b = 0:.05:1
RGB(r,g,b)
end
@test observe(ui)[] == RGB(0.5, 0.5, 0.5)
observe(ui, :r)[] = 0.1
sleep(0.1)
@test observe(ui)[] == RGB(0.1, 0.5, 0.5)
ui = @manipulate throttle = 1 for r = 0:.05:1, g = 0:.05:1, b = 0:.05:1
RGB(r,g,b)
end
observe(ui, :r)[] = 0.1
sleep(0.1)
observe(ui, :r)[] = 0.3
sleep(0.1)
observe(ui, :g)[] = 0.1
sleep(0.1)
observe(ui, :g)[] = 0.3
sleep(0.1)
observe(ui, :b)[] = 0.1
sleep(0.1)
observe(ui, :b)[] = 0.3
sleep(0.1)
@test observe(ui)[] != RGB(0.3, 0.3, 0.3)
sleep(1.5)
@test observe(ui)[] == RGB(0.3, 0.3, 0.3)
end
@testset "output" begin
@test isfile(InteractBase.katex_min_js)
@test isfile(InteractBase.katex_min_css)
l = Observable("\\sum_{i=1}^{\\infty} e^i")
a = latex(l)
@test widgettype(a) == :latex
@test observe(a)[] == l[]
l[] == "\\sum_{i=1}^{12} e^i"
@test observe(a)[] == l[]
@test isfile(joinpath(dirname(@__FILE__), "..", "assets", "prism.js"))
@test isfile(joinpath(dirname(@__FILE__), "..", "assets", "prism.css"))
l = Observable("1+1+exp(2)")
a = highlight(l)
@test widgettype(a) == :highlight
@test observe(a)[] == l[]
l[] == "1-1"
@test observe(a)[] == l[]
l = Observable("1+1+exp(2)")
a = widget(Val(:highlight), l)
@test widgettype(a) == :highlight
@test observe(a)[] == l[]
l[] == "1-1"
@test observe(a)[] == l[]
a = alert()
a("Error!")
@test a["text"] isa Observable
@test a["text"][] == "Error!"
a = widget(Val(:alert), "Error 2!")
a()
@test a["text"] isa Observable
@test a["text"][] == "Error 2!"
a = confirm()
a("Error!")
@test a["text"] isa Observable
@test a["text"][] == "Error!"
@test observe(a)[] == false
@test a["function"](1) === nothing
a = widget(Val(:confirm), "Error 2!")
a()
@test a["text"] isa Observable
@test a["text"][] == "Error 2!"
@test observe(a)[] == false
v = Any["A"]
f = notifications(v)
sleep(0.1)
@test observe(f)[] == v
list = children(f.scope.dom[])[1]
@test begin
Widgets.scope(f)[:to_delete][] = 1
sleep(0.1)
observe(f)[] == []
end
v = OrderedDict("a" => checkbox(), "b" => 12)
wdg = InteractBase.accordion(v, multiple = true)
sleep(0.1)
@test observe(wdg)[] == Int[]
@test observe(wdg["options"])[] == v
observe(wdg)[] = [1]
sleep(0.1)
@test observe(wdg)[] == [1]
observe(wdg["options"])[] = OrderedDict("a" => 12)
sleep(0.1)
@test observe(wdg)[] == [1]
v = OrderedDict("a" => checkbox(), "b" => 12)
wdg = InteractBase.accordion(v, multiple = false)
sleep(0.1)
@test observe(wdg)[] == 1
@test observe(wdg["options"])[] == v
observe(wdg)[] = 2
sleep(0.1)
@test observe(wdg)[] == 2
observe(wdg["options"])[] = OrderedDict("a" => 12)
sleep(0.1)
@test observe(wdg)[] == 2
a = tabulator(OrderedDict("a" => 1.1, "b" => 1.2, "c" => 1.3))
@test a[:navbar] isa InteractBase.Widget{:tabs}
@test a[:navbar][:index][] == 1
@test observe(a, :navbar)[] == 1
observe(a)[] = 2
sleep(0.1)
@test a[:navbar][:index][] == 2
@test observe(a, :navbar)[] == 2
@test observe(a, "key")[] == "b"
a = tabulator(OrderedDict("a" => 1.1, "b" => 1.2, "c" => 1.3), value = 0)
@test a[:navbar][:index][] == 0
@test observe(a, :key)[] == nothing
v = OrderedDict("a" => checkbox(), "b" => 12)
wdg = InteractBase.mask(v, multiple = true)
sleep(0.1)
@test observe(wdg)[] == Int[]
@test observe(wdg["options"])[] == v
observe(wdg)[] = [1]
sleep(0.1)
@test observe(wdg)[] == [1]
observe(wdg["options"])[] = OrderedDict("a" => 12)
sleep(0.1)
@test observe(wdg)[] == [1]
v = OrderedDict("a" => checkbox(), "b" => 12)
wdg = InteractBase.mask(v; multiple = false)
sleep(0.1)
@test observe(wdg)[] == 1
@test observe(wdg["options"])[] == v
observe(wdg)[] = 2
sleep(0.1)
@test observe(wdg)[] == 2
observe(wdg["options"])[] = OrderedDict("a" => 12)
sleep(0.1)
@test observe(wdg)[] == 2
end
@testset "node" begin
@test InteractBase.node("a", "b") isa Node
@test InteractBase.div("a", "b") isa Node
end
@testset "onchange" begin
value = Observable(50)
changes = Observable(0)
s0 = slider(1:100, value = value, changes = changes)
s1 = onchange(s0)
onrelease = InteractBase.triggeredby(s0, s0[:changes])
@test onrelease[] == 50 == s1[]
s0[] = 12
sleep(0.1)
@test onrelease[] == 50 == s1[]
s0[:changes][] += 1
sleep(0.1)
@test onrelease[] == 12 == s1[][]
@test changes[] == 1
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 509 | struct MyTheme<:InteractBase.WidgetTheme; end
InteractBase.registertheme!(:mytheme, MyTheme())
@testset "theme" begin
@test gettheme() == NativeHTML()
settheme!(MyTheme())
@test gettheme() == MyTheme()
resettheme!()
@test gettheme() == NativeHTML()
settheme!("mytheme")
@test gettheme() == MyTheme()
settheme!(:nativehtml)
@test gettheme() == NativeHTML()
@test availablethemes() == [:mytheme, :nativehtml]
@test_throws ErrorException settheme!("not a theme")
end
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | code | 2746 | using Interact, Blink, Colors
w = Window()
#---
f = filepicker(label = "Upload");
body!(w, f)
observe(f)
#---
f = filepicker(multiple = true, accept = ".csv");
display(f)
observe(f)
#---
s = InteractBase.input("Write here")
body!(w, s)
observe(s)
#---
s = textbox("Write here", value = "A", className="is-danger")
body!(w, s)
observe(s)
#---
s = autocomplete(["Opt 1", "Option 2", "Opt 3"], "Write here")
body!(w, s)
observe(s)
opentools(w)
#---
v = Observable(RGB(1,0,0))
s = colorpicker(v)
body!(w, s)
observe(s)
#---
s1 = slider(1:20, style = Dict("width"=>"400px"))
sobs = observe(s1)
body!(w, vbox(s1, sobs));
#---
s1 = slider(vcat(0, exp10.(range(-2, stop = 2, length = 50))), label = "Log slider")
sobs = observe(s1)
body!(w, vbox(s1, sobs));
#---
button1 = button("button one {{clicks}}")
num_clicks = observe(button1)
button2 = button("button two {{clicks}}", value = num_clicks)
body!(w, hbox(button1, button2, num_clicks));
#---
body!(w, button(label = "Press!"))
#---
v = checkbox(label = "Agree")
body!(w, v)
observe(v)
#---
v = toggle(true, "Agree", className="is-danger")
body!(w, v)
observe(v)
#---
v = checkboxes(["A", "B", "C"]);
body!(w, v)
observe(v)
#---
v = toggles(["A", "B", "C"], className="is-danger");
body!(w, v)
observe(v)
#---
width, height = 700, 300
colors = ["black", "gray", "silver", "maroon", "red", "olive", "yellow", "green", "lime", "teal", "aqua", "navy", "blue", "purple", "fuchsia"]
_color(i) = colors[i%length(colors)+1]
ui = @manipulate for nsamples in 1:200,
sample_step in slider(0.01:0.01:1.0, value=0.1, label="sample step"),
phase in slider(0:0.1:2pi, value=0.0, label="phase"),
radii in 0.1:0.1:60,
show_image in true,
s in Observable(true)
cxs_unscaled = [i*sample_step + phase for i in 1:nsamples]
cys = sin.(cxs_unscaled) .* height/3 .+ height/2
cxs = cxs_unscaled .* width/4pi
show_image ? dom"svg:svg[width=$width, height=$height]"(
(dom"svg:circle[cx=$(cxs[i]), cy=$(cys[i]), r=$radii, fill=$(_color(i))]"()
for i in 1:nsamples)...
) : dom"div"("Nothing to see here")
end
body!(w, ui)
opentools(w)
#---
using Plots, DataStructures
x = y = 0:0.1:30
freqs = OrderedDict(zip(["pi/4", "π/2", "3π/4", "π"], [π/4, π/2, 3π/4, π]))
mp = @manipulate for freq1 in freqs, freq2 in slider(0.01:0.1:4π; label="freq2")
y = @. sin(freq1*x) * sin(freq2*x)
plot(x, y)
end
body!(w, mp)
#---
s = dropdown(["a1", "a2nt", "a3"], label = "test")
body!(w, s)
observe(s)
#---
s = togglebuttons(["a1", "a2nt", "a3"], label = "x");
body!(w, s)
observe(s)
#---
s = radiobuttons(["a1", "a2nt", "a3"]);
display(s)
observe(s)
#---
# IJulia
ui = s
display(ui);
# Mux
using Mux
WebIO.webio_serve(page("/", req -> ui))
#---
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | docs | 2775 | # News
## Version 0.7
### Breaking
- Output widgets with options (`tabulator`, `accordion` and `mask`) can be set with `key` or `index` and have as value the `index` of the elemenet(s) that are displayed
- Option widgets now try to preserve value as much as possible when reset.
### Bugfixes
- Fixed `checkboxes`
- Fixed `filepicker` initialization
## Version 0.6
### Breaking
- Deprecated `showvalue` in favor of `readout` to see the output of a slider.
- Removed obsolete `Vue` methods (`props2kwargs` and `kwargs2vueprops`)
### Features
- Added `notifications` widget to display a set of notifications that can be closed.
- Added `highlight` widget to display Julia syntax highlighted code
- Added `alert` and `confirm` widget to display javascript alerts and confirmation dialogues.
- `label` now appears above a `dropdown` and not below it
- Implemented `placeholder` for `dropdown`: a "zeroth" disabled option that appears when value does not match anything
- Added experimental `rangeslider`, a slider with multiple handles, and `rangepicker`
- Added experimental `accordion` and `tooltip!`, to wrap the [accordion](https://wikiki.github.io/components/accordion/) and [tooltip](https://wikiki.github.io/elements/tooltip/) Bulma extension
## Version 0.5
### Breaking
- Deprecated `tabulator(keys, vals)` in favor of `tabulator(OrderedDict(zip(keys, vals)))`
- In `togglebuttons(options, value = x)` `x` should now be one of the values of `options`, rather than one index from `1` to `length(options)`, consistently with all other option widgets
- `style` can no longer be passed as a string but should be passed as a dictionary, i.e. `style=Dict("text-align" => "center", "width" => "100px")`
- `class` can no longer be used, instead one should use the DOM property `className`, i.e. `textbox(className="is-danger")`
- The `outer` keyword no longer exists, to modify a `WebIO.Scope` `s` simply change its DOM, i.e. `s.dom = ...`
### Features
- Observables of widgets can be used in conjunction with `observe`, meaning, if `wdg = Observable(dropdown(["a", "b", "c"]))`, then `observe(wdg)` is an observable that holds the selected value of the dropdown. This is useful when creating a widget from some observable using `map`, for example `options = Observable(["a", "b", "c"]); wdg = map(dropdown, options)`
- Option widgets now store their options as observable, it can be accessed with `observe(wdg, "options")` and modified with `observe(wdg, "options")[] = ["d", "e", "f"]`
### Bugfixes
- Option widgets now accept `OrderedDict` with strings as keys and any Julia value as values
- For any widget, changing the Julia observable also updates the visual widget (the javascript value), even for cases where the Julia type has no javascript equivalent
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | docs | 818 | # InteractBase
[](https://github.com/JuliaGizmos/InteractBase.jl/actions?query=workflow%3ACI+branch%3Amaster)
[](https://JuliaGizmos.github.io/Interact.jl/latest)
[](http://codecov.io/github/JuliaGizmos/InteractBase.jl?branch=master)
This package is a developer target and it includes the implementation of [Interact](https://github.com/JuliaGizmos/Interact.jl) widgets. The user-facing package is [Interact](https://github.com/JuliaGizmos/Interact.jl) See [the API reference](https://juliagizmos.github.io/Interact.jl/latest/widgets.html) to see which widgets are implemented.
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"MIT"
] | 0.10.10 | aa5daeff326db0a9126a225b58ca04ae12f57259 | docs | 1108 | ---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Version info (please complete the following information):**
- include the output of `versioninfo()` and `Pkg.status()`
- how are you deploying the widgets? Jupyter Notebook/Lab, Juno, Blink or Mux?
**Before opening an issue**
- make sure you are on the latest release of InteractBase and try rebuilding it with `Pkg.build("InteractBase")`
**If widgets do not appear**
- test that your WebIO is correctly installed. Make sure you're on latest release and rebuild it with `Pkg.build("WebIO")`
- try a simple code to produce a slider: `using WebIO; display(Node(:input, attributes = Dict("type" => "range")))`
- if this doesn't produce a slider, your WebIO is not installed correctly and you may wish to open an issue at WebIO rather than here,
| InteractBase | https://github.com/JuliaGizmos/InteractBase.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 1016 | using Documenter, ModelConstructors
makedocs(modules = [ModelConstructors],
clean = false,
format = Documenter.HTML(),
sitename = "ModelConstructors.jl",
authors = "FRBNY-DSGE",
linkcheck = false,
strict = false,
pages = Any[
"Home" => "index.md",
"Model Design" => "model_design.md",
"Creating Models" => "example_model.md",
"Implementation Details" => "implementation_details.md",
"Contributing to ModelConstructors.jl" => "contributing.md",
"License" => "license.md"
],
doctest = false # for now
)
deploydocs(
repo = "github.com/FRBNY-DSGE/ModelConstructors.jl.git",
target = "build",
deps = nothing,
devbranch = "main",
branch = "gh-pages",
make = nothing
)
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 2825 | using ModelConstructors, FileIO, Random, SMC
### Estimate a single factor CAPM model
# R_{it} = α_i + β_i R_{Mt} + ϵ_{it}, i = 1,...,N; t = 1,...,T
# where R_{Mt} is the excess return on a market index in time period t,
# and ϵ_{it} is an i.i.d. normally distributed mean zero shock with variance σ_i^2
### Construct a generic model and populate it with parameters
capm = GenericModel()
fn = dirname(@__FILE__)
capm <= Setting(:dataroot, "$(fn)/../save/input_data/")
capm <= Setting(:saveroot, "$(fn)/../save/")
capm <= parameter(:α1, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:β1, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:σ1, 1., (1e-5, 1e5), (1e-5, 1e5), SquareRoot(), Uniform(0, 1e3),
fixed = false)
capm <= parameter(:α2, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:β2, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:σ2, 1., (1e-5, 1e5), (1e-5, 1e5), SquareRoot(), Uniform(0, 1e3),
fixed = false)
capm <= parameter(:α3, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:β3, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
capm <= parameter(:σ3, 1., (1e-5, 1e5), (1e-5, 1e5), SquareRoot(), Uniform(0, 1e3),
fixed = false)
### Estimate with SMC
## Get data
N = 3 # number of asset returns
lik_data = load("../../../save/input_data/capm.jld2", "lik_data")
market_data = load("../../../save/input_data/capm.jld2", "market_data")
## Construct likelihood function:
# likelihood function is just R_{it} ∼ N(α_i + β_i R_{Mt}, σ_i)
# parameters to estimate are α_i, β_i, σ_i
# data is a time series of individual factor returns
# use S&P 500 data and a returns on a couple stocks. To get into returns,
# just take the log of the prices and regress those on each other.
function likelihood_fnct(p, d)
# we assume the ordering of (α_i, β_i, σ_i)
Σ = zeros(N,N)
α = Vector{Float64}(undef,N)
β = Vector{Float64}(undef,N)
for i in 1:N
α[i] = p[i * 3 - 2]
β[i] = p[i * 3 - 1]
Σ[i,i] = p[i * 3]^2
end
det_Σ = det(Σ)
inv_Σ = inv(Σ)
term1 = -N / 2 * log(2 * π) - 1 /2 * log(det_Σ)
logprob = 0.
errors = d .- α .- β .* market_data
for t in 1:size(d,2)
logprob += term1 - 1/2 * dot(errors, inv_Σ * errors)
end
return logprob
end
Random.seed!(1793)
println("Starting to estimate CAPM with SMC . . .")
@everywhere using SMC, OrderedCollections
smc(likelihood_fnct, capm.parameters, lik_data)
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 3452 | isdefined(Base, :__precompile__) && __precompile__(false)
module ModelConstructors
using DataFrames, Dates, Distributed, Distributions
using ForwardDiff, Nullables, Printf, Random
using LinearAlgebra, OrderedCollections, SpecialFunctions
import Base.isempty, Base.<, Base.min, Base.max, Base.length
import Distributions.log2π, Distributions.params, Distributions.mean, Distributions.std
import Distributions.pdf, Distributions.logpdf, Distributions.Distribution
import Distributions.rand, Distributions.Matrixvariate, Distributions.LinearAlgebra
import LinearAlgebra.rank
import SpecialFunctions.gamma
import UnPack: unpack
export
# distributions_ext.jl
BetaAlt, GammaAlt, RootInverseGamma, DegenerateMvNormal, DegenerateDiagMvTDist,
MatrixNormal, <=, logpdf, init_deg_mvnormal,
# settings.jl
Setting, get_setting,
# observables.jl
Observable, PseudoObservable, check_mnemonics,
# defaults.jl
default_settings!, default_test_settings!,
# abstractmodel.jl
AbstractModel, description,
n_states, n_states_augmented, n_shocks_exogenous, n_shocks_expectational,
n_equilibrium_conditions, n_observables, n_parameters, n_parameters_regime_switching, n_parameters_steady_states,
n_parameters_free, n_pseudo_observables, get_dict, get_key,
spec, subspec, saveroot, dataroot,
data_vintage, data_id, cond_vintage,
logpath, workpath, rawpath, tablespath, figurespath, inpath, filestring_base, workpath,
rawpath, tablespath, figurespath, logpath, savepath, inpath, filestring,
# parameters.jl
parameter, parameter_ad, Transform, NullablePrior, AbstractParameter,
Parameter, ParameterVector, ScaledParameter,
UnscaledParameter, SteadyStateParameter, SteadyStateParameterGrid,
transform_to_real_line, transform_to_model_space,
differentiate_transform_to_real_line, differentiate_transform_to_model_space,
update, update!, transform_to_model_space, transform_to_real_line, Interval,
ParamBoundsError, Untransformed, SquareRoot, moments,
prior,
# distributions_ext.jl
Uniform, Exponential, Normal, BetaAlt, GammaAlt, RootInverseGamma, pdf, logpdf, rand,
DegenerateMvNormal, rank, length, DgenerateDiagMvTDist, mean, std,
MatrixNormal, size, params, truncmean,
AbstractVectorParameter, VectorParameter, VectorParameterVector, ScaledVectorParameter,
UnscaledVectorParameter, Untransformed,
# regimes.jl
set_regime_val!, regime_val, set_regime_prior!, regime_prior, set_regime_fixed!, regime_fixed,
set_regime_valuebounds!, regime_valuebounds, toggle_regime!,
# statistics.jl
prior, posterior, posterior!,
# util.jl
info_print, warn_print, println, print, @test_matrix_approx_eq, @test_matrix_eq2,
# Generic Model
GenericModel,
# Linear Regression
LinearRegression
const VERBOSITY = Dict(:none => 0, :low => 1, :high => 2)
include("parameters.jl")
include("distributions_ext.jl")
include("abstractmodel.jl")
include("settings.jl")
include("observables.jl")
include("defaults.jl")
include("statistics.jl")
include("util.jl")
include("regimes.jl")
include("generic_model.jl")
include("linear_regression.jl")
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 16095 | abstract type AbstractModel{T} end
function Base.show(io::IO, m::AbstractModel)
@printf io "Model \n"
@printf io "no. parameters: %i\n" n_parameters(m)
@printf io "description:\n %s\n" description(m)
end
@inline function Base.getindex(m::AbstractModel, i::Integer)
if i <= (j = length(m.parameters))
return m.parameters[i]
else
return m.steady_state[i-j]
end
end
# Need to define like this so as to disable bounds checking
@inline function Base.getindex(m::AbstractModel, k::Symbol)
i = m.keys[k]
@inbounds if i <= (j = length(m.parameters))
return m.parameters[i]
else
return m.steady_state[i-j]
end
end
@inline function Base.setindex!(m::AbstractModel, value::Number, i::Integer)
if i <= (j = length(m.parameters))
param = m.parameters[i]
param.value = value
if isa(param, ScaledParameter)
param.scaledvalue = param.scaling(value)
end
return param
else
steady_state_param = m.steady_state[i-j]
steady_state_param.value = value
return steady_state_param
end
end
Base.setindex!(m::AbstractModel, value::Array, k::Symbol) = Base.setindex!(m, value, m.keys[k])
@inline function Base.setindex!(m::AbstractModel, value::Array, i::Integer)
if i <= (j = length(m.parameters))
param = m.parameters[i]
param.value = value
if isa(param, ScaledParameter)
param.scaledvalue = param.scaling(value)
end
return param
else
steady_state_param = m.steady_state[i-j]
steady_state_param.value = value
return steady_state_param
end
end
"""
```
setindex!(m::AbstractModel, param::AbstractParameter, i::Integer)
```
If `i`<length(m.parameters), overwrites m.parameters[i] with
param. Otherwise, overwrites m.steady_state[i-length(m.parameters).
"""
@inline function Base.setindex!(m::AbstractModel, param::AbstractParameter, i::Integer)
if i <= (j = length(m.parameters))
m.parameters[i] = param
else
m.steady_state[i-j] = param
end
return param
end
Base.setindex!(m::AbstractModel, value, k::Symbol) = Base.setindex!(m, value, m.keys[k])
"""
```
(<=)(m::AbstractModel{T}, p::AbstractParameter{T}) where T
```
Syntax for adding a parameter to a model: m <= parameter.
NOTE: If `p` is added to `m` and length(m.steady_state) > 0, `keys(m)` will not generate the
index of `p` in `m.parameters`.
"""
function (<=)(m::AbstractModel{T}, p::AbstractParameter{T}) where T
if !in(p.key, keys(m.keys))
new_param_index = length(m.keys) + 1
# grow parameters and add the parameter
push!(m.parameters, p)
# add parameter location to dict
setindex!(m.keys, new_param_index, p.key)
else
# overwrite the previous parameter with the new one
setindex!(m, p, p.key)
end
end
"""
```
(<=)(m::AbstractModel{T}, ssp::Union{SteadyStateParameter,SteadyStateParameterArray}) where {T}
```
Add a new steady-state value to the model by appending `ssp` to the `m.steady_state` and
adding `ssp.key` to `m.keys`.
"""
function (<=)(m::AbstractModel{T}, ssp::Union{SteadyStateParameter, SteadyStateParameterArray}) where {T}
if !in(ssp.key, keys(m.keys))
new_param_index = length(m.keys) + 1
# append ssp to steady_state vector
push!(m.steady_state, ssp)
# add parameter location to dict
setindex!(m.keys, new_param_index, ssp.key)
else
# overwrite the previous parameter with the new one
setindex!(m, ssp, ssp.key)
end
end
"""
```
(<=)(m::AbstractModel{T}, ssp::SteadyStateParameterGrid) where {T}
```
Add a new steady-state value to the model by appending `ssp` to the `m.steady_state` and
adding `ssp.key` to `m.keys`.
"""
function (<=)(m::AbstractModel{T}, ssp::SteadyStateParameterGrid) where {T}
if !in(ssp.key, keys(m.keys))
new_param_index = length(m.keys) + 1
# append ssp to steady_state vector
push!(m.steady_state, ssp)
# add parameter location to dict
setindex!(m.keys, new_param_index, ssp.key)
else
# overwrite the previous parameter with the new one
setindex!(m, ssp, ssp.key)
end
end
Distributions.logpdf(m::AbstractModel) = logpdf(m.parameters)
Distributions.pdf(m::AbstractModel) = exp(logpdf(m))
# Convenience functions
n_states(m::AbstractModel) = length(m.endogenous_states)
n_states_augmented(m::AbstractModel) = n_states(m) + length(m.endogenous_states_augmented)
n_shocks_exogenous(m::AbstractModel) = length(m.exogenous_shocks)
n_shocks_expectational(m::AbstractModel) = length(m.expected_shocks)
n_observables(m::AbstractModel) = length(m.observables)
n_pseudo_observables(m::AbstractModel) = length(m.pseudo_observables)
n_equilibrium_conditions(m::AbstractModel) = length(m.equilibrium_conditions)
n_parameters(m::AbstractModel) = length(m.parameters)
n_parameters_steady_state(m::AbstractModel) = length(m.steady_state)
n_parameters_free(m::AbstractModel) = length(get_free_para_inds(m.parameters; regime_switching = true))
function n_parameters_regime_switching(m::AbstractModel)
return n_parameters_regime_switching(m.parameters)
end
function get_fixed_para_inds(parameters::ParameterVector; regime_switching::Bool = false,
toggle::Bool = true)
if regime_switching
if toggle
toggle_regime!(parameters, 1)
end
reg_fixed = [θ.fixed for θ in parameters] # it is assumed all regimes are toggled to regime 1
for θ in parameters
if !isempty(θ.regimes) # this parameter has regimes
if haskey(θ.regimes, :fixed)
push!(reg_fixed, [regime_fixed(θ, i) for i in 2:length(θ.regimes[:value])]...)
elseif θ.fixed # since regimes[:fixed] is non-existent but θ.fixed is true,
# it is assumed all regimes are fixed.
push!(reg_fixed, trues(length(θ.regimes[:value]) - 1)...)
else # All regimes are not fixed
push!(reg_fixed, falses(length(θ.regimes[:value]) - 1)...)
end
end
end
return findall(reg_fixed)
else
return findall([θ.fixed for θ in parameters])
end
end
function get_free_para_inds(parameters::ParameterVector; regime_switching::Bool = false,
toggle::Bool = true)
if regime_switching
if toggle
toggle_regime!(parameters, 1)
end
reg_free = [!θ.fixed for θ in parameters] # it is assumed all regimes are toggled to regime 1
for θ in parameters
if !isempty(θ.regimes) # this parameter has regimes
if haskey(θ.regimes, :fixed)
push!(reg_free, [!regime_fixed(θ, i) for i in 2:length(θ.regimes[:value])]...)
elseif θ.fixed # since regimes[:fixed] is non-existent but θ.fixed is true,
# it is assumed all regimes are fixed.
push!(reg_free, falses(length(θ.regimes[:value]) - 1)...)
else # All regimes are not fixed
push!(reg_free, trues(length(θ.regimes[:value]) - 1)...)
end
end
end
return findall(reg_free)
else
return findall([!θ.fixed for θ in parameters])
end
end
"""
```
get_dict(m, class, index)
```
"""
function get_dict(m::AbstractModel, class::Symbol)
if class == :states
m.endogenous_states
elseif class == :obs
m.observables
elseif class == :pseudo
m.pseudo_observables
elseif class in [:shocks, :stdshocks]
m.exogenous_shocks
else
throw(ArgumentError("Invalid class: $class. Must be :states, :obs, :pseudo, :shocks, or :stdshocks"))
end
end
"""
```
get_key(m, class, index)
```
Returns the name of the state (`class = :states`), observable (`:obs`),
pseudo-observable (`:pseudo`), or shock (`:shocks` or `:stdshocks`)
corresponding to the given `index`.
"""
function get_key(m::AbstractModel, class::Symbol, index::Int)
dict = get_dict(m, class)
out = Base.filter(key -> dict[key] == index, collect(keys(dict)))
if length(out) == 0
error("Key corresponding to index $index not found for class: $class")
elseif length(out) > 1
error("Multiple keys corresponding to index $index found for class: $class")
else
return out[1]
end
end
# Interface for I/O settings
spec(m::AbstractModel) = m.spec
subspec(m::AbstractModel) = m.subspec
saveroot(m::AbstractModel) = get_setting(m, :saveroot)
dataroot(m::AbstractModel) = get_setting(m, :dataroot)
# Interface for data
data_vintage(m::AbstractModel) = get_setting(m, :data_vintage)
data_id(m::AbstractModel) = get_setting(m, :data_id)
#=
Build paths to where input/output/results data are stored.
Description:
Creates the proper directory structure for input and output files, treating the DSGE/save
directory as the root of a savepath directory subtree. Specifically, the following
structure is implemented:
dataroot/
savepathroot/
output_data/<spec>/<subspec>/log/
output_data/<spec>/<subspec>/<out_type>/raw/
output_data/<spec>/<subspec>/<out_type>/work/
output_data/<spec>/<subspec>/<out_type>/tables/
output_data/<spec>/<subspec>/<out_type>/figures/
Note: we refer to the savepathroot/output_data/<spec>/<subspec>/ directory as saveroot.
=#
# """
# ```
# logpath(model)
# ```
# Returns path to log file. Path built as
# ```
# <output root>/output_data/<spec>/<subspec>/log/log_<filestring>.log
# ```
# """
# function logpath(m::AbstractModel)
# return savepath(m, "log", "log.log")
# end
strs = [:work, :raw, :tables, :figures, :log]
fns = [Symbol(x, "path") for x in strs]
for (str, fn) in zip(strs, fns)
@eval begin
# First eval function
function $fn(m::AbstractModel,
out_type::String,
file_name::String = "",
filestring_addl::Vector{String}=Vector{String}())
return savepath(m, out_type, $(string(str)), file_name, filestring_addl)
end
# Then, add docstring to it
@doc $(
"""
```
$fn(m::AbstractModel, out_type::String, file_name::String="",
filestring_addl::Vector{String}=Vector{String}())
```
Returns path to specific $str output file, creating containing directory as needed. If
`file_name` not specified, creates and returns path to containing directory only.
Path built as
```
<output root>/output_data/<spec>/<subspec>/<out_type>/$str/<file_name>_<filestring>.<ext>
```
"""
) $fn
end
end
# Not exposed to user. Actually create path and insert model string to file name.
function savepath(m::AbstractModel,
out_type::String,
sub_type::String,
file_name::String = "",
filestring_addl::Vector{String} = Vector{String}())
# Containing directory
dir = String(joinpath(saveroot(m), "output_data", spec(m), subspec(m), out_type, sub_type))
if !isempty(file_name)
base = filestring_base(m)
return savepath(dir, file_name, base, filestring_addl)
else
return dir
end
end
function savepath(dir::String,
file_name::String = "",
filestring_base::Vector{String} = Vector{String}(),
filestring_addl::Vector{String} = Vector{String}())
if !isdir(dir)
mkpath(dir)
end
if !isempty(file_name)
(base, ext) = splitext(file_name)
myfilestring = filestring(filestring_base, filestring_addl)
file_name_detail = base * myfilestring * ext
return joinpath(dir, file_name_detail)
else
return dir
end
end
# Input data handled slightly differently, because it is not model-specific.
"""
```
inpath(m::AbstractModel, in_type::T, file_name::T="") where T<:String
```
Returns path to specific input data file, creating containing directory as needed. If
`file_name` not specified, creates and returns path to containing directory only. Valid
`in_type` includes:
* `\"raw\"`: raw input series
* `\"data\"`: transformed data in model units
* `\"cond\"`: conditional data - nowcasts for the current forecast quarter, or related
* `\"user\"`: user-supplied data for starting parameter vector, hessian, or related
* `\"scenarios\"`: alternative scenarios
Path built as
```
<data root>/<in_type>/<file_name>
```
"""
function inpath(m::AbstractModel, in_type::String, file_name::String="")
path = dataroot(m)
# Normal cases.
if in_type in ["raw", "data", "cond", "scenarios"]
path = joinpath(path, in_type)
# User-provided inputs. May treat this differently in the future.
elseif in_type == "user"
path = joinpath(path, "user")
else
error("Invalid in_type: ", in_type)
end
# Containing dir
if !isdir(path)
mkpath(path)
end
# If file_name provided, return full path
if !isempty(file_name)
path = joinpath(path, file_name)
end
return path
end
function filestring_base(m::AbstractModel)
if !m.testing
base = Vector{String}()
for (skey, sval) in m.settings
if sval.print
push!(base, to_filestring(sval))
end
end
return base
else
return ["test"]
end
end
filestring(m::AbstractModel) = filestring(m, Vector{String}(undef, 0))
filestring(m::AbstractModel, d::String) = filestring(m, [String(d)])
function filestring(m::AbstractModel, d::Vector{String})
base = filestring_base(m)
return filestring(base, d)
end
function filestring(base::Vector{String}, d::Vector{String})
filestrings = vcat(base, d)
sort!(filestrings)
return "_" * join(filestrings, "_")
end
function filestring(d::Vector{String})
sort!(d)
return "_" * join(d, "_")
end
"""
```
rand(d::Union{DegenerateMvNormal,MvNormal}, m::AbstractModel; cc::AbstractFloat = 1.0)
```
Generate a draw from `d` with variance optionally scaled by `cc^2`.
"""
function rand(d::Union{DegenerateMvNormal,MvNormal}, m::AbstractModel; cc::AbstractFloat = 1.0)
return d.μ + cc*d.σ*randn(m.rng, length(d))
end
"""
```
rand(d::Union{DegenerateMvNormal,MvNormal}, rng::MersenneTwister; cc::AbstractFloat = 1.0)
```
Generate a draw from `d` with variance optionally scaled by `cc^2`.
"""
function rand(d::Union{DegenerateMvNormal,MvNormal}, rng::MersenneTwister; cc::AbstractFloat = 1.0)
return d.μ + cc*d.σ*randn(rng, length(d))
end
"""
`rand_prior(m::AbstractModel; ndraws::Int = 100_000)`
Draw a random sample from the model's prior distribution.
"""
function rand_prior(m::AbstractModel; ndraws::Int = 100_000)
T = typeof(m.parameters[1].value)
npara = length(m.parameters)
priorsim = Array{T}(undef, ndraws, npara)
for i in 1:ndraws
priodraw = Array{T}(undef, npara)
# Parameter draws per particle
for j in 1:length(m.parameters)
priodraw[j] = if !m.parameters[j].fixed
prio = rand(m.parameters[j].prior.value)
# Resample until all prior draws are within the value bounds
while !(m.parameters[j].valuebounds[1] < prio < m.parameters[j].valuebounds[2])
prio = rand(m.parameters[j].prior.value)
end
prio
else
m.parameters[j].value
end
end
priorsim[i,:] = priodraw'
end
priorsim
end
@inline unpack(m::AbstractModel, ::Val{k}) where {k} = isa(m[k], ScaledParameter) ? m[k].scaledvalue : m[k].value
function parameters2namedtuple(m::AbstractModel)
return parameters2namedtuple(get_parameters(m))
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 1908 | """
```
default_settings!(m::AbstractModel)
```
Default Settings are constructed, initialized and added to `m.settings`.
"""
function default_settings!(m::AbstractModel)
settings = m.settings
# I/O File locations
saveroot = normpath(joinpath(dirname(@__FILE__), "..","save"))
datapath = normpath(joinpath(dirname(@__FILE__), "..","save","input_data"))
settings[:saveroot] = Setting(:saveroot, saveroot, "Root of data directory structure")
settings[:dataroot] = Setting(:dataroot, datapath, "Input data directory path")
# Data settings for released and conditional data. Default behavior is to set vintage
# of data to today's date.
vint = Dates.format(now(), "yyyymmdd")
settings[:data_vintage] = Setting(:data_vintage, vint, true, "vint",
"Data vintage")
settings[:data_id] = Setting(:data_id, 3,
"Dataset identifier")
return settings
end
"""
```
default_test_settings!(m::AbstractModel)
```
The following Settings are constructed, initialized and added to
`m.test_settings`. Their purposes are identical to those in
`m.settings`, but these values are used to test package.
### I/O Locations and identifiers
- `saveroot::Setting{String}`: A temporary directory in /tmp/
- `dataroot::Setting{String}`: dsgeroot/test/reference/
- `data_vintage::Setting{String}`: \"_REF\"
"""
function default_test_settings!(m::AbstractModel)
test = m.test_settings
# I/O
dataroot = normpath(joinpath(dirname(@__FILE__), "..", "test", "reference", "input_data"))
saveroot = mktempdir()
# General
test[:saveroot] = Setting(:saveroot, saveroot,
"Where to write files when in test mode")
test[:dataroot] = Setting(:dataroot, dataroot,
"Location of input files when in test mode" )
test[:data_vintage] = Setting(:data_vintage, "REF", true, "vint",
"Reference data identifier")
return test
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 10508 | #=
This file defines additional functions to return objects of type Distribution. This is
necessary because we specify prior distributions wrt mean and SD
(for beta and gamma-distributed parameters) and ν and σ (for inverse gamma-distributed
parameters). Note these functions are NOT new methods for the Distributions.Beta, etc.
functions, but rather new functions with the same names.
=#
"""
```
BetaAlt(μ::T, σ::T) where {T<:Real}
```
Given μ and σ, calculate α and β and return a Distributions.Beta Distribution object.
### Arguments
`μ`: The mean of the desired distribution
`σ`: The standard deviation of the desired distribution
"""
function BetaAlt(μ::T, σ::T) where {T<:Real}
α = (1-μ) * μ^2 / σ^2 - μ
β = α * (1/μ - 1)
return Distributions.Beta(α, β)
end
"""
```
GammaAlt(μ::T, σ::T) where {T<:Real}
```
Given μ and σ, calculate α and β and return a Distributions.Gamma object.
### Arguments
`μ`: The mean of the desired distribution
`σ`: The standard deviation of the desired distribution
"""
function GammaAlt(μ::T, σ::T) where {T<:Real}
β = σ^2 / μ
α = μ / β
return Distributions.Gamma(α, β)
end
"""
```
mutable struct RootInverseGamma <: Distribution{Univariate, Continuous}
```
If x ~ RootInverseGamma(ν, τ), then
x² ~ ScaledInverseChiSquared(ν, τ²)
x² ~ InverseGamma(ν/2, ντ²/2)
x has mode τ and ν degrees of freedom.
"""
mutable struct RootInverseGamma <: Distribution{Univariate, Continuous}
ν::Float64
τ::Float64
end
Distributions.params(d::RootInverseGamma) = (d.ν, d.τ)
"""
```
Distributions.pdf(d::RootInverseGamma, x::T) where {T<:Real}
```
Compute the pdf of a RootInverseGamma distribution at x.
"""
function Distributions.pdf(d::RootInverseGamma, x::T) where {T<:Real}
(ν, τ) = params(d)
return 2 * (ν*τ^2/2)^(ν/2) * exp((-ν*τ^2)/(2x^2)) / gamma(ν/2) / x^(ν+1)
end
"""
```
Distributions.logpdf(d::RootInverseGamma, x::T) where {T<:Real}
```
Compute the log pdf of a RootInverseGamma distribution at x.
"""
function Distributions.logpdf(d::RootInverseGamma, x::T) where {T<:Real}
(ν, τ) = params(d)
return log(2) - log(gamma(ν/2)) + (ν/2)*log(ν*τ^2/2) - ((ν+1)/2)*log(x^2) - ν*τ^2/(2x^2)
end
"""
```
Distributions.rand(d::RootInverseGamma; cc::T = 1.0) where T <: AbstractFloat
```
Generate a draw from the RootInverseGamma distribution `d`.
"""
function Distributions.rand(d::RootInverseGamma; cc::T = 1.0) where T<:AbstractFloat
return sqrt(d.ν * d.τ^2 / sum(randn(round(Int,d.ν)).^2))
end
"""
```
DegenerateMvNormal <: Distribution{Multivariate, Continuous}
```
The `DegenerateMvNormal` mutable struct implements a degenerate multivariate normal
distribution. The covariance matrix may not be full rank (hence degenerate).
See [Multivariate normal distribution - Degenerate case](en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case).
"""
mutable struct DegenerateMvNormal <: Distribution{Multivariate, Continuous}
μ::Vector # mean
σ::Matrix # standard deviation
σ_inv::Matrix # inverse of variance-covariance matrix
λ_vals::Vector # eigenvalues of σ
end
"""
```
DegenerateMvNormal(μ::Vector, σ::Matrix)
```
Constructor for DegenerateMvNormal type.
"""
function DegenerateMvNormal(μ::Vector, σ::Matrix)
return DegenerateMvNormal(μ, σ, Matrix{eltype(μ)}(undef,0,0), Vector{eltype(μ)}(undef,0))
end
"""
```
function init_deg_mvnormal(μ::Vector, σ::Matrix)
```
Initializes fields for DegenerateMvNormal type.
"""
function init_deg_mvnormal(μ::Vector, σ::Matrix)
U, λ_vals, Vt = svd(σ)
λ_inv = [λ > 1e-6 ? 1/λ : 0.0 for λ in λ_vals]
σ_inv = Vt' * Diagonal(λ_inv) * U'
return DegenerateMvNormal(μ, σ, σ_inv, λ_vals)
end
"""
```
Distributions.logpdf(d::DegenerateMvNormal)
```
Method bypasses Distributions package implementation of logpdf so as to minimize numerical error.
"""
function Distributions.logpdf(d::DegenerateMvNormal, x::Vector{T}) where T<:Real
# Occurs if one initialized a DegenerateMvNormal w/o storing inverted covariance matrix
if isempty(d.σ_inv)
d.σ_inv = inv(d.σ)
λ_all, _ = eigen(d.σ)
d.λ_vals = filter(x -> x>1e-6, λ_all)
end
return -(length(d.μ) * log2π + sum(log.(d.λ_vals)) + ((x .- d.μ)'*d.σ_inv*(x .- d.μ))) / 2.0
end
"""
```
rank(d::DegenerateMvNormal)
```
Returns the rank of `d.σ`.
"""
function LinearAlgebra.rank(d::DegenerateMvNormal)
return rank(d.σ)
end
"""
```
length(d::DegenerateMvNormal)
```
Returns the dimension of `d`.
"""
Base.length(d::DegenerateMvNormal) = length(d.μ)
"""
```
Distributions.rand(d::DegenerateMvNormal; cc::T = 1.0) where T<:AbstractFloat
```
Generate a draw from `d` with variance optionally scaled by `cc^2`.
"""
function Distributions.rand(d::DegenerateMvNormal; cc::T = 1.0) where T<:AbstractFloat
return d.μ + cc*d.σ*randn(length(d))
end
"""
```
Distributions.rand(d::DegenerateMvNormal, n::Int)
```
Generate `n` draws from `d`. This returns a matrix of size `(length(d), n)`,
where each column is a sample.
"""
function Distributions.rand(d::DegenerateMvNormal, n::Int)
return d.μ .+ d.σ*randn(length(d), n)
end
"""
```
DegenerateDiagMvTDist <: Distribution{Multivariate, Continuous}
```
The `DegenerateDiagMvTDist` mutable struct implements a degenerate multivariate Student's t
distribution, where the covariance matrix is diagonal. The covariance matrix may
not be full rank (hence degenerate).
"""
mutable struct DegenerateDiagMvTDist <: Distribution{Multivariate, Continuous}
μ::Vector # mean
σ::Matrix # standard deviation
ν::Int # degrees of freedom
function DegenerateDiagMvTDist(μ::Vector, σ::Matrix, ν::Int)
ν > 0 ? nothing : error("Degrees of freedom (ν) must be positive")
isdiag(σ^2) ? nothing : error("Covariance matrix (σ^2) must be diagonal")
return new(μ, σ, ν)
end
end
"""
```
LinearAlgebra.rank(d::DegenerateDiagMvTDist)
```
Returns the rank of `d.σ`.
"""
function rank(d::DegenerateDiagMvTDist)
return rank(d.σ)
end
"""
```
length(d::DegenerateDiagMvTDist)
```
Returns the dimension of `d`.
"""
Base.length(d::DegenerateDiagMvTDist) = length(d.μ)
"""
```
Distributions.rand(d::DegenerateDiagMvTDist)
```
Generate a draw from `d`.
"""
function Distributions.rand(d::DegenerateDiagMvTDist)
return d.μ + d.σ*rand(TDist(d.ν), length(d))
end
"""
```
Distributions.rand(d::DegenerateDiagMvTDist, n::Int)
```
Generate `n` draws from `d`. This returns a matrix of size `(length(d), n)`,
where each column is a sample.
"""
function Distributions.rand(d::DegenerateDiagMvTDist, n::Int)
return d.μ .+ d.σ*rand(TDist(d.ν), length(d), n)
end
# Compute the mean μ and standard deviation σ of a RootInverseGamma object.
# A Root Inverse Gamma / Nagasaki Scaled Chi2 Distribution's mean and standard deviation
# can be computed as follows:
# μ = √(β) * Γ(α - 0.5) / Γ(α)
# σ = √(β / (α - 1) - μ²)
# where α = ν/2 and β = τ²*ν/2.
function mean(dist::RootInverseGamma)
α = dist.ν/2
β = dist.τ^2 * dist.ν/2
μ = β^(.5) * gamma(α - 0.5) / gamma(α)
return μ
end
function std(dist::RootInverseGamma)
μ = mean(dist)
α = dist.ν/2
β = dist.τ^2 * dist.ν/2
σ = (β / (α - 1) - μ^2)^(0.5)
return σ
end
"""
```
MatrixNormal <: Distribution{Matrixvariate, Continuous}
```
The `MatrixNormal` mutable struct implements a matrixvariate normal
distribution. Note that the matrix must be square.
See [Matrix normal distribution - Degenerate case](en.wikipedia.org/wiki/Matrix_normal_distribution).
"""
mutable struct MatrixNormal <: Distribution{Matrixvariate, Continuous}
μ::Matrix # mean
U::Matrix # row variance
V::Matrix # col variance
U_sqrt::Matrix # cholesky of U
V_sqrt::Matrix # choleksy of V
U_inv::Matrix # inverse of U
V_inv::Matrix # inverse of V
function MatrixNormal(μ::Matrix, U::Matrix, V::Matrix)
size(μ,1) == size(U,1) || error("μ and U must have the same number of rows")
size(μ,2) == size(V,1) || error("μ and V must have the same number of columns")
isposdef(U) || error("U is not a positive definite matrix")
isposdef(V) || error("V is not a positive definite matrix")
U_sqrt = Matrix(chol(U))
V_sqrt = Matrix(chol(V))
U_inv = inv(U)
V_inv = inv(V)
return new(μ, U, V, U_sqrt, V_sqrt, U_inv, V_inv)
end
function MatrixNormal(μ::Matrix, Σ::Matrix)
size(μ) == size(Σ) || error("μ and Σ must be the same size")
isposdef(Σ) || error("Σ is not a positive definite matrix")
Σ_sqrt = Matrix(chol(U))
Σ_inv = inv(U)
return new(μ, Σ, Σ, Σ_sqrt, Σ_sqrt, Σ_inv, Σ_inv)
end
end
"""
```
size(d::MatrixNormal)
```
Returns the dimension of `d`.
"""
Base.size(d::MatrixNormal) = size(d.μ)
"""
```
Distributions.rand(d::MatrixNormal)
```
Generate a draw from `d`.
"""
function Distributions.rand(d::MatrixNormal)
return d.μ + d.U_sqrt*randn(size(d.μ))*d.V_sqrt'
end
function mean(d::MatrixNormal)
return d.μ
end
Distributions.params(d::MatrixNormal) = d.μ, d.U, d.V
"""
```
Distributions.pdf(d::MatrixNormal, x::Matrix)
```
Compute the pdf of a MatrixNormal distribution at x.
"""
function Distributions.pdf(d::MatrixNormal, x::Matrix)
μ, U, V = params(d)
n, p = size(μ)
U_inv = d.U_inv
V_inv = d.V_inv
return exp(-.5*trace(V_inv * (x-μ)' * U_inv * (x-μ))) / ((2π)^(n*p/2) * det(U)^(p/2) * det(V)^(n/2))
end
"""
```
Distributions.logpdf(d::MatrixNormal, x::Matrix)
```
Compute the logpdf of a MatrixNormal distribution at x.
"""
function Distributions.logpdf(d::MatrixNormal, x::Matrix)
μ, U, V = params(d)
n, p = size(μ)
U_inv = d.U_inv
V_inv = d.V_inv
return -.5*trace(V_inv * (x-μ)' * U_inv * (x-μ)) - log((2π)^(n*p/2) * det(U)^(p/2) * det(V)^(n/2))
end
"""
```
truncmean(Dist::Truncated)
```
Computes the mean of truncated continuous and discrete distributions.
Written by person in this [comment](https://github.com/JuliaStats/Distributions.jl/issues/709).
Thanks, dude!
"""
function truncmean(Dist::Truncated)
F(x) = x*pdf(Dist,x)
y = 0.0;
if typeof(Dist) <: ContinuousDistribution # Continuous distribution
y = quadgk(F, Dist.lower, Dist.upper)[1]
else # Discrete distriubtion
x = ceil(Dist.lower)
q_max = 1 - 1E-9;
x_max = min(Dist.upper, quantile(Dist.untruncated, q_max))
while x < x_max
y += F(x)
x += 1
end
end
return y
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 1732 | mutable struct GenericModel{T} <: AbstractModel{T}
parameters::ParameterVector{T}
steady_state::ParameterVector{T}
keys::Dict{Symbol, Int}
endogenous_states::Dict{Symbol,Int} # these fields used to create matrices in the
exogenous_shocks::Dict{Symbol,Int} # measurement and equilibrium condition equations.
observables::Dict{Symbol,Int} #
pseudo_observables::Dict{Symbol,Int} #
spec::String
subspec::String
settings::Dict{Symbol, Setting}
test_settings::Dict{Symbol, Setting}
rng::MersenneTwister
testing::Bool
observable_mappings::Dict{Symbol, Observable}
pseudo_observable_mappings::Dict{Symbol, PseudoObservable}
end
function GenericModel(spec::String = "", subspec::String = ""; custom_settings::Dict{Symbol, Setting} = Dict{Symbol, Setting}(), testing = false)
settings = Dict{Symbol, Setting}()
test_settings = Dict{Symbol, Setting}()
rng = MersenneTwister(0)
m = GenericModel{Float64}(
Vector{AbstractParameter{Float64}}(), Vector{AbstractParameter{Float64}}(),
Dict{Symbol, Int}(),
Dict{Symbol, Int}(), Dict{Symbol, Int}(), Dict{Symbol, Int}(), Dict{Symbol, Int}(),
spec, subspec, settings, test_settings, rng, testing,
Dict{Symbol, Observable}(), Dict{Symbol, PseudoObservable}())
model_settings!(m)
default_test_settings!(m)
for custom_setting in values(custom_settings)
m <= custom_setting
end
return m
end
description(m::GenericModel) = "A generic model: You can put parameters, states, shocks, observables, pseudo-observables, spec, subpsec, settings inside of me."
function model_settings!(m::GenericModel)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 1724 | mutable struct LinearRegression{T} <: AbstractModel{T}
parameters::ParameterVector{T}
keys::Dict{Symbol, Int}
spec::String
subspec::String
settings::Dict{Symbol, Setting}
test_settings::Dict{Symbol, Setting}
rng::MersenneTwister
testing::Bool
end
description(m::LinearRegression) = "LinearRegression model."
function LinearRegression(spec::String="", subspec::String="ss0";
custom_settings::Dict{Symbol, Setting} = Dict{Symbol, Setting}(),
testing = false)
settings = Dict{Symbol,Setting}()
test_settings = Dict{Symbol,Setting}()
rng = MersenneTwister(0)
m = LinearRegression{Float64}(
Vector{AbstractParameter{Float64}}(), Dict{Symbol, Int}(),
spec,
subspec,
settings, test_settings,
rng,
testing)
default_settings!(m)
default_test_settings!(m)
for custom_setting in values(custom_settings)
m <= custom_setting
end
init_parameters!(m)
return m
end
"""
```
init_parameters!(m::LinearRegression)
```
Initializes the model's parameters, as well as empty values for the steady-state
parameters (in preparation for `steadystate!(m)` being called to initialize
those).
"""
function init_parameters!(m::LinearRegression)
m <= parameter(:α, 1., (-1e3, 1e3), (-1e3, 1e3), Untransformed(),
Normal(0., 1.0), fixed = false)
m <= parameter(:β, 1., (-1e3, 1e3), (-1e3, 1e3), Untransformed(),
Normal(0., 1.0), fixed = false)
m <= parameter(:σ, 1., (0., 1e3), (1e-3, 1e3), Untransformed(),
Normal(1., 1.0), fixed = false)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 2140 | """
```
mutable struct Observable
```
### Fields
- `key::Symbol`
- `input_series::Vector{Symbol}`: vector of mnemonics, each in the form
`:MNEMONIC__SOURCE` (e.g. `:GDP__FRED`). This vector is parsed to determine
source (e.g. per-capita consumption gets population and consumption).
- `fwd_transform::Function`: Extracts appropriate `input_series` from a
DataFrame of levels, and transforms data to model units (for example, computes
per-capita growth rates from levels).
- `rev_transform::Function`: Transforms a series from model units into
observable units. May take kwargs.
- `name::String`: e.g. \"Real GDP growth\"
- `longname::String`: e.g. \"Real GDP growth per capita\"
"""
mutable struct Observable
key
input_series::Vector{Symbol} # (vector of Mnemonics, e.g. GDPC1@FRED)
# parse this to determine source
# (eg consumption per cap gets population and consumption)
fwd_transform::Function # corresponds to data_transforms field.
# Operates on dataframe of levels, that has every data series
# requested by any observable
rev_transform::Function # corresponds to getyp, or getyp4q. May take kwargs (untransformed,
# 1q transforms, 4q transforms, levels/growth rates, etc)
name::String
longname::String
end
"""
```
mutable struct PseudoObservable
```
### Fields
- `key::Symbol`
- `name::String`: e.g. \"Flexible Output Growth\"
- `longname::String`: e.g. \"Output that would prevail in a flexible-price
economy\"
- `rev_transform::Function`: Transforms a series from model units into
observable units. May take kwargs.
"""
mutable struct PseudoObservable
key::Symbol
name::String
longname::String
rev_transform::Function
end
function PseudoObservable(k::Symbol)
PseudoObservable(k, "", "", identity)
end
function check_mnemonics(levels::DataFrame, mnemonics::Symbol)
for mnemonic in mnemonics
@assert in(mnemonic, names(levels)) "Dataframe is missing $(mnemonic)"
end
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 63633 | import Base: <=
Interval{T} = Tuple{T,T}
"""
```
Transform
```
Subtypes of the abstract Transform type indicate how a `Parameter`'s
value is transformed from model space (which can be bounded to a
limited section of the real line) to the entire real line (which is
necessary for mode-finding using csminwel). The transformation is
performed by the `transform_to_real_line` function, and is reversed by the
`transform_to_model_space` function.
"""
abstract type Transform end
struct Untransformed <: Transform end
struct SquareRoot <: Transform end
struct Exponential <: Transform end
Base.show(io::IO, t::Untransformed) = @printf io "x -> x\n"
Base.show(io::IO, t::SquareRoot) = @printf io "x -> (a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)\n"
Base.show(io::IO, t::Exponential) = @printf io "x -> b + (1/c) * log(x-a)\n"
"""
```
AbstractParameter{T<:Number}
```
The AbstractParameter type is the common supertype of all model
parameters, including steady-state values. Its subtype structure is
as follows:
-`AbstractParameter{T<:Number}`: The common abstract supertype for all parameters.
-`Parameter{S<:Real,T<:Number, U<:Transform}`: The abstract supertype for parameters that are directly estimated.
-`UnscaledParameter{S<:Real, T<:Number, U:<Transform}`: Concrete type for parameters that do not need to be scaled for equilibrium conditions.
-`ScaledParameter{S<:Real, T<:Number, U:<Transform}`: Concrete type for parameters that are scaled for equilibrium conditions.
-`SteadyStateParameter{T<:Number}`: Concrete type for steady-state parameters.
"""
abstract type AbstractParameter{T<:Number} end
abstract type AbstractVectorParameter{V<:Vector, T<:Number} end
#abstract type AbstractArrayParameter{A<:Array} end
"""
```
Parameter{ S<:Real, T<:Number, U<:Transform} <: AbstractParameter{T}
```
The Parameter type is the common supertype of time-invariant, non-steady-state model
parameters. It has 2 subtypes, `UnscaledParameter` and `ScaledParameter`.
`ScaledParameter`s are parameters whose values are scaled when used in the model's
equilibrium conditions. The scaled value is stored for convenience, and updated when the
parameter's value is updated.
The Parameter type has separate `T` and `S` types to allow for
automatic differentiation, which will make the type of `S` a Dual type. By specifying
this difference, while we cannot enforce `T` and `S` to always sensibly match
each others types, we can avoid the issue of having to recast the types of fields
with type `T` to be Duals as well.
"""
abstract type Parameter{T,U<:Transform} <: AbstractParameter{T} end
abstract type ParameterAD{S<:Real,T,U} <: Parameter{T,U} end
abstract type VectorParameter{V,T,U<:Transform} <: AbstractVectorParameter{V,T} end
#abstract type ArrayParameter{A,U<:Transform} <: AbstractArrayParameter{A} end
# ParameterVector is a wrapper for a vector
# that takes any subtype of AbstractParameter, but it is not
# an "abstract" type since we are not intending
# to define subtypes of ParameterVector.
ParameterVector{T} = Vector{AbstractParameter{T}}
VectorParameterVector{V,T} = Vector{AbstractVectorParameter{V,T}}
#ArrayParameterVector{A} = Vector{AbstractArrayParameter{A}}
NullablePriorUnivariate = Nullables.Nullable{ContinuousUnivariateDistribution}
NullablePriorMultivariate = Nullables.Nullable{ContinuousMultivariateDistribution}
"""
```
UnscaledParameter{S<:Real,T<:Number,U<:Transform} <: Parameter{S,T,U}
```
Time-invariant model parameter whose value is used as-is in the model's equilibrium
conditions.
#### Fields
- `key::Symbol`: Parameter name. For maximum clarity, `key`
should conform to the guidelines established in the DSGE Style Guide.
- `value::S`: Parameter value. Initialized in model space (guaranteed
to be between `valuebounds`), but can be transformed between model
space and the real line via calls to `transform_to_real_line` and
`transform_to_model_space`.
- `valuebounds::Interval{T}`: Bounds for the parameter's value in model space.
- `transform_parameterization::Interval{T}`: Parameters used to
transform `value` between model space and the real line.
- `transform::U`: Transformation used to transform `value` between
model space and real line.
- `prior::NullablePrior`: Prior distribution for parameter value.
- `fixed::Bool`: Indicates whether the parameter's value is fixed rather than estimated.
- `regimes::Dict{Symbol,OrderedDict{Int64,Any}}`: Dictionary for holding information
when there are multiple regimes for parameter values
- `description::String`: A short description of the parameter's economic
significance.
- `tex_label::String`: String for printing the parameter name to LaTeX.
"""
mutable struct UnscaledParameterAD{S,T,U} <: ParameterAD{S,T,U} # New parameter type for Autodiff
key::Symbol
value::S # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorUnivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
mutable struct UnscaledParameter{T,U} <: Parameter{T,U} # Old parameter type
key::Symbol
value::T # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorUnivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
mutable struct UnscaledVectorParameter{V,T,U} <: VectorParameter{V,T,U}
key::Symbol
value::V # parameter value in model space
valuebounds::Interval{T} # bounds of parameter value
transform_parameterization::Interval{T} # parameters for transformation
transform::U # transformation between model space and real line for optimization
prior::NullablePriorMultivariate # prior distribution
fixed::Bool # is this parameter fixed at some value?
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String # LaTeX label for printing
end
"""
```
ScaledParameter{S,T,U} <: Parameter{S,T,U}
```
Time-invariant model parameter whose value is scaled for use in the model's equilibrium
conditions.
#### Fields
- `key::Symbol`: Parameter name. For maximum clarity, `key`
should conform to the guidelines established in the DSGE Style Guide.
- `value::T`: The parameter's unscaled value. Initialized in model
space (guaranteed to be between `valuebounds`), but can be
transformed between model space and the real line via calls to
`transform_to_real_line` and `transform_to_model_space`.
- `scaledvalue::T`: Parameter value scaled for use in `eqcond.jl`
- `valuebounds::Interval{T}`: Bounds for the parameter's value in model space.
- `transform_parameterization::Interval{T}`: Parameters used to
transform `value` between model space and the real line.
- `transform::U`: The transformation used to convert `value` between model space and the
real line, for use in optimization.
- `prior::NullablePrior`: Prior distribution for parameter value.
- `fixed::Bool`: Indicates whether the parameter's value is fixed rather than estimated.
- `scaling::Function`: Function used to scale parameter value for use in equilibrium
conditions.
- `regimes::Dict{Symbol,OrderedDict{Int64,Any}}`: Dictionary for holding information
when there are multiple regimes for parameter values
- `description::String`: A short description of the parameter's economic
significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct ScaledParameterAD{S,T,U} <: ParameterAD{S,T,U}
key::Symbol
value::S
scaledvalue::S
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorUnivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
mutable struct ScaledParameter{T,U} <: Parameter{T,U}
key::Symbol
value::T #S
scaledvalue::T #S
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorUnivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
mutable struct ScaledVectorParameter{V,T,U} <: VectorParameter{V,T,U}
key::Symbol
value::V
scaledvalue::V
valuebounds::Interval{T}
transform_parameterization::Interval{T}
transform::U
prior::NullablePriorMultivariate
fixed::Bool
scaling::Function
regimes::Dict{Symbol,OrderedDict{Int64,Any}}
description::String
tex_label::String
end
"""
```
SteadyStateParameter{T} <: AbstractParameter{T}
```
Steady-state model parameter whose value depends upon the value of other (non-steady-state)
`Parameter`s. `SteadyStateParameter`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameter`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameter`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::T`: The parameter's steady-state value.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameter{T} <: AbstractParameter{T}
key::Symbol
value::T
description::String
tex_label::String
end
"""
```
SteadyStateValueGrid{T} <: AbstractParameter{T}
```
Steady-state model parameter grid (for heterogeneous agent models) whose value is calculated by an
iterative procedure.
`SteadyStateParameterGrid`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameterGrid`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameter`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::Array{T}`: The parameter's steady-state value grid.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameterGrid{T} <: AbstractParameter{T}
key::Symbol
value::Array{T}
description::String
tex_label::String
end
function SteadyStateParameterGrid(key::Symbol,
value::Array{T};
description::String = "No description available",
tex_label::String = "") where {T<:Number}
return SteadyStateParameterGrid{T}(key, value, description, tex_label)
end
"""
```
SteadyStateParameterArray{T} <: AbstractParameter{T}
```
Steady-state model parameter whose value is an Array and
depends upon the value of other (non-steady-state)
`Parameter`s. `SteadyStateParameterArray`s must be constructed and added to an instance of a
model object `m` after all other model `Parameter`s have been defined. Once added to `m`,
`SteadyStateParameterArray`s are stored in `m.steady_state`. Their values are calculated and set
by `steadystate!(m)`, rather than being estimated directly. `SteadyStateParameterArray`s do not
require transformations from the model space to the real line or scalings for use in
equilibrium conditions.
#### Fields
- `key::Symbol`: Parameter name. Should conform to the guidelines
established in the DSGE Style Guide.
- `value::Array{T}`: The parameter's steady-state values.
- `description::String`: Short description of the parameter's economic significance.
- `tex_label::String`: String for printing parameter name to LaTeX.
"""
mutable struct SteadyStateParameterArray{T} <: AbstractParameter{T}
key::Symbol
value::Array{T}
description::String
tex_label::String
end
"""
```
SteadyStateParameterArray{T<:Number}(key::Symbol, value::Array{T};
description::String = "",
tex_label::String = "")
```
SteadyStateParameter constructor with optional `description` and `tex_label` arguments.
"""
function SteadyStateParameterArray(key::Symbol,
value::Array{T};
description::String = "No description available",
tex_label::String = "") where {T<:Number}
return SteadyStateParameterArray(key, value, description, tex_label)
end
# TypeError: non-boolean (BitArray{1}) used in boolean context
# gets thrown when we print the value.
function Base.show(io::IO, p::SteadyStateParameterArray{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: [%+6f,...,%+6f]\n" p.value[1] p.value[end]
end
hasprior(p::Union{Parameter, ParameterAD, VectorParameter}) = !isnull(p.prior)
NullableOrPriorUnivariate = Union{NullablePriorUnivariate, ContinuousUnivariateDistribution}
NullableOrPriorMultivariate = Union{NullablePriorMultivariate, ContinuousMultivariateDistribution}
# We want to use value field from UnscaledParameters and
# SteadyStateParameters in computation, so we alias their union here.
UnscaledOrSteadyState = Union{UnscaledParameter, SteadyStateParameter}
"""
```
ParamBoundsError <: Exception
```
A `ParamBoundsError` is thrown upon an attempt to assign a parameter value that is not
between `valuebounds`.
"""
mutable struct ParamBoundsError <: Exception
msg::String
end
ParamBoundsError() = ParamBoundsError("Value not between valuebounds")
Base.showerror(io::IO, ex::ParamBoundsError) = print(io, ex.msg)
"""
```
parameter{S,T,U<:Transform}(key::Symbol, value::S, valuebounds = (value,value),
transform_parameterization = (value,value),
transform = Untransformed(), prior = NullablePrior();
fixed = true, scaling::Function = identity, description = "",
tex_label::String = "")
```
By default, returns a fixed `UnscaledParameter` object with key `key`
and value `value`. If `scaling` is given, a `ScaledParameter` object
is returned.
"""
function parameter(key::Symbol,
value::Union{T, V}, #value::Union{S,V},
valuebounds::Interval{T} = (value,value),
transform_parameterization::Interval{T} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, T <: Real, U <:Transform} #{V<:Vector, S<:Real, T <: Float64, U <:Transform}
# If fixed=true, force bounds to match and leave prior as null. We need to define new
# variable names here because of lexical scoping.
valuebounds_new = valuebounds
transform_parameterization_new = transform_parameterization
transform_new = transform
U_new = U
prior_new = prior
if fixed
# value[1] because need to deal with case in which value is a vector (but if only Float, [1] just takes the Float
transform_parameterization_new = (value[1],value[1]) # value is transformed already
transform_new = Untransformed() # fixed priors should stay untransformed
U_new = Untransformed
if isa(transform, Untransformed)
valuebounds_new = (value[1],value[1])
end
else
transform_parameterization_new = transform_parameterization
end
# ensure that we have a Nullable{Distribution}, if not construct one
prior_new = if isa(prior_new, NullableOrPriorUnivariate)
!isa(prior_new,NullablePriorUnivariate) ? NullablePriorUnivariate(prior_new) : prior_new
elseif isa(prior_new, NullableOrPriorMultivariate)
!isa(prior_new,NullablePriorMultivariate) ? NullablePriorMultivariate(prior_new) : prior_new
else
@error "Must be a PriorOrNullable or PriorOrNullableMultivariate"
end
if scaling == identity
if typeof(value) <: Number #Real
return UnscaledParameter{T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label) #S
elseif typeof(value) <: Vector
return UnscaledVectorParameter{V,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label)
else
@error "Type of value not yet supported"
end
else
if typeof(value) <: Number #Real
return ScaledParameter{T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
elseif typeof(value) <: Vector
return ScaledVectorParameter{V,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
end
end
end
function parameter(key::Symbol,
value::Union{T1, V}, #value::Union{S,V},
valuebounds::Interval{T2} = (value,value),
transform_parameterization::Interval{T3} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, T1 <: Real, T2 <: Real, T3 <: Real, U <:Transform}
warn_str = "The element types of the fields `value` ($(typeof(value))), `valuebounds` ($(eltype(valuebounds))), " *
"and `transform_parameterization` ($(eltype(transform_parameterization))) do not match. " *
"Attempting to convert all types to the same type as `value`. Note that the element type for the prior " *
"distribution should also be $(typeof(value))."
@warn warn_str
valuebounds_new = (convert(T1, valuebounds[1]), convert(T1, valuebounds[2]))
transform_parameterization_new = (convert(T1, transform_parameterization[1]),
convert(T1, transform_parameterization[2]))
return parameter(key, value, valuebounds_new, transform_parameterization_new,
transform, prior; fixed = fixed, scaling = scaling,
regimes = regimes, description = description, tex_label = tex_label)
end
function parameter_ad(key::Symbol,
value::Union{S,V},
valuebounds::Interval{T} = (value,value),
transform_parameterization::Interval{T} = (value,value),
transform::U = Untransformed(),
prior::Union{NullableOrPriorUnivariate, NullableOrPriorMultivariate} = NullablePriorUnivariate();
fixed::Bool = true,
scaling::Function = identity,
regimes::Dict{Symbol,OrderedDict{Int64,Any}} = Dict{Symbol,OrderedDict{Int64,Any}}(),
description::String = "No description available.",
tex_label::String = "") where {V<:Vector, S<:Real, T <: Float64, U <:Transform}
# If fixed=true, force bounds to match and leave prior as null. We need to define new
# variable names here because of lexical scoping.
valuebounds_new = valuebounds
transform_parameterization_new = transform_parameterization
transform_new = transform
U_new = U
prior_new = prior
if fixed
# value[1] because need to deal with case in which value is a vector (but if only Float, [1] just takes the Float
transform_parameterization_new = (value[1],value[1]) # value is transformed already
transform_new = Untransformed() # fixed priors should stay untransformed
U_new = Untransformed
if isa(transform, Untransformed)
valuebounds_new = (value[1],value[1])
end
else
transform_parameterization_new = transform_parameterization
end
# ensure that we have a Nullable{Distribution}, if not construct one
prior_new = if isa(prior_new, NullableOrPriorUnivariate)
!isa(prior_new,NullablePriorUnivariate) ? NullablePriorUnivariate(prior_new) : prior_new
elseif isa(prior_new, NullableOrPriorMultivariate)
!isa(prior_new,NullablePriorMultivariate) ? NullablePriorMultivariate(prior_new) : prior_new
else
@error "Must be a PriorOrNullable or PriorOrNullableMultivariate"
end
if scaling == identity
if typeof(value) <: Real
return UnscaledParameterAD{S,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label) #S
elseif typeof(value) <: Vector
return UnscaledVectorParameter{V,T,U_new}(key, value, valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, regimes, description, tex_label)
else
@error "Type of value not yet supported"
end
else
if typeof(value) <: Real
return ScaledParameterAD{S,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
elseif typeof(value) <: Vector
return ScaledVectorParameter{V,T,U_new}(key, value, scaling(value), valuebounds_new,
transform_parameterization_new, transform_new,
prior_new, fixed, scaling, regimes, description, tex_label)
end
end
end
function parameter(key::Symbol,
prior::Union{ContinuousUnivariateDistribution, ContinuousMultivariateDistribution};
fixed::Bool = false,
description::String = "No description available",
tex_label::String = "")
val = length(prior) > 1 ? repeat([NaN], length(prior)) : NaN
return parameter(key, val, (NaN, NaN), (NaN, NaN), Untransformed(), prior, fixed = fixed, scaling = identity, description = description, tex_label = tex_label)
end
"""
```
SteadyStateParameter(key::Symbol, value::T; description::String = "",
tex_label::String = "") where {T <: Number}
```
SteadyStateParameter constructor with optional `description` and `tex_label` arguments.
"""
function SteadyStateParameter(key::Symbol, value::T;
description::String = "No description available",
tex_label::String = "") where {T <: Number}
return SteadyStateParameter(key, value, description, tex_label)
end
"""
```
parameter(p::UnscaledParameter{S,T,U}, newvalue::S) where {S<:Real,T<:Number,U<:Transform}
```
Returns an UnscaledParameter with value field equal to `newvalue`. If `p` is a fixed
parameter, it is returned unchanged.
"""
function parameter(p::UnscaledParameter{T,U}, newvalue::T) where {T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
UnscaledParameter{T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
function parameter_ad(p::UnscaledParameterAD{S,T,U}, newvalue::Snew;
change_value_type::Bool = false) where {S<:Real, Snew<:Real, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
if !change_value_type && (typeof(p.value) != typeof(newvalue))
error("Type of newvalue $(newvalue) does not match the type of the current value for parameter $(string(p.key)). Set keyword change_value_type = true if you want to overwrite the type of the parameter value.")
end
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
if change_value_type
UnscaledParameterAD{Snew,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
else
UnscaledParameterAD{S,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
end
function parameter(p::UnscaledVectorParameter{V,T,U}, newvalue::V) where {V <: Vector, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !all(a .<= newvalue .<= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
UnscaledVectorParameter{V,T,U}(p.key, newvalue, p.valuebounds, p.transform_parameterization,
p.transform, p.prior, p.fixed, p.regimes, p.description, p.tex_label)
end
"""
```
parameter(p::ScaledParameter{S,T,U}, newvalue::S) where {S<:Real, T<:Number,U<:Transform}
```
Returns a ScaledParameter with value field equal to `newvalue` and scaledvalue field equal
to `p.scaling(newvalue)`. If `p` is a fixed parameter, it is returned unchanged.
"""
function parameter(p::ScaledParameter{T,U}, newvalue::T) where {T <: Number, U <: Transform} #S:<Real, Snew:< Real
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
ScaledParameter{T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
function parameter_ad(p::ScaledParameterAD{S,T,U}, newvalue::Snew;
change_value_type::Bool = false) where {S<:Real, Snew<:Real, T<:Number, U<:Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
if !change_value_type && (typeof(p.value) != typeof(newvalue))
error("Type of newvalue $(newvalue) does not match value of parameter $(string(p.key)).")
end
a,b = p.valuebounds
if !(a <= newvalue <= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
if change_value_type
ScaledParameterAD{Snew,T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
else
ScaledParameterAD{S,T,U}(p.key, newvalue, p.scaling(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
end
function parameter(p::ScaledVectorParameter{V,T,U}, newvalue::V) where {V <: Vector, T <: Number, U <: Transform}
p.fixed && return p # if the parameter is fixed, don't change its value
a,b = p.valuebounds
if !all(a .<= newvalue .<= b)
throw(ParamBoundsError("New value of $(string(p.key)) ($(newvalue)) is out of bounds ($(p.valuebounds))"))
end
ScaledVectorParameter{V,T,U}(p.key, newvalue, p.scaling.(newvalue), p.valuebounds,
p.transform_parameterization, p.transform, p.prior, p.fixed,
p.scaling, p.regimes, p.description, p.tex_label)
end
function Base.show(io::IO, p::Parameter{T,U}) where {T, U} #S,T,U
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
@printf io "unscaled, untransformed value: %+6f\n" p.value
isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::ParameterAD{S,T,U}) where {S,T,U}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
@printf io "unscaled, untransformed value: %+6f\n" p.value
isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::VectorParameter{V,T,U}) where {V,T, U}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
#@printf io "real value: %+6f\n" transform_to_real_line(p)
join([@printf io "%+6f\n" x for x in p.value], ", ")
#isa(p,ScaledParameter) && @printf "scaled, untransformed value: %+6f\n" p.scaledvalue
#!isa(U(),Untransformed) && @printf io "transformed value: %+6f\n" p.value
if hasprior(p)
@printf io "prior distribution:\n\t%s\n" get(p.prior)
else
@printf io "prior distribution:\n\t%s\n" "no prior"
end
@printf io "transformation for csminwel:\n\t%s" U()
@printf io "parameter is %s\n" p.fixed ? "fixed" : "not fixed"
end
function Base.show(io::IO, p::SteadyStateParameter{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: %+6f\n" p.value
end
function Base.show(io::IO, p::SteadyStateParameterGrid{T}) where {T}
@printf io "%s\n" typeof(p)
@printf io "(:%s)\n%s\n" p.key p.description
@printf io "LaTeX label: %s\n" p.tex_label
@printf io "-----------------------------\n"
@printf io "value: [%f,...,%f]" p.value[1] p.value[end]
end
"""
```
transform_to_model_space{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Transforms `x` from the real line to lie between `p.valuebounds` without updating `p.value`.
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: `x`
- SquareRoot: `(a+b)/2 + (b-a)/2 * c * x/sqrt(1 + c^2 * x^2)`
- Exponential: `a + exp(c*(x-b))`
"""
transform_to_model_space(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = x
function transform_to_model_space(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
(a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)
end
transform_to_model_space(p::Parameter{T,Untransformed}, x::T) where T = x
function transform_to_model_space(p::Parameter{T,SquareRoot}, x::T) where T
(a,b), c = p.transform_parameterization, one(T)
(a+b)/2 + (b-a)/2*c*x/sqrt(1 + c^2 * x^2)
end
function transform_to_model_space(p::ParameterAD{S,<:Number,Exponential}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
a + exp(c*(x-b))
end
function transform_to_model_space(p::Parameter{T,Exponential}, x::T) where T
(a,b), c = p.transform_parameterization, one(T)
a + exp(c*(x-b))
end
@inline function transform_to_model_space(pvec::ParameterVector{T}, values::Vector{T};
regime_switching::Bool = false) where T
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_model_space, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_model_space(p, values[plen + i])
end
end
end
end
return output
else
return map(transform_to_model_space, pvec, values)
end
end
@inline function transform_to_model_space(pvec::ParameterVector, values::Vector{S};
regime_switching::Bool = false) where S
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_model_space, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_model_space(p, values[plen + i])
end
end
end
end
return output
else
return map(transform_to_model_space, pvec, values)
end
end
"""
```
differentiate_transform_to_model_space{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Differentiates the transform of `x` from the real line to lie between `p.valuebounds`
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: `x`
- SquareRoot: `(a+b)/2 + (b-a)/2 * c * x/sqrt(1 + c^2 * x^2)`
- Exponential: `a + exp(c*(x-b))`
Their gradients are therefore
- Untransformed: `1`
- SquareRoot: `(b-a)/2 * c / (1 + c^2 * x^2)^(3/2)`
- Exponential: `c * exp(c*(x-b))`
"""
differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = one(S)
function differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
(b-a)/2 * c / (1 + c^2 * x^2)^(3/2)
end
function differentiate_transform_to_model_space(p::ParameterAD{S,<:Number,Exponential}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
c * exp(c*(x-b))
end
differentiate_transform_to_model_space(pvec::ParameterVector, values::Vector{S}) where S = map(differentiate_transform_to_model_space, pvec, values)
"""
```
transform_to_real_line(p::Parameter{S,T,U}, x::S = p.value) where {S<:Real, T<:Number, U<:Transform}
```
Transforms `p.value` from model space (between `p.valuebounds`) to the real line, without updating
`p.value`. The transformations are defined as follows,
where (a,b) = p.transform_parameterization, c a scalar (default=1), and x = p.value:
- Untransformed: x
- SquareRoot: (1/c)*cx/sqrt(1 - cx^2), where cx = 2 * (x - (a+b)/2)/(b-a)
- Exponential: b + (1 / c) * log(x-a)
"""
transform_to_real_line(p::ParameterAD{S,<:Number,Untransformed}, x::S = p.value) where S = x
function transform_to_real_line(p::ParameterAD{S,<:Number,SquareRoot}, x::S = p.value) where S
(a,b), c = p.transform_parameterization, one(S)
cx = 2. * (x - (a+b)/2.)/(b-a)
if cx^2 >1
println("Parameter is: $(p.key)")
println("a is $a")
println("b is $b")
println("x is $x")
println("cx is $cx")
error("invalid paramter value")
end
(1/c)*cx/sqrt(1 - cx^2)
end
function transform_to_real_line(p::ParameterAD{S,<:Number,Exponential}, x::S = p.value) where S
(a,b),c = p.transform_parameterization,one(S)
b + (1 ./ c) * log(x-a)
end
transform_to_real_line(pvec::ParameterVector, values::Vector{S}) where S = map(transform_to_real_line, pvec, values)
transform_to_real_line(pvec::ParameterVector{S}) where S = map(transform_to_real_line, pvec)
transform_to_real_line(p::Parameter{T,Untransformed}, x::T = p.value) where T = x
function transform_to_real_line(p::Parameter{T,SquareRoot}, x::T = p.value) where T
(a,b), c = p.transform_parameterization, one(T)
cx = 2. * (x - (a+b)/2.)/(b-a)
if cx^2 >1
println("Parameter is: $(p.key)")
println("a is $a")
println("b is $b")
println("x is $x")
println("cx is $cx")
error("invalid paramter value")
end
(1/c)*cx/sqrt(1 - cx^2)
end
function transform_to_real_line(p::Parameter{T,Exponential}, x::T = p.value) where T
(a,b),c = p.transform_parameterization,one(T)
b + (1 ./ c) * log(x-a)
end
@inline function transform_to_real_line(pvec::ParameterVector{T}, values::Vector{T}; regime_switching::Bool = false) where T
if regime_switching
# Transform values in the first regime
output = similar(values)
plen = length(pvec)
map!(transform_to_real_line, output, pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
output[plen + i] = transform_to_real_line(p, values[plen + i])
end
end
end
end
return output
else
map(transform_to_real_line, pvec, values)
end
end
@inline function transform_to_real_line(pvec::ParameterVector{T}; regime_switching::Bool = false) where T
if regime_switching
values = get_values(pvec) # regime-switching parameters returned by default
# Transform values in the first regime
plen = length(pvec) # since values is not passed, we can mutate values directly to avoid extra allocations
map!(transform_to_real_line, (@view values[1:plen]), pvec, values[1:plen])
# Now transform values in the second regime and on
i = 0
for p in pvec
if !isempty(p.regimes)
for (k, v) in p.regimes[:value]
if k != 1 # Skip the first regime.
i += 1 # `values` stores regime values (after the first regime) beside each other.
values[plen + i] = transform_to_real_line(p, values[plen + i])
end
end
end
end
return values
else
map(transform_to_real_line, pvec)
end
end
"""
```
differentiate_transform_to_real_line{S<:Real,T<:Number, U<:Transform}(p::Parameter{S,T,U}, x::S)
```
Differentiates the transform of `x` from the model space lying between `p.valuebounds` to the real line.
The transformations are defined as follows, where (a,b) = p.transform_parameterization and c
a scalar (default=1):
- Untransformed: x
- SquareRoot: (1/c)*cx/sqrt(1 - cx^2), where cx = 2 * (x - (a+b)/2)/(b-a)
- Exponential: b + (1 / c) * log(x-a)
Their gradients are therefore
- Untransformed: `1`
- SquareRoot: `(1/c) * (1 / ( 1 - cx^2)^(-3/2)) * (2/(b-a))`
- Exponential: `1 / (c * (x - a))`
"""
differentiate_transform_to_real_line(p::ParameterAD{S,<:Number,Untransformed}, x::S) where S = one(S)
function differentiate_transform_to_real_line(p::ParameterAD{S,<:Number,SquareRoot}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
cx = 2 * (x - (a+b)/2)/(b-a)
(1/c) * (1 / (1 - cx^2)^(-3/2)) * (2/(b-a))
end
function differentiate_transform_to_real_line(p::ParameterAD{S,<:Number,Exponential}, x::S) where S
(a,b), c = p.transform_parameterization, one(S)
1 / (c * (x - a))
end
differentiate_transform_to_real_line(pvec::ParameterVector, values::Vector{S}) where S = map(differentiate_transform_to_real_line, pvec, values)
differentiate_transform_to_real_line(pvec::ParameterVector{S}) where S = map(differentiate_transform_to_real_line, pvec)
# define operators to work on parameters
Base.convert(::Type{T}, p::UnscaledParameter) where {T<:Real} = convert(T,p.value)
Base.convert(::Type{T}, p::UnscaledVectorParameter) where {T <: Vector} = convert(T,p.value)
Base.convert(::Type{T}, p::ScaledParameter) where {T<:Real} = convert(T,p.scaledvalue)
Base.convert(::Type{T}, p::ScaledVectorParameter) where {T <: Vector} = convert(T,p.scaledvalue)
Base.convert(::Type{T}, p::SteadyStateParameter) where {T<:Real} = convert(T,p.value)
Base.convert(::Type{ForwardDiff.Dual{T,V,N}}, p::UnscaledParameter) where {T,V,N} = convert(V,p.value)
Base.convert(::Type{ForwardDiff.Dual{T,V,N}}, p::ScaledParameter) where {T,V,N} = convert(V,p.scaledvalue)
Base.promote_rule(::Type{AbstractParameter{T}}, ::Type{U}) where {T<:Real, U<:Number} = promote_rule(T,U)
Base.promote_rule(::Type{AbstractVectorParameter{T}}, ::Type{U}) where {T<:Vector, U<:Vector} = promote_rule(T,U)
# Define scalar operators on parameters
for op in (:(Base.:+),
:(Base.:-),
:(Base.:*),
:(Base.:/),
:(Base.:^))
@eval ($op)(p::UnscaledOrSteadyState, q::UnscaledOrSteadyState) = ($op)(p.value, q.value)
@eval ($op)(p::UnscaledOrSteadyState, x::Integer) = ($op)(p.value, x)
@eval ($op)(p::UnscaledOrSteadyState, x::Number) = ($op)(p.value, x)
@eval ($op)(x::Number, p::UnscaledOrSteadyState) = ($op)(x, p.value)
@eval ($op)(p::ScaledParameter, q::ScaledParameter) = ($op)(p.scaledvalue, q.scaledvalue)
@eval ($op)(p::ScaledParameter, x::Integer) = ($op)(p.scaledvalue, x)
@eval ($op)(p::ScaledParameter, x::Number) = ($op)(p.scaledvalue, x)
@eval ($op)(x::Number, p::ScaledParameter) = ($op)(x, p.scaledvalue)
@eval ($op)(p::ScaledParameter, q::UnscaledOrSteadyState) = ($op)(p.scaledvalue, q.value)
@eval ($op)(p::UnscaledOrSteadyState, q::ScaledParameter) = ($op)(p.value, q.scaledvalue)
end
for op in (:(Base.:+),
:(Base.:-),
:(Base.:*),
:(Base.:/),
:(Base.:^))
@eval ($op)(p::UnscaledVectorParameter, q::UnscaledVectorParameter) = ($op)(p.value, q.value) #@eval ($op)(p::UnscaledOrSteadyState, q::UnscaledOrSteadyState) = ($op)(p.value, q.value)
@eval ($op)(p::UnscaledVectorParameter, x::Integer) = ($op)(p.value, x) #@eval ($op)(p::UnscaledOrSteadyState, x::Integer) = ($op)(p.value, x)
@eval ($op)(p::UnscaledVectorParameter, x::Number) = ($op)(p.value, x) #@eval ($op)(p::UnscaledOrSteadyState, x::Number) = ($op)(p.value, x)
#@eval ($op)(x::Number, p::UnscaledOrSteadyState) = ($op)(x, p.value)
@eval ($op)(p::ScaledVectorParameter, q::ScaledVectorParameter) = ($op)(p.scaledvalue, q.scaledvalue)
@eval ($op)(p::ScaledVectorParameter, x::Integer) = ($op)(p.scaledvalue, x)
@eval ($op)(p::ScaledVectorParameter, x::Number) = ($op)(p.scaledvalue, x)
@eval ($op)(x::Number, p::ScaledVectorParameter) = ($op)(x, p.scaledvalue)
@eval ($op)(p::ScaledVectorParameter, q::UnscaledOrSteadyState) = ($op)(p.scaledvalue, q.value)
#@eval ($op)(p::UnscaledOrSteadyState, q::ScaledVectorParameter) = ($op)(p.value, q.scaledvalue)
end
# Define scalar functional mappings and comparisons
for f in (:(Base.exp),
:(Base.log),
:(Base.transpose),
:(Base.:-),
:(Base.:<),
:(Base.:>),
:(Base.:<=),
:(Base.:>=))
@eval ($f)(p::UnscaledOrSteadyState) = ($f)(p.value)
@eval ($f)(p::ScaledParameter) = ($f)(p.scaledvalue)
if f != :(Base.:-)
@eval ($f)(p::UnscaledOrSteadyState, x::Number) = ($f)(p.value, x)
@eval ($f)(p::ScaledParameter, x::Number) = ($f)(p.scaledvalue, x)
end
end
# Define scalar functional mappings and comparisons
for f in (:(Base.exp),
:(Base.log),
:(Base.transpose),
:(Base.:-),
:(Base.:<),
:(Base.:>),
:(Base.:<=),
:(Base.:>=))
@eval ($f)(p::UnscaledOrSteadyState) = ($f)(p.value)
@eval ($f)(p::ScaledParameterAD) = ($f)(p.scaledvalue)
if f != :(Base.:-)
@eval ($f)(p::UnscaledOrSteadyState, x::Number) = ($f)(p.value, x)
@eval ($f)(p::ScaledParameterAD, x::Number) = ($f)(p.scaledvalue, x)
end
end
# Define scalar operators on grids
for op in (:(Base.:+),
:(Base.:-),
:(Base.:*),
:(Base.:/))
@eval ($op)(g::SteadyStateParameterGrid, x::Integer) = ($op)(g.value, x)
@eval ($op)(g::SteadyStateParameterGrid, x::Number) = ($op)(g.value, x)
@eval ($op)(x::Integer, g::SteadyStateParameterGrid) = ($op)(x, g.value)
@eval ($op)(x::Number, g::SteadyStateParameterGrid) = ($op)(x, g.value)
end
# Define vectorized arithmetic for Unscaled or Steady-State Parameters
for op in (:(Base.:+),
:(Base.:-),
:(Base.:*),
:(Base.:/))
@eval ($op)(p::UnscaledOrSteadyState, x::Vector) = ($op)(p.value, x)
@eval ($op)(p::UnscaledOrSteadyState, x::Matrix) = ($op)(p.value, x)
@eval ($op)(x::Vector, p::UnscaledOrSteadyState) = ($op)(x, p.value)
@eval ($op)(x::Matrix, p::UnscaledOrSteadyState) = ($op)(x, p.value)
end
# Overload length, iterate to broadcast works properly
Base.length(p::Parameter) = length(p.value)
Base.iterate(p::Parameter, state=1) = state > length(p.value) ? nothing : (state, state+1)
"""
```
update!(pvec::ParameterVector, values::Vector{S}; change_value_type::Bool = false) where S
```
Update all parameters in `pvec` that are not fixed with
`values`. Length of `values` must equal length of `pvec`.
Function optimized for speed.
"""
function update!(pvec::ParameterVector, values::Vector{T};
change_value_type::Bool = false) where T
# this function is optimised for speed
# @assert length(values) == length(pvec) "Length of input vector (=$(length(values))) must match length of parameter vector (=$(length(pvec)))"
if change_value_type
tmp = if eltype(pvec) <: ParameterAD
(x,y) -> parameter_ad(x, y; change_value_type = change_value_type)
else
(x,y) -> parameter(x, y; change_value_type = change_value_type)
end
map!(tmp, pvec, pvec, values)
else
if eltype(pvec) <: ParameterAD
map!(parameter_ad, pvec, pvec, values[1:length(pvec)])
else
map!(parameter, pvec, pvec, values[1:length(pvec)])
end
# It is assumed that, if regime-switching, the regimes are toggled to regime 1 before calling update!
# If length of values (Floats) is longer than of parameters (Parameters), put the extra stuff into regimes fields
# in the following order. Say α, β, γ are parameters, where β has 3 regimes and γ has 4 regimes.
# For elements in values after the first `length(pvec)`, values[length(pvec) + 1] is the second regime value of β,
# values[length(pvec) + 2] is the third regime value of β, values[length(pvec) + 3] is the second regime of γ,
# values[length(pvec) + 4] is the third regime of γ, and values[length(pvec) + 5] is the fourth regime of γ.
if length(values) > length(pvec)
i = length(pvec)
for para in pvec
if haskey(para.regimes, :value)
for key in keys(para.regimes[:value])
if key == 1
set_regime_val!(para, key, para.value)
else
# Note that set_regime_val! handles what to do if para is fixed, enforce valuebounds, etc.
i += 1
set_regime_val!(para, key, values[i])
end
end
end
end
end
end
end
"""
```
update!(pvec::ParameterVector, values::Vector{S},
indices::BitArray{1}; change_value_type::Bool = false) where S
```
Updates a subset of parameters in `pvec` specified by indices. Assumes `values`
is sorted in the same order as the parameters in `pvec`, ignoring parameters
that are to be left unchanged.
However, `update!` will not overwrite fixed parameters, even if
`indices` has a true in an index corresponding to a fixed parameter.
# Examples
```jldoctest
julia> pvec = ParameterVector{Float64}(undef, 3);
julia> pvec[1] = parameter(:a, 1., (0., 3.), (0., 3.), fixed = false);
julia> pvec[2] = parameter(:b, 1.);
julia> pvec[3] = parameter(:c, 1., (0., 3.), (0., 3.), fixed = false);
julia> values = [2., 2.];
julia> update!(pvec, values, [true, false, true]);
julia> map(x -> x.value, pvec)
3-element Array{Float64,1}:
2.0
1.0
2.0
```
```jldoctest
julia> pvec = ParameterVector{Float64}(undef, 3);
julia> pvec[1] = parameter(:a, 1.);
julia> pvec[2] = parameter(:b, 1.);
julia> pvec[3] = parameter(:c, 1.);
julia> values = [2., 2.];
julia> update!(pvec, values, [true, false, true]);
julia> map(x -> x.value, pvec)
3-element Array{Float64,1}:
1.0
1.0
1.0
```
"""
function update!(pvec::ParameterVector, values::AbstractVector{S}, indices::BitArray{1};
change_value_type::Bool = false) where S
# Are you changing all indices? Or a subset?
if all(indices)
current_vals = values
else
@assert count(indices) == length(values) "Length of input vector (=$(length(values))) must match number of values in parameter vector that `indices` specified to be changed (=$(count(indices)))"
# Infer whether we need to declare current_vals as a Vector{<:Real}
# (e.g. if values are ForwardDiff.Dual types)
# or if current_vals can be a smaller memory type (e.g. Float64)
try
eltype(values)::AbstractFloat
current_vals = Vector{eltype(values)}([x.value for x in pvec])
catch
current_vals = Vector{Real}([x.value for x in pvec])
end
current_vals[indices] .= values
end
update!(pvec, current_vals; change_value_type = change_value_type)
end
"""
```
update(pvec::ParameterVector, values::Vector{S}) where S
```
Returns a copy of `pvec` where non-fixed parameter values are updated
to `values`. `pvec` remains unchanged. Length of `values` must
equal length of `pvec`.
We define the non-mutating version like this because we need the type stability of map!
"""
function update(pvec::ParameterVector, values::Vector{S}) where S
tmp = copy(pvec)
update!(tmp, values)
return tmp
end
Distributions.pdf(p::AbstractParameter) = exp(logpdf(p))
# we want the unscaled value for ScaledParameters
function Distributions.logpdf(p::Parameter{T,U}) where {T, U}
if haskey(p.regimes, :value) # regime-switching values
free_para_regimes = if haskey(p.regimes, :fixed) # Figure out which regimes
findall(.!values(p.regimes[:fixed])) # are not fixed. Note p.regimes[:fixed] is an OrderedDict
else
1:length(p.regimes[:value])
end
if isnothing(free_para_regimes) # Regimes can't all be fixed
error("All regimes are fixed. The log prior cannot be evaluated for Parameter $(p.key)")
end
if haskey(p.regimes, :prior) # does prior also regime switch?
return sum([logpdf(get(regime_prior(p, i)), regime_val(p, i)) for i in free_para_regimes])
else
_prior = get(p.prior)
return sum([logpdf(_prior, regime_val(p, i)) for i in free_para_regimes])
end
else # no regime-switching values
return logpdf(get(p.prior), p.value)
end
end
# this function is optimised for speed
function Distributions.logpdf(pvec::ParameterVector{T}) where T
x = zero(T)
@inbounds for i = 1:length(pvec)
if hasprior(pvec[i])
x += logpdf(pvec[i])
end
end
x
end
# calculate logpdf at new values, without needing to allocate a temporary array with update
function Distributions.logpdf(pvec::ParameterVector, values::Vector{S}) where S
@assert length(values) == length(pvec) "Length of input vector (=$(length(values))) must match length of parameter vector (=$(length(pvec)))"
x = zero(S)
@inbounds for i = 1:length(pvec)
if hasprior(pvec[i])
x += logpdf(parameter(pvec[i], values[i]))
end
end
x
end
Distributions.pdf(pvec::ParameterVector{T}) where T = exp(logpdf(pvec))
Distributions.pdf(pvec::ParameterVector, values::Vector{S}) where S = exp(logpdf(pvec, values))
"""
```
Distributions.rand(p::Vector{AbstractParameter{Float64}}; regime_switching::Bool = false,
toggle::Bool = true)
```
Generate a draw from the prior of each parameter in `p`.
"""
function Distributions.rand(p::Vector{AbstractParameter{Float64}}; regime_switching::Bool = false,
toggle::Bool = true)
if regime_switching
return rand_regime_switching(p; toggle = toggle)
else
draw = zeros(length(p))
for (i, para) in enumerate(p)
draw[i] = if para.fixed
para.value
else
# Resample until all prior draws are within the value bounds
prio = rand(para.prior.value)
while !(para.valuebounds[1] < prio < para.valuebounds[2])
prio = rand(para.prior.value)
end
prio
end
end
return draw
end
end
"""
```
rand_regime_switching(p::Vector{AbstractParameter{Float64}}; toggle::Bool = true)
```
Generate a draw from the prior of each parameter in `p`.
"""
function rand_regime_switching(p::Vector{AbstractParameter{Float64}}; toggle::Bool = true)
draw = zeros(length(p))
# Handle the regime 1 values
for (i, para) in enumerate(p)
draw[i] = if para.fixed # It is assumed regimes are toggled to regime 1, so para.fixed = regimes[:fixed][1] if haskey(regimes, :fixed)
para.value
elseif (haskey(para.regimes, :prior) ? haskey(para.regimes[:prior], 1) : false)
# Resample until all prior draws are within the value bounds
prio = rand(regime_prior(para, 1).value)
while !(para.valuebounds[1] < prio < para.valuebounds[2])
prio = rand(regime_prior(para, 1).value)
end
prio
else
# Resample until all prior draws are within the value bounds
prio = rand(para.prior.value)
while !(para.valuebounds[1] < prio < para.valuebounds[2])
prio = rand(para.prior.value)
end
prio
end
end
for para in p
if haskey(para.regimes, :value)
for regime in keys(para.regimes[:value])
if regime != 1
one_draw = if (haskey(para.regimes, :fixed) ? regime_fixed(para, regime) : para.fixed)
# regimes are toggled to regime 1, so need to examine para.regimes[:fixed].
# If it doesn't exist and `para.fixed = true`, then we assume all regimes are fixed.
regime_val(para, regime)
elseif (haskey(para.regimes, :prior) ? haskey(para.regimes[:prior], regime) : false) # regime-switching in prior
# Resample until all prior draws are within the value bounds
prio = rand(regime_prior(para, regime).value)
lowerbound, upperbound = haskey(para.regimes, :valuebounds) ? regime_valuebounds(para, regime) : para.valuebounds
while !(lowerbound < prio < upperbound)
prio = rand(regime_prior(para, regime).value)
end
prio
else # just use para.prior for prior draws
# Resample until all prior draws are within the value bounds
prio = rand(para.prior.value)
lowerbound, upperbound = haskey(para.regimes, :valuebounds) ? regime_valuebounds(para, regime) : para.valuebounds
while !(lowerbound < prio < upperbound)
prio = rand(para.prior.value)
end
prio
end
push!(draw, one_draw)
end
end
end
end
return draw
end
"""
```
Distributions.rand(p::Vector{AbstractParameter{Float64}}, n::Int;
regime_switching::Bool = false, toggle::Bool = true)
```
Generate `n` draws from the priors of each parameter in `p`.This returns a matrix of size
`(length(p),n)`, where each column is a sample. To sample from `p` when it has
regime-switching, set `regime_switching = true`. The `toggle` keyword is only
relevant for regime-switching sampling. Please see `?ModelConstructors.rand_regime_switching`.
"""
function Distributions.rand(p::Vector{AbstractParameter{Float64}}, n::Int;
regime_switching::Bool = false, toggle::Bool = true)
priorsim = regime_switching ? zeros(length(rand_regime_switching(p)), n) : zeros(length(p), n)
for i in 1:n
if regime_switching
priorsim[:, i] = rand_regime_switching(p)
else
priorsim[:, i] = rand(p)
end
end
return priorsim
end
"""
```
moments(θ::Parameter)
```
If θ's prior is a `RootInverseGamma`, τ and ν. Otherwise, returns the mean
and standard deviation of the prior. If θ is fixed, returns `(θ.value, 0.0)`.
"""
function moments(θ::Parameter)
if θ.fixed
return θ.value, 0.0
else
prior = get(θ.prior)
if isa(prior, RootInverseGamma)
return prior.τ, prior.ν
else
return mean(prior), std(prior)
end
end
end
function describe_prior(param::Parameter)
if param.fixed
return "fixed at " * string(param.value)
elseif !param.fixed && !isnull(param.prior)
(prior_mean, prior_std) = moments(param)
prior_dist = string(typeof(get(param.prior)))
prior_dist = replace(prior_dist, "Distributions." => "")
prior_dist = replace(prior_dist, "DSGE." => "")
prior_dist = replace(prior_dist, "{Float64}" => "")
mom1, mom2 = if isa(prior, RootInverseGamma)
"tau", "nu"
else
"mu", "sigma"
end
return prior_dist * "(" * mom1 * "=" * string(round(prior_mean, digits=4)) * ", " *
mom2 * "=" * string(round(prior_std, digits=4)) * ")"
else
error("Parameter must either be fixed or have non-null prior: " * string(param.key))
end
end
"""
```
function n_parameters_regime_switching(p::ParameterVector)
```
calculates the total number of parameters in `p` across all regimes.
"""
function n_parameters_regime_switching(p::ParameterVector)
base_num = length(p)
for para in p
if !isempty(para.regimes)
if haskey(para.regimes, :value)
base_num += length(para.regimes[:value]) - 1 # first regime is already counted
end
end
end
return base_num
end
"""
```
parameters2namedtuple(m)
```
returns the parameters of `m` as a `NamedTuple`. The input `m`
can be either an `AbstractVector{<: AbstractParameter}` or
an `AbstractModel`.
"""
function parameters2namedtuple(pvec::AbstractVector{S}) where {S <: AbstractParameter}
tuple_names = Tuple(p.key for p in pvec)
tuple_vals = [(isa(p, ScaledParameter) ? p.scaledvalue : p.value) for p in pvec]
return NamedTuple{tuple_names}(tuple_vals)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 16881 | """
```
set_regime_val!(p::Parameter{S},
i::Int, v::S; override_bounds::Bool = false) where S <: Real
set_regime_val!(p::Parameter{S},
model_regime::Int, v::S, d::AbstractDict{Int, Int}; override_bounds::Bool = false) where S <: Real
```
sets the value in regime `i` of `p` to be `v`. By default, we enforce
the bounds that are currently in `p`, but the bounds can be ignoerd by
setting `override_bounds = true`.
The second method allows the user to pass a dictionary to permit the case where
there may be differences between the regimes of a regime-switching model and
the regimes for the parameters. For example, aside from regime-switching in parameters,
the model may also include other forms of regime-switching. To allow
estimation of regime-switching parameters in such a model, the dictionary `d`
maps each "model" regime to a "parameter" regime. In this way,
the second method specifies which "parameter" regime should be used at a given
"model" regime.
"""
function set_regime_val!(p::Parameter{S},
i::Int, v::S; override_bounds::Bool = false) where S <: Real
if !haskey(p.regimes, :value)
p.regimes[:value] = OrderedDict{Int,S}()
end
# First check if fixed and enforce valuebounds so
# `set_regime_val!` mirrors `parameter(p::Parameter, newvalue::S)` functionality
if haskey(p.regimes, :fixed) ? regime_fixed(p, i) : false
if haskey(p.regimes[:value], i)
return p.regimes[:value][i]
else # If it doesn't exist yet, then we want to set the value for this regime
p.regimes[:value][i] = v
p.regimes[:valuebounds][i] = (v, v)
end
elseif (haskey(p.regimes, :valuebounds) ?
((regime_valuebounds(p, i)[1] <= v <= regime_valuebounds(p, i)[2]) || override_bounds) : false)
p.regimes[:value][i] = v
elseif (p.valuebounds[1] <= v <= p.valuebounds[2]) || override_bounds
p.regimes[:value][i] = v
elseif p.fixed
# When parameters are initialized as non-regime-switching and fixed,
# the valuebounds is automatically set to (p.value, p.value).
# Unless valuebounds are set to regime-switching, it is not possible
# to add extra regimes without using `override_bounds = true` (unless using the same value).
# Note that the rest of ModelConstructors.jl assumes that if `p.fixed = true`
# and haskey(p.regimes, :fixed) is false, then all regimes (if any) are also fixed.
throw(ParamBoundsError("Parameter $(p.key) is fixed. Regimes cannot be added unless " *
"keyword `override_bounds` is set to `true`."))
else
throw(ParamBoundsError("New value of $(string(p.key)) ($(v)) is out of bounds ($(p.valuebounds))"))
end
return v
end
function set_regime_val!(p::Parameter{S}, model_regime::Int,
v::S, d::AbstractDict{Int, Int}; override_bounds::Bool = false) where S <: Real
return set_regime_val!(p, d[model_regime], v; override_bounds = override_bounds)
end
"""
```
regime_val(p::Parameter{S}, i::Int) where S <: Real
regime_val(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
```
returns the value of `p` in regime `i` for the first method
and the value of `p` in regime `d[model_regime` for the second.
"""
function regime_val(p::Parameter{S}, i::Int) where S <: Real
if !haskey(p.regimes, :value) || !haskey(p.regimes[:value], i)
@error "regime_val(), Input Error: No regime $(i)"
end
return p.regimes[:value][i]
end
regime_val(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real = regime_val(p, d[model_regime])
"""
```
set_regime_prior!(p::Parameter{S}, i::Int, v)
set_regime_prior!(p::Parameter{S}, model_regime::Int, v, d::AbstractDict{Int, Int})
```
sets the prior in regime `i` of `p` to be `v`. The type of `v`
can be a `NullablePriorUnivariate`, `NullablePriorMultivariate`,
`ContinuousUnivariateDistribution`, or `ContinuousMultivariateDistribution'.
The second method allows the user to pass a dictionary to permit the case where
there may be differences between the regimes of a regime-switching model and
the regimes for the parameters. For example, aside from regime-switching in parameters,
the model may also include other forms of regime-switching. To allow
estimation of regime-switching parameters in such a model, the dictionary `d`
maps each "model" regime to a "parameter" regime. In this way,
the second method specifies which "parameter" regime should be used at a given
"model" regime.
"""
function set_regime_prior!(p::Parameter, i::Int, v::S) where {S <: Union{NullablePriorUnivariate, NullablePriorMultivariate}}
if !haskey(p.regimes, :prior)
p.regimes[:prior] = OrderedDict{Int, Union{NullablePriorUnivariate, NullablePriorMultivariate}}()
end
p.regimes[:prior][i] = v
return v
end
function set_regime_prior!(p::Parameter, i::Int, v::S) where S <: ContinuousUnivariateDistribution
return set_regime_prior!(p, i, NullablePriorUnivariate(v))
end
function set_regime_prior!(p::Parameter, i::Int, v::S) where S <: ContinuousMultivariateDistribution
return set_regime_prior!(p, i, NullablePriorMultivariate(v))
end
function set_regime_prior!(p::Parameter, model_regime::Int, v::S,
d::AbstractDict{Int, Int}) where {S <: Union{NullablePriorUnivariate, NullablePriorMultivariate}}
return set_regime_prior!(p, d[model_regime], v)
end
function set_regime_prior!(p::Parameter, model_regime::Int,
v::S, d::AbstractDict{Int, Int}) where S <: ContinuousUnivariateDistribution
return set_regime_prior!(p, model_regime, NullablePriorUnivariate(v), d)
end
function set_regime_prior!(p::Parameter, model_regime::Int, v::S,
d::AbstractDict{Int, Int}) where S <: ContinuousMultivariateDistribution
return set_regime_prior!(p, model_regime, NullablePriorMultivariate(v), d)
end
"""
```
regime_prior(p::Parameter{S}, i::Int) where S <: Real
regime_prior(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
```
returns the prior of `p` in regime `i` for the first method
and the prior of `p` in regime `d[model_regime]` for the second.
"""
function regime_prior(p::Parameter{S}, i::Int) where S <: Real
if !haskey(p.regimes, :prior) || !haskey(p.regimes[:prior], i)
@error "regime_prior(), Input Error: No regime $(i)"
end
return p.regimes[:prior][i]
end
regime_prior(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real = regime_prior(p, d[model_regime])
"""
```
set_regime_fixed!(p::Parameter{S}, i::Int, v::S; update_valuebounds::Interval = (NaN, NaN))
```
sets whether `p` is fixed in regime `i` of `p`. Set update_valuebounds to true to
set the valuebounds to match the fixed value.
The second method allows the user to pass a dictionary to permit the case where
there may be differences between the regimes of a regime-switching model and
the regimes for the parameters. For example, aside from regime-switching in parameters,
the model may also include other forms of regime-switching. To allow
estimation of regime-switching parameters in such a model, the dictionary `d`
maps each "model" regime to a "parameter" regime. In this way,
the second method specifies which "parameter" regime should be used at a given
"model" regime.
"""
function set_regime_fixed!(p::Parameter{S1}, i::Int, v::S; update_valuebounds::Interval{S1} = (NaN, NaN)) where {S <: Bool, S1 <: Real}
if !haskey(p.regimes, :fixed)
p.regimes[:fixed] = OrderedDict{Int, Bool}()
end
p.regimes[:fixed][i] = v
if !haskey(p.regimes, :valuebounds)
p.regimes[:valuebounds] = OrderedDict{Int, typeof(p.value)}()
end
if isnan(update_valuebounds[1]) || isnan(update_valuebounds[2])
# Do nothing unless `v` is true (fixed in regime `i`) or
# !haskey(p.regimes[:valuebounds], i) (no value for regime `i` for valuebounds dict)
if v
if (haskey(p.regimes, :value) ? haskey(p.regimes[:value], i) : false)
# Regime is fixed, so valuebounds should be set to (value, value), if it exists
p.regimes[:valuebounds][i] = (regime_val(p, i), regime_val(p, i))
else
error("Regime $(i) for parameter $(p.key) does not have a value. Set the value " *
"using `set_regime_val!` before making it a fixed value with `set_regime_fixed!`.")
end
elseif !haskey(p.regimes[:valuebounds], i)
# If valuebounds is nonexistent in regime i, initialize to p.valuebounds
p.regimes[:valuebounds][i] = p.valuebounds
end
else # Otherwise update the valuebounds. Note that there is no check that p.regimes[:value][i] lies inside the valuebounds
p.regimes[:valuebounds][i] = update_valuebounds
end
return v
end
function set_regime_fixed!(p::Parameter, model_regime::Int, v::S,
d::AbstractDict{Int, Int}; update_valuebounds::Interval{S1} = (NaN, NaN)) where {S <: Bool, S1 <: Real}
set_regime_fixed!(p, d[model_regime], v; update_valuebounds = update_valuebounds)
end
"""
```
regime_fixed(p::Parameter{S}, i::Int) where S <: Real
regime_fixed(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
```
returns whether `p` is fixed in regime `i` for the first method
and whether true `p` is fixed in regime `d[model_regime]` for the second method.
"""
function regime_fixed(p::Parameter{S}, i::Int) where S <: Real
if !haskey(p.regimes, :fixed) || !haskey(p.regimes[:fixed], i)
@error "regime_fixed(), Input Error: No regime $(i)"
end
return p.regimes[:fixed][i]
end
regime_fixed(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real = regime_fixed(p, d[model_regime])
"""
```
set_regime_valuebounds!(p::Parameter{S}, i::Int, v::S)
```
sets valuebounds for `p` in regime `i` to `v`.
The second method allows the user to pass a dictionary to permit the case where
there may be differences between the regimes of a regime-switching model and
the regimes for the parameters. For example, aside from regime-switching in parameters,
the model may also include other forms of regime-switching. To allow
estimation of regime-switching parameters in such a model, the dictionary `d`
maps each "model" regime to a "parameter" regime. In this way,
the second method specifies which "parameter" regime should be used at a given
"model" regime.
"""
function set_regime_valuebounds!(p::Parameter, i::Int, v::Interval{S}) where {S <: Real}
if !haskey(p.regimes, :valuebounds)
p.regimes[:valuebounds] = OrderedDict{Int, typeof(p.value)}()
end
p.regimes[:valuebounds][i] = v
return v
end
function set_regime_valuebounds!(p::Parameter, model_regime::Int, v::Interval{S},
d::AbstractDict{Int, Int}) where {S <: Real}
set_regime_valuebounds!(p, d[model_regime], v)
end
"""
```
regime_valuebounds(p::Parameter{S}, i::Int) where S <: Real
regime_valuebounds(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
```
returns the `valuebounds` of `p` in regime `i` for the first method
and the `valuebounds` of `p` in regime `d[model_regime]` for the second method.
"""
function regime_valuebounds(p::Parameter{S}, i::Int) where S <: Real
if !haskey(p.regimes, :valuebounds) || !haskey(p.regimes[:valuebounds], i)
@error "regime_valuebounds(), Input Error: No regime $(i)"
end
return p.regimes[:valuebounds][i]
end
regime_valuebounds(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real = regime_valuebounds(p, d[model_regime])
"""
```
toggle_regime!(p::Parameter{S}, i::Int) where S <: Real
toggle_regime!(pvec::ParameterVector{S}, i::Int) where S <: Real
toggle_regime!(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
toggle_regime!(pvec::ParameterVector{S}, model_regime::Int, d::AbstractDict{Symbol, <: AbstractDict{Int, Int}}) where S <: Real
toggle_regime!(pvec::ParameterVector{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real
```
changes the fields of `p` to regime `i`.
For example, if
```
p.regimes[:value] = OrderedDict{Int, Any}(1 => 1, 2 => 3)
```
then `toggle_regime!(p, 1)` will cause `p.value = 1` and `toggle_regime!(p, 2)`
will cause `p.value = 3`.
The third method allows the user to pass a dictionary to permit the case where
there may be differences between the regimes of a regime-switching model and
the regimes for the parameters. For example, aside from regime-switching in parameters,
the model may also include other forms of regime-switching. To allow
estimation of regime-switching parameters in such a model, the dictionary `d`
maps each "model" regime to a "parameter" regime. In this way,
the second method specifies which "parameter" regime should be used at a given
"model" regime.
The fourth method extends the third to a ParameterVector, with the possibility
that each parameter may have different mappings to the model regimes. Each key
of `d` corresponds to the key of a parameter, and each value of `d` is
the mapping for model regimes to the parameter regimes of `p.key`.
The fifth method is similar to the fourth but assumes
any regime-switching parameter has the same mapping from model regimes
to parameter regimes, hence the use of a common dictionary.
"""
function toggle_regime!(p::Parameter{S}, i::Int) where S <: Real
if !isempty(p.regimes)
for field in [:value, :valuebounds, :transform_parameterization,
:transform, :prior, :fixed]
if haskey(p.regimes, field) && haskey(p.regimes[field], i)
if field == :value
p.value = p.regimes[field][i]
elseif field == :valuebounds
p.valuebounds = p.regimes[field][i]
elseif field == :transform_parameterization
p.transform_parameterization = p.regimes[field][i]
elseif field == :transform
p.transform = p.regimes[field][i]
elseif field == :prior
p.prior = p.regimes[field][i]
elseif field == :fixed
p.fixed = p.regimes[field][i]
end
elseif haskey(p.regimes, field) && !haskey(p.regimes[field], i)
error("Regime $i for field $field not found")
end
end
end
end
function toggle_regime!(pvec::ParameterVector{S}, i::Int) where {S <: Real}
for p in pvec
toggle_regime!(p, i)
end
end
toggle_regime!(p::Parameter{S}, model_regime::Int, d::AbstractDict{Int, Int}) where S <: Real = toggle_regime!(p, d[model_regime])
function toggle_regime!(pvec::ParameterVector{S}, model_regime::Int, d::AbstractDict{Symbol, <: AbstractDict{Int, Int}}) where S <: Real
for p in pvec
toggle_regime!(p, model_regime, d[p.key])
end
end
toggle_regime!(pvec::ParameterVector{S}, model_regime::Int, d::AbstractDict{Int, Int}) where {S <: Real} = toggle_regime!(pvec, d[model_regime])
"""
```
get_values(pvec::ParameterVector{S}; regime_switching::Bool = true) where {S <: Real}
```
constructs a vector of the underlying values in a `ParameterVector`, including
if there are regime-switching values.
"""
function get_values(pvec::ParameterVector{S}; regime_switching::Bool = true) where {S <: Real}
if regime_switching # Check if regime switching occurs
np_reg = n_parameters_regime_switching(pvec)
np = length(pvec)
if np == np_reg # No regime-switching
vals = [x.value for x in pvec.parameters]
else
vals = Vector{S}(undef, np_reg)
# An initial pass to find regime 1 values
for i in 1:np
if isempty(pvec[i].regimes)
vals[i] = pvec[i].value
elseif haskey(pvec[i].regimes, :value)
vals[i] = pvec[i].regimes[:value][1]
end
end
# A second loop to add in the extra regimes
ct = np # a counter to assist us
for i in 1:np
if !isempty(pvec[i].regimes)
if haskey(pvec[i].regimes, :value)
for j in 1:length(pvec[i].regimes[:value])
if j > 1
ct += 1
vals[ct] = pvec[i].regimes[:value][j]
end
end
end
end
end
end
else # Regime switching doesn't occur, so just directly map
vals = [x.value for x in pvec]
end
return vals
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 4132 | """
```
Setting{T}
```
The `Setting` type is an interface for computational settings that affect how the code runs
without affecting the mathematical definition of the model. It also provides support for
non-conflicting file names for output of 2 models that differ only in the values of their
computational settings.
### Fields
- `key::Symbol`: Name of setting
- `value::T`: Value of setting
- `print::Bool`: Indicates whether to append this setting's code and value to output file
names. If true, output file names will include a suffix of the form `_code1=val1_code2=val2`
etc. where codes are listed in alphabetical order.
- `code::String`: string to print to output file suffixes when
`print=true`.
- `description::String`: Short description of what the setting is used for.
"""
mutable struct Setting{T}
key::Symbol # name of setting
value::T # whatever the setting is
print::Bool # whether or not to add this setting to the print
code::String # what gets printed to the print
description::String # description of what the setting is for
end
# for printing codes to filename string
Base.convert(::Type{T}, s::Setting{U}) where {T<:Number, U<:Number} = convert(T, s.value)
Base.convert(::Type{String}, s::Setting{String}) = convert(String, s.value)
Base.promote_rule(::Type{Setting{T}}, ::Type{U}) where {T<:Number,U<:Number} = promote_rule(T,U)
Base.promote_rule(::Type{Setting{String}}, ::Type{String}) = String # promote_rule(String, String)
Base.promote_rule(::Type{Setting{Bool}}, ::Type{Bool}) = Bool #promote_rule(Bool, Bool)
Base.string(s::Setting{String}) = string(s.value)
to_filestring(s::Setting) = string(s.code) * "=" * string(s.value)
# key, value constructor
Setting(key, value) = Setting(key, value, false, "", "")
Setting(key, value, description) = Setting(key, value, false, "", description)
function Base.show(io::IO, s::Setting)
@printf io "%s: %s" s.key s.value
end
"""
```
(<=)(m::AbstractModel, s::Setting)
```
Syntax for adding a setting to a model/overwriting a setting via `m <= Setting(...)`
"""
function (<=)(m::AbstractModel, s::Setting)
if !m.testing
setting_field_name = :settings
else
setting_field_name = :test_settings
end
if !haskey(getfield(m, setting_field_name), s.key) ||
isa(s.value, Function)
getfield(m, setting_field_name)[s.key] = s
else
update!(getfield(m, setting_field_name)[s.key], s)
end
end
"""
```
update!(a::Setting, b::Setting)
```
Update `a` with the fields of `b` if:
- The `key` field is updated if `a.key == b.key`
- The `print` boolean and `code` string are overwritten if `a.print` is false and
`b.print` is true, or `a.print` is true, `b.print` is false, and
b.code is non-empty.
- The `description` field is updated if `b.description` is nonempty
"""
function update!(a::Setting, b::Setting)
# Make sure Setting a can appropriately be updated by b.
if a.key ≠ b.key
return
end
a.value = b.value
# b overrides the print boolean of a if:
# - a.print is false and b.print is true.
# - a.print is true, b.print is false, and b.code is non-empty.
# We must be able to tell if b was created via a constructor like `Setting(:key,
# value)`, in which case the print, code, and description values are set to defaults. We
# do not overwrite if we can't determine whether or not those fields are just the
# defaults.
if (a.print == false && b.print == true) ||
(a.print == true && b.print == false && !isempty(b.code))
a.print = b.print
end
if !isempty(b.code) && b.code ≠ a.code
a.code = b.code
end
if !isempty(b.description) && b.description ≠ a.description
a.description = b.description
end
end
"""
```
get_setting(m::AbstractModel, setting::Symbol)
```
Returns the value of the setting
"""
function get_setting(m::AbstractModel, s::Symbol)
if m.testing && in(s, keys(m.test_settings))
return m.test_settings[s].value
else
return m.settings[s].value
end
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 3222 | """
`prior(parameters::ParameterVector{T}) where {T<:Number}`
Calculates log joint prior density of m.parameters.
"""
function prior(parameters::ParameterVector{T}) where {T<:Number}
free_params = Base.filter(x -> !_filter_all_fixed_para(x), parameters)
logpdfs = map(logpdf, free_params)
return sum(logpdfs)
end
_filter_all_fixed_para(p::Parameter) = haskey(p.regimes, :fixed) ? all(values(p.regimes[:fixed])) : p.fixed
"""
```
posterior(loglikelihood::Function, parameters::ParameterVector,
data::AbstractArray; ϕ_smc::Float64 = 1.)
```
Calculates and returns the log of the posterior distribution for `m.parameters`:
```
log posterior = log likelihood + log prior + const
log Pr(Θ|data) = log Pr(data|Θ) + log Pr(Θ) + const
```
### Arguments
- `loglikelihood`: Function which takes vector of parameters and data, and
outputs the log-loglikelihood of a parameters given data.
- `parameters`: Vector of parameters whose likelihood is to be evaluated
- `data`: Matrix of data for observables
### Optional Arguments
- `φ_smc`: a tempering factor to change the relative weighting of the prior and
the likelihood when calculating the posterior. It is used primarily in SMC.
"""
function posterior(loglikelihood::Function, parameters::ParameterVector,
data::AbstractArray; ϕ_smc::Float64 = 1.)
like = loglikelihood(parameters, data)
post = ϕ_smc * like + prior(parameters)
return post
end
"""
```
posterior!(loglikelihood::Function, parameters::ParameterVector,
para_draw::Vector{T}, data::Matrix{T};
sampler::Bool = false, catch_errors::Bool = false,
φ_smc = 1) where {T<:AbstractFloat}
```
Evaluates the log posterior density at `parameters`.
### Arguments
- `loglikelihood`: a function which takes vector of parameters and data, and
outputs the log-loglikelihood of a parameters given data.
- `para_draw`: New values for the model parameters
- `data`: Matrix of input data for observables
### Optional Arguments
- `sampler`: Whether metropolis_hastings or smc is the caller. If `sampler=true`,
the log likelihood and the transition matrices for the zero-lower-bound
period are also returned.
- `catch_errors`: Whether to catch errors of type `GensysError` or `ParamBoundsError`
If `sampler = true`, both should always be caught.
- `φ_smc`: a tempering factor to change the relative weighting of the prior and
the likelihood when calculating the posterior. It is used primarily in SMC.
"""
function posterior!(loglikelihood::Function, parameters::ParameterVector,
para_draw::Vector{T}, data::Matrix{T};
sampler::Bool = false, catch_errors::Bool = false,
ϕ_smc::Float64 = 1.) where {T<:AbstractFloat}
catch_errors = catch_errors | sampler
if sampler
try
update!(parameters, para_draw)
catch err
if isa(err, ParamBoundsError)
return -Inf
else
throw(err)
end
end
else
update!(parameters, para_draw)
end
return posterior(loglikelihood, parameters, data; ϕ_smc = ϕ_smc)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 6533 | """
```
sendto(p::Int; args...)
```
Function to send data from master process to particular worker, p. Code from ChrisRackauckas, avavailable at: https://github.com/ChrisRackauckas/ParallelDataTransfer.jl/blob/master/src/ParallelDataTransfer.jl.
"""
function sendto(p::Int; args...)
for (nm, val) in args
@spawnat(p, Core.eval(Main, Expr(:(=), nm, val)))
end
end
"""
```
sendto(ps::AbstractVector{Int}; args...)
```
Function to send data from master process to list of workers. Code from ChrisRackauckas, available at: https://github.com/ChrisRackauckas/ParallelDataTransfer.jl/blob/master/src/ParallelDataTransfer.jl.
"""
function sendto(ps::AbstractVector{Int}; args...)
for p in ps
sendto(p; args...)
end
end
"""
```
abbrev_symbol(s::Symbol, n::Int=4)
```
Abbreviate the symbol `s` to an `n`-character string.
"""
function abbrev_symbol(s::Symbol, n::Int=4)
str = string(s)
if length(str) ≤ n
return str
else
return str[1:n]
end
end
function sorted_list_insert!(v::Vector{T}, x::T) where T
insert_index = 1
for val in v
if x<val
break
else
insert_index += 1
end
end
insert!(v,insert_index,x)
end
"""
```
quarter_range(t0::Date, t1::Date)
```
Returns a vector of `Dates`, consisting of the last days of each quarter between
`t0` and `t1`, inclusive.
"""
function quarter_range(t0::Date, t1::Date)
dr = t0:Day(1):t1
return Base.filter(d -> Dates.lastdayofquarter(d) == d, dr)
end
"""
```
detexify(s::String)
detexify(s::Symbol)
```
Remove Unicode characters from the string `s`, replacing them with ASCII
equivalents. For example, `detexify(\"π\")` returns `\"pi\"`.
"""
function detexify(s::String)
s = replace(s, "α" => "alpha")
s = replace(s, "β" => "beta")
s = replace(s, "γ" => "gamma")
s = replace(s, "δ" => "delta")
s = replace(s, "ϵ" => "epsilon")
s = replace(s, "ε" => "epsilon")
s = replace(s, "ζ" => "zeta")
s = replace(s, "η" => "eta")
s = replace(s, "θ" => "theta")
s = replace(s, "ι" => "iota")
s = replace(s, "κ" => "kappa")
s = replace(s, "λ" => "lambda")
s = replace(s, "μ" => "mu")
s = replace(s, "ν" => "nu")
s = replace(s, "ξ" => "xi")
s = replace(s, "π" => "pi")
s = replace(s, "ρ" => "rho")
s = replace(s, "ϱ" => "rho")
s = replace(s, "σ" => "sigma")
s = replace(s, "ς" => "sigma")
s = replace(s, "τ" => "tau")
s = replace(s, "υ" => "upsilon")
s = replace(s, "ϕ" => "phi")
s = replace(s, "φ" => "phi")
s = replace(s, "χ" => "chi")
s = replace(s, "ψ" => "psi")
s = replace(s, "ω" => "omega")
s = replace(s, "Α" => "Alpha")
s = replace(s, "Β" => "Beta")
s = replace(s, "Γ" => "Gamma")
s = replace(s, "Δ" => "Delta")
s = replace(s, "Ε" => "Epsilon")
s = replace(s, "Ζ" => "Zeta")
s = replace(s, "Η" => "Eta")
s = replace(s, "Θ" => "Theta")
s = replace(s, "Ι" => "Iota")
s = replace(s, "Κ" => "Kappa")
s = replace(s, "Λ" => "Lambda")
s = replace(s, "Μ" => "Mu")
s = replace(s, "Ν" => "Nu")
s = replace(s, "Ξ" => "Xi")
s = replace(s, "Π" => "Pi")
s = replace(s, "Ρ" => "Rho")
s = replace(s, "Σ" => "Sigma")
s = replace(s, "Τ" => "Tau")
s = replace(s, "Υ" => "Upsilon")
s = replace(s, "Φ" => "Phi")
s = replace(s, "Χ" => "Chi")
s = replace(s, "Ψ" => "Psi")
s = replace(s, "Ω" => "Omega")
s = replace(s, "′" => "'")
return s
end
function detexify(s::Symbol)
Symbol(detexify(string(s)))
end
dispfns = [:print, :println]
for disp in dispfns
@eval begin
function Base.$disp(verbose::Symbol, min::Symbol, xs...)
if VERBOSITY[verbose] >= VERBOSITY[min]
$disp(xs...)
end
end
end
end
function info_print(verbose::Symbol, min::Symbol, x::String)
if VERBOSITY[verbose] >= VERBOSITY[min]
@info(x)
end
end
function warn_print(verbose::Symbol, min::Symbol, x::String)
if VERBOSITY[verbose] >= VERBOSITY[min]
@warn(x)
end
end
## Testing functions
function test_matrix_eq2(expect::AbstractArray,
actual::AbstractArray,
expstr::String,
actstr::String,
ϵ_abs::Float64 = 1e-6,
ϵ_rel::Float64 = 1e-2) where {T<:AbstractFloat}
if length(expect) ≠ length(actual)
error("lengths of ", expstr, " and ", actstr, " do not match: ",
"\n ", expstr, " (length $(length(expect))) = ", expect,
"\n ", actstr, " (length $(length(actual))) = ", actual)
end
# Absolute difference filter
abs_diff = abs.(actual .- expect) .> ϵ_abs
n_abs_diff = sum(skipmissing(abs_diff))
# Relative difference filter
rel_diff = 100*abs.((actual .- expect) ./ expect) .> ϵ_rel
n_rel_diff = sum(skipmissing(rel_diff))
# Element is only problematic if it fails *both* tests.
mixed_diff = abs_diff .& rel_diff
n_mixed_diff = sum(skipmissing(mixed_diff))
if n_mixed_diff ≠ 0
sdiff = string("|a - b| <= ", ϵ_abs,
" or |a - b|/|b| <= ", ϵ_rel, "%,",
" ∀ a ∈ ", actstr, ",",
" ∀ b ∈ ",expstr)
@warn "assertion failed:\n",
" ", sdiff,
"\n$(n_abs_diff) entries fail absolute equality filter",
"\n$(n_rel_diff) entries fail relative equality filter",
"\n$(n_mixed_diff) entries fail both equality filters\n"
return false
end
return true
end
"""
@test_matrix_approx_eq(a, b)
Test two matrices of floating point numbers `a` and `b` for approximate equality.
"""
macro test_matrix_approx_eq(a,b)
:(test_matrix_eq2($(esc(a)),$(esc(b)),$(string(a)),$(string(b))))
end
"""
@test_matrix_approx_eq_eps(a, b, ϵ_abs, ϵ_rel)
Test two matrices of floating point numbers `a` and `b` for equality taking in account a
margin of absolute tolerance given by `ϵ_abs` and a margin of relative tolerance given by
`ϵ_rel` (in comparison to `b`).
"""
macro test_matrix_approx_eq_eps(a,b,c,d)
:(test_matrix_eq2($(esc(a)),$(esc(b)),$(string(a)),$(string(b)),$(esc(c)),$(esc(d))))
end
"""
Sparse identity matrix - since deprecated in 0.7
"""
function speye(n::Integer)
return SparseMatrixCSC{Float64}(I, n, n)
end
"""
Sparse identity matrix - since deprecated in 0.7
"""
function speye(T::Type, n::Integer)
return SparseMatrixCSC{T}(I, n, n)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 419 | using Test, ModelConstructors, UnPack
m = GenericModel()
m <= parameter(:a, 1., (0., 1.), (0., 1.), Untransformed(), fixed = false)
m <= parameter(:b, 1., (0., 1.), (0., 1.), Untransformed(), fixed = false, scaling = x -> x / 100.)
@testset "UnPack works with AbstractModel" begin
@unpack a, b = m
@test a == 1.
@test b == 1e-2
@unpack a = m
@unpack b = m
@test a == 1.
@test b == 1e-2
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 899 | import Distributions.I
Random.seed!(22)
i, j, k = 3, 60, 200
U = rand(InverseWishart(i + 2, Matrix(1.0I, i, i)))
V = rand(InverseWishart(j + 2, Matrix(1.0I, j, j)))
Q = rand(InverseWishart(k + 2, Matrix(1.0I, k, k)))
m = randn(i)
n = randn(j)
o = randn(k)
σ = 2.0rand()
σ² = σ ^ 2
q = MvNormal(m, σ² * U)
r = MvNormal(n, σ² * V)
s = MvNormal(o, σ² * Q)
qᴰ = DegenerateMvNormal(m, σ² * U)
rᴰ = DegenerateMvNormal(n, σ² * V)
sᴰ = DegenerateMvNormal(o, σ² * Q)
@testset "Test logpdf of DegenerateMvNormal at mean" begin
@test logpdf(q, q.μ) ≈ logpdf(qᴰ, qᴰ.μ)
@test logpdf(r, r.μ) ≈ logpdf(rᴰ, rᴰ.μ)
@test logpdf(s, s.μ) ≈ logpdf(sᴰ, sᴰ.μ)
end
x = rand(i)
y = rand(j)
z = rand(k)
@testset "Test logpdf of DegenerateMvNormal at random location" begin
@test logpdf(q, x) ≈ logpdf(qᴰ, x)
@test logpdf(r, y) ≈ logpdf(rᴰ, y)
@test logpdf(s, z) ≈ logpdf(sᴰ, z)
end
nothing
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 8909 | using Test, ModelConstructors, Distributions, Dates, Nullables
@testset "Ensure transformations to the real line/model space are valid" begin
for T in subtypes(Transform)
global u = parameter(:σ_pist, 2.5230, (1e-8, 5.), (1e-8, 5.), T(), fixed=false)
@test ( transform_to_real_line(u) |> x -> transform_to_model_space(u,x) ) == u.value
if !isa(T,Type{ModelConstructors.Untransformed})
# check transform_to_real_line and transform_to_model_space to different things if T is not ModelConstructors.Untransformed
@test transform_to_real_line(u,u.value) != transform_to_model_space(u,u.value)
end
end
end
tomodel_answers = zeros(3)
toreal_answers = zeros(3)
a = 1e-8; b = 5.; c = 1.
x = 2.5230
cx = 2 * (x - (a+b)/2)/(b-a)
toreal_answers[1] = 1. / (c * (x - a))
toreal_answers[2] = (1/c) * (1. / (1. - cx^2)^(-3/2)) * (2/(b-a))
toreal_answers[3] = 1.
x = transform_to_real_line(parameter(:σ_pist, 2.5230, (1e-8, 5.), (1e-8, 5.),
ModelConstructors.Exponential(), fixed=false))
tomodel_answers[1] = c * exp(c * (x - b))
x = transform_to_real_line(parameter(:σ_pist, 2.5230, (1e-8, 5.), (1e-8, 5.),
ModelConstructors.SquareRoot(), fixed=false))
tomodel_answers[2] = (b - a) / 2 * c / (1 + c^2 * x^2)^(3/2)
tomodel_answers[3] = 1.
@testset "Ensure derivatives of transformations to the real line/model space are valid" begin
for (i,T) in enumerate(subtypes(Transform))
global u = parameter_ad(:σ_pist, 2.5230, (1e-8, 5.), (1e-8, 5.), T(), fixed=false)
@test differentiate_transform_to_real_line(u, u.value) == toreal_answers[i]
global x = transform_to_real_line(u)
@test differentiate_transform_to_model_space(u,x) == tomodel_answers[i]
if !isa(T,Type{ModelConstructors.Untransformed})
# check transform_to_real_line and transform_to_model_space to different things if T is not ModelConstructors.Untransformed
@test differentiate_transform_to_real_line(u,u.value) != differentiate_transform_to_model_space(u,u.value)
end
end
end
@testset "Check type conversion for `value`, `valuebounds`, and `transform_parameterization`" begin
@info "The following warning is expected"
u1 = parameter(:σ_pist, 2.5230, (1, 5), (Float32(1), Float32(5)), Untransformed())
u2 = parameter(:σ_pist, 2.5230, (1., 5.), (1., 5.), Untransformed())
@test u1.value == u2.value
@test u1.valuebounds == u2.valuebounds
@test u1.transform_parameterization == u2.transform_parameterization
@test typeof(u1.value) == typeof(u2.value)
@test eltype(u1.valuebounds) == eltype(u2.valuebounds)
@test eltype(u1.transform_parameterization) == eltype(u2.transform_parameterization)
end
# probability
N = 10^2
u = parameter(:bloop, 2.5230, (1e-8, 5.), (1e-8, 5.), ModelConstructors.SquareRoot(); fixed = true)
v = parameter(:cat, 2.5230, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), Gamma(2.00, 0.1))
pvec = ParameterVector{Float64}(undef, N)
for i in 1:length(pvec)
global pvec[i] = (i%2 == 0) ? u : v
end
@testset "Check logpdf/pdf function approximations" begin
@test logpdf(pvec) ≈ 50*logpdf(v)
@test pdf(pvec) ≈ exp(50*logpdf(v))
end
updated = ModelConstructors.update(pvec, ones(length(pvec)))
ModelConstructors.update!(pvec, ones(length(pvec)))
@testset "Check if update! preserves dimensions and values" begin
@test all(updated .== pvec)
@test logpdf(pvec) == logpdf(updated)
end
# test we only update non-fixed parameters
@testset "Ensure only non-fixed parameters are updated" begin
for p in pvec
if p.fixed
@test p.value == 2.5230
elseif isa(p, Parameter)
@test p.value == one(Float64)
end
end
end
# vector of new values must be the same length
@testset "Ensure update! enforces the same length of the parameter vector being updated" begin
@test_throws BoundsError ModelConstructors.update!(pvec, ones(length(pvec)-1))
end
@testset "Ensure parameters being updated are of the same type." begin
for w in [parameter_ad(:moop, 3.0, fixed=false), parameter_ad(:moop, 3.0; scaling = log, fixed=false)]
# new values must be of the same type
@test_throws ErrorException parameter_ad(w, one(Int))
# new value is out of bounds
@test_throws ParamBoundsError parameter_ad(w, -1.)
end
end
@testset "Ensure parameter value types can be changed when forced by keyword." begin
for w in [parameter_ad(:moop, 1.0, fixed=false), parameter_ad(:moop, 1.0; scaling = log, fixed=false)]
# new values must be of the same type
@test typeof(parameter_ad(w, one(Int); change_value_type = true).value) == Int
end
end
# Tests moved from DSGE.jl core.jl
# UnscaledParameter, fixed=false
α = parameter(:α, 0.1596, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), Normal(0.30, 0.05), fixed=false)
@testset "Test non-fixed UnscaledParameter" begin
@test isa(α, UnscaledParameter)
@test α.key == :α
@test isa(α.prior.value, Normal)
@test α.prior.value.μ == 0.3
@test α.description == "No description available."
@test α.tex_label == ""
@test isa(α.transform, ModelConstructors.SquareRoot)
end
# UnscaledParameter, fixed = true
α_fixed = parameter(:α_fixed, 0.1596, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.Untransformed(), Normal(0.30, 0.05), fixed=true)
@testset "Test fixed UnscaledParameter" begin
@test α_fixed.transform_parameterization == (0.1596,0.1596)
@test isa(α_fixed.transform, ModelConstructors.Untransformed)
end
# UnscaledParameter, fixed = true, transform should be overwritten given fixed
α_fixed = parameter(:α_fixed, 0.1596, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), Normal(0.30, 0.05), fixed=true)
@testset "Test fixed UnscaledParameter, ensuring transform is overwritten" begin
@test isa(α_fixed.transform, ModelConstructors.Untransformed)
end
# Fixed UnscaledParameter, minimal constructor
δ = parameter(:δ, 0.025)
@testset "Test fixed UnscaledParameter minimal constructor" begin
@test δ.fixed
@test δ.transform_parameterization == (0.025, 0.025)
@test δ.valuebounds == (0.025, 0.025)
end
# Scaled parameter
β = parameter(:β, 0.1402, (1e-5, 10.), (1e-5, 10.), ModelConstructors.Exponential(), GammaAlt(0.25, 0.1), fixed=false, scaling = x -> (1 + x/100)\1, description="β: Discount rate.", tex_label="\\beta ")
@testset "Test ScaledParameter constructor" begin
@test isa(β, ScaledParameter)
@test isa(β.prior.value, Gamma)
@test isa(β.transform, ModelConstructors.Exponential)
end
# Invalid transform
@testset "Ensure error thrown on invalid transform" begin
@test_throws UndefVarError α_bad = parameter(:α, 0.1596, (1e-5, 0.999), (1e-5, 0.999),
InvalidTransform(), Normal(0.30, 0.05), fixed=false)
end
# Arithmetic with parameters
@testset "Check arithmetic with parameters" begin
@test promote_type(AbstractParameter{Float64}, Float16) == Float64
@test promote_type(AbstractParameter{Float64}, Int8) == Float64
## @test promote_rule(AbstractParameter{Float64}, Float16) == Float64
## @test promote_rule(AbstractParameter{Float64}, Int8) == Float64
@test δ + δ == 0.05
@test δ^2 == 0.025^2
@test -δ == -0.025
@test log(δ) == log(0.025)
end
# transform_to_real_line and transform_to_model_space
cx = 2 * (α - 1/2)
@testset "Check parameter transformations for optimization" begin
@test abs(transform_to_real_line(α) - cx / sqrt(1 - cx^2)) < .001
@test transform_to_real_line(δ) == 0.025
end
# Check parameters can be declared as vectors
@testset "Test vector-valued parameters" begin
p = parameter(:test, ones(5), (0.0, 5.), (0., 5.0), Untransformed(), MvNormal(ones(5), ones(5)), fixed = false, scaling = x -> x/2)
@test all(ones(5) ./ 2 .== parameter(p, ones(5)).scaledvalue)
end
# Check we can update only specific parameter values in a ParameterVector
@testset "Test updating specific values of a ParameterVector" begin
# Check you can overwrite values which are unfixed
global pvec = ParameterVector{Float64}(undef, 3)
pvec[1] = parameter(:a, 1., (0., 3.), (0., 3.), fixed = false)
pvec[2] = parameter(:b, 1.)
pvec[3] = parameter(:c, 1., (0., 3.), (0., 3.), fixed = false)
global vals = [2., 2.]
update!(pvec, vals, BitArray([true, false, true]))
@test map(x -> x.value, pvec) == [2., 1., 2.]
# Check that overwriting fixed parameter values does not work, even if you pass
# the BitArray telling update! to change the values.
pvec[1] = parameter(:a, 1.)
pvec[2] = parameter(:b, 1.)
pvec[3] = parameter(:c, 1.)
global vals = [2., 2.]
update!(pvec, vals, BitArray([true, false, true]))
@test map(x -> x.value, pvec) == [1., 1., 1.]
end
nothing
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 383 | m = GenericModel()
# model paths. all this should work without errors
m.testing = true
addl_strings = ["foo=bar", "hat=head", "city=newyork"]
@testset "Check proper model paths" begin
for fn in [:rawpath, :workpath, :tablespath, :figurespath]
@eval $(fn)(m, "test")
@eval $(fn)(m, "test", "temp")
@eval $(fn)(m, "test", "temp", addl_strings)
end
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 7879 | using Test, ModelConstructors
# CURRENTLY ONLY TESTS VALUE, PRIOR, FIXED, AND VALUEBOUNDS SWITCHING, NO REGIME SWITCHING IN OTHER CASES
# ALSO TESTS IF TRANSFORMS WORK CORRECTLY WITH REGIME-SWITCHING
@info "The following error 'get_regime_val(), Input Error: No regime 3' is expected."
@testset "Regime switching with parameters" begin
u = parameter(:bloop, 2.5230, (1e-8, 5.), (1e-8, 5.), ModelConstructors.SquareRoot(); fixed = false)
ModelConstructors.set_regime_val!(u, 1, 2.5230)
@test_throws ParamBoundsError ModelConstructors.set_regime_val!(u, 2, 0.)
ModelConstructors.set_regime_val!(u, 2, 0.; override_bounds = true)
uvec = ParameterVector{Float64}(undef, 2)
uvec[1] = u
uvec[2] = u
# Test set_regime_val! and regime_val
@test !isempty(u.regimes)
@test u.regimes[:value][1] == 2.5230
@test u.regimes[:value][2] == 0.
@test u.value == 2.5230
@test ModelConstructors.regime_val(u, 1) == 2.5230
@test ModelConstructors.regime_val(u, 2) == 0.
@test_throws KeyError ModelConstructors.regime_val(u, 3)
ModelConstructors.toggle_regime!(u, 2)
@test u.value == 0.
@test ModelConstructors.regime_val(u, 1) == 2.5230
@test ModelConstructors.regime_val(u, 2) == 0.
ModelConstructors.toggle_regime!(u, 1)
@test u.value == 2.5230
@test ModelConstructors.regime_val(u, 1) == 2.5230
@test ModelConstructors.regime_val(u, 2) == 0.
# Test get_values and toggling regimes
@test n_parameters_regime_switching(uvec) == 4
ModelConstructors.toggle_regime!(u, 1)
@test ModelConstructors.get_values(uvec; regime_switching = false) == [2.5230, 2.5230]
@test ModelConstructors.get_values(uvec) == [2.5230, 2.5230, 0., 0.]
# Test set_regime_prior! and regime_prior
ModelConstructors.set_regime_prior!(u, 1, Uniform(0., 5.))
ModelConstructors.set_regime_prior!(u, 2, Normal(0., 1.))
@test get(ModelConstructors.regime_prior(u, 1)) == Uniform(0., 5.)
@test get(ModelConstructors.regime_prior(u, 2)) == Normal(0., 1.)
# Test set_regime_fixed! and regime_fixed
@test !haskey(u.regimes, :valuebounds)
ModelConstructors.set_regime_fixed!(u, 1, true)
@test haskey(u.regimes, :valuebounds)
ModelConstructors.set_regime_fixed!(u, 2, false)
@show u.regimes[:value]
@test_throws ErrorException ModelConstructors.set_regime_fixed!(u, 3, true)
@test ModelConstructors.regime_fixed(u, 1)
@test !ModelConstructors.regime_fixed(u, 2)
@test ModelConstructors.regime_valuebounds(u, 1) == (2.5230, 2.5230)
@test ModelConstructors.regime_valuebounds(u, 2) == (1e-8, 5.)
# test regime-switching value bounds
ModelConstructors.set_regime_valuebounds!(u, 1, (1e-6, 5.))
ModelConstructors.set_regime_valuebounds!(u, 2, (1e-7, 5.))
@test ModelConstructors.regime_valuebounds(u, 1) == (1e-6, 5.)
@test ModelConstructors.regime_valuebounds(u, 2) == (1e-7, 5.)
# test set_regime_fixed w/update_valuebounds
ModelConstructors.set_regime_fixed!(u, 1, true; update_valuebounds = (10., 11.))
ModelConstructors.set_regime_fixed!(u, 2, false; update_valuebounds = (10., 11.))
@test u.regimes[:valuebounds][1] == (10., 11.)
@test u.regimes[:valuebounds][2] == (10., 11.)
# test transform_to_real_line
ModelConstructors.toggle_regime!(uvec, 1)
set_regime_val!(uvec[1], 2, 1.; override_bounds = true) # break the valuebounds for now
set_regime_val!(uvec[2], 2, 1.; override_bounds = true)
values = ModelConstructors.get_values(uvec)
real_vals_true = similar(values)
real_vals_true[1] = ModelConstructors.transform_to_real_line(uvec[1], uvec[1].regimes[:value][1])
real_vals_true[2] = ModelConstructors.transform_to_real_line(uvec[2], uvec[2].regimes[:value][1])
real_vals_true[3] = ModelConstructors.transform_to_real_line(uvec[1], uvec[1].regimes[:value][2])
real_vals_true[4] = ModelConstructors.transform_to_real_line(uvec[2], uvec[2].regimes[:value][2])
real_vals1 = transform_to_real_line(uvec; regime_switching = true)
real_vals2 = transform_to_real_line(uvec, values; regime_switching = true)
@test real_vals1 == real_vals2 == real_vals_true
# test transform_to_model_space
model_vals = transform_to_model_space(uvec, real_vals1; regime_switching = true)
@test model_vals == values
end
@testset "Regime switching with parameters when model regimes are different" begin
u = parameter(:bloop, 2.5230, (1e-8, 5.), (1e-8, 5.), ModelConstructors.SquareRoot(); fixed = false)
ModelConstructors.set_regime_val!(u, 1, 2.5230)
d = Dict(2 => 1, 3 => 2, 4 => 3)
@test_throws ParamBoundsError ModelConstructors.set_regime_val!(u, 3, 0., d)
ModelConstructors.set_regime_val!(u, 3, 0., d; override_bounds = true)
uvec = ParameterVector{Float64}(undef, 2)
uvec[1] = u
uvec[2] = u
# Test set_regime_val! and regime_val
@test !isempty(u.regimes)
@test u.regimes[:value][1] == 2.5230
@test u.regimes[:value][2] == 0.
@test u.value == 2.5230
@test ModelConstructors.regime_val(u, 2, d) == 2.5230
@test ModelConstructors.regime_val(u, 3, d) == 0.
@test_throws KeyError ModelConstructors.regime_val(u, 4, d)
ModelConstructors.toggle_regime!(u, 3, d)
@test u.value == 0.
@test ModelConstructors.regime_val(u, 2, d) == 2.5230
@test ModelConstructors.regime_val(u, 3, d) == 0.
ModelConstructors.toggle_regime!(u, 2, d)
@test u.value == 2.5230
@test ModelConstructors.regime_val(u, 2, d) == 2.5230
@test ModelConstructors.regime_val(u, 3, d) == 0.
# Test get_values and toggling regimes
@test n_parameters_regime_switching(uvec) == 4
ModelConstructors.toggle_regime!(u, 2, d)
@test ModelConstructors.get_values(uvec; regime_switching = false) == [2.5230, 2.5230]
@test ModelConstructors.get_values(uvec) == [2.5230, 2.5230, 0., 0.]
# Test set_regime_prior! and regime_prior
ModelConstructors.set_regime_prior!(u, 2, Uniform(0., 5.), d)
ModelConstructors.set_regime_prior!(u, 3, Normal(0., 1.), d)
@test get(ModelConstructors.regime_prior(u, 1)) == Uniform(0., 5.)
@test get(ModelConstructors.regime_prior(u, 2)) == Normal(0., 1.)
@test get(ModelConstructors.regime_prior(u, 2, d)) == Uniform(0., 5.)
@test get(ModelConstructors.regime_prior(u, 3, d)) == Normal(0., 1.)
# Test set_regime_fixed! and regime_fixed
ModelConstructors.set_regime_fixed!(u, 2, true, d)
ModelConstructors.set_regime_fixed!(u, 3, false, d)
@test_throws ErrorException ModelConstructors.set_regime_fixed!(u, 4, true, d)
@test ModelConstructors.regime_fixed(u, 1)
@test !ModelConstructors.regime_fixed(u, 2)
@test ModelConstructors.regime_fixed(u, 2, d)
@test !ModelConstructors.regime_fixed(u, 3, d)
@test ModelConstructors.regime_valuebounds(u, 2, d) == (2.5230, 2.5230)
@test ModelConstructors.regime_valuebounds(u, 3, d) == (1e-8, 5.)
# test regime-switching value bounds
ModelConstructors.set_regime_valuebounds!(u, 2, (1e-6, 5.), d)
ModelConstructors.set_regime_valuebounds!(u, 3, (1e-7, 5.), d)
ModelConstructors.set_regime_valuebounds!(u, 4, (1e-8, 5.), d)
@test ModelConstructors.regime_valuebounds(u, 1) ==
ModelConstructors.regime_valuebounds(u, 2, d) == (1e-6, 5.)
@test ModelConstructors.regime_valuebounds(u, 2) ==
ModelConstructors.regime_valuebounds(u, 3, d) == (1e-7, 5.)
@test ModelConstructors.regime_valuebounds(u, 3) ==
ModelConstructors.regime_valuebounds(u, 4, d) == (1e-8, 5.)
# test set_regime_fixed w/update_valuebounds
ModelConstructors.set_regime_fixed!(u, 2, true, d; update_valuebounds = (10., 11.))
ModelConstructors.set_regime_fixed!(u, 3, false, d; update_valuebounds = (10., 11.))
@test u.regimes[:valuebounds][1] == (10., 11.)
@test u.regimes[:valuebounds][2] == (10., 11.)
end
nothing
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 430 | using Test
using ModelConstructors
using Distributions, InteractiveUtils
using Nullables, Printf, Random
my_tests = [
"parameters",
"distributions_ext",
"settings",
"statistics",
"paths",
"regimes",
"abstractmodel"
]
for test in my_tests
test_file = string("$test.jl")
@printf " * %s\n" test_file
include(test_file)
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 1976 | m = GenericModel()
settings = Dict{Symbol, Setting}()
# settings - boolean, string, and number. adding to model. overwriting. filestrings. testing/not testing.
m <= Setting(:n_mh_blocks, 22) # short constructor
n_mh_blocks = m.settings[:n_mh_blocks]
m <= Setting(:reoptimize, false)
reoptimize = m.settings[:reoptimize]
m <= Setting(:data_vintage, "REF", true, "vint", "Date of data") # full constructor
vint = m.settings[:data_vintage]
@testset "Check settings corresponding to parameters" begin
@test promote_rule(Setting{Float64}, Float16) == Float64
@test promote_rule(Setting{Bool}, Bool) == Bool
@test promote_rule(Setting{String}, String) == String
@test convert(Int64, n_mh_blocks) == 22
@test convert(String, vint) == "REF"
@test get_setting(m, :n_mh_blocks) == m.settings[:n_mh_blocks].value
m.testing = true
m <= m.settings[:n_mh_blocks]
@test get_setting(m, :n_mh_blocks) == m.test_settings[:n_mh_blocks].value
@test ModelConstructors.filestring(m) == "_test"
m.testing = false
m <= Setting(:n_mh_blocks, 5, true, "mhbk", "Number of blocks for Metropolis-Hastings")
@test m.settings[:n_mh_blocks].value == 5
@test occursin(r"^\s*_mhbk=5_vint=REF", ModelConstructors.filestring(m))
ModelConstructors.filestring(m, "key=val")
ModelConstructors.filestring(m, ["key=val", "foo=bar"])
m.testing = true
# Overwriting settings
global a = gensym() # unlikely to clash
global b = gensym()
m <= Setting(a, 0, true, "abcd", "a")
m <= Setting(a, 1)
@test m.test_settings[a].value == 1
@test m.test_settings[a].print == true
@test m.test_settings[a].code == "abcd"
@test m.test_settings[a].description == "a"
m <= Setting(b, 2, false, "", "b")
m <= Setting(b, 3, true, "abcd", "b1")
@test m.test_settings[b].value == 3
@test m.test_settings[b].print == true
@test m.test_settings[b].code == "abcd"
@test m.test_settings[b].description == "b1"
end
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | code | 4399 | using ModelConstructors, Test, Random
@testset "Prior computation" begin
p = ParameterVector{Float64}(undef, 3)
p[1] = ModelConstructors.parameter(:a, 0.1, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = false)
p[2] = ModelConstructors.parameter(:b, 0., (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = true)
p[3] = ModelConstructors.parameter(:c, 0.4, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.25, 1.); fixed = false)
@test ModelConstructors.prior(p) == logpdf(p[1]) + logpdf(p[3])
end
@testset "Posterior computation" begin
p = ParameterVector{Float64}(undef, 3)
p[1] = ModelConstructors.parameter(:a, 0.1, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = false)
p[2] = ModelConstructors.parameter(:b, 0., (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = true)
p[3] = ModelConstructors.parameter(:c, 0.4, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.25, 1.); fixed = false)
loglh = (x, data) -> 2.
data = rand(2,2)
@test posterior(loglh, p, data, ϕ_smc = 3.104) == 2. * 3.104 + ModelConstructors.prior(p)
oldvals = map(x -> x.value, p)
oldpost = 2. * 3.104 + ModelConstructors.prior(p)
@test posterior!(loglh, p, oldvals, data, ϕ_smc = 3.104) == oldpost
newvals = copy(oldvals)
newvals[1] += 0.4 # moves value to the mean
newvals[3] -= 0.15 # moves value to the mean
@test posterior!(loglh, p, newvals, data, ϕ_smc = 3.104) > oldpost
end
@testset "Prior computation, updating, and sampling with regime-switching" begin
p = ParameterVector{Float64}(undef, 3)
p[1] = ModelConstructors.parameter(:a, 0.1, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = false)
p[2] = ModelConstructors.parameter(:b, 0., (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.5, 1.); fixed = true)
p[3] = ModelConstructors.parameter(:c, 0.4, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.25, 1.); fixed = false)
p3copy = ModelConstructors.parameter(:c, 0.5, (0., 1.), (0., 1.), ModelConstructors.Untransformed(), Normal(0.25, 1.); fixed = false)
# Set up parameter switching
set_regime_val!(p[1], 1, 0.1) # test prior switching
set_regime_val!(p[1], 2, 0.2)
set_regime_val!(p[1], 3, 0.3)
set_regime_prior!(p[1], 1, Normal(0.5, 1.))
set_regime_prior!(p[1], 2, Normal(0.2, 1.))
set_regime_prior!(p[1], 3, Normal(0.2, 1.))
set_regime_val!(p[2], 1, 0.1; override_bounds = true)
set_regime_val!(p[2], 2, 0.2; override_bounds = true)
set_regime_fixed!(p[2], 1, true)
set_regime_fixed!(p[2], 2, true)
@test set_regime_val!(p[2], 2, 0.2) == 0.2 # trying to reset a fixed value won't do anything
@test regime_val(p[2], 2) == 0.2
set_regime_val!(p[3], 1, 0.4)
set_regime_val!(p[3], 2, 0.5; override_bounds = true)
set_regime_fixed!(p[3], 1, true)
set_regime_fixed!(p[3], 2, false)
@test !ModelConstructors._filter_all_fixed_para(p[1])
@test ModelConstructors._filter_all_fixed_para(p[2])
@test !ModelConstructors._filter_all_fixed_para(p[3])
set_regime_fixed!(p[3], 2, true)
@test ModelConstructors._filter_all_fixed_para(p[3])
set_regime_fixed!(p[3], 2, false)
set_regime_valuebounds!(p[3], 2, (0., 1.)) # set_regime_fixed!(p[3], 2, true) will change the valuebounds
@test prior(p) == sum([logpdf(p[1]), logpdf(p3copy)])
p_in = [0.2, 0.1, 0.5, 0.3, 0.9, 0.2, 0.6]
toggle_regime!(p, 1)
update!(p, p_in)
p_out = [0.2, 0.1, 0.4, 0.3, 0.9, 0.2, 0.6]
@test ModelConstructors.get_values(p) == p_out
@test regime_val(p[1], 1) == 0.2
@test regime_val(p[1], 2) == 0.3
@test regime_val(p[1], 3) == 0.9
Random.seed!(1793)
out1 = ModelConstructors.rand_regime_switching(p; toggle = true)
Random.seed!(1793)
for para in p
toggle_regime!(para, 1)
end
out2 = rand(p; regime_switching = true, toggle = false)
update!(p, out1)
@test out1 == out2
@test regime_val(p[1], 1) == out1[1]
@test regime_val(p[1], 2) == out1[4]
@test regime_val(p[1], 3) == out1[5]
@test regime_val(p[2], 1) == 0.1
@test regime_val(p[2], 2) == 0.2
@test regime_val(p[3], 1) == 0.4
@test regime_val(p[3], 2) == out1[end]
end
nothing
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 2249 | # ModelConstructors.jl v0.2.4
- Extend `transform_to_model_space` and `transform_to_real_line` for regime-switching parameters.
# ModelConstructors.jl v0.2.3
- Move methods for computing free and fixed indices of parameters from SMC.jl to ModelConstructors.jl
# ModelConstructors.jl v0.2.2
- Try to convert types to match rather than throwing a `MethodError` immediately
when calling `parameter`.
# ModelConstructors.jl v0.2.1
- Raise compat bounds for some packages
# ModelConstructors.jl v0.2.0
- Restrict Julia version to at least 1.0
- Add @unpack macro for accessing parameters of a model
- Extend regime-switching to allow switching in `prior`, `fixed`, and `valuebounds` fields.
- Allow difference between the notion of "model regimes" and "parameter regimes" by specifying a dictionary which maps model regimes to parameter regimes.
# ModelConstructors.jl v0.1.12 Release Notes
- Update compatibility bounds
- Fix bugs in examples
# ModelConstructors.jl v0.1.11 Release Notes
- Fix bugs in v0.1.10
# ModelConstructors.jl v0.1.10 Release Notes
- Add random sampling with regime switching in Parameter types
# ModelConstructors.jl v0.1.9 Release Notes
- Implement regime switching in Parameter types.
# ModelConstructors.jl v0.1.8 Release Notes
- Add back New Parameter types that work with both Autodiff functionality and allow backwards compatibility
# ModelConstructors.jl v0.1.7 Release Notes
- Temporarily revert back to old Parameter types to fix SMC.jl tests and allow full backwards compatibility to old Parameters
# ModelConstructors.jl v0.1.6 Release Notes
- Resolve package compatibility issues, so as to be backwards-compatible with Julia 0.7.
# ModelConstructors.jl v0.1.5 Release Notes
Update tests
- Generalize to permit Real types (e.g. allows integration for ForwardDiff)
- Gradients of parameter transformations
- Fix package loading for v1.1
- Add function to initialize DegenerateMvNormal object (needed in the DSGE.jl package)
# ModelConstructors.jl v0.1.4 Release Notes
Update tests
Bug fixes and cleanup
# ModelConstructors.jl v0.1.3 Release Notes
Bug fixes and cleanup
# ModelConstructors.jl v0.1.2 Release Notes
Bug fixes and cleanup
# ModelConstructors.jl v0.1.1 Release Notes
Bug fixes and cleanup
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 3583 | # ModelConstructors.jl

[](https://frbny-dsge.github.io/ModelConstructors.jl/stable)
[](https://frbny-dsge.github.io/ModelConstructors.jl/latest)
[](https://codecov.io/gh/FRBNY-DSGE/ModelConstructors.jl)
This package contains the building blocks of model objects, such as `Parameter`, `Observable`, `Setting`, and `State` types. You may define any custom model, so long as it has parameters. The model object is used in both [DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl) and [SMC.jl](https://github.com/FRBNY-DSGE/SMC.jl).
See `/docs/examples` for examples of how to construct your custom model, then use [SMC.jl](https://github.com/FRBNY-DSGE/SMC.jl) to estimate it (available for any type of model) and [DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl) to construct forecasts, shock decompositions, impulse responses, etc. (available for DSGE models).
## Installation
`ModelConstructors.jl` is a registered Julia package in the [`General`](https://github.com/JuliaRegistries/General) registry. To install, open your Julia REPL, type `]` (enter package manager), and run
```julia
pkg> add ModelConstructors
```
## Versioning
`ModelConstructors.jl` is compatible with Julia `v1.x`. To use `ModelConstructors.jl` with Julia 0.7, please use tag `v0.1.12` or lower.
## Precompilation
The `ModelConstructors.jl` package is not precompiled by default because when running code in parallel, we want to re-compile
the copy of `ModelConstructors.jl` on each processor to guarantee the right version of the code is being used. If users do not
anticipate using parallelism, then users ought to change the first line of `src/ModelConstructors.jl` from
```
isdefined(Base, :__precompile__) && __precompile__(false)
```
to
```
isdefined(Base, :__precompile__) && __precompile__(true)
```
## Disclaimer
Copyright Federal Reserve Bank of New York. You may reproduce, use, modify, make derivative works of, and distribute and this code in whole or in part so long as you keep this notice in the documentation associated with any distributed works. Neither the name of the Federal Reserve Bank of New York (FRBNY) nor the names of any of the authors may be used to endorse or promote works derived from this code without prior written permission. Portions of the code attributed to third parties are subject to applicable third party licenses and rights. By your use of this code you accept this license and any applicable third party license.
THIS CODE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, EXCEPT TO THE EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. FRBNY IS NOT, UNDER ANY CIRCUMSTANCES, LIABLE TO YOU FOR DAMAGES OF ANY KIND ARISING OUT OF OR IN CONNECTION WITH USE OF OR INABILITY TO USE THE CODE, INCLUDING, BUT NOT LIMITED TO DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, SPECIAL OR EXEMPLARY DAMAGES, WHETHER BASED ON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT OR OTHER LEGAL OR EQUITABLE THEORY, EVEN IF FRBNY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES OR LOSS AND REGARDLESS OF WHETHER SUCH DAMAGES OR LOSS IS FORESEEABLE.
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 383 | # Model Constructors
[](https://travis-ci.org/FRBNY-DSGE/ModelConstructors.jl)
[](https://FRBNY-DSGE.github.io/ModelConstructors.jl/stable)
[](https://FRBNY-DSGE.github.io/ModelConstructors.jl/latest)
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 6825 | # [Contributing to ModelConstructors.jl](@id contributing)
## Notes for ModelConstructors.jl Contributors
We may add more features to this package as new use cases emerge.
As these steps are under development, we would welcome improvements to
the existing code from the community. Some examples could be:
- Performance improvements
- Features of certain models that our code cannot implement
- Expanding the regime switching functionality of `Parameter` types.
- Other general improvements
- Adding documentation/test coverage
- Adding existing notable models into the docs/examples directory.
### Git Recommendations For Pull Requests
These are adapted from JuliaLang.
- Avoid working from the `main` branch of your fork, creating a new branch
will make it easier if ModelConstructor's `main` changes and you need to update your
pull request.
- Try to
[squash](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html)
together small commits that make repeated changes to the same section of
code so your pull request is easier to review, and Julia's history won't
have any broken intermediate commits. A reasonable number of separate
well-factored commits is fine, especially for larger changes.
- If any conflicts arise due to changes in ModelConstructors's `main`, prefer updating
your pull request branch with `git rebase` versus `git merge` or `git pull`,
since the latter will introduce merge commits that clutter the git history
with noise that makes your changes more difficult to review.
- Descriptive commit messages are good.
- Using `git add -p` or `git add -i` can be useful to avoid accidentally
committing unrelated changes.
- GitHub does not send notifications when you push a new commit to a pull
request, so please add a comment to the pull request thread to let reviewers
know when you've made changes.
- When linking to specific lines of code in discussion of an issue or pull
request, hit the `y` key while viewing code on GitHub to reload the page
with a URL that includes the specific version that you're viewing. That way
any lines of code that you refer to will still make sense in the future,
even if the content of the file changes.
- Whitespace can be automatically removed from existing commits with `git rebase`.
- To remove whitespace for the previous commit, run
`git rebase --whitespace=fix HEAD~1`.
- To remove whitespace relative to the `main` branch, run
`git rebase --whitespace=fix main`.
## ModelConstructors Julia Style Guide
### Intro
This document lists Julia coding recommendations consistent with best practices
in the software development community. The recommendations are based on
guidelines for other languages collected from a number of sources and on
personal experience. These guidelines are written with the New York Fed DSGE
code in mind. All pull requests submitted should follow these general style
guidelines.
### Naming conventions
Emphasize readability! Our goal is for the code to mimic the mathematical
notation used in New York Fed DSGE papers as closely as possible.
- The names of variables should document their meaning or
use. Variables with a large scope should have especially meaningful
names. Variables with a small scope can have short names.
- Exhibit consistency with the existing codebase.
- Modules and type names in UpperCamelCase
- Variable names in snake_case.
Variable names should be in lower case, using underscores to
separate parts of a compound variable name. For example,
`steady_state` and `equilibrium_conditions` are two fields in the
`Model990()` object that follow this convention. Also notice that,
though the words could be shortened, they are spelled out for maximum
clarity.
- The prefix `n_` should be used for variables representing the
number of objects (e.g. `n_parameters` or `n_anticipated_shocks`)
use the suffix `s` as is natural in spoken language.
- Negative Boolean variable names should be avoided. A problem arises
when such a name is used in conjunction with the logical negation
operator as this results in a double negative. It is not immediately
apparent what `!isNotFound` means. Use `isFound`. Avoid `isNotFound`.
- Named constants can be all uppercase using underscore to separate words:
`MAX_ITERATIONS`
- Naming mathematical objects
Variables with mathematical significance should use
unicode characters and imitate LaTeX syntax. For example, ρ should be used to
name the autocorrelation coefficient in an AR(1) process, and σ should be used
to name standard deviation. Parameters in the text should keep the same
symbol in the code (e.g. α in the code is the same α as in [this
paper](http://www.newyorkfed.org/research/staff_reports/sr647.html),
and takes on it usual significance as the capital share in a
Cobb-Douglas output function.
- General conventions
- Underscores can and should be used when the variable refers to a
mathematical object that has a subscript. (In this case, we are
imitating LaTeX syntax.) For example, $r_m$ in LaTeX should be
represented by the variable `r_m`.
- If the mathematical object has multiple subscripts, for example $x_{i,j}$,
simply concatenate the subscripts: `x_ij`.
- If the object has superscripts as well as subscripts, for example
$y^f_t$, separate the superscripts with an underscore and place them
first: `y_f_t`.
- For compatibility with existing code, variables with numeric subscripts
should exclude the underscore: `G0`, `ψ1`.
- Matrices that have mathematical significance (e.g. the matrices of the
transition and measurement equations) should be upper case, as they are
in mathematical notation, and can repeat the letter to avoid collisions:
`TTT` or `QQ`.
- Symbols such as overbars (which indicate mean values) and tildes (which indicate
log-deviations from the steady state) are written using a 3- or
4-letter abbreviation immediately after the variable they modify:
`kbar_t`, `ztil` (z tilde).
- Stars indicating steady-state variables are included as
subscripts: `π_star_t`
- Suffixes
- Time: Consistent with the previous bullet points, the suffix `_t` as in
`x_t` signifies the value of `x` at time `t`. The suffix `_t1`
signifies the value of `x` at time `t-1`.
- Shocks: The suffix `_sh` refers to a model shock.
- Prefixes
- The prefix `eq_` refers to an equilibrium condition.
- The prefix `obs_` refers to an observable.
- The prefix `E` refers to the expectation operator.
- The prefix `I` refers to the indicator operator.
- Observables with the prefix `g` refer to growth rates.
### Code Formatting Guidelines
- Indent 4 spaces
- Wrap lines at 92 characters
- Use whitespace to enhance readability
- No trailing whitespace
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 3770 | # Creating Models
```@meta
CurrentModule = ModelConstructors
```
The ModelConstructors.jl provides several two models as well as example scripts
that show how to estimate a model.
- A generic model `GenericModel` designed as a template for user-defined models
and for users who only needs functionality to estimate parameters.
- An example of a `LinearRegression` model with minimal fields.
To see examples of more complex models, we recommend looking at the source code
of models in [DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl). These models
use most, if not all, of the fields of `GenericModel`.
## `GenericModel`
### Template for New Models
The idea of `GenericModel` is that it should have most fields required to define
a generic mathematical model. For most purposes, it will have more fields
than needed. If a user wants to create their own model but are not familiar
with the process of defining a new model type, then we recommend that the user copy
the source code of `GenericModel` into a new file and editing that file. Referencing
the source code of models in [DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl)
will be useful.
### [Estimating CAPM](@id estim-capm)
Some users only need the ability to estimate parameters. `GenericModel` provides
a convenient way to do that since it includes functionality to choose settings
and observables. The script estimate_capm.jl in the examples/factor_model folder
in docs shows how to use `GenericModel` in this way. We can write
```julia
capm = GenericModel()
capm <= parameter(:α, 0., (-1e5, 1e5), (-1e5, 1e5), Untransformed(), Normal(0, 1e3),
fixed = false)
# add in more parameters...
```
This code instantiates a `GenericModel` object and adds a parameter called `α`, which
takes a default value of `0.` and is assigned a normal prior with mean zero and variance 1000.
The two `(-1e5, 1e5)` intervals specify the bounds of the parameter before and after
transformation. The `Untransformed()` call indicates that we do not transform the parameter,
hence why the bounds are the same. For more details on parameters,
see the [The `Parameter` type](@ref).
The example script then constructs a likelihood function. To use
[SMC.jl](https://github.com/FRBNY-DSGE/SMC.jl), the likelihood function
needs to take two arguments: parameters and data.
Using `GenericModel` makes this simple
because we just use `capm.parameters` as the parameters provided
as inputs to the likelihood function.
Finally, we just call `smc(likelihood_fnct, capm.parameters, data)` to estimate
the parameters of the CAPM model we have defined!
## `LinearRegression`
The `LinearRegression` type is an example of a model type that does not need to use
all the fields provided in `GenericModel` when estimating. For comparison,
the type definition for `GenericModel` is
```julia
mutable struct GenericModel{T} <: AbstractModel{T}
parameters::ParameterVector{T}
steady_state::ParameterVector{T}
keys::Dict{Symbol, Int}
endogenous_states::Dict{Symbol,Int}
exogenous_shocks::Dict{Symbol,Int}
observables::Dict{Symbol,Int}
pseudo_observables::Dict{Symbol,Int}
spec::String
subspec::String
settings::Dict{Symbol, Setting}
test_settings::Dict{Symbol, Setting}
rng::MersenneTwister
testing::Bool
observable_mappings::Dict{Symbol, Observable}
pseudo_observable_mappings::Dict{Symbol, PseudoObservable}
```
while the type definition for `LinearRegression` is only
```julia
mutable struct LinearRegression{T} <: AbstractModel{T}
parameters::ParameterVector{T}
keys::Dict{Symbol, Int}
spec::String
subspec::String
settings::Dict{Symbol, Setting}
test_settings::Dict{Symbol, Setting}
rng::MersenneTwister
testing::Bool
end
```
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 11172 | # Implementation Details
```@meta
CurrentModule = ModelConstructors
```
This section describes important functions and implementation features in
greater detail. Additional documentation
can also be found in function documentation or in-line.
This section focuses on what the code does and why. Docstrings and the code itself
(including comments) provide detailed information regarding *how* these basic
procedures are implemented.
## The `AbstractModel` Type
The `AbstractModel` type provides a common interface for all model objects,
which greatly facilitates the implementation of new model specifications. Any
concrete subtype of `AbstractModel` can be passed to any function defined for
`AbstractModel`, provided that the concrete type has the fields that the
function expects to be available.
If a user wants to define a new
subclass of models, say regression models, then the user could
create a new `AbstractRegressionModel` type as a subtype of `AbstractModel`.
Functions defined for `AbstractRegressionModel` would only
apply to concrete subtypes of `AbstractRegressionModel`, but
functions defined for `AbstractModel` will still work on these
concrete subtypes.
## The `AbstractParameter` Type
The `AbstractParameter` type implements our notion of a model parameter: a
time-invariant, unobserved value that has significance in the model, e.g.
for likelihood computation and estimation.
Though all parameters are time-invariant, they can have different features.
Some parameters are scaled for use when solving the model[^1] and
constructing the model's measurement equations[^2].
During optimization, parameters may be transformed from
model space to the real line via one of three different transformations: `Untransformed`,
`SquareRoot`, and `Exponential`. These
transformations are also defined as types, and require additional information
for each parameter. Typically, we have two "hyperparameters" for
these transformations, `a`, and `b`.
- `Untransformed`: `a` and `b` do nothing
- `SquareRoot`: `a` and `b` specify the bounds the parameter takes, i.e. ``x\in (a, b)``
- `Exponential`: `a` and `b` are the parameters in the transformation ``a + exp(x - b)``
In some models, steady state values might be relevant parameters.
They are typically functions of other parameters, so they do not need
to be estimated directly.
While parameters are "time-invariant", we do allow regime switching.
As an example, suppose that we have a linear regression with data
from time periods $t = 1,\dots, T$, where $T > 4$, and in $t = 3$,
the intercept of the regression is assumed to change values because of
a structural break in the time series. We can
model the intercept as a parameter with regime-switching. The parameter
has one value in periods $t = 1, 2$ and a different value in periods
$t = 3,\dots, T$. Currently, only regime-switching in the values
of the parameter has been tested, but we have implemented
regime switching in all the features. For example, you may
want a different prior in each regime. See [Regime-Switching Interface](@ref) for
documentation on the interface for regime-switching parameters.
The various requirements on parameters are nicely addressed using a parameterized type
hierarchy.
- `AbstractParameter{T<:Number}`: The common abstract supertype for all
parameters.
- `Parameter{T<:Number, U<:Transform}`: The abstract supertype for
parameters that are directly estimated.
- `UnscaledParameter{T<:Number, U:<Transform}`: Concrete type for
parameters that do not need to be scaled for equilibrium conditions.
- `ScaledParameter{T<:Number, U:<Transform}`: Concrete type for
parameters that are scaled for equilibrium conditions.
- `SteadyStateParameter{T<:Number}`: Concrete type for steady-state
parameters.
All `Parameter`s have the fields defined in `UnscaledParameter`:
```@docs
UnscaledParameter
```
`ScaledParameters` also have the following fields:
- `scaledvalue::T`: Parameter value scaled for use in `eqcond.jl`
- `scaling::Function`: Function used to scale parameter value for use in
equilibrium conditions.
*Note:* Though not strictly necessary, defining a scaling with the parameter
object allows for much a much cleaner definition of the equilibrium conditions.
Because the values of `SteadyStateParameter`s are directly computed as a
function of `ScaledParameter`s and `UnscaledParameter`s, they only require 4
fields:
```@docs
SteadyStateParameter
```
## The `Observable` and `PseudoObservable` Types
We similarly encapsulate information about observables and pseudo-observables
(unobserved linear combinations of states, e.g. the output gap) into the
`Observable` and `PseudoObservable` types. Each type has identifier fields
`key`, `name`, and `longname`.
Most importantly, both `Observable`s and `PseudoObservable`s include the
information needed for transformations to and from model units. For
`Observable`s, these are the `input_series`, `fwd_transform`, and
`rev_transform` fields. "Forward transformations" are applied to transform
the raw input data series specified in `input_series` to model units. The
model is estimated and forecasted in model units, and then we apply "reverse
transformations" to get human-readable units before computing means and bands or
plotting. Pseudo-observables are not observed, so they do not have
`input_series` or `fwd_transform`s, but they may however have `rev_transform`s.
As an example, the `:obs_gdp` `Observable` uses as `input_series` aggregate
nominal GDP in levels, the GDP price index, and population in levels, all from
FRED.[^3] These series are `fwd_transform`ed to get quarter-over-quarter log growth
rates of per-capita real GDP, which are the `Observable`'s model units. The
reverse transformation then converts `:obs_gdp` into annualized
quarter-over-quarter percent changes of *aggregate* real GDP.
```@docs
Observable
PseudoObservable
```
## Model Settings
The `Setting` type implements computational settings that affect how the code
runs without affecting the mathematical definition of the model. Depending on the model,
these may include flags (e.g. whether or not to recompute the Hessian),
parameterization for the Metropolis-Hastings algorithm (e.g. number of times
to draw from the posterior distribution), and the vintage of data being used
(`Setting` is a parametric type - a `Setting{T<:Any}`, so Booleans, Numbers,
and Strings can all be turned into `Setting`s). If settings exist for
a model type, then they should be stored centrally in
the `settings` dictionary within the model object.
Why implement a `Setting` type when we could put their values directly into the
source code or dictionary? The most obvious answer is that the parametric type
allows us to implement a single interface for all `Setting`s (Booleans, Strings,
etc.), so that when we access a particular setting during the estimation and
forecast steps, we don't have to think about the setting's type.
`Setting`s play an important role in addition to providing useful abstraction.
Estimating and forecasting the New York Fed DSGE model takes many hours of
computation time and creates a lot of output files. It is useful to be able to
compare model output from two different models whose settings differ slightly
(for example, consider two identical models that use different vintages of data
as input). A central feature of the `Setting` type is a mechanism that generates
unique, meaningful filenames when code is executed with different settings.
Specifically, when a setting takes on a non-default value, a user-defined
setting code (along with the setting's value) are appended to all output files
generated during execution.
The `Setting{T<:Any}` type is defined as follows:
```@docs
Setting
```
We provide two functions `default_settings!` and `default_test_settings!`
to initialize settings that most models can have. The settings are
- save root
- input data root
- vintage of data to be used
- dataset id
To update the value of an existing function, the user has two
options. First, the user may use the `<=` syntax. However, for this
to work properly, it is essential that the setting's `key` field be
exactly the same as that of an existing entry in
`m.settings`. Otherwise, an additional entry will be added to
`m.settings` and the old setting will be the one accessed from other
all routines. A potentially safer, though clunkier, option is to use the [`update!`](@ref) method.
## Type Interfaces
### `Parameter` Interface
```@autodocs
Modules = [ModelConstructors]
Pages = ["parameters.jl"]
Order = [:function]
```
### Regime-Switching Interface
To implement regime-switching, we add a field to `Parameter` types
called `regimes::Dict{Symbol, OrderedDict{Int, Any}}`. The keys
of the top level dictionary are the names of the other fields
in a `Parameter` type, e.g. `:value`. Each key then points to
an `OrderedDict`, whose keys are the numbers of different regimes
and values are the corresponding values for each regime.
The field `regimes` functions as a "storage" of information.
When a `Parameter` type interacts with another object in Julia,
e.g. `p + 1.`, where `p` is a `Parameter`, what actually happens is
`p.value + 1.`. Only the current fields of `p` will be used
when interacting with other objects. To use a different value
(or different fields) from another regime, the user needs to
tell the parameter to switch regimes the `toggle_regime!` function (see below).
By default, the `regimes` field is empty (see the documentation
of the `parameter` function in [`Parameter` Interface](@ref)).
To add values, either pass in the dictionary as a keyword
to `parameter` or use `set_regime_val!`. Note that the latter
function is not exported.
*Note that regimes must be sorted in order* because we
store the regimes as an `OrderedDict`, and `OrderedDict`
objects are sorted by insertion order.
```@autodocs
Modules = [ModelConstructors]
Pages = ["regimes.jl"]
Order = [:function]
```
### `Setting` Interface
```@autodocs
Modules = [ModelConstructors]
Pages = ["settings.jl"]
Order = [:function]
```
rng::MersenneTwister
testing::Bool
observable_mappings::Dict{Symbol, Observable}
pseudo_observable_mappings::Dict{Symbol, PseudoObservable}
[^1]: By solving the model, we mean a mapping from parameters to
some objects of interest. In a state space model,
solving the model is a mapping from parameters
to a state transition function. By constructing
[^2]: In the context of a state space model,
a measurement equation is mapping from states to observable data.
[^3]: In [DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl), we implement a
`load_data` function that parses `input_series` to retrieve data
from FRED. To take full advantage of the `Observable` type, users may
want to write their own `load_data` function. For example, it may
be convenient to write a `load_data` function that parses `input_series`
to select column(s) from saved CSV files and combines them into
a single data frame.
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 1064 | # ModelConstructors
```@meta
CurrentModule = ModelConstructors
```
The *ModelConstructors.jl* package implements a generic mathematical model object.
A model of any type can be defined as long as it has parameters.
Moreover, this package contains the building blocks of model objects used for both
Dynamic Stochastic General Equilibrium models
([DSGE.jl](https://github.com/FRBNY-DSGE/DSGE.jl)) and
Sequential Monte Carlo ([SMC.jl](https://github.com/FRBNY-DSGE/SMC.jl)).
The Parameter, Observable, Setting, State, etc. types are included.
## Table of Contents
```@contents
Pages = [
"model_design.md",
"example_model.md",
"implementation_details.md",
"contributing.md",
"license.md"
]
```
## Acknowledgements
Developers of this package at the
[New York Fed](https://www.newyorkfed.org/research) include
* [William Chen](https://github.com/chenwilliam77)
* [Shlok Goyal](https://github.com/ShlokG)
* [Alissa Johnson](https://github.com/alissarjohnson)
* [Ethan Matlin](https://github.com/ethanmatlin)
* [Reca Sarfati](https://github.com/rsarfati)
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"BSD-3-Clause"
] | 0.2.4 | 7e6c55714cc0609e6cce3eedece3190799384bf5 | docs | 1462 | # Model Design
*ModelConstructors.jl* is an object-oriented approach to
working with mathematical models. This approach
takes advantage of Julia's type system, multiple dispatch, package-handling
mechanism, and other features. A single model object centralizes
all information about the model's parameters, states, equilibrium conditions, and
settings in a single data structure. The model object also keeps track of file locations
for all I/O operations.
The most minimal model only needs to have parameters, but a generic model may
have one or more of the following objects:
- **Parameters**: Have values, bounds, fixed-or-not status, priors, and regime switching. An
instance of the `AbstractParameter` type houses all information about a given
parameter in a single data structure. See
[The `AbstractParameter` Type](@ref).
- **Settings**: Provide a general way to choose settings that affect how a model
is manipulated. See [The `Setting` Type](@ref).
- **Observables and Pseudo-Observables**: Mapping of names to indices, as well as
information necessary for transformations. See
[The `Observable` and `PseudoObservable` Types](@ref).
These are enough to define a generic model. *Everything else* is essentially
a function of these basics. For example, estimating a model requires two more steps:
defining likelihood function and selecting an estimation routine.
See [Estimating CAPM](@ref estim-capm) for an example estimation using SMC.
| ModelConstructors | https://github.com/FRBNY-DSGE/ModelConstructors.jl.git |
|
[
"MIT"
] | 1.0.1 | 915df0ee2a8278941ca076c855c0ca305e4b192d | code | 792 | # push!(LOAD_PATH,"../src/")
using Documenter
using McmcHermes
import Pkg; Pkg.add("Distributions")
import Pkg; Pkg.add("Plots")
import Pkg; Pkg.add("LaTeXStrings")
import Pkg; Pkg.add("DataFrames")
import Pkg; Pkg.add("ProgressMeter")
import Pkg; Pkg.add("PairPlots")
import Pkg; Pkg.add("CairoMakie")
using Distributions, Plots, LaTeXStrings, DataFrames, ProgressMeter
using PairPlots, CairoMakie
makedocs(
sitename="McmcHermes",
format=Documenter.HTML(;
prettyurls = get(ENV, "CI", nothing) == "true"),
modules=[McmcHermes]
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
repo="github.com/stevenalfonso/McmcHermes.jl.git",
)#
| McmcHermes | https://github.com/stevenalfonso/McmcHermes.jl.git |
|
[
"MIT"
] | 1.0.1 | 915df0ee2a8278941ca076c855c0ca305e4b192d | code | 4169 | module McmcHermes
using Distributions
export one_mcmc, run_mcmc, get_flat_chain, gelman_rubin_diagnostic, sampler
"""
one_mcmc(log_prob, data, parameters, n_iter, a)
Returns one chain with dimension of (n_iter, 1, n_dim)
"""
function one_mcmc(log_prob::Function,
data::Vector,
parameters::Vector,
n_iter::Int64,
a::Float64)
x = ones(( n_iter, length(parameters) ))
x[1,:] = [parameters][1]
new_parameters = zeros(length(parameters))
for i in 2:n_iter
# Propose new parameters
for j in 1:length(parameters)
new_parameters[j] = x[i-1,j] + a * randn(1)[1]
end
present = log_prob(data, parameters)
future = log_prob(data, new_parameters)
# Accept or reject the proposed parameters
alpha = min( exp(future - present), 1.0)
if rand() < alpha
for k in 1:length(parameters)
x[i,k] = new_parameters[k]
end
else
x[i,:] = x[i-1,:]
end
end
return x[:,:,:]
end
"""
run_mcmc(log_prob, data, seed, n_iter, n_walkers, n_dim, a)
Returns chains with dimension of (n_iter, n_walkers, n_dim)
"""
function run_mcmc(log_prob::Function,
data::Vector,
seed::Matrix,
n_iter::Int64,
n_walkers::Int64,
n_dim::Int64;
a::Float64=0.1)
println("Running chains...")
mcmc_chains = ones(( n_iter, n_dim, n_walkers ))
start_time = time_ns()
Threads.@threads for walkers in 1:n_walkers
one_chain = one_mcmc(log_prob, data, seed[walkers,:], n_iter, a)
mcmc_chains[:,:,walkers] = one_chain
end
elapsed_time = (time_ns() - start_time) / 1_000_000_000 # Convert to seconds
if elapsed_time < 60
println("Time elapsed running mcmc: $(elapsed_time) seconds.")
elseif (elapsed_time >= 60) && (elapsed_time < 3600)
println("Time elapsed running mcmc: $(elapsed_time / 60) minutes.")
else
println("Time elapsed running mcmc: $(elapsed_time / 3600) hours.")
end
chains = permutedims(mcmc_chains, [1, 3, 2])
return chains
end
"""
get_flat_chain(array, burn_in, thin)
Returns the stored chain of MCMC samples.
"""
function get_flat_chain(array::Array; burn_in::Int=1, thin::Int=1)
l = ones(( size([i for i in 1:size(array)[1] if i%thin==0])[1], size(array)[2], size(array)[3] ))
ind = 0
for (index, value) in enumerate(1:size(array)[1])
if mod(index, thin) == 0
ind += 1
l[ind,:,:] = array[index,:,:]
end
end
l_thin = reshape( l, (size(l)[1] * size(l)[2], size(l)[3] ) )
return l_thin[burn_in:end,:]
end
"""
gelman_rubin_diagnostic(chains)
Get the Gelman Rubin convergence diagnostic of the chains.
Returns the Gelman-Rubin number.
"""
function gelman_rubin_diagnostic(chains)
s_j = var(chains, dims=2) # within chain variance
W = mean(s_j)
theta = mean(chains, dims=2) # chain mean
theta_j = mean(theta, dims=1) # grand mean
M, N = size(chains)[1], size(chains)[2]
B = N / (M - 1) * sum((theta_j .- theta).^2) # between chain variance
var_theta = (N - 1) / N * W + B / N
R_hat = sqrt(var_theta / W) # Gelma-Rubin statistic
return R_hat
end
"""
sampler(pdf, n_samples, intervals, params)
Get n_samples samples from a 1D Probability Density Distribution
given some parameters. The interval works for the range of samples.
"""
function sampler(pdf::Function,
n_samples::Number,
interval::Vector,
params::Vector)
#states = []
states = ones(n_samples)
current = rand(Uniform(interval[1], interval[2]), 1)[1]
for i in 1:n_samples
#push!(states, current)
states[i] = current
movement = rand(Uniform(interval[1], interval[2]), 1)[1]
current_prob = pdf(current, params)
movement_prob = pdf(movement, params)
alpha = min(movement_prob / current_prob, 1.0)
if rand() < alpha
current = movement
end
end
return states
end
end # module McmcHermes
| McmcHermes | https://github.com/stevenalfonso/McmcHermes.jl.git |
|
[
"MIT"
] | 1.0.1 | 915df0ee2a8278941ca076c855c0ca305e4b192d | code | 1524 | using McmcHermes
using Test
@testset "McmcHermes.jl" begin
# Write your tests here.
using Distributions
mu, sigma = 10, 2
l_b, u_b = 0, 20
d = truncated(Normal(mu, sigma), l_b, u_b)
N = 1000
data = rand(d, N)
function log_likelihood(X::Vector, parameters::Vector)
mu, sigma = parameters[1], parameters[2]
y = 1 ./ (sqrt(2 * pi) .* sigma) .* exp.( -0.5 * ((X .- mu)./sigma).^2 )
return sum(log.(y))
end
function log_prior(parameters::Vector)
mu, sigma = parameters[1], parameters[2]
if 5.0 < mu < 15.0 && 0.0 < sigma < 4.0
return 0.0
end
return -Inf
end
function log_probability(X::Vector, parameters::Vector)
lp = log_prior(parameters)
if !isfinite(lp)
return -Inf
end
return lp + log_likelihood(X, parameters)
end
mu, sigma = 10, 2
initparams = Vector{Float64}([mu, sigma])
n_iter, n_walkers = 100, 50
n_dim, a = 2, 0.02
seed = rand(n_walkers, n_dim) * 1e-4 .+ transpose(initparams)
chain_tests = McmcHermes.run_mcmc(log_probability, data, seed, n_iter, n_walkers, n_dim, a=a)
@test typeof(chain_tests) == Array{Float64, 3}
println(size(chain_tests))
g_r = McmcHermes.gelman_rubin_diagnostic(chain_tests)
@test typeof(g_r) == Float64
flat_chains = McmcHermes.get_flat_chain(chain_tests, burn_in=10, thin=10)
@test typeof(flat_chains) == Matrix{Float64}
println(size(flat_chains))
end | McmcHermes | https://github.com/stevenalfonso/McmcHermes.jl.git |
|
[
"MIT"
] | 1.0.1 | 915df0ee2a8278941ca076c855c0ca305e4b192d | docs | 1099 | [](https://github.com/stevenalfonso/McmcHermes.jl/actions/workflows/Runtests.yml)
[](https://github.com/stevenalfonso/McmcHermes.jl/actions/workflows/documentation.yml)
[](https://github.com/stevenalfonso/McmcHermes.jl/actions/workflows/CI.yml)
# McmcHermes.jl
<div align="center">
<img src="./docs/src/assets/logo.png" alt="logo" width="200"/>
</div>
McmcHermes is a pure-Julia implementation of [Metropolis Hasting Algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm) under an MIT license. McmcHermes will help you if you want to estimate model parameters or sample a probability density distribution.
## Installation
```julia
using Pkg
Pkg.add("McmcHermes")
```
Some examples and basic usage are in the [documentation](https://stevenalfonso.github.io/McmcHermes.jl/dev/). | McmcHermes | https://github.com/stevenalfonso/McmcHermes.jl.git |
|
[
"MIT"
] | 1.0.1 | 915df0ee2a8278941ca076c855c0ca305e4b192d | docs | 4540 | # McmcHermes.jl
*A documentation for the McmcHermes package.*
McmcHermes is a pure-Julia implementation of [Metropolis Hasting Algorithm](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm) under an MIT license. McmcHermes will help you if you want to estimate model parameters or sample a probability density distribution.
```@contents
```
## Installation
```julia
using Pkg
Pkg.add("McmcHermes")
```
## Basic Usage
!!! note
This guide assumes that you already have define your likelihood, prior and the logarithm of the posterior probability as in the example below.
### Sampling
If you want to draw samples from two Gaussian distributions, you would do something like:
```julia
function pdf(X::Number, params::Vector)
s1, s2, mu1, mu2 = params[1], params[2], params[3], params[4]
return 1 / (sqrt(2 * pi) * s1) * exp( -0.5*((X - mu1)/s1)^2 ) + 1 / (sqrt(2 * pi) * s2) * exp( -0.5*((X - mu2)/s2)^2 )
end
function gaussian_function(X::Vector, params::Vector)
x_values = collect(range(minimum(X), maximum(X), length=length(X)))
s1, s2, mu1, mu2 = params[1], params[2], params[3], params[4]
return 0.5 ./ (sqrt(2 * pi) .* s1) .* exp.(-0.5*((x_values .- mu1)./s1).^2) .+ 0.5 ./ (sqrt(2 * pi) .* s2) .* exp.(-0.5*((x_values .- mu2)./s2).^2)
end
using McmcHermes
params = [3, 1.5, -5, 5]
interval = [-20, 20]
sampling = McmcHermes.sampler(pdf, 10000, interval, params)
x_values = Vector{Float64}(range(interval[1], interval[2], 100))
histogram(sampling, xlabel=L"samples", ylabel=L"p(x)", xguidefontsize=12, color=:gray, yguidefontsize=12, normalize=:pdf, show=true, label="samples")
plot!(x_values, gaussian_function(x_values, params), lw=3, size=(500,400), label="Function", lc=:orange, show=true)
```

### Parameter estimation
To estimate parameters $\mu$ and $\sigma$ from a gaussian distribution. First, you need some data
```julia
using Distributions, Plots, LaTeXStrings, DataFrames
mu, sigma = 10, 2 # truths
l_b, u_b = 0, 20
d = Truncated(Normal(mu, sigma), l_b, u_b)
N = 10000
data = rand(d, N)
histogram(data, legend=false, size=(400,400), xlabel=L"data", show=true, normalize=:pdf, ylabel=L"p(x)", xguidefontsize=12, color=:gray, yguidefontsize=12)
```

Now, define likelihood and prior
```julia
function log_likelihood(X::Vector, parameters::Vector)
mu, sigma = parameters[1], parameters[2]
y = 1 ./ (sqrt(2 * pi) .* sigma) .* exp.( -0.5 * ((X .- mu)./sigma).^2 )
return sum(log.(y))
end
function log_prior(parameters::Vector)
mu, sigma = parameters[1], parameters[2]
if 5.0 < mu < 15.0 && 0.0 < sigma < 4.0
return 0.0
end
return -Inf
end
function log_probability(X::Vector, parameters::Vector)
lp = log_prior(parameters)
if !isfinite(lp)
return -Inf
end
return lp + log_likelihood(X, parameters)
end
```
Then, define the number of walkers, iterations, dimension of the parameter space and the initial guess.
```julia
using McmcHermes
mu, sigma = 10, 2
initparams = Vector{Float64}([mu, sigma])
n_iter, n_walkers = 5000, 30
n_dim = 2
seed = rand(n_walkers, n_dim) * 1e-4 .+ transpose(initparams)
chains = McmcHermes.run_mcmc(log_probability, data, seed, n_iter, n_walkers, n_dim, a=0.01)
println(size(chains)) # (5000, 30, 2)
```
The convergence of the chains can be validated by the Gelman-Rubin's diagnostic:
```julia
println("Gelman Rubin Diagnostic: ", McmcHermes.get_gelman_rubin(chains)) # 1.0206366055
```
Finally, plot the chains.
```julia
labels = Tuple([L"\mu", L"\sigma"])
x = 1:size(chains)[1]
p = []
for ind in 1:n_dim
push!(p, plot(x, [chains[:,i,ind] for i in 1:size(chains)[2]], legend=false,
lc=:black, lw=1, ylabel=labels[ind], alpha = 0.1, xticks=false))
end
plot(p[1], p[2], layout = (2,1))
plot!(size=(600,200), xlims = (0, size(chains)[1]), show=true)
```

Chains can also be plotted in a corner. To do so, get the flat chain
```julia
flat_chains = McmcHermes.get_flat_chain(chains, burn_in=100, thin=10)
println(size(flat_chains)) # (14901, 2)
mean_posterior = quantile(flat_chains[:, 1], 0.5) # 10.0273672
std_posterior = quantile(flat_chains[:, 2], 0.5) # 1.9998453
using PairPlots, CairoMakie
table = (; x=flat_chains[:,1], y=flat_chains[:,2],)
fig = pairplot(table, labels = Dict(:x => L"\mu", :y => L"\sigma"))
```

*Develop by [J. Alfonso](https://github.com/stevenalfonso).*
```@index
```
```@autodocs
Modules = [McmcHermes]
``` | McmcHermes | https://github.com/stevenalfonso/McmcHermes.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 4796 | module OpenQuantumBase
using DocStringExtensions
import LinearAlgebra: mul!, lmul!, axpy!, ishermitian, Hermitian, eigen, eigen!,
tr, diag, Diagonal, norm, I, Bidiagonal, qr, diagm
import StaticArrays: SMatrix, MMatrix
import SparseArrays: sparse, issparse, spzeros, SparseMatrixCSC
import LinearAlgebra.BLAS: her!, gemm!
import QuadGK: quadgk!, quadgk
"""
$(TYPEDEF)
This is a supertype for Hamiltonians with elements of type `T`. Any object of a
subtype of `AbstractHamiltonian` should implement two methods corresponding to
the call signatures `H(t)` and `H(du, u, p, t)`.
`H(t)`: This method, when called with a single argument `t`, should return the
value of the Hamiltonian at time `t`.
`H(du, u, p, t)`: This method should update the `du` object in-place according to
the evolution equation ``du += -i H(t) u`` when ``u`` is a vector, or
``du += -i [H(t), u]`` when ``u`` is a matrix. Here, `u` is the state vector or
density matrix, `p` contains parameters for the ODE solver, and `t` is the
current time.
"""
abstract type AbstractHamiltonian{T<:Number} end
"""
$(TYPEDEF)
Base for types defining Hamiltonians using dense matrices.
"""
abstract type AbstractDenseHamiltonian{T<:Number} <: AbstractHamiltonian{T} end
"""
$(TYPEDEF)
Base for types defining Hamiltonians using sparse matrices.
"""
abstract type AbstractSparseHamiltonian{T<:Number} <: AbstractHamiltonian{T} end
"""
$(TYPEDEF)
Base for types defining quantum annealing process.
"""
abstract type AbstractAnnealing{constant_hamiltonian} end
"""
$(TYPEDEF)
Base for types defining system bath coupling operators in open quantum system models.
"""
abstract type AbstractCouplings end
"""
$(TYPEDEF)
Base for types defining bath object.
"""
abstract type AbstractBath end
"""
$(TYPEDEF)
"""
abstract type AbstractLiouvillian end
include("lobpcg.jl")
include("base_util.jl")
include("unit_util.jl")
include("math_util.jl")
include("matrix_util.jl")
include("interpolation.jl")
include("dev_tools.jl")
include("coupling/coupling.jl")
include("coupling/interaction.jl")
include("bath/bath_util.jl")
include("bath/ohmic.jl")
include("bath/hybrid_ohmic.jl")
include("bath/spin_fluc.jl")
include("bath/custom.jl")
include("integration/cpvagk.jl")
include("integration/ext_util.jl")
include("hamiltonian/hamiltonian_base.jl")
include("hamiltonian/interface.jl")
include("hamiltonian/dense_hamiltonian.jl")
include("hamiltonian/sparse_hamiltonian.jl")
include("hamiltonian/static_array_hamiltonian.jl")
include("hamiltonian/adiabatic_frame_hamiltonian.jl")
include("hamiltonian/interp_hamiltonian.jl")
include("hamiltonian/custom_hamiltonian.jl")
include("annealing/annealing_type.jl")
include("annealing/displays.jl")
include("opensys/opensys_util.jl")
include("opensys/diffeq_liouvillian.jl")
include("opensys/redfield.jl")
include("opensys/davies.jl")
include("opensys/cgme.jl")
include("opensys/lindblad.jl")
include("opensys/stochastic.jl")
include("opensys/trajectory_jump.jl")
include("projection/projection.jl")
export SparseHamiltonian, DenseHamiltonian, AdiabaticFrameHamiltonian,
InterpDenseHamiltonian, InterpSparseHamiltonian, CustomDenseHamiltonian, Hamiltonian, ConstantHamiltonian
export rotate, isconstant, isdimensionlesstime
export eigen_decomp, haml_eigs
export temperature_2_β, temperature_2_freq, β_2_temperature, freq_2_temperature
export σx, σz, σy, σi, σ, ⊗, PauliVec, spσx, spσz, spσi, spσy, σ₊, σ₋,
bloch_to_state, creation_operator, annihilation_operator, number_operator
export q_translate, standard_driver, local_field_term, two_local_term,
single_clause, q_translate_state, collective_operator, hamming_weight_operator
export check_positivity, check_unitary, check_density_matrix, partial_trace,
matrix_decompose, low_level_matrix, fidelity, inst_population, gibbs_state, purity, check_pure_state, find_degenerate
export haar_unitary
export construct_interpolations, gradient, log_uniform
export hamiltonian_from_function, evaluate, issparse, get_cache, update_cache!,
update_vectorized_cache!
export ConstantCouplings, TimeDependentCoupling, TimeDependentCouplings,
CustomCouplings, collective_coupling, Interaction, InteractionSet
export Annealing, ODEParams, set_u0!, Evolution
export Lindblad, EnsembleFluctuator, DiffEqLiouvillian
export Ohmic, OhmicBath, CustomBath, CorrelatedBath, ULEBath, HybridOhmic,
HybridOhmicBath
export correlation, polaron_correlation, γ, S, spectrum, info_freq
export τ_B, τ_SB, coarse_grain_timescale
export InplaceUnitary, EᵨEnsemble, sample_state_vector
export ProjectedSystem, project_to_lowlevel, get_dθ, concatenate
# APIs for test and developement tools, may move to a different repo latter
export random_ising, alt_sec_chain, build_example_hamiltonian
end # module OpenQuantumBase
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 3200 | macro CSI_str(str)
return :(string("\x1b[", $(esc(str)), "m"))
end
const TYPE_COLOR = CSI"36"
const NO_COLOR = CSI"0"
"""
function unit_scale(u)
Determine the value of ``1/ħ``. Return ``2π`` if `u` is `:h`; and return 1 if `u` is `:ħ`.
"""
function unit_scale(u)
if u == :h
return 2π
elseif u == :ħ
return 1
else
throw(ArgumentError("The unit can only be :h or :ħ."))
end
end
"""
function allequal(x; rtol = 1e-6, atol = 1e-6)
Check if all elements in `x` are equal upto an absolute error tolerance `atol` and relative error tolerance `rtol`.
"""
@inline function allequal(x; rtol=1e-6, atol=1e-6)
length(x) < 2 && return true
e1 = x[1]
i = 2
@inbounds for i = 2:length(x)
isapprox(x[i], e1, rtol=rtol, atol=atol) || return false
end
return true
end
function numargs(f)
numparam = maximum([num_types_in_tuple(m.sig) for m in methods(f)])
return (numparam - 1) # -1 in v0.5 since it adds f as the first parameter
end
function num_types_in_tuple(sig)
length(sig.parameters)
end
function num_types_in_tuple(sig::UnionAll)
length(Base.unwrap_unionall(sig).parameters)
end
"""
$(TYPEDEF)
A statistical ensemble that is equivalent to a density matrix ρ.
# Fields
$(FIELDS)
"""
struct EᵨEnsemble
"The weights for each state vector"
ω::Vector
"The states vectors in the ensemble"
vec::Vector
function EᵨEnsemble(ω::Vector, vec::Vector)
if !(eltype(ω) <: Number && all((x) -> x >= 0, ω))
throw(ArgumentError("Weights vector ω must be 1-d array of positive numbers."))
end
if !(eltype(vec) <: Vector)
throw(ArgumentError("vec must be 1-d array of vectors."))
end
new(ω, vec)
end
end
sample_state_vector(Eᵨ::EᵨEnsemble) = sample(Eᵨ.vec, Weights(Eᵨ.ω))
"""
$(TYPEDEF)
A container for a matrix whose elements are the same function. Getting any indices of this type returns the same function.
$(FIELDS)
"""
struct SingleFunctionMatrix
"Internal function"
fun::Any
end
@inline Base.getindex(F::SingleFunctionMatrix, ind...) = F.fun
"""
$(SIGNATURES)
Convert bloch sphere angle `θ` and `ϕ` to the corresponding state vector according to ``cos(θ/2)|0⟩+exp(iϕ)sin(θ/2)|1⟩``.
"""
function bloch_to_state(θ::Real, ϕ::Real)
if !(0<=θ<=π)
throw(ArgumentError("θ is out of range 0≤θ≤π."))
end
if !(0<=ϕ<=2π)
throw(ArgumentError("ϕ is out of range 0≤ϕ≤2π."))
end
cos(θ / 2) * PauliVec[3][1] + exp(1.0im * ϕ) * sin(θ / 2) * PauliVec[3][2]
end
"""
$(SIGNATURES)
Split a Pauli expression (a string like "-0.1X1X2+Z1") into a list of substrings
that represent each Pauli clause. Each substring contains three parts: the sign;
the prefix; and the Pauli string.
# Example
```julia-repl
julia> split_pauli_expression("-0.1X1X2+Z2")
2-element Vector{Any}:
SubString{String}["-", "0.1", "X1X2"]
SubString{String}["+", "", "Z2"]
```
"""
function split_pauli_expression(p_str)
p_str = filter((x)->!isspace(x), p_str)
re_str = r"(\+|-|^)([0-9im.]*|^)([XYZ0-9]+)"
res = []
for m in eachmatch(re_str, p_str)
push!(res, [m[1], m[2], m[3]])
end
res
end
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 4895 | # All functions here are for development purpose
"""
$(SIGNATURES)
Construct the matrix of a random 2D Ising lattice ``∑ᵢⱼJᵢⱼZᵢZⱼ``, where ``Jᵢⱼ``s are uniformly distributed between [-1, 1). Generate sparse matrix when `sp` is set to true.
"""
function random_ising(num_qubits::Integer; sp=false)
J = Vector{Float64}()
idx = Vector{Vector{Int64}}()
for i ∈ 1:num_qubits
for j ∈ i+1:num_qubits
push!(J, 2 * rand() - 1)
push!(idx, [i, j])
end
end
two_local_term(J, idx, num_qubits, sp=sp)
end
"""
$(SIGNATURES)
Construct the matrix of the alternating sectors chain model described in (https://www.nature.com/articles/s41467-018-05239-9#Sec1). Generate sparse matrix when `sp` is set to true.
"""
function alt_sec_chain(w1, w2, n, num_qubits; sp=false)
J = Vector{Float64}()
idx = Vector{Vector{Int64}}()
for i in 1:num_qubits-1
push!(J, isodd(ceil(Int, i / n)) ? w1 : w2)
push!(idx, [i, i + 1])
end
two_local_term(J, idx, num_qubits, sp=sp)
end
function build_example_hamiltonian(num_qubits; sp=false)
A = (s) -> (1 - s)
B = (s) -> s
if num_qubits == 1
sp ? SparseHamiltonian([A, B], [spσx, spσz]) : DenseHamiltonian([A, B], [σx, σz])
elseif num_qubits == 4
Hd = -standard_driver(4, sp=sp)
Hp = -q_translate("ZIII+IZII+IIZI+IIIZ", sp=sp)
sp ? SparseHamiltonian([A, B], [Hd, Hp]) : DenseHamiltonian([A, B], [Hd, Hp])
end
end
"""
$(SIGNATURES)
Find the unique gap values upto `sigdigits` number of significant digits.
"""
function find_unique_gap(w::AbstractVector{T}; digits::Integer=8, sigdigits::Integer=8) where {T<:Real}
w_matrix = w' .- w
w_matrix = round.(w_matrix, digits = digits)
w_matrix = round.(w_matrix, sigdigits=sigdigits)
uniq_w = unique(w_matrix)
uniq_w = sort(uniq_w[findall((x) -> x > 0, uniq_w)])
indices = []
for uw in uniq_w
push!(indices, findall((x) -> x == uw, w_matrix))
end
uniq_w, indices, findall((x) -> x == 0, w_matrix)
end
"""
$(SIGNATURES)
The function calculates the derivative of the density matrix obtained by applying the Davies generators on the density matric `ρ``. This function is for test purpose only.
"""
function ame_update_test(ops, ρ, w, v, γ, S)
l = length(w)
uniq_w, positive_indices, zero_indices = find_unique_gap(w)
cs = [v' * c * v for c in ops]
ρ = v' * ρ * v
dρ = zeros(ComplexF64, l, l)
Hₗₛ = zeros(ComplexF64, l, l)
for (w, idx) in zip(uniq_w, positive_indices)
g₊ = γ(w)
g₋ = γ(-w)
a = [x.I[1] for x in idx]
b = [x.I[2] for x in idx]
for c in cs
L₊ = sparse(a, b, c[a+(b.-1)*l], l, l)
L₋ = sparse(b, a, c[b+(a.-1)*l], l, l)
LL₊ = L₊' * L₊
LL₋ = L₋' * L₋
dρ += g₊ * (L₊ * ρ * L₊' - 0.5 * (LL₊ * ρ + ρ * LL₊)) + g₋ * (L₋ * ρ * L₋' - 0.5 * (LL₋ * ρ + ρ * LL₋))
Hₗₛ += S(w) * LL₊ + S(-w) * LL₋
end
end
g0 = γ(0)
a = [x.I[1] for x in zero_indices]
b = [x.I[2] for x in zero_indices]
for c in cs
L = sparse(a, b, c[a+(b.-1)*l], l, l)
LL = L' * L
dρ += g0 * (L * ρ * L' - 0.5 * (LL * ρ + ρ * LL))
Hₗₛ += S(0) * LL
end
dρ -= 1.0im * (Hₗₛ * ρ - ρ * Hₗₛ)
v * dρ * v'
end
"""
$(SIGNATURES)
The function calculates the effective Hamiltonian for the AME quantum trajectories. It is for test purpose only.
"""
function ame_trajectory_Heff_test(ops, w, v, γ, S)
l = length(w)
d = size(v, 1)
uniq_w, positive_indices, zero_indices = find_unique_gap(w)
cs = [v' * c * v for c in ops]
H_eff = zeros(ComplexF64, d, d)
for (w, idx) in zip(uniq_w, positive_indices)
g₊ = γ(w)
g₋ = γ(-w)
a = [x.I[1] for x in idx]
b = [x.I[2] for x in idx]
for c in cs
L₊ = sparse(a, b, c[a+(b.-1)*l], l, l)
L₋ = sparse(b, a, c[b+(a.-1)*l], l, l)
LL₊ = v * L₊' * L₊ * v'
LL₋ = v * L₋' * L₋ * v'
H_eff += S(w) * LL₊ + S(-w) * LL₋ - 0.5im * g₊ * LL₊ - 0.5im * g₋ * LL₋
end
end
g0 = γ(0)
a = [x.I[1] for x in zero_indices]
b = [x.I[2] for x in zero_indices]
for c in cs
L = sparse(a, b, c[a+(b.-1)*l], l, l)
LL = v * L' * L * v'
H_eff += S(0) * LL - 0.5im * g0 * LL
end
H_eff
end
"""
$(SIGNATURES)
The function calculates dρ for one-sided AME. It is for test purpose only.
"""
function onesided_ame_update_test(ops, ρ, w, v, γ, S)
l = size(v, 1)
ω_ba = transpose(w) .- w
Γ = 0.5 * γ.(ω_ba) + 1.0im * S.(ω_ba)
res = zeros(ComplexF64, l, l)
for op in ops
L = v * (Γ .* (v' * op * v)) * v'
K = L * ρ * op - op * L * ρ
res += K + K'
end
res
end
function vectorized_commutator(A)
iden = one(A)
iden⊗A - transpose(A)⊗iden
end | OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 4880 | import Interpolations:
interpolate,
BSpline,
Quadratic,
Line,
OnGrid,
scale,
gradient1,
extrapolate,
Linear,
Gridded,
NoInterp,
Cubic,
Constant,
Flat
"""
$(SIGNATURES)
Construct interpolation of N-D array `y` along its last dimension on grid `x`. `method` specifies the interpolation algorithm, which can be either "BSpline" or "Gridded". If `x` is an `AbstractRange`, the default method is "BSpline", otherwise the default `method` is "Gridded". `order` is the interpolation order. If `x` is `AbstractRange`, the default order is 2, otherwise the default order is 1. `extrapolation` specifies the extrapolation methods, which defines what happens if you try to index into the interpolation object with coordinates outside of its bounds in any dimension. The implemented extrapolation methods are "line", "flat", or you can pass a constant to be used as a "fill" value returned for any out-of-bounds evaluation. The default value is 0.
"""
function construct_interpolations(
x::AbstractRange{S},
y::AbstractArray{T,N};
method="BSpline",
order=2,
extrapolation=0,
) where {S <: Real,T <: Number,N}
method = interp_tuple(N, method, order)
itp = interpolate(y, method)
itp = extrapolate(itp, extrap_method(extrapolation))
index = interp_index(x, size(y))
scale(itp, index...)
end
function construct_interpolations(
x::AbstractArray{S},
y::AbstractArray{T,N};
method="Gridded",
order=1,
extrapolation=0,
) where {S <: Real,T <: Number,N}
if lowercase(method) == "bspline"
Δ = diff(x)
if allequal(Δ)
x = range(x[1], x[end], length=length(x))
return construct_interpolations(
x,
y,
method=method,
order=order,
extrapolation=extrapolation,
)
else
@warn "The grid is not uniform. Using grided linear interpolation."
method = "Gridded"
end
end
method = interp_tuple(N, method, order)
index = interp_index(x, size(y))
itp = interpolate(index, y, method)
extrapolate(itp, extrap_method(extrapolation))
end
function construct_interpolations(
x::AbstractRange{S},
y::AbstractArray{W,1};
method="BSpline",
order=2,
extrapolation=0,
) where {S <: Real,W <: AbstractArray}
y = cat(y...; dims=ndims(y[1]) + 1)
construct_interpolations(
x,
y,
method=method,
order=order,
extrapolation=extrapolation,
)
end
"""
$(SIGNATURES)
Construct interpolation of a nested array. If `x` is an `AbstractRange`, the nested array will be converted into multi-dimensional array for interpolation. Otherwise only "Gridded" method and `order` 1 is supported.
"""
function construct_interpolations(
x::AbstractArray{S,1},
y::AbstractArray{W,1};
method="Gridded",
order=1,
extrapolation=0,
) where {S <: Real,W <: AbstractArray}
itp = interpolate((x,), y, interp_method(method, order))
extrapolate(itp, extrap_method(extrapolation))
end
function interp_index(x, s)
res = []
for i = 1:(length(s) - 1)
push!(res, 1:s[i])
end
push!(res, x)
(res...,)
end
function interp_tuple(N, method, order)
res = []
for i = 1:(N - 1)
push!(res, NoInterp())
end
interp_term = interp_method(method, order)
push!(res, interp_term)
(res...,)
end
function interp_method(method, order::Integer; boundary=Line(OnGrid()))
if lowercase(method) == "bspline"
if order == 0
res = BSpline(Constant())
elseif order == 1
res = BSpline(Linear())
elseif order == 2
res = BSpline(Quadratic(boundary))
elseif order == 3
res = BSpline(Cubic(boundary))
else
throw(ArgumentError("Order $order for method $method is not implemented."))
end
elseif lowercase(method) == "gridded"
if order == 0
res = Gridded(Constant())
elseif order == 1
res = Gridded(Linear())
else
throw(ArgumentError("Oder $order for method $method is not implemented."))
end
elseif lowercase(method) == "none"
res = NoInterp()
else
throw(ArgumentError("Method $method is invalid."))
end
res
end
function extrap_method(method::String)
if lowercase(method) == "line"
Line()
elseif lowercase(method) == "flat"
Flat()
else
throw(ArgumentError("Extrapolation method: $method is not supported."))
end
end
extrap_method(method::Number) = method
"""
$(SIGNATURES)
Calculate the gradient of `itp` at `s`.
"""
function gradient(itp, s::Number)
gradient1(itp, s)
end
function gradient(itp, s::AbstractArray)
[gradient1(itp, x) for x in s]
end
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 19936 | # Adapted from the DFTK.jl (https://github.com/JuliaMolSim/DFTK.jl)
# implementation.
# Implementation of the LOBPCG algorithm, seeking optimal performance
# and stability (it should be very, very hard to break, even at tight
# tolerance criteria). The code is not 100% optimized yet, but the
# most time-consuming parts (BLAS3 and matvecs) should be OK. The
# implementation follows the scheme of Hetmaniuk & Lehoucq (see also
# the refinements in Duersch et. al.), with the following
# modifications:
# - Cholesky factorizations are used instead of the eigenvalue
# decomposition of Stathopolous & Wu for the orthogonalization.
# Cholesky orthogonalization is fast but has an unwarranted bad
# reputation: when applied twice to a matrix X with κ(X) <~
# sqrt(1/ε), where ε is the machine epsilon, it will produce a set
# of very orthogonal vectors, just as the eigendecomposition-based
# method. It can fail when κ >~ sqrt(1/ε), but that can be fixed by
# shifting the overlap matrix. This is very reliable while being
# much faster than eigendecompositions.
# - Termination criteria for the orthogonalization are based on cheap
# estimates instead of costly explicit checks.
# - The default tolerances are very tight, yielding a very stable
# algorithm. This can be tweaked (see keyword ortho_tol) to
# compromise on stability for less Cholesky factorizations.
# - Implicit product updates (reuse of matvecs) are performed whenever
# it is safe to do so, ie only with orthogonal transformations. An
# exception is the B matrix reuse, which seems to be OK even with very
# badly conditioned B matrices. The code is easy to modify if this is
# not the case.
# - The locking is performed carefully to ensure minimal impact on the
# other eigenvectors (which is not the case in many - all ? - other
# implementations)
## TODO micro-optimization of buffer reuse
## TODO write a version that doesn't assume that B is well-conditionned, and doesn't reuse B applications at all
## TODO it seems there is a lack of orthogonalization immediately after locking, maybe investigate this to save on some choleskys
## TODO debug orthogonalizations when A=I
# TODO Use @debug for this
# vprintln(args...) = println(args...) # Uncomment for output
vprintln(args...) = nothing
using LinearAlgebra
import LinearAlgebra: BlasFloat
import Base: *
import Base.size, Base.adjoint, Base.Array
import StaticArrays: @SArray, StaticArray
"""
Simple wrapper to represent a matrix formed by the concatenation of column blocks:
it is mostly equivalent to hcat, but doesn't allocate the full matrix.
LazyHcat only supports a few multiplication routines: furthermore, a multiplication
involving this structure will always yield a plain array (and not a LazyHcat structure).
LazyHcat is a lightweight subset of BlockArrays.jl's functionalities, but has the
advantage to be able to store GPU Arrays (BlockArrays is heavily built on Julia's CPU Array).
"""
struct LazyHcat{T<:Number,D<:Tuple} <: AbstractMatrix{T}
blocks::D
end
function LazyHcat(arrays::AbstractArray...)
@assert length(arrays) != 0
n_ref = size(arrays[1], 1)
@assert all(size.(arrays, 1) .== n_ref)
T = promote_type(map(eltype, arrays)...)
LazyHcat{T,typeof(arrays)}(arrays)
end
function Base.size(A::LazyHcat)
n = size(A.blocks[1], 1)
m = sum(size(block, 2) for block in A.blocks)
(n, m)
end
Base.Array(A::LazyHcat) = hcat(A.blocks...)
Base.adjoint(A::LazyHcat) = Adjoint(A)
@views function Base.:*(Aadj::Adjoint{T,<:LazyHcat}, B::LazyHcat) where {T}
A = Aadj.parent
rows = size(A)[2]
cols = size(B)[2]
ret = similar(A.blocks[1], rows, cols)
orow = 0 # row offset
for blA in A.blocks
ocol = 0 # column offset
for blB in B.blocks
ret[orow.+(1:size(blA, 2)), ocol.+(1:size(blB, 2))] .= blA' * blB
ocol += size(blB, 2)
end
orow += size(blA, 2)
end
ret
end
Base.:*(Aadj::Adjoint{T,<:LazyHcat}, B::AbstractMatrix) where {T} = Aadj * LazyHcat(B)
@views function *(Ablock::LazyHcat, B::AbstractMatrix)
res = Ablock.blocks[1] * B[1:size(Ablock.blocks[1], 2), :] # First multiplication
offset = size(Ablock.blocks[1], 2)
for block in Ablock.blocks[2:end]
mul!(res, block, B[offset.+(1:size(block, 2)), :], 1, 1)
offset += size(block, 2)
end
res
end
function LinearAlgebra.mul!(res::AbstractMatrix, Ablock::LazyHcat,
B::AbstractVecOrMat, α::Number, β::Number)
mul!(res, Ablock * B, I, α, β)
end
# Perform a Rayleigh-Ritz for the N first eigenvectors.
function rayleigh_ritz(X, AX, N)
XAX = X' * AX
@assert !any(isnan, XAX)
rayleigh_ritz(Hermitian(XAX), N)
end
@views function rayleigh_ritz(XAX::Hermitian, N)
# Fallback: Use whatever is the default dense eigensolver.
# Note: GenericLinearAlgebra uses a QR-based algorithm, which is pretty safe in terms
# of keeping the vectors orthogonal
values, vectors = eigen(XAX)
vectors[:, 1:N], values[1:N]
end
@views function rayleigh_ritz(XAX::Hermitian{<:BlasFloat,<:Array}, N)
# LAPACK sysevr (the Julia default dense eigensolver) can actually return eigenvectors
# that are significantly non-orthogonal (1e-4 in Float32 in some tests) here,
# presumably because it tries hard to make them eigenvectors in the presence
# of small gaps. Since we care more about them being orthogonal
# than about them being eigenvectors, re-orthogonalize.
# TODO To avoid orthogonalization: Use syevd,
# which does a much better job, see https://github.com/JuliaLang/julia/pull/49262
# and https://github.com/JuliaLang/julia/pull/49355
values, vectors = eigen(XAX)
v = vectors[:, 1:N]
ortho!(v)
v, values[1:N]
end
# B-orthogonalize X (in place) using only one B apply.
# This uses an unstable method which is only OK if X is already
# orthogonal (not B-orthogonal) and B is relatively well-conditioned
# (which implies that X'BX is relatively well-conditioned, and
# therefore that it is safe to cholesky it and reuse the B apply)
function B_ortho!(X, BX)
O = Hermitian(X' * BX)
U = cholesky(O).U
@assert !any(isnan, U)
rdiv!(X, U)
rdiv!(BX, U)
end
normest(M) = maximum(abs.(diag(M))) + norm(M - Diagonal(diag(M)))
# Orthogonalizes X to tol
# Returns the new X, the number of Cholesky factorizations algorithm, and the
# growth factor by which small perturbations of X can have been
# magnified
function ortho!(X::AbstractArray{T}; tol=2eps(real(T))) where {T}
local R
# # Uncomment for "gold standard"
# U,S,V = svd(X)
# return U*V', 1, 1
growth_factor = one(real(T))
success = false
nchol = 0
while true
O = Hermitian(X'X)
try
R = cholesky(O).U
nchol += 1
success = true
catch err
@assert isa(err, PosDefException)
vprintln("fail")
# see https://arxiv.org/pdf/1809.11085.pdf for a nice analysis
# We are not being very clever here; but this should very rarely happen
# so it should be OK
α = 100
nbad = 0
while true
O += α * eps(real(T)) * norm(X)^2 * I
α *= 10
try
R = cholesky(O).U
nchol += 1
break
catch err
@assert isa(err, PosDefException)
end
nbad += 1
if nbad > 10
error("Cholesky shifting is failing badly, this should never happen")
end
end
success = false
end
invR = inv(R)
@assert !any(isnan, invR)
rmul!(X, invR) # we do not use X/R because we use invR next
# We would like growth_factor *= opnorm(inv(R)) but it's too
# expensive, so we use an upper bound which is sharp enough to
# be close to 1 when R is close to I, which we need for the
# outer loop to terminate
# ||invR|| = ||D + E|| ≤ ||D|| + ||E|| ≤ ||D|| + ||E||_F,
# where ||.|| is the 2-norm and ||.||_F the Frobenius
norminvR = normest(invR)
growth_factor *= norminvR
# condR = 1/LAPACK.trcon!('I', 'U', 'N', Array(R))
condR = normest(R) * norminvR # in practice this seems to be an OK estimate
vprintln("Ortho(X) success? $success ", eps(real(T)) * condR^2, " < $tol")
# a good a posteriori error is that X'X - I is eps()*κ(R)^2;
# in practice this seems to be sometimes very overconservative
success && eps(real(T)) * condR^2 < tol && break
nchol > 10 && error("Ortho(X) is failing badly, this should never happen")
end
# @assert norm(X'X - I) < tol
(; X, nchol, growth_factor)
end
# Randomize the columns of X if the norm is below tol
function drop!(X::AbstractArray{T}, tol=2eps(real(T))) where {T}
dropped = Int[]
for i = 1:size(X, 2)
n = norm(@views X[:, i])
if n <= tol
X[:, i] = randn(T, size(X, 1))
push!(dropped, i)
end
end
dropped
end
# Find X that is orthogonal, and B-orthogonal to Y, up to a tolerance tol.
function ortho!(X::AbstractArray{T}, Y, BY; tol=2eps(real(T))) where {T}
# normalize to try to cheaply improve conditioning
Threads.@threads for i = 1:size(X, 2)
n = norm(@views X[:, i])
@views X[:, i] ./= n
end
niter = 1
ninners = zeros(Int, 0)
while true
BYX = BY' * X
mul!(X, Y, BYX, -1, 1) # X -= Y*BY'X
# If the orthogonalization has produced results below 2eps, we drop them
# This is to be able to orthogonalize eg [1;0] against [e^iθ;0],
# as can happen in extreme cases in the ortho!(cP, cX)
dropped = drop!(X)
if dropped != []
X[:, dropped] .-= Y * (BY' * X[:, dropped])
end
if norm(BYX) < tol && niter > 1
push!(ninners, 0)
break
end
X, ninner, growth_factor = ortho!(X; tol)
push!(ninners, ninner)
# norm(BY'X) < tol && break should be the proper check, but
# usually unnecessarily costly. Instead, we predict the error
# according to the growth factor of the orthogonalization.
# Assuming BY'Y = 0 to machine precision, after the
# Y-orthogonalization, BY'X is O(eps), so BY'X will be bounded
# by O(eps * growth_factor).
# If we're at a fixed point, growth_factor is 1 and if tol >
# eps(), the loop will terminate, even if BY'Y != 0
growth_factor * eps(real(T)) < tol && break
niter > 10 && error("Ortho(X,Y) is failing badly, this should never happen")
niter += 1
end
vprintln("ortho choleskys: ", ninners) # get how many Choleskys are performed
# @assert (norm(BY'X)) < tol
# @assert (norm(X'X-I)) < tol
X
end
function final_retval(X, AX, resid_history, niter, n_matvec)
λ = real(diag(X' * AX))
residuals = AX .- X * Diagonal(λ)
(; λ, X,
residual_norms=[norm(residuals[:, i]) for i in 1:size(residuals, 2)],
residual_history=resid_history[:, 1:niter+1], n_matvec)
end
### The algorithm is Xn+1 = rayleigh_ritz(hcat(Xn, A*Xn, Xn-Xn-1))
### We follow the strategy of Hetmaniuk and Lehoucq, and maintain a B-orthonormal basis Y = (X,R,P)
### After each rayleigh_ritz step, the B-orthonormal X and P are deduced by an orthogonal rotation from Y
### R is then recomputed, and orthonormalized explicitly wrt BX and BP
### We reuse applications of A/B when it is safe to do so, ie only with orthogonal transformations
function LOBPCG(A, X, B=I, precon=I, tol=1e-10, maxiter=100;
miniter=1, ortho_tol=2eps(real(eltype(X))),
n_conv_check=nothing, display_progress=false)
N, M = size(X)
# If N is too small, we will likely get in trouble
error_message(verb) = "The eigenproblem is too small, and the iterative " *
"eigensolver $verb fail; increase the number of " *
"degrees of freedom, or use a dense eigensolver."
N > 3M || error(error_message("will"))
N >= 3M + 5 || @warn error_message("might")
n_conv_check === nothing && (n_conv_check = M)
resid_history = zeros(real(eltype(X)), M, maxiter + 1)
# B-orthogonalize X
X = ortho!(copy(X), tol=ortho_tol)[1]
if B != I
BX = similar(X)
BX = mul!(BX, B, X)
B_ortho!(X, BX)
end
n_matvec = M # Count number of matrix-vector products
AX = similar(X)
AX = mul!(AX, A, X)
@assert !any(isnan, AX)
# full_X/AX/BX will always store the full (including locked) X.
# X/AX/BX only point to the active part
P = zero(X)
AP = zero(X)
R = zero(X)
AR = zero(X)
if B != I
BR = zero(X)
# BX was already computed
BP = zero(X)
else
# The B arrays are just pointers to the same data
BR = R
BX = X
BP = P
end
nlocked = 0
niter = 0 # the first iteration is fake
λs = @views [(X[:, n]' * AX[:, n]) / (X[:, n]'BX[:, n]) for n = 1:M]
λs = oftype(X[:, 1], λs) # Offload to GPU if needed
new_X = X
new_AX = AX
new_BX = BX
full_X = X
full_AX = AX
full_BX = BX
while true
if niter > 0 # first iteration is just to compute the residuals (no X update)
### Perform the Rayleigh-Ritz
mul!(AR, A, R)
n_matvec += size(R, 2)
# Form Rayleigh-Ritz subspace
if niter > 1
Y = LazyHcat(X, R, P)
AY = LazyHcat(AX, AR, AP)
BY = LazyHcat(BX, BR, BP) # data shared with (X, R, P) in non-general case
else
Y = LazyHcat(X, R)
AY = LazyHcat(AX, AR)
BY = LazyHcat(BX, BR) # data shared with (X, R) in non-general case
end
cX, λs = rayleigh_ritz(Y, AY, M - nlocked)
# Update X. By contrast to some other implementations, we
# wait on updating P because we have to know which vectors
# to lock (and therefore the residuals) before computing P
# only for the unlocked vectors. This results in better convergence.
new_X = Y * cX
new_AX = AY * cX # no accuracy loss, since cX orthogonal
new_BX = (B == I) ? new_X : BY * cX
end
### Compute new residuals
begin
new_R = new_AX .- new_BX .* λs'
@views for i = 1:size(X, 2)
resid_history[i+nlocked, niter+1] = norm(new_R[:, i])
end
end
vprintln(niter, " ", resid_history[:, niter+1])
# it is actually a good question of knowing when to
# precondition. Here seems sensible, but it could plausibly be
# done before or after
if precon !== I
begin
precondprep!(precon, X) # update preconditioner if needed; defaults to noop
ldiv!(precon, new_R)
end
end
### Compute number of locked vectors
prev_nlocked = nlocked
if niter ≥ miniter # No locking if below miniter
for i = nlocked+1:M
if resid_history[i, niter+1] < tol
nlocked += 1
vprintln("locked $nlocked")
else
# We lock in order, assuming that the lowest
# eigenvectors converge first; might be tricky otherwise
break
end
end
end
if display_progress
println("Iter $niter, converged $(nlocked)/$(n_conv_check), resid ",
norm(resid_history[1:n_conv_check, niter+1]))
end
if nlocked >= n_conv_check # Converged!
X .= new_X # Update the part of X which is still active
AX .= new_AX
return final_retval(full_X, full_AX, resid_history, niter, n_matvec)
end
newly_locked = nlocked - prev_nlocked
active = newly_locked+1:size(X, 2) # newly active vectors
if niter > 0
### compute P = Y*cP only for the newly active vectors
Xn_indices = newly_locked+1:M-prev_nlocked
# TODO understand this for a potential save of an
# orthogonalization, see Hetmaniuk & Lehoucq, and Duersch et. al.
# cP = copy(cX)
# cP[Xn_indices,:] .= 0
lenXn = length(Xn_indices)
e = zeros_like(X, size(cX, 1), M - prev_nlocked)
lower_diag = one(similar(X, lenXn, lenXn))
# e has zeros everywhere except on one of its lower diagonal
e[Xn_indices[1]:last(Xn_indices), 1:lenXn] = lower_diag
cP = cX .- e
cP = cP[:, Xn_indices]
# orthogonalize against all Xn (including newly locked)
ortho!(cP, cX, cX, tol=ortho_tol)
# Get new P
new_P = Y * cP
new_AP = AY * cP
if B != I
new_BP = BY * cP
else
new_BP = new_P
end
end
# Update all X, even newly locked
X .= new_X
AX .= new_AX
if B != I
BX .= new_BX
end
# Quick sanity check
for i = 1:size(X, 2)
@views if abs(BX[:, i]'X[:, i] - 1) >= sqrt(eps(real(eltype(X))))
error("LOBPCG is badly failing to keep the vectors normalized; this should never happen")
end
end
# Restrict all views to active
@views begin
X = X[:, active]
AX = AX[:, active]
BX = BX[:, active]
R = new_R[:, active]
AR = AR[:, active]
BR = BR[:, active]
P = P[:, active]
AP = AP[:, active]
BP = BP[:, active]
λs = λs[active]
end
# Update newly active P
if niter > 0
P .= new_P
AP .= new_AP
if B != I
BP .= new_BP
end
end
# Orthogonalize R wrt all X, newly active P
if niter > 0
Z = LazyHcat(full_X, P)
BZ = LazyHcat(full_BX, BP) # data shared with (full_X, P) in non-general case
else
Z = full_X
BZ = full_BX
end
ortho!(R, Z, BZ; tol=ortho_tol)
if B != I
mul!(BR, B, R)
B_ortho!(R, BR)
end
niter < maxiter || break
niter = niter + 1
end
final_retval(full_X, full_AX, resid_history, maxiter, n_matvec)
end
function lobpcg_hyper(A, X0; maxiter=100, prec=nothing,
tol=20size(A, 2) * eps(real(eltype(A))),
largest=false, n_conv_check=nothing, kwargs...)
prec === nothing && (prec = I)
@assert !largest "Only seeking the smallest eigenpairs is implemented."
result = LOBPCG(A, X0, I, prec, tol, maxiter; n_conv_check, kwargs...)
n_conv_check === nothing && (n_conv_check = size(X0, 2))
converged = maximum(result.residual_norms[1:n_conv_check]) < tol
iterations = size(result.residual_history, 2) - 1
merge(result, (; iterations, converged))
end
"""
Create an array of same "array type" as X filled with zeros, minimizing the
number of allocations. This unifies CPU and GPU code, as the output will always
be on the same device as the input.
"""
function zeros_like(X::AbstractArray, T::Type=eltype(X), dims::Integer...=size(X)...)
Z = similar(X, T, dims...)
Z .= zero(T)
Z
end
zeros_like(X::AbstractArray, dims::Integer...) = zeros_like(X, eltype(X), dims...)
zeros_like(X::Array, T::Type=eltype(X), dims::Integer...=size(X)...) = zeros(T, dims...)
zeros_like(X::StaticArray, T::Type=eltype(X), dims::Integer...=size(X)...) = @SArray zeros(T, dims...) | OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 9886 | import LinearAlgebra: kron, eigmin
const σx = [0.0 + 0.0im 1; 1 0]
const σy = [0.0 + 0.0im -1.0im; 1.0im 0]
const σz = [1.0 + 0.0im 0; 0 -1]
const σi = [1.0 + 0.0im 0; 0 1]
const σ₋ = [0.0im 0;1 0]
const σ₊ = [0.0im 1;0 0]
const σ = [σx, σy, σz, σi]
xvec = [[1.0 + 0.0im, 1.0] / sqrt(2), [1.0 + 0.0im, -1.0] / sqrt(2)]
yvec = [[1.0, 1.0im] / sqrt(2), [1.0, -1.0im] / sqrt(2)]
zvec = [[1.0 + 0.0im, 0], [0, 1.0 + 0.0im]]
const spσz = sparse(σz)
const spσx = sparse(σx)
const spσy = sparse(σy)
const spσi = sparse(I, 2, 2)
"""
PauliVec
A constant that holds the eigenvectors of the Pauli matrices. Indices 1, 2 and 3 corresponds to the eigenvectors of ``σ_x``, ``σ_y`` and ``σ_z``.
# Examples
```julia-repl
julia> σx*PauliVec[1][1] == PauliVec[1][1]
true
```
"""
const PauliVec = [xvec, yvec, zvec]
"""
⊗(A, B)
Calculate the tensor product of `A` and `B`.
# Examples
```julia-repl
julia> σx⊗σz
4×4 Array{Complex{Float64},2}:
0.0+0.0im 0.0+0.0im 1.0+0.0im 0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -1.0+0.0im
1.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im -1.0+0.0im 0.0+0.0im -0.0+0.0im
```
"""
⊗ = kron
"""
$(SIGNATURES)
Decompse matrix `mat` onto matrix basis `basis`
# Examples
```julia-repl
julia> matrix_decompose(1.0*σx+2.0*σy+3.0*σz, [σx,σy,σz])
3-element Array{Complex{Float64},1}:
1.0 + 0.0im
2.0 + 0.0im
3.0 + 0.0im
```
"""
function matrix_decompose(mat::AbstractMatrix, basis::Vector{<:AbstractMatrix})
dim = size(basis[1])[1]
[tr(mat * b) / dim for b in basis]
end
"""
check_positivity(m)
Check if matrix `m` is positive. Return `true` is the minimum eigenvalue of `m` is greater than or equal to 0.
"""
function check_positivity(m::AbstractMatrix)
if !ishermitian(m)
@warn "Input fails the numerical test for Hermitian matrix. Use the upper triangle to construct a new Hermitian matrix."
d = Hermitian(m)
else
d = m
end
eigmin(d) >= 0
end
"""
gibbs_state(h, β)
Calculate the Gibbs state of the matrix `h` at temperature `T` (mK).
# Examples
```julia-repl
julia> gibbs_state(σz, 10)
2×2 Array{Complex{Float64},2}:
0.178338+0.0im 0.0+0.0im
0.0+0.0im 0.821662+0.0im
```
"""
function gibbs_state(h, T)
β = temperature_2_β(T)
Z = 0.0
w, v = eigen(Hermitian(h))
res = zeros(eltype(v), size(h))
for (i, E) in enumerate(w)
t = exp(-β * E)
vi = @view v[:, i]
res += t * vi * vi'
Z += t
end
res / Z
end
"""
low_level_matrix(M, lvl)
Calculate the matrix `M` projected to lower energy subspace containing `lvl` energy lvl.
# Examples
```julia-repl
julia> low_level_matrix(σx⊗σx, 2)
4×4 Array{Complex{Float64},2}:
-0.5+0.0im 0.0+0.0im 0.0+0.0im 0.5+0.0im
0.0+0.0im -0.5+0.0im 0.5+0.0im 0.0+0.0im
0.0+0.0im 0.5+0.0im -0.5+0.0im 0.0+0.0im
0.5+0.0im 0.0+0.0im 0.0+0.0im -0.5+0.0im
```
"""
function low_level_matrix(M, lvl)
if lvl > size(M, 1)
@warn "Subspace dimension bigger than total dimension."
return M
else
w, v = eigen(Hermitian(M))
res = zeros(eltype(v), size(M))
for i in range(1, stop = lvl)
vi = @view v[:, i]
res += w[i] * vi * vi'
end
return res
end
end
"""
$(SIGNATURES)
Test if `𝐔` is a unitary matrix. The function checks how close both `` 𝐔𝐔^† `` and `` 𝐔^†𝐔 `` are to `` I ``, with relative and absolute error given by `rtol`, `atol`.
# Examples
```julia-repl
julia> check_unitary(exp(-1.0im*5*0.5*σx))
true
```
"""
function check_unitary(𝐔::AbstractMatrix; rtol = 1e-6, atol = 1e-8)
a1 = isapprox(
𝐔 * 𝐔',
Matrix{eltype(𝐔)}(I, size(𝐔)),
rtol = rtol,
atol = atol,
)
a2 = isapprox(
𝐔' * 𝐔,
Matrix{eltype(𝐔)}(I, size(𝐔)),
rtol = rtol,
atol = atol,
)
a1 && a2
end
"""
$(SIGNATURES)
Generate a log-uniformly distributed array with `num` elements between `a` and `b`. The base of log is `base` with default value 10.
"""
function log_uniform(a, b, num; base = 10)
loga = log(base, a)
logb = log(base, b)
10 .^ range(loga, logb, length = num)
end
"""
$(SIGNATURES)
Calculate the partial trace of the density matrix `ρ`, assuming all the subsystems are qubits. `qubit_2_keep` denotes the indices whose corresponding qubits are not traced out.
# Examples
```julia-repl
julia> ρ1 = [0.4 0.2; 0.2 0.6]; ρ2 = [0.5 0; 0 0.5];
julia> partial_trace(ρ1⊗ρ2, [1])
2×2 Array{Float64,2}:
0.4 0.2
0.2 0.6
```
"""
function partial_trace(ρ::Matrix, qubit_2_keep::AbstractVector{Int})
num = Int(log2(size(ρ, 1)))
partial_trace(ρ, [2 for i in 1:num], qubit_2_keep)
end
"""
$(SIGNATURES)
Calculate the partial trace of the density matrix `ρ`. Assume `ρ` is in the tensor space of ``ℋ₁⊗ℋ₂⊗…``,
`sys_dim` is an array of the corresponding sub-system dimensions. `dim_2_keep` is an array of the indices
whose corresponding subsystems are not traced out.
# Examples
```julia-repl
julia> ρ1 = [0.4 0.2; 0.2 0.6]; ρ2 = [0.5 0; 0 0.5];
julia> partial_trace(ρ1⊗ρ2, [2, 2], [1])
2×2 Array{Float64,2}:
0.4 0.2
0.2 0.6
```
"""
partial_trace(ρ::AbstractMatrix, sys_dim::AbstractVector{<:Integer}, dim_2_keep::Integer) = partial_trace(ρ,sys_dim,[dim_2_keep])
function partial_trace(ρ::AbstractMatrix, sys_dim::AbstractVector{<:Integer}, dim_2_keep::AbstractVector{<:Integer})
size(ρ, 1) != size(ρ, 2) && throw(ArgumentError("ρ is not a square matrix."))
prod(sys_dim) != size(ρ, 1) && throw(ArgumentError("System dimensions do not multiply to density matrix dimension."))
N = length(sys_dim)
iden = CartesianIndex(ones(Int, 2*N)...)
sys_dim = reverse(sys_dim)
ρ = reshape(ρ, sys_dim..., sys_dim...)
dim_2_keep = N .+ 1 .- dim_2_keep
dim_2_trace = [i for i in 1:N if !(i in dim_2_keep)]
re_dim = copy(sys_dim)
re_dim[dim_2_trace] .= 1
tr_dim = copy(sys_dim)
tr_dim[dim_2_keep] .= 1
res = zeros(eltype(ρ), re_dim..., re_dim...)
for I in CartesianIndices(size(res))
for k in CartesianIndices((tr_dim...,))
delta = CartesianIndex(k, k)
res[I] += ρ[I + delta - iden]
end
end
reshape(res, sys_dim[dim_2_keep]..., sys_dim[dim_2_keep]...)
end
"""
$(SIGNATURES)
Calculate the indices of the degenerate values in list `w`. `w` must be sorted in ascending order.
If the `digits` keyword argument is provided, it rounds the energies to the specified number of digits after the decimal place (or before if negative), in base 10. The default value is 8.
# Examples
```julia-repl
julia> w = [1,1,1,2,3,4,4,5]
julia> find_degenerate(w)
2-element Array{Array{Int64,1},1}:
[1, 2, 3]
[6, 7]
```
"""
function find_degenerate(w; digits::Integer=8)
w = round.(w, digits = digits)
res = []
tmp = []
flag = true
for i in 2:length(w)
if w[i] == w[i-1] && flag
push!(tmp, i-1, i)
flag = false
elseif w[i] == w[i-1]
push!(tmp, i)
elseif !flag
push!(res, tmp)
tmp = []
flag = true
end
end
isempty(tmp) ? nothing : push!(res, tmp)
res
end
"""
$(SIGNATURES)
Calculate the fidelity between two density matrices `ρ` and `σ`: ``Tr[\\sqrt{\\sqrt{ρ}σ\\sqrt{ρ}}]²``.
# Examples
```julia-repl
julia> ρ = PauliVec[1][1]*PauliVec[1][1]'
julia> σ = PauliVec[3][1]*PauliVec[3][1]'
julia> fidelity(ρ, σ)
0.49999999999999944
```
"""
function fidelity(ρ, σ)
if !check_density_matrix(ρ) || !check_density_matrix(σ)
throw(ArgumentError("Inputs are not valid density matrices."))
end
temp = sqrt(ρ)
real(tr(sqrt(temp * σ * temp))^2)
end
"""
$(SIGNATURES)
Check whether matrix `ρ` is a valid density matrix. `atol` and `rtol` is the absolute and relative error tolerance to use when checking `ρ` ≈ 1.
# Examples
```julia-repl
julia> check_density_matrix(σx)
false
julia> check_density_matrix(σi/2)
true
```
"""
function check_density_matrix(ρ; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps())
ishermitian(ρ) && (eigmin(ρ) >= 0) && isapprox(tr(ρ), 1, atol=atol, rtol=rtol)
end
"""
$(SIGNATURES)
Calculate the purity of density matrix `ρ`: ``tr(ρ²)``. This function does not check whether `ρ` is a valid density matrix.
"""
function purity(ρ)
tr(ρ*ρ)
end
"""
$(SIGNATURES)
Check whether the input `ρ` is a pure state: ``tr(ρ²)≈1``. This function will first check if `ρ` is a valid density matrix. `atol` and `rtol` are the corresponding absolute and relative error tolerance used for float point number comparison. The default values are `atol = 0` and `rtol = atol>0 ? 0 : √eps`.
"""
function check_pure_state(ρ; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps())
check_density_matrix(ρ) && isapprox(purity(ρ), 1, atol=atol, rtol=rtol)
end
"""
$(SIGNATURES)
Generate a Haar random unitary matrix of dimension `(dim, dim)` using the QR decomposition method.
# Arguments
- `dim::Int`: the dimension of the matrix.
# Returns
- A Haar random unitary matrix of size `(dim, dim)`.
# Details
A Haar random unitary matrix is a matrix whose entries are complex numbers of modulus 1, chosen randomly with respect to the Haar measure on the unitary group U(dim). This implementation uses the QR decomposition method, where a complex Gaussian matrix of size `(dim, dim)` is generated, and then it is QR decomposed into the product of an orthogonal matrix and an upper triangular matrix with positive diagonal entries. The diagonal entries are then normalized by their absolute values to obtain the unitary matrix.
# Examples
```julia
julia> haar_unitary(3)
3×3 Matrix{ComplexF64}:
0.407398+0.544041im 0.799456-0.213793im -0.439273+0.396871im
-0.690274-0.288499im 0.347444+0.446328im 0.426262+0.505472im
0.437266-0.497024im -0.067918-0.582238im 0.695026+0.186022im
```
"""
function haar_unitary(dim)
M = randn(dim,dim)+im*randn(dim, dim)
q,r = qr(M)
L = diag(r)
L=L./abs.(L)
q*diagm(0=>L)
end
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 11079 | import LinearAlgebra: normalize
"""
q_translate(h::String; sp = false)
Convert a string `h` representing multi-qubits Pauli matrices summation into its numerical form. Generate sparse matrix when `sp` is set to true.
# Examples
```julia-repl
julia> q_translate("X+2.0Z")
2×2 Array{Complex{Float64},2}:
2.0+0.0im 1.0+0.0im
1.0+0.0im -2.0+0.0im
```
"""
function q_translate(h::String; sp = false)
# define operator map to replace [XYZI] with corresponding Pauli matrices
function operator_map(x)
if sp == false
σ_tag = "σ"
else
σ_tag = "spσ"
end
res = ""
for i in range(1, length = length(x) - 1)
res = res * σ_tag * lowercase(x[i]) * "⊗"
end
res = res * σ_tag * lowercase(x[end])
end
h_str = replace(h, r"[XYZI]+" => operator_map)
eval(Meta.parse(h_str))
end
"""
single_clause(ops::Vector{String}, q_ind, weight, num_qubit; sp=false)
Construct a single clause of the multi-qubits Hamiltonian. `ops` is a list of Pauli operator names which appear in this clause. `q_ind` is the list of indices corresponding to the Pauli matrices in `ops`. `weight` is the constant factor of this clause. `num_qubit` is the total number of qubits. A sparse matrix can be construct by setting `sp` to `true`. The following example construct a clause of `` Z_1 I Z_3/2 ``.
# Examples
```julia-repl
julia> single_clause(["z", "z"], [1, 3], 0.5, 3)
8×8 Array{Complex{Float64},2}:
0.5+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im -0.5+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im
0.0+0.0im 0.0+0.0im 0.5+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.5+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im -0.5+0.0im -0.0+0.0im -0.0+0.0im -0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im 0.5-0.0im -0.0+0.0im 0.0-0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im -0.5+0.0im -0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im 0.0-0.0im -0.0+0.0im 0.5-0.0im
```
"""
function single_clause(ops::Vector{String}, q_ind, weight, num_qubit; sp = false)
if sp == false
σ_tag = "σ"
i_tag = σi
else
σ_tag = "spσ"
i_tag = spσi
end
res = weight
for i = 1:num_qubit
idx = findfirst((x) -> x == i, q_ind)
if !isnothing(idx)
op2 = eval(Meta.parse(σ_tag * lowercase(ops[idx])))
res = res ⊗ op2
else
res = res ⊗ i_tag
end
end
res
end
"""
single_clause(ops::Vector{T}, q_ind, weight, num_qubit; sp=false) where T<:AbstractMatrix
Construct a single clause of the multi-qubits Hamiltonian. `ops` is a list of single-qubit operators that appear in this clause. The sparse identity matrix is used once `sp` is set to `true`. The following example construct a clause of `` Z_1 I Z_3/2 ``.
# Examples
```julia-repl
julia> single_clause([σz, σz], [1, 3], 0.5, 3)
8×8 Array{Complex{Float64},2}:
0.5+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im -0.5+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im
0.0+0.0im 0.0+0.0im 0.5+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.5+0.0im 0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im -0.5+0.0im -0.0+0.0im -0.0+0.0im -0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im 0.5-0.0im -0.0+0.0im 0.0-0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im -0.5+0.0im -0.0+0.0im
0.0+0.0im -0.0+0.0im 0.0+0.0im -0.0+0.0im -0.0+0.0im 0.0-0.0im -0.0+0.0im 0.5-0.0im
```
"""
function single_clause(ops::Vector{T}, q_ind, weight, num_qubit; sp = false) where T<:AbstractMatrix
i_tag = sp == false ? σi : spσi
res = weight
for i = 1:num_qubit
idx = findfirst((x) -> x == i, q_ind)
if !isnothing(idx)
res = res ⊗ ops[idx]
else
res = res ⊗ i_tag
end
end
res
end
"""
collective_operator(op, num_qubit; sp=false)
Construct the collective operator for a system of `num_qubit` qubits. `op` is the name of the collective Pauli matrix. For example, the following code construct an `` IZ + ZI `` matrix. Generate sparse matrix when `sp` is set to true.
# Examples
```julia-repl
julia> collective_operator("z", 2)
4×4 Array{Complex{Float64},2}:
2.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im -2.0+0.0im
```
"""
function collective_operator(op, num_qubit; sp = false)
op_name = uppercase(op)
res = ""
for idx = 1:num_qubit
res = res * "I"^(idx - 1) * op_name * "I"^(num_qubit - idx) * "+"
end
q_translate(res[1:end-1]; sp = sp)
end
"""
standard_driver(num_qubit; sp=false)
Construct the standard driver Hamiltonian for a system of `num_qubit` qubits. For example, a two qubits standard driver matrix is `` IX + XI ``. Generate sparse matrix when `sp` is set to true.
"""
function standard_driver(num_qubit; sp = false)
res = ""
for idx = 1:num_qubit
res = res * "I"^(idx - 1) * "X" * "I"^(num_qubit - idx) * "+"
end
q_translate(res[1:end-1], sp = sp)
end
"""
hamming_weight_operator(num_qubit::Int64, op::String; sp=false)
Construct the Hamming weight operator for system of size `num_qubit`. The type of the Hamming weight operator is specified by op: "x", "y" or "z". Generate sparse matrix when `sp` is set to true.
# Examples
```julia-repl
julia> hamming_weight_operator(2,"z")
4×4 Array{Complex{Float64},2}:
0.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 1.0+0.0im 0.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 1.0+0.0im 0.0+0.0im
0.0+0.0im 0.0+0.0im 0.0+0.0im 2.0+0.0im
```
"""
function hamming_weight_operator(num_qubit::Int64, op::String; sp = false)
0.5 *
(num_qubit * I - collective_operator(op, num_qubit = num_qubit, sp = sp))
end
"""
local_field_term(h, idx, num_qubit; sp=false)
Construct local Hamiltonian of the form ``∑hᵢσᵢᶻ``. `idx` is the index of all local field terms and `h` is a list of the corresponding weights. `num_qubit` is the total number of qubits. Generate sparse matrix when `sp` is set to true.
# Examples
```julia-repl
julia> local_field_term([1.0, 0.5], [1, 2], 2) == σz⊗σi+0.5σi⊗σz
true
```
"""
function local_field_term(h, idx, num_qubit; sp = false)
res = single_clause(["z"], [idx[1]], h[1], num_qubit, sp = sp)
for i = 2:length(idx)
res += single_clause(["z"], [idx[i]], h[i], num_qubit, sp = sp)
end
res
end
"""
two_local_term(j, idx, num_qubit; sp=false)
Construct local Hamiltonian of the form ``∑Jᵢⱼσᵢᶻσⱼᶻ``. `idx` is the index of all two local terms and `j` is a list of the corresponding weights. `num_qubit` is the total number of qubits. Generate sparse matrix when `sp` is set to true.
# Examples
```julia-repl
julia> two_local_term([1.0, 0.5], [[1,2], [1,3]], 3) == σz⊗σz⊗σi + 0.5σz⊗σi⊗σz
true
```
"""
function two_local_term(j, idx, num_qubit; sp = false)
res = single_clause(["z", "z"], idx[1], j[1], num_qubit, sp = sp)
for i = 2:length(idx)
res += single_clause(["z", "z"], idx[i], j[i], num_qubit, sp = sp)
end
res
end
"""
q_translate_state(h::String; normal=false)
Convert a string representation of quantum state to a vector. The keyword argument `normal` indicates whether to normalize the output vector. (Currently only '0' and '1' are supported)
# Examples
Single term:
```julia-repl
julia> q_translate_state("001")
8-element Array{Complex{Float64},1}:
0.0 + 0.0im
1.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
```
Multiple terms:
```julia-repl
julia> q_translate_state("(101)+(001)", normal=true)
8-element Array{Complex{Float64},1}:
0.0 + 0.0im
0.7071067811865475 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.7071067811865475 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
```
"""
function q_translate_state(h::String; normal = false)
# TODO: add "+", "-" into the symbol list
if occursin("(", h) || occursin(")", h)
h_str = replace(
h,
r"\(([01]+)\)" =>
(x) -> begin
res = ""
for i in range(2, length = length(x) - 3)
res =
res *
"PauliVec[3]" *
"[" *
string(parse(Int, x[i]) + 1) *
"]" *
"⊗"
end
res =
res *
"PauliVec[3]" *
"[" *
string(parse(Int, x[end-1]) + 1) *
"]"
end,
)
else
h_str = replace(
h,
r"[01]+" =>
(x) -> begin
res = ""
for i in range(1, length = length(x) - 1)
res =
res *
"PauliVec[3]" *
"[" *
string(parse(Int, x[i]) + 1) *
"]" *
"⊗"
end
res =
res *
"PauliVec[3]" *
"[" *
string(parse(Int, x[end]) + 1) *
"]"
end,
)
end
res = eval(Meta.parse(h_str))
if normal == true
normalize(res)
else
res
end
end
"""
$(SIGNATURES)
Return the creation operator truncated at `num_levels`.
# Examples
```julia-repl
julia> creation_operator(3)
3×3 LinearAlgebra.Bidiagonal{Float64, Vector{Float64}}:
0.0 ⋅ ⋅
1.0 0.0 ⋅
⋅ 1.41421 0.0
```
"""
creation_operator(num_levels::Int) = Bidiagonal(zeros(num_levels), sqrt.(1:num_levels-1), :L)
"""
$(SIGNATURES)
Return the annihilation operator truncated at `num_levels`.
# Examples
```julia-repl
julia> annihilation_operator(3)
3×3 LinearAlgebra.Bidiagonal{Float64, Vector{Float64}}:
0.0 1.0 ⋅
⋅ 0.0 1.41421
⋅ ⋅ 0.0
```
"""
annihilation_operator(num_levels::Int) = Bidiagonal(zeros(num_levels), sqrt.(1:num_levels-1), :U);
"""
$(SIGNATURES)
Return the number operator truncated at `num_levels`.
# Examples
```julia-repl
julia> number_operator(3)
3×3 LinearAlgebra.Diagonal{Int64, UnitRange{Int64}}:
0 ⋅ ⋅
⋅ 1 ⋅
⋅ ⋅ 2
```
"""
number_operator(num_levels::Int) = Diagonal(0:num_levels-1) | OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 775 | ħ = 1.054571800e-34
Planck = 6.626070040e-34
Boltzmann = 1.38064852e-23
_h = 6.62607004
_k = 1.38064852
"""
temperature_2_β(T)
Convert physical temperature `T` in mK to thermodynamic `β` in the unit of inverse angular frequency, that is to say ``β = ħ/kT``.
"""
function temperature_2_β(T)
5*_h/_k/pi/T
end
"""
temperature_2_freq(T)
Convert temperature from mK to GHz.
"""
function temperature_2_freq(T)
_k/_h/10*T
end
"""
β_2_temperature(β)
Convert thermodynamic `β` in the unit of inverse angular frequency to physical temperature `T` in GHz.
"""
function β_2_temperature(β)
5*_h/_k/pi/β
end
"""
freq_2_temperature(freq)
Convert frequency in GHz to temperature in mK.
"""
function freq_2_temperature(freq)
10 * freq * _h / _k
end
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 2094 | """
$(TYPEDEF)
`Annealing` type defines the evolution of a time-dependent Hamiltonian in both closed-system and open-system settings. It is called `Annealing` because HOQST started as a toolbox for quantum annealing.
# Fields
$(FIELDS)
"""
mutable struct Annealing{constant_hamiltonian} <: AbstractAnnealing{constant_hamiltonian}
"Hamiltonian for the annealing."
H
"Initial state for the annealing."
u0
"Function of annealing parameter s wrt to t"
annealing_parameter::Any
"A system bath interaction set."
interactions::Union{InteractionSet,Nothing}
end
Evolution = Annealing
function Annealing(
H::AbstractHamiltonian{T},
u0;
coupling=nothing,
bath=nothing,
interactions=nothing,
annealing_parameter=(tf, t) -> t / tf
) where {T}
if !isnothing(coupling) && !isnothing(bath)
if !isnothing(interactions)
throw(ArgumentError("Both interactions and coupling/bath are specified. Please merge coupling/bath into interactions."))
end
interactions = InteractionSet(Interaction(coupling, bath))
end
H = (T <: Complex) ? H : convert(Complex, H)
Annealing{isconstant(H)}(H, u0, annealing_parameter, interactions)
end
set_u0!(A::Annealing, u0) = A.u0 = u0
set_annealing_parameter!(A::Annealing, param) = A.annealing_parameter = param
"""
$(TYPEDEF)
The `ODEParams` struct represents a complete set of parameters for an Ordinary
Differential Equation (ODE), including the Liouville operator, total evolution
time, an annealing parameter function, and an object storing accepted keyword
arguments for subroutines.
# Fields
$(FIELDS)
"""
struct ODEParams
"Liouville operator"
L::Any
"Total evolution time"
tf::Real
"Function to convert physical time to annealing parameter"
annealing_parameter::Function
"Keyword arguments for subroutines"
accepted_kwargs::Any
end
# TODO: filter the keyword argument
ODEParams(L, tf::Real, annealing_param; kwargs...) =
ODEParams(L, tf, annealing_param, kwargs)
(P::ODEParams)(t::Real) = P.annealing_parameter(P.tf, t)
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 970 | Base.summary(annealing::AbstractAnnealing) = string(
TYPE_COLOR,
nameof(typeof(annealing)),
NO_COLOR,
" with ",
TYPE_COLOR,
typeof(annealing.H),
NO_COLOR,
" and u0 ",
TYPE_COLOR,
typeof(annealing.u0),
NO_COLOR,
)
function Base.show(io::IO, A::AbstractAnnealing)
println(io, summary(A))
print(io, "u0 size: ")
show(io, size(A.u0))
end
Base.summary(interaction::Interaction) = string(
TYPE_COLOR,
nameof(typeof(interaction)),
NO_COLOR,
)
function Base.show(io::IO, I::Interaction)
print(io, summary(I))
print(io, " with ")
show(io, I.coupling)
println(io)
print(io, "and bath: ")
show(io, I.bath)
end
Base.summary(interactions::InteractionSet) = string(
TYPE_COLOR,
nameof(typeof(interactions)),
NO_COLOR,
)
function Base.show(io::IO, I::InteractionSet)
print(io, summary(I))
print(io, " with ")
show(io, length(I))
print(io, " interactions")
end
| OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 3665 | """
$(TYPEDEF)
Base for types defining stochastic bath object.
"""
abstract type StochasticBath <: AbstractBath end
build_correlation(bath::AbstractBath) =
SingleFunctionMatrix((t₁, t₂) -> correlation(t₁ - t₂, bath))
build_spectrum(bath::AbstractBath) = (ω) -> spectrum(ω, bath)
"""
$(SIGNATURES)
Calculate the Lamb shift of `bath`. All the keyword arguments of `quadgk` function is supported.
"""
S(w, bath::AbstractBath; kwargs...) = lambshift(w, (ω) -> spectrum(ω, bath); kwargs...)
"""
$(SIGNATURES)
Calculate spectral density ``γ(ω)`` of `bath`.
"""
γ(ω, bath::AbstractBath) = spectrum(ω, bath)
function build_lambshift(ω_range::AbstractVector, turn_on::Bool, bath::AbstractBath, lambshift_kwargs::Dict)
if turn_on == true
if isempty(ω_range)
S_loc = (ω) -> S(ω, bath; lambshift_kwargs...)
else
s_list = [S(ω, bath; lambshift_kwargs...) for ω in ω_range]
S_loc = construct_interpolations(ω_range, s_list)
end
else
S_loc = (ω) -> 0.0
end
S_loc
end
# This function is for compatibility purpose
build_lambshift(ω_range::AbstractVector, turn_on::Bool, bath::AbstractBath, ::Nothing) = build_lambshift(ω_range, turn_on, bath, Dict())
"""
$(SIGNATURES)
Calculate the two point correlation function ``C(t1, t2)`` of `bath`. Fall back to `correlation(t1-t2, bath)` unless otherwise defined.
"""
@inline correlation(t1, t2, bath::AbstractBath) = correlation(t1 - t2, bath)
"""
$(SIGNATURES)
Calculate the bath time scale ``τ_{SB}`` from the bath correlation function `cfun`. ``τ_{SB}`` is defined as ``1/τ_{SB}=∫_0^∞ |C(τ)|dτ``. The upper limit of the integration can be modified using keyword `lim`. `atol` and `rtol` are the absolute and relative error tolerance of the integration.
"""
function τ_SB(cfun; lim=Inf, rtol=sqrt(eps()), atol=0)
res, err = quadgk((x) -> abs(cfun(x)), 0, lim, rtol=rtol, atol=atol)
1 / res, err / abs2(res)
end
"""
$(SIGNATURES)
Calculate the bath time scale ``τ_{SB}`` for the `bath` object.
"""
τ_SB(bath::AbstractBath; lim=Inf, rtol=sqrt(eps()), atol=0) =
τ_SB((t) -> correlation(t, bath), lim=lim, rtol=rtol, atol=atol)
"""
$(SIGNATURES)
Calculate the bath time scale ``τ_B`` from the correlation function `cfun`. ``τ_B`` is defined as ``τ_B/τ_{SB} = ∫_0^T τ|C(τ)|dτ``. The upper limit of the integration ``T`` is specified by `lim`. `τsb` is the other bath time scale ``1/τ_{SB}=∫_0^∞ |C(τ)|dτ``. `atol` and `rtol` are the absolute and relative error tolerance for the integration.
"""
function τ_B(cfun, lim, τsb; rtol=sqrt(eps()), atol=0)
res, err = quadgk((x) -> x * abs(cfun(x)), 0, lim, rtol=rtol, atol=atol)
res * τsb, err * τsb
end
"""
$(SIGNATURES)
Calculate the bath time scale ``τ_B`` for the `bath` object.
"""
τ_B(bath::AbstractBath, lim, τsb; rtol=sqrt(eps()), atol=0) =
τ_B((t) -> correlation(t, bath), lim, τsb; rtol=rtol, atol=atol)
function coarse_grain_timescale(cfun, lim; rtol=sqrt(eps()), atol=0)
τsb, err_sb = τ_SB(cfun, rtol=rtol, atol=atol)
τb, err_b = τ_B(cfun, lim, τsb, rtol=rtol, atol=atol)
sqrt(τsb * τb / 5), (err_sb * τb + τsb * err_b) / 10 / sqrt(τsb * τb / 5)
end
"""
$(SIGNATURES)
Calculate the optimal coarse grain time scale ``T_a=√{τ_{SB}τ_B/5}`` for a total evolution time `lim`. `atol` and `rtol` are the absolute and relative error for the integration.
"""
function coarse_grain_timescale(
bath::AbstractBath,
lim;
rtol=sqrt(eps()),
atol=0
)
τsb, err_sb = τ_SB(bath, rtol=rtol, atol=atol)
τb, err_b = τ_B(bath, lim, τsb, rtol=rtol, atol=atol)
sqrt(τsb * τb / 5), (err_sb * τb + τsb * err_b) / 10 / sqrt(τsb * τb / 5)
end | OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
|
[
"MIT"
] | 0.7.9 | fb083fe83f74926e63328d412d6d37838142c524 | code | 3135 | """
$(TYPEDEF)
An custum bath object defined by the two-point correlation function and the corresponding spectrum.
$(FIELDS)
"""
mutable struct CustomBath{lambshift} <: AbstractBath
"correlation function"
cfun::Any
"spectrum"
γ::Any
"lambshift S function"
lamb::Any
end
function CustomBath(; correlation=nothing, spectrum=nothing, lambshift=nothing)
correlation === nothing ? @warn("Correlation not specified. Certain solvers may not work for this bath object.") : nothing
spectrum === nothing ? @warn("Spectrum not specified. Certain solvers may not work for this bath object.") : nothing
lamb = lambshift === nothing ? false : true
CustomBath{lamb}(correlation, spectrum, lambshift)
end
correlation(τ, bath::CustomBath) = bath.cfun(τ)
spectrum(ω, bath::CustomBath) = bath.γ(ω)
S(w, bath::CustomBath{true}; kwargs...) = bath.lamb(w; kwargs...)
function build_correlation(bath::CustomBath)
isnothing(bath.cfun) && error("Correlation function is not specified.")
if numargs(bath.cfun) == 1
SingleFunctionMatrix((t₁, t₂) -> bath.cfun(t₁ - t₂))
else
SingleFunctionMatrix(bath.cfun)
end
end
build_spectrum(bath::CustomBath) =
isnothing(bath.γ) ? error("Noise spectrum is not specified.") : bath.γ
"""
$(TYPEDEF)
`CorrelatedBath` defines a correlated bath type by the matrices of its two-point correlation functions and corresponding spectrums.
$(FIELDS)
"""
mutable struct CorrelatedBath <: AbstractBath
"correlation function"
cfun::Any
"spectrum"
γ::Any
"bath correlator idx"
inds::Any
end
CorrelatedBath(inds; correlation=nothing, spectrum=nothing) = CorrelatedBath(correlation, spectrum, inds)
build_correlation(bath::CorrelatedBath) = isnothing(bath.cfun) ? throw(ArgumentError("Correlation function is not specified.")) : bath.cfun
build_spectrum(bath::CorrelatedBath) = isnothing(bath.γ) ? error("Spectrum is not specified.") : bath.γ
build_inds(bath::CorrelatedBath) = bath.inds
function build_lambshift(ω_range::AbstractVector, turn_on::Bool, bath::CorrelatedBath, lambshift_kwargs::Dict)
gamma = build_spectrum(bath)
l = size(gamma)
if turn_on == true
if isempty(ω_range)
S_loc = Array{Function,2}(undef, l)
for i in eachindex(gamma)
S_loc[i] = (w) -> lambshift(w, gamma[i]; lambshift_kwargs...)
end
else
S_loc = Array{Any,2}(undef, l)
for i in eachindex(gamma)
s_list = [lambshift(ω, gamma[i]; lambshift_kwargs...) for ω in ω_range]
S_loc[i] = construct_interpolations(ω_range, s_list)
end
end
else
S_loc = Array{Function,2}(undef, size(gamma))
S_loc .= (ω) -> 0.0
end
S_loc
end
"""
$(TYPEDEF)
A bath object to hold jump correlator of ULE.
$(FIELDS)
"""
struct ULEBath <: AbstractBath
"correlation function"
cfun::Any
end
function build_jump_correlation(bath::ULEBath)
if numargs(bath.cfun) == 1
SingleFunctionMatrix((t₁, t₂) -> bath.cfun(t₁ - t₂))
else
SingleFunctionMatrix(bath.cfun)
end
end | OpenQuantumBase | https://github.com/USCqserver/OpenQuantumBase.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.