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.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4231 | using FluxReconstruction, KitBase, Plots, OrdinaryDiffEq, LinearAlgebra
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = TriFRPSpace("../assets/square.msh", 2)
γ = 5 / 3
u0 = zeros(size(ps.cellid, 1), ps.np, 4)
for i in axes(u0, 1), j in axes(u0, 2)
prim = [
max(exp(-300 * ((ps.xpg[i, j, 1] - 0.5)^2 + (ps.xpg[i, j, 2] - 0.5)^2)), 1e-2),
0.0,
0.0,
1.0,
]
#prim = [1.0, 0.0, 0.0, 1.0]
u0[i, j, :] .= prim_conserve(prim, γ)
end
function dudt!(du, u, p, t)
J, lf, cell_normal, fpn, ∂l, ϕ, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
deg = size(fpn, 3) - 1
f = zeros(ncell, nsp, 4, 2)
for i in axes(f, 1)
for j in axes(f, 2)
fg, gg = euler_flux(u[i, j, :], γ)
for k in axes(f, 3)
f[i, j, k, :] .= inv(J[i]) * [fg[k], gg[k]]
end
end
end
u_face = zeros(ncell, 3, deg + 1, 4)
f_face = zeros(ncell, 3, deg + 1, 4, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
u_face[i, j, k, l] = sum(u[i, :, l] .* lf[j, k, :])
f_face[i, j, k, l, 1] = sum(f[i, :, l, 1] .* lf[j, k, :])
f_face[i, j, k, l, 2] = sum(f[i, :, l, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
fn_face[i, j, k, l] = dot(f_face[i, j, k, l, :], n[j])
end
fn_interaction = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
ni, nj, nk = fpn[i, j, k]
fwn_local = zeros(4)
if ni > 0
uR = local_frame(
u_face[ni, nj, nk, :],
cell_normal[i, j, 1],
cell_normal[i, j, 2],
)
flux_hll!(fwn_local, uL, uR, γ, 1.0)
end
fwn_global = global_frame(fwn_local, cell_normal[i, j, 1], cell_normal[i, j, 2])
fwn_xy = zeros(4, 2)
for idx = 1:4
fwn_xy[idx, :] .= fwn_global[idx] .* cell_normal[i, j, :]
end
fws_rs = zeros(4, 2)
for idx = 1:4
fws_rs[idx, :] .= inv(J[i]) * fwn_xy[idx, :]
end
fwns = [sum(fws_rs[idx, :] .* n[j]) for idx = 1:4]
#fwns = [sum(fws_rs[idx, :]) for idx in 1:4]
fn_interaction[i, j, k, :] .= fwns
end
#=
for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
ni, nj, nk = fpn[i, j, k]
fwn_local = zeros(4)
if ni > 0
uR = local_frame(u_face[ni, nj, nk, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
flux_hll!(fwn_local, uL, uR, γ, 1.0)
end
fwn_global = global_frame(fwn_local, cell_normal[i, j, 1], cell_normal[i, j, 2])
fn_interaction[i, j, k, :] .= fwn_global ./ det(J[i])
end
=#
rhs1 = zeros(ncell, nsp, 4)
for i in axes(rhs1, 1), j in axes(rhs1, 2), k = 1:4
if ps.cellType[i] == 0
rhs1[i, j, k] =
-sum(f[i, :, k, 1] .* ∂l[j, :, 1]) - sum(f[i, :, k, 2] .* ∂l[j, :, 2])
end
end
rhs2 = zero(rhs1)
for i = 1:ncell
if ps.cellType[i] == 0
for j = 1:nsp, k = 1:4
rhs2[i, j, k] =
-sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k]) .* ϕ[:, :, j])
end
end
end
for i = 1:ncell
if ps.cellType[i] == 0
du[i, :, :] .= rhs1[i, :, :] .+ rhs2[i, :, :]
end
end
return nothing
end
tspan = (0.0, 0.1)
p = (ps.J, ps.lf, ps.cellNormals, ps.fpn, ps.∂l, ps.ϕ, γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.002
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:20
step!(itg)
end
begin
prim = zero(itg.u)
for i in axes(prim, 1), j in axes(prim, 2)
prim[i, j, :] .= conserve_prim(itg.u[i, j, :], γ)
prim[i, j, 4] = 1 / prim[i, j, 4]
end
write_vtk(ps.points, ps.cellid, prim[:, 2, :])
end
du = zero(u0)
dudt!(du, u0, p, 1.0)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4589 | using FluxReconstruction, KitBase, Plots, OrdinaryDiffEq, LinearAlgebra
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
cd(@__DIR__)
ps = TriFRPSpace("../assets/naca0012.msh", 2)
ps0 = deepcopy(ps)
for i in eachindex(ps.cellType)
if ps.cellType[i] != 0 && norm(ps.cellCenter[i, :]) > 2
ps.cellType[i] = 2
end
end
γ = 5 / 3
mach = 0.5
angle = (3 / 180) * π
u0 = zeros(size(ps.cellid, 1), ps.np, 4)
for i in axes(u0, 1), j in axes(u0, 2)
c = mach * (γ / 2)^0.5
if true#ps.cellType[i] == 2
prim = [1.0, c * cos(angle), c * sin(angle), 1.0]
else
prim = [1.0, 0.0, 0.0, 1.0]
end
u0[i, j, :] .= prim_conserve(prim, γ)
end
function dudt!(du, u, p, t)
J, lf, cell_normal, fpn, ∂l, ϕ, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
deg = size(fpn, 3) - 1
f = zeros(ncell, nsp, 4, 2)
@inbounds @threads for i in axes(f, 1)
for j in axes(f, 2)
fg, gg = euler_flux(u[i, j, :], γ)
for k in axes(f, 3)
f[i, j, k, :] .= inv(J[i]) * [fg[k], gg[k]]
end
end
end
u_face = zeros(ncell, 3, deg + 1, 4)
f_face = zeros(ncell, 3, deg + 1, 4, 2)
@inbounds @threads for i = 1:ncell
for j = 1:3, k = 1:deg+1, l = 1:4
u_face[i, j, k, l] = sum(u[i, :, l] .* lf[j, k, :])
f_face[i, j, k, l, 1] = sum(f[i, :, l, 1] .* lf[j, k, :])
f_face[i, j, k, l, 2] = sum(f[i, :, l, 2] .* lf[j, k, :])
end
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1, 4)
@inbounds @threads for i = 1:ncell
for j = 1:3, k = 1:deg+1, l = 1:4
fn_face[i, j, k, l] = dot(f_face[i, j, k, l, :], n[j])
end
end
fn_interaction = zeros(ncell, 3, deg + 1, 4)
@inbounds for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
ni, nj, nk = fpn[i, j, k]
fwn_local = zeros(4)
if ni > 0
uR = local_frame(
u_face[ni, nj, nk, :],
cell_normal[i, j, 1],
cell_normal[i, j, 2],
)
flux_hll!(fwn_local, uL, uR, γ, 1.0)
elseif ps.cellType[i] == 1
prim = conserve_prim(u_face[i, j, k, :], γ)
pn = zeros(4)
pn[2] = -prim[2]
pn[3] = -prim[3]
pn[4] = 2.0 - prim[4]
tmp = (prim[4] - 1.0)
pn[1] = (1 - tmp) / (1 + tmp) * prim[1]
un = prim_conserve(pn, γ)
uR = local_frame(un, cell_normal[i, j, 1], cell_normal[i, j, 2])
flux_hll!(fwn_local, uL, uR, γ, 1.0)
end
fwn_global = global_frame(fwn_local, cell_normal[i, j, 1], cell_normal[i, j, 2])
fwn_xy = zeros(4, 2)
for idx = 1:4
fwn_xy[idx, :] .= fwn_global[idx] .* cell_normal[i, j, :]
end
fws_rs = zeros(4, 2)
for idx = 1:4
fws_rs[idx, :] .= inv(J[i]) * fwn_xy[idx, :]
end
fwns = [sum(fws_rs[idx, :] .* n[j]) for idx = 1:4]
#fwns = [sum(fws_rs[idx, :]) for idx in 1:4]
fn_interaction[i, j, k, :] .= fwns
end
rhs1 = zeros(ncell, nsp, 4)
@inbounds for i in axes(rhs1, 1)
for j in axes(rhs1, 2), k = 1:4
if ps.cellType[i] in [0, 1]
rhs1[i, j, k] =
-sum(f[i, :, k, 1] .* ∂l[j, :, 1]) - sum(f[i, :, k, 2] .* ∂l[j, :, 2])
end
end
end
rhs2 = zero(rhs1)
@inbounds for i = 1:ncell
if ps.cellType[i] in [0, 1]
for j = 1:nsp, k = 1:4
rhs2[i, j, k] =
-sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k]) .* ϕ[:, :, j])
end
end
end
@inbounds for i = 1:ncell
if ps.cellType[i] in [0, 1]
du[i, :, :] .= rhs1[i, :, :] .+ rhs2[i, :, :]
end
end
return nothing
end
tspan = (0.0, 0.1)
p = (ps.J, ps.lf, ps.cellNormals, ps.fpn, ps.∂l, ps.ϕ, γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.0005
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
function output(ps, itg)
prim = zero(itg.u)
for i in axes(prim, 1), j in axes(prim, 2)
prim[i, j, :] .= conserve_prim(itg.u[i, j, :], γ)
prim[i, j, 4] = 1 / prim[i, j, 4]
end
write_vtk(ps.points, ps.cellid, prim[:, 2, :])
end
@showprogress for iter = 1:500
step!(itg)
if iter % 50 == 0
output(ps, itg)
end
end
output(ps, itg)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2803 | using FluxRC, KitBase, Plots, OrdinaryDiffEq, LinearAlgebra
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = UnstructPSpace("square.msh")
ncell = size(ps.cellid, 1)
nface = size(ps.faceType, 1)
ax = -1.0
ay = -1.0
u = zeros(size(ps.cellid, 1))
for i in axes(u, 1)
u[i] = max(
exp(-300 * ((ps.cellCenter[i, 1] - 0.5)^2 + (ps.cellCenter[i, 2] - 0.5)^2)),
1e-4,
)
end
u0 = deepcopy(u)
cell_normal = zeros(ncell, 3, 2)
for i = 1:ncell
pids = ps.cellid[i, :]
cell_normal[i, 1, :] .= unit_normal(ps.points[pids[1], :], ps.points[pids[2], :])
cell_normal[i, 2, :] .= unit_normal(ps.points[pids[2], :], ps.points[pids[3], :])
cell_normal[i, 3, :] .= unit_normal(ps.points[pids[3], :], ps.points[pids[1], :])
p =
[
ps.points[pids[1], :] .+ ps.points[pids[2], :],
ps.points[pids[2], :] .+ ps.points[pids[3], :],
ps.points[pids[3], :] .+ ps.points[pids[1], :],
] / 2
for j = 1:3
if dot(cell_normal[i, j, :], p[j][1:2] - ps.cellCenter[i, 1:2]) < 0
cell_normal[i, j, :] .= -cell_normal[i, j, :]
end
end
end
cell_length = zeros(ncell, 3)
for i = 1:ncell
pids = ps.cellid[i, :]
cids = ps.cellNeighbors[i, :]
for j = 1:3
if cids[j] > 0
nodes = intersect(pids, ps.cellid[cids[j], :])
cell_length[i, j] = norm(ps.points[nodes[1], 1:2] - ps.points[nodes[2], 1:2])
end
end
end
function flux_ad(fL, fR, uL, uR)
au = @. (fL - fR) / (uL - uR + 1e-6)
return @. 0.5 * (fL + fR) #- 0.5 * abs(au) * (uL - uR) # 这个有问题
end
function dudt!(du, u, p, t)
ps, ax, ay = p
du .= 0.0
f = zeros(ncell, 2)
for i in axes(f, 1)
if ps.cellType[i] == 0
f[i, :] .= [ax * u[i], ay * u[i]]
u1 = u[ps.cellNeighbors[i, 1]]
u2 = u[ps.cellNeighbors[i, 2]]
u3 = u[ps.cellNeighbors[i, 3]]
f1 = [ax * u1, ay * u1]
f2 = [ax * u2, ay * u2]
f3 = [ax * u3, ay * u3]
fa1 = flux_ad(f[i, :], f1, u[i], u1)
fa2 = flux_ad(f[i, :], f2, u[i], u2)
fa3 = flux_ad(f[i, :], f3, u[i], u3)
du[i] = -(
dot(fa1, cell_normal[i, 1, :]) * cell_length[i, 1] +
dot(fa2, cell_normal[i, 2, :]) * cell_length[i, 2] +
dot(fa3, cell_normal[i, 3, :]) * cell_length[i, 3]
)
du[i] /= ps.cellArea[i]
end
end
return nothing
end
du = zero(u)
p = (ps, ax, ay)
dudt!(du, u, p, 0.0)
tspan = (0.0, 1.0)
#p = ()
prob = ODEProblem(dudt!, u, tspan, p)
dt = 0.01
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:10
step!(itg)
end
write_vtk(ps.points, ps.cellid, itg.u)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 7726 | using FluxRC, KitBase, Plots, OrdinaryDiffEq, LinearAlgebra
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = UnstructPSpace("../assets/square.msh")
N = deg = 2
Np = (N + 1) * (N + 2) ÷ 2
ncell = size(ps.cellid, 1)
nface = size(ps.faceType, 1)
J = rs_jacobi(ps.cellid, ps.points)
spg = global_sp(ps.points, ps.cellid, N)
fpg = global_fp(ps.points, ps.cellid, N)
pl, wl = tri_quadrature(N)
V = vandermonde_matrix(N, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, pl[:, 1], pl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
ϕ = correction_field(N, V)
pf, wf = triface_quadrature(N)
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
lf = zeros(3, N + 1, Np)
for i = 1:3, j = 1:N+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
γ = 5 / 3
u0 = zeros(size(ps.cellid, 1), Np, 4)
for i in axes(u0, 1), j in axes(u0, 2)
prim = [
max(exp(-300 * ((spg[i, j, 1] - 0.5)^2 + (spg[i, j, 2] - 0.5)^2)), 1e-3),
0.0,
0.0,
1.0,
]
#prim = [1., 0., 0., 1.]
u0[i, j, :] .= prim_conserve(prim, γ)
end
cell_normal = zeros(ncell, 3, 2)
for i = 1:ncell
pids = ps.cellid[i, :]
cell_normal[i, 1, :] .= unit_normal(ps.points[pids[1], :], ps.points[pids[2], :])
cell_normal[i, 2, :] .= unit_normal(ps.points[pids[2], :], ps.points[pids[3], :])
cell_normal[i, 3, :] .= unit_normal(ps.points[pids[3], :], ps.points[pids[1], :])
p =
[
ps.points[pids[1], :] .+ ps.points[pids[2], :],
ps.points[pids[2], :] .+ ps.points[pids[3], :],
ps.points[pids[3], :] .+ ps.points[pids[1], :],
] / 2
for j = 1:3
if dot(cell_normal[i, j, :], p[j][1:2] - ps.cellCenter[i, 1:2]) < 0
cell_normal[i, j, :] .= -cell_normal[i, j, :]
end
end
end
function dudt!(du, u, p, t)
du .= 0.0
deg, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
f = zeros(ncell, nsp, 4, 2)
for i in axes(f, 1)
for j in axes(f, 2)
fg, gg = euler_flux(u[i, j, :], γ)
for k in axes(f, 3)
f[i, j, k, :] .= inv(J[i]) * [fg[k], gg[k]]
end
end
end
u_face = zeros(ncell, 3, deg + 1, 4)
f_face = zeros(ncell, 3, deg + 1, 4, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
u_face[i, j, k, l] = sum(u[i, :, l] .* lf[j, k, :])
f_face[i, j, k, l, 1] = sum(f[i, :, l, 1] .* lf[j, k, :])
f_face[i, j, k, l, 2] = sum(f[i, :, l, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
fn_face[i, j, k, l] = dot(f_face[i, j, k, l, :], n[j])
end
fn_interaction = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
fwn_local = zeros(4)
if ni > 0
uR = local_frame(
u_face[ni, nj, nk, :],
cell_normal[i, j, 1],
cell_normal[i, j, 2],
)
flux_hll!(fwn_local, uL, uR, γ, 1.0)
end
fwn_global = global_frame(fwn_local, cell_normal[i, j, 1], cell_normal[i, j, 2])
fwn_xy = zeros(4, 2)
for idx = 1:4
fwn_xy[idx, :] .= fwn_global[idx] .* cell_normal[i, j, :]
end
fws_rs = zeros(4, 2)
for idx = 1:4
fws_rs[idx, :] .= inv(J[i]) * fwn_xy[idx, :]
end
fwns = [sum(fws_rs[idx, :] .* n[j]) for idx = 1:4]
#fwns = [sum(fws_rs[idx, :]) for idx in 1:4]
fn_interaction[i, j, k, :] .= fwns
end
#=
for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], 1., 0.)
uD = local_frame(u_face[i, j, k, :], 0., 1.)
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
fw1_local = zeros(4)
fw2_local = zeros(4)
if ni > 0
uR = local_frame(u_face[ni, nj, nk, :], 1., 0.)
uU = local_frame(u_face[ni, nj, nk, :], 0., 1.)
flux_hll!(fw1_local, uL, uR, γ, 1.0)
flux_hll!(fw2_local, uD, uU, γ, 1.0)
end
fw1_global = global_frame(fw1_local, 1., 0.)
fw2_global = global_frame(fw2_local, 0., 1.)
fw_xy = hcat(fw1_global, fw2_global)
fw_rs = zeros(4, 2)
for idx in 1:4
fw_rs[idx, :] .= inv(J[i]) * fw_xy[idx, :]
end
fwns = [sum(fw_rs[idx, :] .* n[j]) for idx in 1:4]
#fwns = [sum(fws_rs[idx, :]) for idx in 1:4]
fn_interaction[i, j, k, :] .= fwns
end=#
#=
for i = 1:ncell, j = 1:3, k = 1:deg+1
fw1 = zeros(4)
fw2 = zeros(4)
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
if ni > 0
flux_roe!(fw1, u_face[i, j, k, :], u_face[ni, nj, nk, :], γ, 1., [1., 0.])
flux_roe!(fw2, u_face[i, j, k, :], u_face[ni, nj, nk, :], γ, 1., [0., 1.])
end
fi = zeros(4, 2)
for id in 1:4
fi[id, :] .= inv(J[i]) * [fw1[id], fw2[id]]
end
for l = 1:4
fn_interaction[i, j, k, l] = sum(fi[l, :] .* n[j])
end
end=#
#=
for i = 1:ncell, j = 1:3, k = 1:deg+1
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
if ni > 0
fR = f_face[ni, nj, nk, :, :]
fRg = zeros(4, 2)
for id = 1:4
fRg[id, :] .= J[ni] * f_face[ni, nj, nk, id, :]
end
fRl = zeros(4, 2)
for id = 1:4
fRl[id, :] .= inv(J[i]) * fRg[id, :]
end
_f0 = (f_face[i, j, k, :, :] + fRl) ./ 2
_f1 = -det(J[i]) * 0.5 .* (u_face[i, j, k, :] + u_face[ni, nj, nk, :]) .* (ps.cellArea[i]^0.5 / 2) ./ dt
_f = hcat(_f0[:, 1] + _f1, _f0[:, 2] + _f1)
fn_interaction[i, j, k, :] .= [sum(_f[id, :] .* n[j]) for id = 1:4]
end
end=#
rhs1 = zeros(ncell, nsp, 4)
for i in axes(rhs1, 1), j in axes(rhs1, 2), k = 1:4
if ps.cellType[i] == 0
rhs1[i, j, k] =
-sum(f[i, :, k, 1] .* ∂l[j, :, 1]) - sum(f[i, :, k, 2] .* ∂l[j, :, 2])
end
end
rhs2 = zero(rhs1)
for i = 1:ncell
if ps.cellType[i] == 0
for j = 1:nsp, k = 1:4
rhs2[i, j, k] =
-sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k]) .* ϕ[:, :, j])
#rhs2[i, j, k] = - sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k])) / 3
end
end
end
for i = 1:ncell
if ps.cellType[i] == 0
du[i, :, :] .= rhs1[i, :, :] .+ rhs2[i, :, :]
#du[i, :, :] .= rhs2[i, :, :]
end
end
return nothing
end
tspan = (0.0, 0.1)
p = (N, 5 / 3)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.002
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:20
step!(itg)
end
begin
prim = zero(itg.u)
for i in axes(prim, 1), j in axes(prim, 2)
prim[i, j, :] .= conserve_prim(itg.u[i, j, :], γ)
prim[i, j, 4] = 1 / prim[i, j, 4]
end
write_vtk(ps.points, ps.cellid, prim[:, 2, :])
end
du = zero(u0)
f1, f2 = dudt!(du, u0, p, 1.0)
idx = 1211
f1[idx, 2, 2, :]
f2[idx, 2, 2, :]
fw = zeros(4)
flux_roe!(fw, [1.0, 0.0, 0.0, 1.0], []fw::X, wL::Y, wR::Y, γ, dt, n = [1.0, 0.0])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 5846 | using FluxRC, KitBase, Plots
cd(@__DIR__)
ps = UnstructPSpace("square.msh")
N = 2
Np = (N + 1) * (N + 2) ÷ 2
pl, wl = tri_quadrature(N)
pf, wf = triface_quadrature(N)
spg = zeros(size(ps.cellid, 1), Np, 2)
for i in axes(spg, 1), j in axes(spg, 2)
id1, id2, id3 = ps.cellid[i, :]
spg[i, j, :] .=
rs_xy(pl[j, :], ps.points[id1, 1:2], ps.points[id2, 1:2], ps.points[id3, 1:2])
end
nface = size(ps.faceType, 1)
fpg = zeros(size(ps.faceType, 1), N + 1, 2)
for i in axes(fpg, 1), j in axes(fpg, 2)
idc = ifelse(ps.faceCells[i, 1] != -1, ps.faceCells[i, 1], ps.faceCells[i, 2])
id1, id2, id3 = ps.cellid[idc, :]
if !(id3 in ps.facePoints[i, :])
idf = 1
elseif !(id1 in ps.facePoints[i, :])
idf = 2
elseif !(id2 in ps.facePoints[i, :])
idf = 3
end
fpg[i, j, :] .=
rs_xy(pf[idf, j, :], ps.points[id1, 1:2], ps.points[id2, 1:2], ps.points[id3, 1:2])
end
a = 1.0
u = zeros(size(ps.cellid, 1), Np)
for i in axes(u, 1), j in axes(u, 2)
u[i, j] = exp(-300 * ((spg[i, j, 1] - 0.5)^2 + (spg[i, j, 2] - 0.5)^2))
end
f = zeros(size(ps.cellid, 1), Np, 2)
for i in axes(f, 1)
xr, yr = ps.points[ps.cellid[i, 2], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
xs, ys = ps.points[ps.cellid[i, 3], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
J = xr * ys - xs * yr
for j in axes(f, 2)
fg = a * u[i, j]
gg = a * u[i, j]
f[i, j, :] .= [ys * fg - xs * gg, -yr * fg + xr * gg] ./ J
end
end
V = vandermonde_matrix(N, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, pl[:, 1], pl[:, 2])
∂l = zeros(Np, Np, 2)
for i = 1:Np
∂l[i, :, 1] .= V' \ Vr[i, :]
∂l[i, :, 2] .= V' \ Vs[i, :]
end
du = zeros(size(ps.cellid, 1), Np)
for i in axes(du, 1), j in axes(du, 2)
du[i, j] = -sum(f[i, :, 1] .* ∂l[j, :, 1]) - sum(f[i, :, 2] .* ∂l[j, :, 2])
end
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
lf = zeros(3, N + 1, Np)
for i = 1:3, j = 1:N+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
# correction field
ϕ = zeros(3, N + 1, Np)
σ = zeros(3, N + 1, Np)
for k = 1:Np
for j = 1:N+1
for i = 1:3
σ[i, j, k] = wf[i, j] * ψf[i, j, k]
end
end
end
for f = 1:3, j = 1:N+1, i = 1:Np
ϕ[f, j, i] = sum(σ[f, j, :] .* V[i, :])
end
function dudt!(du, u, p, t)
du .= 0.0
a, deg, nface = p
ncell = size(u, 1)
nsp = size(u, 2)
f = zeros(ncell, nsp, 2)
for i in axes(f, 1)
xr, yr = ps.points[ps.cellid[i, 2], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
xs, ys = ps.points[ps.cellid[i, 3], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
J = xr * ys - xs * yr
for j in axes(f, 2)
fg = a * u[i, j]
gg = a * u[i, j]
f[i, j, :] .= [ys * fg - xs * gg, -yr * fg + xr * gg] ./ J
end
end
u_face = zeros(ncell, 3, deg + 1)
f_face = zeros(ncell, 3, deg + 1, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1
u_face[i, j, k] = sum(u[i, :] .* lf[j, k, :])
f_face[i, j, k, 1] = sum(f[i, :, 1] .* lf[j, k, :])
f_face[i, j, k, 2] = sum(f[i, :, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1)
for i = 1:ncell, j = 1:3, k = 1:deg+1
fn_face[i, j, k] = sum(f_face[i, j, k, :] .* n[j])
end
au = zeros(nface, deg + 1, 2)
f_interaction = zeros(nface, deg + 1, 2)
for i = 1:nface
c1, c2 = ps.faceCells[i, :]
if -1 in (c1, c2)
continue
end
pids = ps.facePoints[i, :]
if ps.cellid[c1, 1] ∉ pids
fid1 = 2
elseif ps.cellid[c1, 2] ∉ pids
fid1 = 3
elseif ps.cellid[c1, 3] ∉ pids
fid1 = 1
end
if ps.cellid[c2, 1] ∉ pids
fid2 = 2
elseif ps.cellid[c2, 2] ∉ pids
fid2 = 3
elseif ps.cellid[c2, 3] ∉ pids
fid2 = 1
end
for j = 1:deg+1, k = 1:2
au[i, j, k] =
(f_face[c1, fid1, j, k] - f_face[c2, fid2, j, k]) /
(u_face[c1, fid1, j] - u_face[c2, fid2, j] + 1e-6)
f_interaction[i, j, k] =
0.5 * (f_face[c1, fid1, j, k] + f_face[c2, fid2, j, k]) -
0.5 * abs(au[i, j, k]) * (u_face[c1, fid1, j] - u_face[c2, fid2, j])
end
end
fn_interaction = zeros(ncell, 3, deg + 1)
for i = 1:ncell
for j = 1:3, k = 1:deg+1
fn_interaction[i, j, k] = sum(f_interaction[ps.cellFaces[i, j], k, :] .* n[j])
end
end
rhs1 = zeros(ncell, nsp)
for i in axes(rhs1, 1), j in axes(rhs1, 2)
rhs1[i, j] = -sum(f[i, :, 1] .* ∂l[j, :, 1]) - sum(f[i, :, 2] .* ∂l[j, :, 2])
end
for i = 1:ncell
if ps.cellType[i] != 1
for j = 1:nsp
du[i, j] =
rhs1[i, j] -
sum(fn_interaction[i, :, :] .- fn_face[i, :, :] .* ϕ[:, :, j])
end
end
end
end
du = zero(u)
dudt!(du, u, (a, N, nface), 0.0)
setdiff([1, 2], [2])
ps.cellFaces[1, :]
ps.cellid[1, :]
ps.facePoints[3, :]
u[idx, :] .* lf[1, 2, :] |> sum
u[idx, :] .* lf[2, 2, :] |> sum
u[idx, :] .* lf[3, 2, :] |> sum
u[idx, :] .* ∂l[1, :, 2] |> sum
u[idx, :] .* ∂l[2, :, 2] |> sum
u[idx, :] .* ∂l[3, :, 2] |> sum
u[idx, :] .* ∂l[4, :, 2] |> sum
u[idx, :] .* ∂l[5, :, 2] |> sum
u[idx, :] .* ∂l[6, :, 2] |> sum
spg[idx, :, :]
u[idx, 4]
u[idx, 6]
idx = 468
id1, id2, id3 = ps.cellFaces[idx, :]
scatter(spg[idx, :, 1], spg[idx, :, 2], legend = :none)
scatter!(fpg[id1, :, 1], fpg[id1, :, 2])
scatter!(fpg[id2, :, 1], fpg[id2, :, 2])
scatter!(fpg[id3, :, 1], fpg[id3, :, 2])
write_vtk(ps.points, ps.cellid, u[:, 1])
scatter(spg[1:10, :, 1], spg[1:10, :, 2], legend = :none, ratio = 1 / 3)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4982 | using FluxRC, KitBase, Plots, OrdinaryDiffEq
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = KitBase.UnstructPSpace("../assets/linesource.msh")
begin
# quadrature
quadratureorder = 8
points, weights = KitBase.legendre_quadrature(quadratureorder)
#points, triangulation = KitBase.octa_quadrature(quadratureorder)
#weights = KitBase.quadrature_weights(points, triangulation)
nq = size(points, 1)
vs = KitBase.UnstructVSpace(-1.0, 1.0, nq, points, weights)
# IC
s2 = 0.03^2
init_field(x, y) = max(1e-4, 1.0 / (4.0 * π * s2) * exp(-(x^2 + y^2) / 4.0 / s2))
# particle
SigmaS = ones(size(ps.cellid, 1))
SigmaA = zeros(size(ps.cellid, 1))
SigmaT = SigmaS + SigmaA
# time
tspan = (0.0, 0.3)
cfl = 0.7
end
N = deg = 2
Np = (N + 1) * (N + 2) ÷ 2
ncell = size(ps.cellid, 1)
nface = size(ps.faceType, 1)
J = rs_jacobi(ps.cellid, ps.points)
spg = global_sp(ps.points, ps.cellid, N)
fpg = global_fp(ps.points, ps.cellid, N)
pl, wl = tri_quadrature(N)
V = vandermonde_matrix(N, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, pl[:, 1], pl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
ϕ = correction_field(N, V)
pf, wf = triface_quadrature(N)
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
lf = zeros(3, N + 1, Np)
for i = 1:3, j = 1:N+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
u = zeros(size(ps.cellid, 1), Np, nq)
for i in axes(u, 1), j in axes(u, 2)
u[i, j, :] .= init_field(spg[i, j, 1], spg[i, j, 2])
end
cell_normal = zeros(ncell, 3, 2)
for i = 1:ncell
pids = ps.cellid[i, :]
cell_normal[i, 1, :] .= unit_normal(ps.points[pids[1], :], ps.points[pids[2], :])
cell_normal[i, 2, :] .= unit_normal(ps.points[pids[2], :], ps.points[pids[3], :])
cell_normal[i, 3, :] .= unit_normal(ps.points[pids[3], :], ps.points[pids[1], :])
p =
[
ps.points[pids[1], :] .+ ps.points[pids[2], :],
ps.points[pids[2], :] .+ ps.points[pids[3], :],
ps.points[pids[3], :] .+ ps.points[pids[1], :],
] / 2
for j = 1:3
if dot(cell_normal[i, j, :], p[j][1:2] - ps.cellCenter[i, 1:2]) < 0
cell_normal[i, j, :] .= -cell_normal[i, j, :]
end
end
end
δu = heaviside.(vs.u[:, 1])
δv = heaviside.(vs.u[:, 2])
function dudt!(du, u, p, t)
du .= 0.0
deg = p
ncell = size(u, 1)
nsp = size(u, 2)
nq = size(u, 3)
f = zeros(ncell, nsp, nq, 2)
for i in axes(f, 1)
for j in axes(f, 2), k in axes(f, 3)
fg = vs.u[k, 1] * u[i, j, k]
gg = vs.u[k, 2] * u[i, j, k]
f[i, j, k, :] .= inv(J[i]) * [fg, gg]
end
end
u_face = zeros(ncell, 3, deg + 1, nq)
f_face = zeros(ncell, 3, deg + 1, nq, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:nq
u_face[i, j, k, l] = sum(u[i, :, l] .* lf[j, k, :])
f_face[i, j, k, l, 1] = sum(f[i, :, l, 1] .* lf[j, k, :])
f_face[i, j, k, l, 2] = sum(f[i, :, l, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1, nq)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:nq
fn_face[i, j, k, l] = sum(f_face[i, j, k, l, :] .* n[j])
end
fn_interaction = zeros(ncell, 3, deg + 1, nq)
for i = 1:ncell
for j = 1:3, k = 1:deg+1
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
if ni > 0
for l = 1:nq
uL = u_face[i, j, k, l]
uR = u_face[ni, nj, nk, l]
fx = vs.u[l, 1] * (uL * δu[l] + uR * (1.0 - δu[l]))
fy = vs.u[l, 2] * (uL * δv[l] + uR * (1.0 - δv[l]))
_f = inv(J[i]) * [fx, fy]
fn_interaction[i, j, k, l] = _f .* n[j] |> sum
end
else
fn_interaction[i, j, k, :] .= 0.0
end
end
end
rhs1 = zeros(ncell, nsp, nq)
for i in axes(rhs1, 1), j in axes(rhs1, 2), k = 1:nq
rhs1[i, j, nq] =
-sum(f[i, :, nq, 1] .* ∂l[j, :, 1]) - sum(f[i, :, nq, 2] .* ∂l[j, :, 2])
end
rhs2 = zero(rhs1)
for i = 1:ncell, k = 1:nq
if ps.cellType[i] != 1
for j = 1:nsp
rhs2[i, j, k] =
-sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k]) .* ϕ[:, :, j])
end
end
end
#du .= rhs1 .+ rhs2
for i = 1:ncell
if ps.cellType[i] == 0
du[i, :, :] .= rhs1[i, :, :] .+ rhs2[i, :, :]
end
end
return nothing
end
tspan = (0.0, 1.0)
p = N
prob = ODEProblem(dudt!, u, tspan, p)
dt = 0.01
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:10
step!(itg)
end
sol = zeros(ncell)
for i in eachindex(sol)
sol[i] = (vs.weights .* itg.u[i, 2, :]) |> sum
end
write_vtk(ps.points, ps.cellid, sol)
du = zero(u)
dudt!(du, u, p, 0.0)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 374 | using OrdinaryDiffEq
u0 = 1 / 2
tspan = (0.0, 1.0)
f1(u, p, t) = u^1.01
f2(u, p, t) = 1.01 * u
prob = SplitODEProblem(f1, f2, u0, tspan)
sol = solve(prob, IMEXEuler(), dt = 0.01, reltol = 1e-8, abstol = 1e-8)
f(u, p, t) = 1.01 * u + u^1.01
prob1 = ODEProblem(f, u0, tspan)
sol1 = solve(prob1, RadauIIA3(), reltol = 1e-8, abstol = 1e-8)
using Plots
plot(sol)
plot!(sol1)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 7067 | """
2D traveling wave solution for the Euler equations in a parallelogram domain
--------
/ /
/ /
/ /
--------
δx = 1, δy = 0.5, θ = π / 4
Instability is somehow detected for order larger than 2.
"""
using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
cd(@__DIR__)
pyplot()
set = Setup(
case = "dev",
space = "2d0f",
flux = "hll",
collision = "nothing",
interpOrder = 2,
limiter = "positivity",
boundary = "euler",
cfl = 0.1,
maxTime = 1.0,
)
begin
lx, ly = 1.0, 0.5
x0 = 0.0
x1 = x0 + lx
nx = 30
Δx = lx / nx
y0 = 0.0
y1 = y0 + ly
ny = 15
Δy = ly / ny
vertices = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, 2)
for j in axes(vertices, 2), i in axes(vertices, 1)
vertices[i, j, 1, 1] = x0 + 0.5 * (j - 1) / ny + (i - 1) * Δx
vertices[i, j, 2, 1] = vertices[i, j, 1, 1] + Δx
vertices[i, j, 3, 1] = vertices[i, j, 2, 1] + Δy
vertices[i, j, 4, 1] = vertices[i, j, 3, 1] - Δx
vertices[i, j, 1, 2] = y0 + 0.5 * (j - 1) * Δy
vertices[i, j, 2, 2] = vertices[i, j, 1, 2]
vertices[i, j, 3, 2] = vertices[i, j, 1, 2] + Δy
vertices[i, j, 4, 2] = vertices[i, j, 3, 2]
end
x = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1)
y = similar(x)
dx = similar(x)
dy = similar(y)
for i = 0:nx+1, j = 0:ny+1
x[i, j] = (vertices[i, j, 1, 1] + vertices[i, j, 4, 1]) / 2 + Δx / 2
y[i, j] = vertices[i, j, 1, 2] + 0.5 * Δy
dx[i, j] = Δx
dy[i, j] = Δy
end
ps0 = PSpace2D(x0, x1, nx, y0, y1, ny, x, y, dx, dy, vertices)
deg = set.interpOrder - 1
ps = FRPSpace2D(ps0, deg)
end
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 0.0, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
function dudt!(du, u, p, t)
iJ, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1) - 2
ny = size(u, 2) - 2
nsp = size(u, 3)
f = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, nsp, nsp, 4, 2)
@inbounds @threads for i in axes(f, 1)
for j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= iJ[i, j][k, l] * [fg[m], gg[m]]
end
end
end
u_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4, 2)
@inbounds @threads for i in axes(u_face, 1)
for j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
@inbounds @threads for i = 1:nx+1
for j = 1:ny, k = 1:nsp
fw = @view fx_interaction[i, j, k, :]
uL = local_frame(u_face[i-1, j, 2, k, :], n1[i, j][1], n1[i, j][2])
uR = local_frame(u_face[i, j, 4, k, :], n1[i, j][1], n1[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n1[i, j][1], n1[i, j][2])
end
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny+1, k = 1:nsp
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], n2[i, j][1], n2[i, j][2])
uR = local_frame(u_face[i, j, 1, k, :], n2[i, j][1], n2[i, j][2])
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, n2[i, j][1], n2[i, j][2])
end
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
end
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
fxL = (iJ[i, j][k, l]*n1[i, j])[1] * fx_interaction[i, j, l, m]
fxR = (iJ[i, j][k, l]*n1[i+1, j])[1] * fx_interaction[i+1, j, l, m]
fyL = (iJ[i, j][k, l]*n2[i, j])[2] * fy_interaction[i, j, l, m]
fyR = (iJ[i, j][k, l]*n2[i, j+1])[2] * fy_interaction[i, j+1, l, m]
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fxL - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fxR - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fyL - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fyR - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
end
return nothing
end
begin
u0 = OffsetArray{Float64}(undef, 0:ps.nx+1, 0:ps.ny+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
ρ = 1.0 + 0.1 * sin(2π * i / ps.nx)
prim = [ρ, 1.0, 0.0, ρ]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
n1 = [[0.0, 0.0] for i = 1:ps.nx+1, j = 1:ps.ny]
for i = 1:ps.nx+1, j = 1:ps.ny
angle = -π / 4
n1[i, j] .= [cos(angle), sin(angle)]
end
n2 = [[0.0, 0.0] for i = 1:ps.nx, j = 1:ps.ny+1]
for i = 1:ps.nx, j = 1:ps.ny+1
n2[i, j] .= [0.0, 1.0]
end
end
tspan = (0.0, 1.0)
p = (ps.iJ, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.001
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
sol0 = zeros(ps.nx, ps.ny, 4)
for i = 1:ps.nx, j = 1:ps.ny
sol0[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
sol0[i, j, 4] = 1 / sol0[i, j, 4]
end
@showprogress for iter = 1:nt÷2
# bcs
itg.u[0, :, :, :, :] .= itg.u[ps.nx, :, :, :, :]
itg.u[ps.nx+1, :, :, :, :] .= itg.u[1, :, :, :, :]
itg.u[:, 0, :, :, :] .= itg.u[:, ps.ny, :, :, :]
itg.u[:, ps.ny+1, :, :, :] .= itg.u[:, 1, :, :, :]
step!(itg)
end
begin
sol = zeros(ps.nx, ps.ny, 4)
for i = 1:ps.nx, j = 1:ps.ny
sol[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
idx = 1
plot(ps.x[1:ps.nx, 1], sol0[1:ps.nx, 10, idx])
plot!(ps.x[1:ps.nx, 1], sol[1:ps.nx, 10, idx])
end
contourf(ps.x[1:ps.nx, 1:ps.ny], ps.y[1:ps.nx, 1:ps.ny], sol[1:ps.nx, 1:ps.ny, 4])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2907 | """
2D traveling wave solution for the Euler equations in a parallelogram domain
--------
/ /
/ /
/ /
--------
δx = 1, δy = 0.5, θ = π / 4
"""
using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
cd(@__DIR__)
pyplot()
set = Setup(
case = "dev",
space = "2d0f0v",
flux = "hll",
collision = "nothing",
interpOrder = 3,
limiter = "positivity",
boundary = "euler",
cfl = 0.1,
maxTime = 1.0,
)
begin
lx, ly = 1.0, 0.5
x0 = 0.0
x1 = x0 + lx
nx = 100
Δx = lx / nx
y0 = 0.0
y1 = y0 + ly
ny = 50
Δy = ly / ny
vertices = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, 2)
for j in axes(vertices, 2), i in axes(vertices, 1)
vertices[i, j, 1, 1] = x0 + 0.5 * (j - 1) / ny + (i - 1) * Δx
vertices[i, j, 2, 1] = vertices[i, j, 1, 1] + Δx
vertices[i, j, 3, 1] = vertices[i, j, 2, 1] + Δy
vertices[i, j, 4, 1] = vertices[i, j, 3, 1] - Δx
vertices[i, j, 1, 2] = y0 + 0.5 * (j - 1) * Δy
vertices[i, j, 2, 2] = vertices[i, j, 1, 2]
vertices[i, j, 3, 2] = vertices[i, j, 1, 2] + Δy
vertices[i, j, 4, 2] = vertices[i, j, 3, 2]
end
x = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1)
y = similar(x)
dx = similar(x)
dy = similar(y)
for i = 0:nx+1, j = 0:ny+1
x[i, j] = (vertices[i, j, 1, 1] + vertices[i, j, 4, 1]) / 2 + Δx / 2
y[i, j] = vertices[i, j, 1, 2] + 0.5 * Δy
dx[i, j] = Δx
dy[i, j] = Δy
end
ps = PSpace2D(x0, x1, nx, y0, y1, ny, x, y, dx, dy, vertices)
end
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 0.0, K = 1.0)
fw = function (x...)
zeros(4)
end
ib = IB(fw, gas)
ks = SolverSet(set, ps, vs, gas, ib)
ctr, a1face, a2face = init_fvm(ks)
for i in axes(ctr, 1), j in axes(ctr, 2)
ρ = 1.0 + 0.1 * sin(2π * i / ps.nx)
ctr[i, j].prim .= [ρ, 1.0, 0.0, ρ]
ctr[i, j].w .= prim_conserve(ctr[i, j].prim, ks.gas.γ)
end
function get_solution(ks, ctr)
sol = zeros(ks.ps.nx, ks.ps.ny, 4)
for i = 1:ks.ps.nx, j = 1:ks.ps.ny
sol[i, j, :] .= conserve_prim(ctr[i, j].w, ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
return sol
end
sol0 = get_solution(ks, ctr)
tspan = (0.0, 1.0)
dt = 0.001
nt = tspan[2] ÷ dt |> Int
t = 0.0
@showprogress for iter = 1:nt÷2
evolve!(
ks,
ctr,
a1face,
a2face,
dt;
mode = :hll,
bc = [:period, :period, :extra, :extra],
)
update!(ks, ctr, a1face, a2face, dt, zeros(4); bc = [:period, :period, :extra, :extra])
t += dt
end
sol = get_solution(ks, ctr)
begin
idx = 4
plot(ps.x[1:ps.nx, 1], sol0[1:ps.nx, 1, 1])
plot!(ps.x[1:ps.nx, 1], sol[1:ps.nx, 1, 1])
end
contourf(ps.x[1:ps.nx, 1:ps.ny], ps.y[1:ps.nx, 1:ps.ny], sol[1:ps.nx, 1:ps.ny, 2])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1710 | using PyCall
py"""
import numpy
def get_phifj_solution_grad_tri(order, P1, Np, Nflux, elem_nfaces, V, Vf):
correction_coeffs = numpy.zeros( shape=(Np, elem_nfaces*P1) )
phifj_solution_r = numpy.zeros( shape=(Np, Nflux) )
phifj_solution_s = numpy.zeros( shape=(Np, Nflux) )
tmp = 1./numpy.sqrt(2)
nhat = numpy.zeros(shape=(Nflux,2))
nhat[0:P1, 0] = 0.0
nhat[0:P1, 1] = -1.0
nhat[P1:2*P1, :] = tmp
nhat[2*P1:, 0] = -1
nhat[2*P1:, 1] = 0.0
#wgauss, rgauss = get_gauss_nodes(order)
rgauss, wgauss = numpy.polynomial.legendre.leggauss(order+1)
for m in range(Np):
for face in range(3):
modal_basis_along_face = Vf[ face*P1:(face+1)*P1, m ]
correction_coeffs[m, face*P1:(face+1)*P1] = modal_basis_along_face*wgauss
# correct the coefficients for face 2 with the Hypotenuse length
correction_coeffs[:, P1:2*P1] *= numpy.sqrt(2)
# Multiply the correction coefficients with the Dubiner basis
# functions evaluated at the solution and flux points to get the
# correction functions
phifj_solution = V.dot(correction_coeffs)
# multiply each row of the correction function with the
# transformed element normals. These matrices will be used to
# compute the gradients and flux divergence
for m in range(Np):
phifj_solution_r[m, :] = phifj_solution[m, :] * nhat[:, 0]
phifj_solution_s[m, :] = phifj_solution[m, :] * nhat[:, 1]
# stack the matrices
phifj_grad = numpy.zeros( shape=(3*Np, Nflux) )
phifj_grad[:Np, :] = phifj_solution_r[:, :]
phifj_grad[Np:2*Np, :] = phifj_solution_s[:, :]
return correction_coeffs, phifj_solution, phifj_grad
"""
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 3421 | using FluxReconstruction, OrdinaryDiffEq, Plots, LinearAlgebra, KitBase
using KitBase.ProgressMeter: @showprogress
ps0 = KitBase.PSpace2D(0.0, 1.0, 20, 0.0, 1.0, 20)
deg = 2
ps = FRPSpace2D(ps0, deg)
a = [0.1, 0.1]
u0 = zeros(ps.nx, ps.ny, deg + 1, deg + 1)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
u0[i, j, k, l] = max(
exp(-300 * ((ps.xpg[i, j, k, l, 1] - 0.5)^2 + (ps.xpg[i, j, k, l, 2] - 0.5)^2)),
1e-2,
)
end
function dudt!(du, u, p, t)
J, ll, lr, dhl, dhr, lpdm, ax, ay = p
nx = size(u, 1)
ny = size(u, 2)
nsp = size(u, 3)
f = zeros(nx, ny, nsp, nsp, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = ax * u[i, j, k, l], ay * u[i, j, k, l]
f[i, j, k, l, :] .= inv(J[i, j][k, l]) * [fg, gg]
end
u_face = zeros(nx, ny, 4, nsp)
f_face = zeros(nx, ny, 4, nsp, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp
u_face[i, j, 1, l] = dot(u[i, j, l, :], ll)
u_face[i, j, 2, l] = dot(u[i, j, :, l], lr)
u_face[i, j, 3, l] = dot(u[i, j, l, :], lr)
u_face[i, j, 4, l] = dot(u[i, j, :, l], ll)
for m = 1:2
f_face[i, j, 1, l, m] = dot(f[i, j, l, :, m], ll)
f_face[i, j, 2, l, m] = dot(f[i, j, :, l, m], lr)
f_face[i, j, 3, l, m] = dot(f[i, j, l, :, m], lr)
f_face[i, j, 4, l, m] = dot(f[i, j, :, l, m], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp)
for i = 2:nx, j = 1:ny, k = 1:nsp
au =
(f_face[i, j, 4, k, 1] - f_face[i-1, j, 2, k, 1]) /
(u_face[i, j, 4, k] - u_face[i-1, j, 2, k] + 1e-6)
fx_interaction[i, j, k] = (
0.5 * (f_face[i, j, 4, k, 1] + f_face[i-1, j, 2, k, 1]) -
0.5 * abs(au) * (u_face[i, j, 4, k] - u_face[i-1, j, 2, k])
)
end
fy_interaction = zeros(nx, ny + 1, nsp)
for i = 1:nx, j = 2:ny, k = 1:nsp
au =
(f_face[i, j, 1, k, 2] - f_face[i, j-1, 3, k, 2]) /
(u_face[i, j, 1, k] - u_face[i, j-1, 3, k] + 1e-6)
fy_interaction[i, j, k] = (
0.5 * (f_face[i, j, 1, k, 2] + f_face[i, j-1, 3, k, 2]) -
0.5 * abs(au) * (u_face[i, j, 1, k] - u_face[i, j-1, 3, k])
)
end
rhs1 = zeros(nx, ny, nsp, nsp)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp
rhs1[i, j, k, l] = dot(f[i, j, :, l, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp
rhs2[i, j, k, l] = dot(f[i, j, k, :, 2], lpdm[l, :])
end
for i = 2:nx-1, j = 2:ny-1, k = 1:nsp, l = 1:nsp
du[i, j, k, l] = -(
rhs1[i, j, k, l] +
rhs2[i, j, k, l] +
(fx_interaction[i, j, l] - f_face[i, j, 4, l, 1]) * dhl[k] +
(fx_interaction[i+1, j, l] - f_face[i, j, 2, l, 1]) * dhr[k] +
(fy_interaction[i, j, k] - f_face[i, j, 1, k, 2]) * dhl[l] +
(fy_interaction[i, j+1, k] - f_face[i, j, 3, k, 2]) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, a[1], a[2])
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.01
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:nt
step!(itg)
end
contourf(ps.x[:, 1], ps.y[1, :], itg.u[:, :, 2, 2])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4804 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using ProgressMeter: @showprogress
begin
set = Setup(
"gas",
"cylinder",
"2d0f",
"hll",
"nothing",
1, # species
3, # order of accuracy
"positivity", # limiter
"euler",
0.1, # cfl
1.0, # time
)
ps0 = KitBase.PSpace2D(0.0, 1.0, 20, 0.0, 1.0, 20)
deg = set.interpOrder - 1
ps = FRPSpace2D(ps0, deg)
vs = nothing
gas = Gas(
1e-6,
2.0, # Mach
1.0,
1.0, # K
5 / 3,
0.81,
1.0,
0.5,
)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
u0 = zeros(ps.nx, ps.ny, deg + 1, deg + 1)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
u0[i, j, k, l] = max(
exp(-300 * ((ps.xpg[i, j, k, l, 1] - 0.5)^2 + (ps.xpg[i, j, k, l, 2] - 0.5)^2)),
1e-2,
)
end
u0 = zeros(ps.nx, ps.ny, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
ρ = max(
exp(-300 * ((ps.xpg[i, j, k, l, 1] - 0.5)^2 + (ps.xpg[i, j, k, l, 2] - 0.5)^2)),
1e-2,
)
prim = [ρ, 0.0, 0.0, 1.0]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
function dudt!(du, u, p, t)
du .= 0.0
J, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1) - 2
ny = size(u, 2) - 2
nsp = size(u, 3)
f = zeros(nx, ny, nsp, nsp, 4, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= inv(J[i, j][k, l]) * [fg[m], gg[m]]
end
end
u_face = zeros(nx, ny, 4, nsp, 4)
f_face = zeros(nx, ny, 4, nsp, 4, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
for i = 2:nx, j = 1:ny, k = 1:nsp
fw = @view fx_interaction[i, j, k, :]
uL = @view u_face[i-1, j, 2, k, :]
uR = @view u_face[i, j, 4, k, :]
flux_hll!(fw, uL, uR, γ, 1.0)
fw .*= 40
#fx_interaction[i, j, k, :] .=
# 0.5 .* (f_face[i-1, j, 2, k, :, 1] .+ f_face[i, j, 4, k, :, 1]) .-
# ps.dx[i, j] .* (u_face[i, j, 4, k, :] - u_face[i-1, j, 2, k, :])
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
for i = 1:nx, j = 2:ny, k = 1:nsp
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], 0.0, 1.0)
uR = local_frame(u_face[i, j, 1, k, :], 0.0, 1.0)
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, 0.0, 1.0) .* 40
#fy_interaction[i, j, k, :] .=
# 0.5 .* (f_face[i, j-1, 3, k, :, 2] .+ f_face[i, j, 1, k, :, 2]) .-
# ps.dy[i, j] .* (u_face[i, j, 1, k, :] - u_face[i, j-1, 3, k, :])
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
for i = 2:nx-1, j = 2:ny-1, k = 1:nsp, l = 1:nsp, m = 1:4
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(fx_interaction[i, j, l, m] - f_face[i, j, 4, l, m, 1]) * dhl[k] +
(fx_interaction[i+1, j, l, m] - f_face[i, j, 2, l, m, 1]) * dhr[k] +
(fy_interaction[i, j, k, m] - f_face[i, j, 1, k, m, 2]) * dhl[l] +
(fy_interaction[i, j+1, k, m] - f_face[i, j, 3, k, m, 2]) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 1.0)
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.005
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:10
step!(itg)
end
sol = zeros(ps.nx, ps.ny, 4)
for i = 1:ps.nx, j = 1:ps.ny
sol[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
sol[i, j, 4] = 1 / sol[i, j, 4]
end
contourf(ps.x, ps.y, sol[:, :, 1], aspect_ratio = 1, legend = true)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4042 | using FluxRC, KitBase, Plots, LinearAlgebra
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = TriFRPSpace("../assets/sod.msh", 2)
eids = (419, 418, 420, 423)
for i in eachindex(ps.cellType)
if i ∉ eids
if ps.cellType[i] == 1
if ps.cellCenter[i, 2] < 0.014 || ps.cellCenter[i, 2] > 0.0835
ps.cellType[i] = 2
end
end
end
end
γ = 5 / 3
u0 = zeros(size(ps.cellid, 1), ps.np, 4)
for i in axes(u0, 1), j in axes(u0, 2)
#if ps.xpg[i, j, 1] < 0.5
if ps.cellCenter[i, 1] < 0.5
prim = [1.0, 0.0, 0.0, 0.5]
else
prim = [0.3, 0.0, 0.0, 0.625]
end
u0[i, j, :] .= prim_conserve(prim, γ)
end
function dudt!(du, u, p, t)
cellType, J, lf, cell_normal, fpn, ∂l, ϕ, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
deg = size(fpn, 3) - 1
f = zeros(ncell, nsp, 4, 2)
for i in axes(f, 1)
for j in axes(f, 2)
fg, gg = euler_flux(u[i, j, :], γ)
for k in axes(f, 3)
f[i, j, k, :] .= inv(J[i]) * [fg[k], gg[k]]
end
end
end
u_face = zeros(ncell, 3, deg + 1, 4)
f_face = zeros(ncell, 3, deg + 1, 4, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
u_face[i, j, k, l] = sum(u[i, :, l] .* lf[j, k, :])
f_face[i, j, k, l, 1] = sum(f[i, :, l, 1] .* lf[j, k, :])
f_face[i, j, k, l, 2] = sum(f[i, :, l, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1, l = 1:4
fn_face[i, j, k, l] = dot(f_face[i, j, k, l, :], n[j])
end
fn_interaction = zeros(ncell, 3, deg + 1, 4)
for i = 1:ncell, j = 1:3, k = 1:deg+1
uL = local_frame(u_face[i, j, k, :], cell_normal[i, j, 1], cell_normal[i, j, 2])
ni, nj, nk = fpn[i, j, k]
fwn_local = zeros(4)
if ni > 0
uR = local_frame(
u_face[ni, nj, nk, :],
cell_normal[i, j, 1],
cell_normal[i, j, 2],
)
flux_hll!(fwn_local, uL, uR, γ, 1.0)
elseif cellType[i] == 2
_uR = u_face[i, j, k, :]
_uR[3] = -_uR[3]
uR = local_frame(_uR, cell_normal[i, j, 1], cell_normal[i, j, 2])
flux_hll!(fwn_local, uL, uR, γ, 1.0)
end
fwn_global = global_frame(fwn_local, cell_normal[i, j, 1], cell_normal[i, j, 2])
fwn_xy = zeros(4, 2)
for idx = 1:4
fwn_xy[idx, :] .= fwn_global[idx] .* cell_normal[i, j, :]
end
fws_rs = zeros(4, 2)
for idx = 1:4
fws_rs[idx, :] .= inv(J[i]) * fwn_xy[idx, :]
end
fwns = [sum(fws_rs[idx, :] .* n[j]) for idx = 1:4]
#fwns = [sum(fws_rs[idx, :]) for idx in 1:4]
fn_interaction[i, j, k, :] .= fwns
end
rhs1 = zeros(ncell, nsp, 4)
for i in axes(rhs1, 1), j in axes(rhs1, 2), k = 1:4
rhs1[i, j, k] =
-sum(f[i, :, k, 1] .* ∂l[j, :, 1]) - sum(f[i, :, k, 2] .* ∂l[j, :, 2])
end
rhs2 = zero(rhs1)
for i = 1:ncell
if ps.cellType[i] ∈ [0, 2]
for j = 1:nsp, k = 1:4
rhs2[i, j, k] =
-sum((fn_interaction[i, :, :, k] .- fn_face[i, :, :, k]) .* ϕ[:, :, j])
end
end
end
for i = 1:ncell
if ps.cellType[i] ∈ [0, 2]
du[i, :, :] .= rhs1[i, :, :] .+ rhs2[i, :, :]
end
end
return nothing
end
tspan = (0.0, 0.1)
p = (ps.cellType, ps.J, ps.lf, ps.cellNormals, ps.fpn, ps.∂l, ps.ϕ, γ)
prob = ODEProblem(dudt!, u0, tspan, p)
dt = 0.0005
nt = tspan[end] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:nt
step!(itg)
end
begin
prim = zero(itg.u)
for i in axes(prim, 1), j in axes(prim, 2)
prim[i, j, :] .= conserve_prim(itg.u[i, j, :], γ)
prim[i, j, 4] = 1 / prim[i, j, 4]
end
write_vtk(ps.points, ps.cellid, prim[:, 2, :])
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2079 | using Plots, FluxRC
using FastGaussQuadrature
"""
N polynomial degree -> Np solution points
"""
N = 2
Np = (N + 1) * (N + 2) ÷ 2
points, weights = tri_quadrature(N)
scatter(points[:, 1], points[:, 2], ratio = 1)
"""
Vandermonde matrix bridges Lagrange polynomials and modal polynomials
Vᵀℓ(r) = P(r)
"""
V = vandermonde_matrix(N, points[:, 1], points[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, points[:, 1], points[:, 2]) # (r_i, ψ_j)
# Lagrange polynomials
∂l = zeros(Np, Np, 2)
for i = 1:Np
∂l[i, :, 1] .= V' \ Vr[i, :]
∂l[i, :, 2] .= V' \ Vs[i, :]
end
# test solution (derivatives at solution point)
u = [3.0, 2.0, 3.0, 2.0, 1.0, 2.0]
uhat = V \ u
uhat .* Vr[1, :] |> sum
u .* ∂l[1, :, 1] |> sum
uhat .* Vs[1, :] |> sum
u .* ∂l[1, :, 2] |> sum
# interface interpolation
function triface_quadrature(N)
Δf = [1.0, √2, 1.0]
pf = Array{Float64}(undef, 3, N + 1, 2)
wf = Array{Float64}(undef, 3, N + 1)
p0, w0 = gausslegendre(N + 1)
pf[1, :, 1] .= p0
pf[2, :, 1] .= p0
pf[3, :, 1] .= -1.0
pf[1, :, 2] .= -1.0
pf[2, :, 2] .= -p0
pf[3, :, 2] .= p0
wf[1, :] .= w0 .* Δf[1]
wf[2, :] .= w0 .* Δf[2]
wf[3, :] .= w0 .* Δf[3]
return pf, wf
end
pf, wf = triface_quadrature(N)
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
∂ψf = zeros(3, N + 1, Np, 2)
for i = 1:3
∂ψf[i, :, :, 1], ∂ψf[i, :, :, 2] = ∂vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
lf = zeros(3, N + 1, Np)
for i = 1:3, j = 1:N+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
u .* lf[2, 2, :] |> sum
uhat .* ψf[2, 2, :] |> sum
∂lf = zeros(3, N + 1, Np, 2)
for i = 1:3, j = 1:N+1, k = 1:2
∂lf[i, j, :, k] .= V' \ ∂ψf[i, j, :, k]
end
uhat .* ∂ψf[1, 2, :, 1] |> sum
u .* ∂lf[1, 2, :, 1] |> sum
# correction field
ϕ = zeros(3, N + 1)
σ = zeros(3, N + 1, Np)
for k = 1:Np
for j = 1:N+1
for i = 1:3
σ[i, j, k] = wf[i, j] * ψf[i, j, k] * Δf[i]
end
end
end
for j = 1:N+1
for i = 1:3
ϕ[i, j] = sum(σ[i, j, :] .* ψf[i, j, :])
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1158 | using KitBase
using KitBase.Plots
using KitBase.SpecialFunctions
using FluxRC
cd(@__DIR__)
ps = UnstructFRPSpace("naca0012.msh", 3)
scatter(ps.rs[:, 1], ps.rs[:, 2], ratio = 1)
i = 6;
scatter(ps.xp[i, :, 1], ps.xp[i, :, 2], ratio = 1);
using PyCall
const itp = pyimport("scipy.interpolate")
const np = pyimport("numpy")
# Lagrange interpolation: hand-written vs. scipy
## value
xGauss = legendre_point(2)
yGauss = exp.(xGauss)
ll = lagrange_point(xGauss, -1.0)
yGauss .* ll |> sum
poly = itp.lagrange(xGauss, yGauss)
np.polyval(poly, -1.0)
## derivative
lpdm = ∂lagrange(xGauss)
yGauss[1] * lpdm[1, 1] + yGauss[2] * lpdm[1, 2] + yGauss[3] * lpdm[1, 3]
p1 = np.polyder(poly, 1)
np.polyval(p1, xGauss[1])
# 2D Lagrange interpolation
x = legendre_point(2)
y = [-0.9, -0.45, 0.0, 0.45, 0.9]
lx = lagrange_point(x, 0.77)
ly = lagrange_point(y, 0.9)
coords = cat(meshgrid(x, y)[1] |> permutedims, meshgrid(x, y)[2] |> permutedims, dims = 3)
val = exp.(coords[:, :, 1] + coords[:, :, 2] .^ 2)
v = 0.0
for i in axes(weights, 1), j in axes(weights, 2)
v += val[i, j] * lx[i] * ly[j]
end
lagrange_point([0, 0.5, 0.5, 1], 0.77)
legendre_point(2) .- -1
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 3935 | using FluxRC, KitBase, Plots, OrdinaryDiffEq
using ProgressMeter: @showprogress
cd(@__DIR__)
ps = UnstructPSpace("../assets/square.msh")
N = deg = 2
Np = (N + 1) * (N + 2) ÷ 2
ncell = size(ps.cellid, 1)
nface = size(ps.faceType, 1)
J = rs_jacobi(ps.cellid, ps.points)
spg = global_sp(ps.points, ps.cellid, N)
fpg = global_fp(ps.points, ps.cellid, N)
pl, wl = tri_quadrature(N)
V = vandermonde_matrix(N, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(N, pl[:, 1], pl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
ϕ = correction_field(N, V)
pf, wf = triface_quadrature(N)
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(N, pf[i, :, 1], pf[i, :, 2])
end
lf = zeros(3, N + 1, Np)
for i = 1:3, j = 1:N+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
a = -1.0
u = zeros(size(ps.cellid, 1), Np)
for i in axes(u, 1), j in axes(u, 2)
u[i, j] = max(exp(-100 * ((spg[i, j, 1] - 0.5)^2 + (spg[i, j, 2] - 0.5)^2)), 1e-4)
end
function dudt!(du, u, p, t)
du .= 0.0
a, deg, nface = p
ncell = size(u, 1)
nsp = size(u, 2)
f = zeros(ncell, nsp, 2)
for i in axes(f, 1)
for j in axes(f, 2)
fg = a * u[i, j]
gg = a * u[i, j]
f[i, j, :] .= inv(J[i]) * [fg, gg]
end
end
u_face = zeros(ncell, 3, deg + 1)
f_face = zeros(ncell, 3, deg + 1, 2)
for i = 1:ncell, j = 1:3, k = 1:deg+1
u_face[i, j, k] = sum(u[i, :] .* lf[j, k, :])
f_face[i, j, k, 1] = sum(f[i, :, 1] .* lf[j, k, :])
f_face[i, j, k, 2] = sum(f[i, :, 2] .* lf[j, k, :])
end
n = [[0.0, -1.0], [1 / √2, 1 / √2], [-1.0, 0.0]]
fn_face = zeros(ncell, 3, deg + 1)
for i = 1:ncell, j = 1:3, k = 1:deg+1
fn_face[i, j, k] = sum(f_face[i, j, k, :] .* n[j])
end
f_interaction = zeros(ncell, 3, deg + 1, 2)
au = zeros(2)
for i = 1:ncell, j = 1:3, k = 1:deg+1
fL = J[i] * f_face[i, j, k, :]
ni, nj, nk = neighbor_fpidx([i, j, k], ps, fpg)
fR = zeros(2)
if ni > 0
fR .= J[ni] * f_face[ni, nj, nk, :]
@. au = (fL - fR) / (u_face[i, j, k] - u_face[ni, nj, nk] + 1e-6)
@. f_interaction[i, j, k, :] =
0.5 * (fL + fR) - 0.5 * abs(au) * (u_face[i, j, k] - u_face[ni, nj, nk])
else
@. f_interaction[i, j, k, :] = 0.0
end
f_interaction[i, j, k, :] .= inv(J[i]) * f_interaction[i, j, k, :]
end
fn_interaction = zeros(ncell, 3, deg + 1)
for i = 1:ncell
for j = 1:3, k = 1:deg+1
fn_interaction[i, j, k] = sum(f_interaction[i, j, k, :] .* n[j])
end
end
rhs1 = zeros(ncell, nsp)
for i in axes(rhs1, 1), j in axes(rhs1, 2)
rhs1[i, j] = -sum(f[i, :, 1] .* ∂l[j, :, 1]) - sum(f[i, :, 2] .* ∂l[j, :, 2])
end
rhs2 = zero(rhs1)
for i = 1:ncell
xr, yr = ps.points[ps.cellid[i, 2], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
xs, ys = ps.points[ps.cellid[i, 3], 1:2] - ps.points[ps.cellid[i, 1], 1:2]
_J = xr * ys - xs * yr
if ps.cellType[i] != 1
for j = 1:nsp
#rhs2[i, j] = - sum((fn_interaction[i, :, :] .- fn_face[i, :, :]) .* ϕ[:, :, j]) / _J
rhs2[i, j] =
-sum((fn_interaction[i, :, :] .- fn_face[i, :, :]) .* ϕ[:, :, j])
#rhs2[i, j] = - sum((fn_interaction[i, :, :] .- fn_face[i, :, :]))
end
end
end
for i = 1:ncell
if ps.cellType[i] == 0
du[i, :] .= rhs1[i, :] .+ rhs2[i, :]
end
end
return nothing
end
tspan = (0.0, 1.0)
p = (a, N, nface)
prob = ODEProblem(dudt!, u, tspan, p)
#sol = solve(prob, Midpoint(), reltol=1e-8, abstol=1e-8, progress=true)
dt = 0.01
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:10
step!(itg)
end
write_vtk(ps.points, ps.cellid, itg.u[:, 2])
du = zero(u)
dudt!(du, u, p, 1.0)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 832 | using KitBase, FluxReconstruction, OrdinaryDiffEq, CUDA, LinearAlgebra, Plots
begin
x0 = -1.0f0
x1 = 1.0f0
ncell = 100
dx = (x1 - x0) / ncell
deg = 2
nsp = deg + 1
cfl = 0.1
dt = cfl * dx
t = 0.0f0
a = 1.0f0
tspan = (0.0f0, 1.0f0)
nt = tspan[2] / dt |> floor |> Int
bc = :period
end
ps = FRPSpace1D(x0, x1, ncell, deg)
u = zeros(Float32, ncell, nsp)
for i = 1:ncell, ppp1 = 1:deg+1
u[i, ppp1] = exp(-20.0 * ps.xpg[i, ppp1]^2)
end
u = u |> CuArray
prob = FR.FRAdvectionProblem(u, tspan, ps, a, bc)
itg = init(prob, Midpoint(), saveat = tspan[2], adaptive = false, dt = dt)
for iter = 1:nt
step!(itg)
end
ut = CUDA.@allowscalar itg.u[:, 2] |> Array
plot(ps.xpg[:, 2], ut, label = "t=2")
plot!(ps.xpg[:, 2], exp.(-20 .* ps.xpg[:, 2] .^ 2), label = "t=0", line = :dash)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1128 | using KitBase, FluxReconstruction, OrdinaryDiffEq, LinearAlgebra, Plots
begin
x0 = -1
x1 = 1
ncell = 16
dx = (x1 - x0) / ncell
deg = 3
nsp = deg + 1
cfl = 0.1
dt = cfl * dx
t = 0.0
a = 1.0
tspan = (0.0, 2.0)
nt = tspan[2] / dt |> Int
bc = :period
end
ps = FRPSpace1D(x0, x1, ncell, deg)
u = zeros(ncell, deg + 1)
for i = 1:ncell, j = 1:deg+1
u[i, j] = sin(π * ps.xpg[i, j])
end
prob = FR.FRAdvectionProblem(u, tspan, ps, a, bc)
itg = init(prob, Tsit5(), saveat = tspan[2], adaptive = false, dt = dt)
for iter = 1:nt
step!(itg)
end
begin
x = zeros(ncell * nsp)
sol = zeros(ncell * nsp)
for i = 1:ncell
idx0 = (i - 1) * nsp
idx = idx0+1:idx0+nsp
for j = 1:nsp
idx = idx0 + j
x[idx] = ps.xpg[i, j]
sol[idx] = itg.u[i, j]
end
end
ref = @. sin(π * x)
end
plot(x, sol, label = "t=1")
plot!(x, ref, line = :dash, label = "t=0")
begin
dx |> println
FR.L1_error(sol, ref, dx) |> println
FR.L2_error(sol, ref, dx) |> println
FR.L∞_error(sol, ref, dx) |> println
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4011 | using KitBase, FluxRC, OrdinaryDiffEq, Plots
using Logging: global_logger
using TerminalLoggers: TerminalLogger
global_logger(TerminalLogger())
begin
x0 = -1
x1 = 1
nx = 100
nface = nx + 1
dx = (x1 - x0) / nx
deg = 2 # polynomial degree
nsp = deg + 1
u0 = -5
u1 = 5
nu = 28
cfl = 0.1
dt = cfl * dx
t = 0.0
a = 1.0
end
pspace = FluxRC.FRPSpace1D(x0, x1, nx, deg)
vspace = VSpace1D(u0, u1, nu)
δ = heaviside.(vspace.u)
begin
xFace = collect(x0:dx:x1)
xGauss = FluxRC.legendre_point(deg)
xsp = FluxRC.global_sp(xFace, xGauss)
ll = FluxRC.lagrange_point(xGauss, -1.0)
lr = FluxRC.lagrange_point(xGauss, 1.0)
lpdm = FluxRC.∂lagrange(xGauss)
dgl, dgr = FluxRC.∂radau(deg, xGauss)
end
u = zeros(nx, nsp)
f = zeros(nx, nu, nsp)
for i = 1:nx, ppp1 = 1:nsp
#u[i, ppp1] = exp(-20.0 * pspace.xp[i, ppp1]^2)
u[i, ppp1] = 1.0 - sin(π * pspace.xp[i, ppp1])
prim = conserve_prim(u[i, ppp1], a)
f[i, :, ppp1] .= maxwellian(vspace.u, prim)
end
e2f = zeros(Int, nx, 2)
for i = 1:nx
if i == 1
e2f[i, 2] = nface
e2f[i, 1] = i + 1
elseif i == nx
e2f[i, 2] = i
e2f[i, 1] = 1
else
e2f[i, 2] = i
e2f[i, 1] = i + 1
end
end
f2e = zeros(Int, nface, 2)
for i = 1:nface
if i == 1
f2e[i, 1] = i
f2e[i, 2] = nx
elseif i == nface
f2e[i, 1] = 1
f2e[i, 2] = i - 1
else
f2e[i, 1] = i
f2e[i, 2] = i - 1
end
end
function mol!(du, u, p, t) # method of lines
dx, e2f, f2e, a, velo, weights, δ, deg, ll, lr, lpdm, dgl, dgr = p
ncell = size(u, 1)
nu = size(u, 2)
nsp = size(u, 3)
ρ = similar(u, ncell, nsp)
M = similar(u, ncell, nu, nsp)
for i = 1:ncell, k = 1:nsp
#ρ[i, k] = discrete_moments(u[i, :, k], weights)
ρ[i, k] = sum(u[i, :, k] .* weights)
#prim = conserve_prim(ρ[i, k], a)
prim = [ρ[i, k], a, 1.0]
#M[i, :, k] .= maxwellian(velo, prim)
@. M[i, :, k] = prim[1] * sqrt(prim[3] / π) * exp(-prim[3] * (velo - prim[2])^2)
end
τ = 2.0 * 0.001
f = similar(u)
for i = 1:ncell, j = 1:nu, k = 1:nsp
J = 0.5 * dx[i]
f[i, j, k] = velo[j] * u[i, j, k] / J
end
u_face = zeros(eltype(u), ncell, nu, 2)
f_face = zeros(eltype(u), ncell, nu, 2)
for i = 1:ncell, j = 1:nu, k = 1:nsp
# right face of element i
u_face[i, j, 1] += u[i, j, k] * lr[k]
f_face[i, j, 1] += f[i, j, k] * lr[k]
# left face of element i
u_face[i, j, 2] += u[i, j, k] * ll[k]
f_face[i, j, 2] += f[i, j, k] * ll[k]
end
f_interaction = similar(u, nface, nu)
for i = 1:nface
@. f_interaction[i, :] =
f_face[f2e[i, 1], :, 2] * (1.0 - δ) + f_face[f2e[i, 2], :, 1] * (δ)
end
rhs1 = zeros(eltype(u), ncell, nu, nsp)
for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp, k = 1:nsp
rhs1[i, j, ppp1] += f[i, j, k] * lpdm[ppp1, k]
end
for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp
du[i, j, ppp1] =
-(
rhs1[i, j, ppp1] +
(f_interaction[e2f[i, 2], j] - f_face[i, j, 2]) * dgl[ppp1] +
(f_interaction[e2f[i, 1], j] - f_face[i, j, 1]) * dgr[ppp1]
) + (M[i, j, ppp1] - u[i, j, ppp1]) / τ
end
end
tspan = (0.0, 0.5)
p = (pspace.dx, e2f, f2e, a, vspace.u, vspace.weights, δ, deg, ll, lr, lpdm, dgl, dgr)
prob = ODEProblem(mol!, f, tspan, p)
sol = solve(
prob,
ROCK4(),
saveat = tspan[2],
#reltol = 1e-8,
#abstol = 1e-8,
adaptive = false,
dt = 0.0005,
progress = true,
progress_steps = 10,
progress_name = "frode",
#autodiff = false,
)
prob = remake(prob, u0 = sol.u[end], p = p, t = tspan)
#--- post process ---#
plot(xsp[:, 2], u[:, 2])
begin
ρ = zeros(nx, nsp)
for i = 1:nx, j = 1:nsp
ρ[i, j] = moments_conserve(sol.u[end][i, :, j], vspace.u, vspace.weights)[1]
end
plot!(xsp[:, 2], ρ[:, 2])
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2407 | using KitBase, FluxReconstruction, OrdinaryDiffEq
using Base.Threads: @threads
function rhs!(du, u, p, t)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, a = p
ncell = size(u, 1)
nsp = size(u, 2)
@inbounds @threads for j = 1:nsp
for i = 1:ncell
f[i, j] = KitBase.advection_flux(u[i, j], a) / J[i]
end
end
u_face[:, 1] .= u * ll
f_face[:, 1] .= f * ll
u_face[:, 2] .= u * lr
f_face[:, 2] .= f * lr
@inbounds @threads for i = 2:ncell
au = (f_face[i, 1] - f_face[i-1, 2]) / (u_face[i, 1] - u_face[i-1, 2] + 1e-8)
f_interaction[i] = (
0.5 * (f_face[i, 1] + f_face[i-1, 2]) -
0.5 * abs(au) * (u_face[i, 1] - u_face[i-1, 2])
)
end
au = (f_face[1, 1] - f_face[ncell, 2]) / (u_face[1, 1] - u_face[ncell, 2] + 1e-8)
f_interaction[1] = (
0.5 * (f_face[ncell, 2] + f_face[1, 1]) -
0.5 * abs(au) * (u_face[1, 1] - u_face[ncell, 2])
)
f_interaction[end] = f_interaction[1]
rhs1 .= 0.0
@inbounds @threads for ppp1 = 1:nsp
for i = 1:ncell
for k = 1:nsp
rhs1[i, ppp1] += f[i, k] * lpdm[ppp1, k]
end
end
end
@inbounds @threads for ppp1 = 1:nsp
for i = 1:ncell
du[i, ppp1] = -(
rhs1[i, ppp1] +
(f_interaction[i] - f_face[i, 1]) * dgl[ppp1] +
(f_interaction[i+1] - f_face[i, 2]) * dgr[ppp1]
)
end
end
end
cfg = (x0 = -1, x1 = 1, nx = 100, deg = 2, cfl = 0.05, t = 0.0, a = 1.0)
dx = (cfg.x1 - cfg.x0) / cfg.nx
dt = cfg.cfl * dx
ps = FRPSpace1D(; cfg...)
u = zeros(ps.nx, ps.deg + 1)
for i in axes(u, 1), j in axes(u, 2)
u[i, j] = sin(π * ps.xpg[i, j])
end
begin
f = zero(u)
rhs = zero(u)
ncell = size(u, 1)
u_face = zeros(eltype(u), ncell, 2)
f_face = zeros(eltype(u), ncell, 2)
f_interaction = zeros(eltype(u), ncell + 1)
p = (
f,
u_face,
f_face,
f_interaction,
rhs,
ps.J,
ps.ll,
ps.lr,
ps.dl,
ps.dhl,
ps.dhr,
cfg.a,
)
end
tspan = (0.0, 2.0)
prob = ODEProblem(rhs!, u, tspan, p)
sol = solve(prob, Tsit5(), progress = true)
using Plots
plot(ps.xpg[:, 2], sol.u[end][:, 2], label = "t=2")
plot!(ps.xpg[:, 2], u[:, 2], label = "t=0", line = :dash)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4484 | using OrdinaryDiffEq
using KitBase, KitBase.Plots
import FluxRC
using Logging: global_logger
using TerminalLoggers: TerminalLogger
global_logger(TerminalLogger())
begin
x0 = 0
x1 = 1
nx = 20
nface = nx + 1
dx = (x1 - x0) / nx
deg = 2 # polynomial degree
nsp = deg + 1
u0 = -5
u1 = 5
nu = 100
cfl = 0.1
dt = cfl * dx / u1
t = 0.0
end
begin
ps = FluxRC.FRPSpace1D(x0, x1, nx, deg)
vs = VSpace1D(u0, u1, nu)
δ = heaviside.(vs.u)
xFace = collect(x0:dx:x1)
xGauss = FluxRC.legendre_point(deg)
xsp = FluxRC.global_sp(xFace, xGauss)
ll, lr, lpdm = FluxRC.standard_lagrange(xGauss)
dgl, dgr = FluxRC.∂radau(deg, xGauss)
end
f0 = zeros(nx, nu, nsp)
for i = 1:nx, ppp1 = 1:nsp
_ρ = 1.0 + 0.1 * sin(2.0 * π * ps.xp[i, ppp1])
_T = 2 * 0.5 / _ρ
f0[i, :, ppp1] .= maxwellian(vs.u, [_ρ, 1.0, 1.0 / _T])
end
e2f = zeros(Int, nx, 2)
for i = 1:nx
if i == 1
e2f[i, 2] = nface
e2f[i, 1] = i + 1
elseif i == nx
e2f[i, 2] = i
e2f[i, 1] = 1
else
e2f[i, 2] = i
e2f[i, 1] = i + 1
end
end
f2e = zeros(Int, nface, 2)
for i = 1:nface
if i == 1
f2e[i, 1] = i
f2e[i, 2] = nx
elseif i == nface
f2e[i, 1] = 1
f2e[i, 2] = i - 1
else
f2e[i, 1] = i
f2e[i, 2] = i - 1
end
end
function mol!(du, u, p, t)
dx, e2f, f2e, velo, weights, δ, deg, ll, lr, lpdm, dgl, dgr = p
ncell = size(u, 1)
nu = size(u, 2)
nsp = size(u, 3)
M = similar(u, ncell, nu, nsp)
for i = 1:ncell, k = 1:nsp
w = moments_conserve(u[i, :, k], velo, weights)
prim = conserve_prim(w, 3.0)
M[i, :, k] .= maxwellian(velo, prim)
end
τ = 1e-2
f = similar(u)
for i = 1:ncell, j = 1:nu, k = 1:nsp
J = 0.5 * dx[i]
f[i, j, k] = velo[j] * u[i, j, k] / J
end
f_face = zeros(eltype(u), ncell, nu, 2)
#=for i = 1:ncell, j = 1:nu, k = 1:nsp
# right face of element i
f_face[i, j, 1] += f[i, j, k] * lr[k]
# left face of element i
f_face[i, j, 2] += f[i, j, k] * ll[k]
end=#
@views for i = 1:ncell, j = 1:nu
FluxRC.interp_interface!(f_face[i, j, :], f[i, j, :], ll, lr)
end
f_interaction = similar(u, nface, nu)
for i = 1:nface
@. f_interaction[i, :] =
f_face[f2e[i, 1], :, 1] * (1.0 - δ) + f_face[f2e[i, 2], :, 2] * δ
end
rhs1 = zeros(eltype(u), ncell, nu, nsp)
#for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp, k = 1:nsp
# rhs1[i, j, ppp1] += f[i, j, k] * lpdm[ppp1, k]
#end
@views for i = 1:ncell, j = 1:nu
FluxRC.poly_derivative!(rhs1[i, j, :], f[i, j, :], lpdm)
end
#@views for i = 1:ncell, j = 1:nu, k = 1:nsp
# rhs1[i, j, k] = dot(f[i, j, :], lpdm[k, :])
#end
for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp
du[i, j, ppp1] =
-(
rhs1[i, j, ppp1] +
(f_interaction[e2f[i, 2], j] - f_face[i, j, 1]) * dgl[ppp1] +
(f_interaction[e2f[i, 1], j] - f_face[i, j, 2]) * dgr[ppp1]
) + (M[i, j, ppp1] - u[i, j, ppp1]) / τ
end
end
tspan = (0.0, 1.0)
p = (ps.dx, e2f, f2e, vs.u, vs.weights, δ, deg, ll, lr, lpdm, dgl, dgr)
prob = ODEProblem(mol!, f0, tspan, p)
sol = solve(
prob,
Midpoint(),
#ABDF2(),
#TRBDF2(),
#Kvaerno3(),
#KenCarp3(),
saveat = tspan[2],
#reltol = 1e-8,
#abstol = 1e-8,
adaptive = false,
dt = dt,
progress = true,
progress_steps = 10,
progress_name = "frode",
#autodiff = false,
)
begin
x = zeros(nx * nsp)
w = zeros(nx * nsp, 3)
prim = zeros(nx * nsp, 3)
prim0 = zeros(nx * nsp, 3)
for i = 1:nx
idx0 = (i - 1) * nsp
idx = idx0+1:idx0+nsp
for j = 1:nsp
idx = idx0 + j
x[idx] = xsp[i, j]
w[idx, :] .= moments_conserve(sol.u[end][i, :, j], vs.u, vs.weights)
prim[idx, :] .= conserve_prim(w[idx, :], 3.0)
prim0[idx, :] .= [
1.0 + 0.1 * sin(2.0 * π * x[idx]),
1.0,
2 * 0.5 / (1.0 + 0.1 * sin(2.0 * π * x[idx])),
]
end
end
end
#FluxRC.L1_error(prim[:, 1], prim0[:, 1], dx) |> println
#FluxRC.L2_error(prim[:, 1], prim0[:, 1], dx) |> println
#FluxRC.L∞_error(prim[:, 1], prim0[:, 1], dx) |> println
plot(x, prim0[:, 1], label = "t=0")
plot!(x[1:end], prim[1:end, 1], label = "t=1")
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4166 | using KitBase, FluxReconstruction, OrdinaryDiffEq, LinearAlgebra, Plots
using KitBase.ProgressMeter: @showprogress
function extract_x(ps)
x = zeros(ps.nx * (ps.deg + 1))
for i = 1:ps.nx
idx0 = (i - 1) * (ps.deg + 1)
for k = 1:ps.deg+1
idx = idx0 + k
x[idx] = ps.xpg[i, k]
end
end
return x
end
function extract_sol(itg, ps, γ)
sol = zeros(ps.nx * (ps.deg + 1), 3)
for i = 1:ps.nx
idx0 = (i - 1) * (ps.deg + 1)
for k = 1:ps.deg+1
idx = idx0 + k
sol[idx, :] .= conserve_prim(itg.u[i, k, :], γ)
sol[idx, end] = 1 / sol[idx, end]
end
end
return sol
end
function extract_sol(itg::ODESolution, ps, γ)
sol = zeros(ps.nx * (ps.deg + 1), 3)
for i = 1:ps.nx
idx0 = (i - 1) * (ps.deg + 1)
for k = 1:ps.deg+1
idx = idx0 + k
sol[idx, :] .= conserve_prim(itg.u[end][i, k, :], γ)
sol[idx, end] = 1 / sol[idx, end]
end
end
return sol
end
begin
x0 = 0
x1 = 1
deg = 3 # polynomial degree
nsp = deg + 1
γ = 5 / 3
cfl = 0.08
end
ncells = [4, 8, 16, 32, 64, 128]
@showprogress for ncell in ncells
dx = (x1 - x0) / ncell
dt = cfl * dx
t = 0.0
ps = FRPSpace1D(x0, x1, ncell, deg)
u = zeros(ncell, nsp, 3)
for i = 1:ncell, ppp1 = 1:nsp
ρ = 1 + 0.2 * sin(2π * ps.xpg[i, ppp1])
prim = [ρ, 1.0, ρ]
u[i, ppp1, :] .= prim_conserve(prim, γ)
end
x = extract_x(ps)
sol0 = zeros(ps.nx * nsp, 3)
for i in axes(x, 1)
ρ = 1 + 0.2 * sin(2π * x[i])
sol0[i, :] .= [ρ, 1.0, 1 / ρ]
end
function dudt!(du, u, p, t)
du .= 0.0
nx, nsp, J, ll, lr, lpdm, dgl, dgr, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
f = zeros(ncell, nsp, 3)
for i = 1:ncell, j = 1:nsp
f[i, j, :] .= euler_flux(u[i, j, :], γ)[1] ./ J[i]
end
u_face = zeros(ncell, 3, 2)
f_face = zeros(ncell, 3, 2)
for i = 1:ncell, j = 1:3
# right face of element i
u_face[i, j, 1] = dot(u[i, :, j], lr)
f_face[i, j, 1] = dot(f[i, :, j], lr)
# left face of element i
u_face[i, j, 2] = dot(u[i, :, j], ll)
f_face[i, j, 2] = dot(f[i, :, j], ll)
end
f_interaction = zeros(nx + 1, 3)
for i = 2:nx
fw = @view f_interaction[i, :]
flux_hll!(fw, u_face[i-1, :, 1], u_face[i, :, 2], γ, 1.0)
end
# periodic boundary condition
fw = @view f_interaction[1, :]
flux_hll!(fw, u_face[nx, :, 1], u_face[1, :, 2], γ, 1.0)
fw = @view f_interaction[nx+1, :]
flux_hll!(fw, u_face[nx, :, 1], u_face[1, :, 2], γ, 1.0)
rhs1 = zeros(ncell, nsp, 3)
for i = 1:ncell, ppp1 = 1:nsp, k = 1:3
rhs1[i, ppp1, k] = dot(f[i, :, k], lpdm[ppp1, :])
end
idx = 1:ncell
for i in idx, ppp1 = 1:nsp, k = 1:3
du[i, ppp1, k] = -(
rhs1[i, ppp1, k] +
(f_interaction[i, k] / J[i] - f_face[i, k, 2]) * dgl[ppp1] +
(f_interaction[i+1, k] / J[i] - f_face[i, k, 1]) * dgr[ppp1]
)
end
end
tspan = (0.0, 2.0)
p = (ps.nx, ps.deg + 1, ps.J, ps.ll, ps.lr, ps.dl, ps.dhl, ps.dhr, γ)
prob = ODEProblem(dudt!, u, tspan, p)
nt = tspan[2] / dt |> Int # Alignment is required here
itg = solve(prob, Tsit5(), saveat = tspan[2], adaptive = false, dt = dt)
#itg = init(prob, Tsit5(), saveat = tspan[2], adaptive = false, dt = dt)
#for iter = 1:nt
# step!(itg)
#end
sol = extract_sol(itg, ps, γ)
Δx = (x1 - x0) / ncell
dx = Δx / nsp
@show l1 = FR.L1_error(sol[:, 1], sol0[:, 1], Δx)
#l1f = FR.L1_error(sol[:, 1], sol0[:, 1], dx)
@show l2 = FR.L2_error(sol[:, 1], sol0[:, 1], Δx)
#l2f = FR.L2_error(sol[:, 1], sol0[:, 1], dx)
#ll = FR.L∞_error(sol[:, 1], sol0[:, 1], Δx)
#llf = FR.L1_error(sol[:, 1], sol0[:, 1], dx)
end
#x, sol = extract_sol(itg, ps, γ)
#plot(x, sol[:, 1])
#plot!(x, sol0[:, 1])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 5747 | # ============================================================
# 2D traveling wave solution for the Euler equations
# ============================================================
using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
cd(@__DIR__)
begin
set = Setup(
"gas",
"cylinder",
"2d0f",
"hll",
"nothing",
1, # species
3, # order of accuracy
"positivity", # limiter
"euler",
0.1, # cfl
1.0, # time
)
ps0 = KitBase.PSpace2D(0.0, 1.0, 20, 0.0, 1.0, 30, 1, 1)
deg = set.interpOrder - 1
ps = FRPSpace2D(ps0, deg)
vs = nothing
gas = Gas(Kn = 1e-6, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)
end
function dudt!(du, u, p, t)
du .= 0.0
J, ll, lr, dhl, dhr, lpdm, γ = p
nx = size(u, 1) - 2
ny = size(u, 2) - 2
nsp = size(u, 3)
f = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, nsp, nsp, 4, 2)
for i in axes(f, 1), j in axes(f, 2), k = 1:nsp, l = 1:nsp
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for m = 1:4
f[i, j, k, l, m, :] .= inv(J[i, j][k, l]) * [fg[m], gg[m]]
end
end
u_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4)
f_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4, 2)
for i in axes(u_face, 1), j in axes(u_face, 2), l = 1:nsp, m = 1:4
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
fx_interaction = zeros(nx + 1, ny, nsp, 4)
for i = 1:nx+1, j = 1:ny, k = 1:nsp
fw = @view fx_interaction[i, j, k, :]
uL = @view u_face[i-1, j, 2, k, :]
uR = @view u_face[i, j, 4, k, :]
flux_hll!(fw, uL, uR, γ, 1.0)
end
fy_interaction = zeros(nx, ny + 1, nsp, 4)
for i = 1:nx, j = 1:ny+1, k = 1:nsp
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], 0.0, 1.0)
uR = local_frame(u_face[i, j, 1, k, :], 0.0, 1.0)
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, 0.0, 1.0)
end
rhs1 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
rhs2 = zeros(nx, ny, nsp, nsp, 4)
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
for i = 1:nx, j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(
fx_interaction[i, j, l, m] * inv(J[i, j][k, l])[1, 1] -
f_face[i, j, 4, l, m, 1]
) * dhl[k] +
(
fx_interaction[i+1, j, l, m] * inv(J[i, j][k, l])[1, 1] -
f_face[i, j, 2, l, m, 1]
) * dhr[k] +
(
fy_interaction[i, j, k, m] * inv(J[i, j][k, l])[2, 2] -
f_face[i, j, 1, k, m, 2]
) * dhl[l] +
(
fy_interaction[i, j+1, k, m] * inv(J[i, j][k, l])[2, 2] -
f_face[i, j, 3, k, m, 2]
) * dhr[l]
)
end
return nothing
end
tspan = (0.0, 0.5)
p = (ps.J, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
dt = 0.002
nt = tspan[2] ÷ dt |> Int
# wave in x direction
u0 = OffsetArray{Float64}(undef, 0:ps.nx+1, 0:ps.ny+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
ρ = 1.0 + 0.1 * sin(2π * ps.xpg[i, j, k, l, 1])
prim = [ρ, 1.0, 0.0, ρ]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
prob = ODEProblem(dudt!, u0, tspan, p)
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:nt
# bcs for traveling wave in x direction
itg.u[0, :, :, :, :] .= itg.u[ps.nx, :, :, :, :]
itg.u[ps.nx+1, :, :, :, :] .= itg.u[1, :, :, :, :]
itg.u[:, 0, :, :, :] .= itg.u[:, ps.ny, :, :, :]
itg.u[:, 0, :, :, 3] .*= -1
itg.u[:, ps.ny+1, :, :, :] .= itg.u[:, 1, :, :, :]
itg.u[:, ps.ny+1, :, :, 3] .*= -1
step!(itg)
end
u1 = deepcopy(itg.u)
plot(ps.x[1:ps.nx, 1], u0[1:ps.nx, 1, 2, 2, 1])
plot!(ps.x[1:ps.nx, 1], itg.u[1:ps.nx, 1, 2, 2, 1])
# wave in y direction
u0 = OffsetArray{Float64}(undef, 0:ps.nx+1, 0:ps.ny+1, deg + 1, deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
ρ = 1.0 + 0.1 * sin(2π * ps.xpg[i, j, k, l, 2])
prim = [ρ, 0.0, 1.0, ρ]
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
prob = ODEProblem(dudt!, u0, tspan, p)
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:nt
# bcs for traveling wave in y direction
itg.u[:, 0, :, :, :] .= itg.u[:, ps.ny, :, :, :]
itg.u[:, ps.ny+1, :, :, :] .= itg.u[:, 1, :, :, :]
itg.u[0, :, :, :, :] .= itg.u[ps.nx, :, :, :, :]
itg.u[0, :, :, :, 2] .*= -1
itg.u[ps.nx+1, :, :, :, :] .= itg.u[1, :, :, :, :]
itg.u[ps.nx+1, :, :, :, 2] .*= -1
step!(itg)
end
plot(ps.y[1, 1:ps.ny], u0[1, 1:ps.ny, 2, 2, 1])
plot!(ps.y[1, 1:ps.ny], itg.u[1, 1:ps.ny, 2, 2, 1])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2003 | using KitBase, FluxReconstruction, OrdinaryDiffEq, LinearAlgebra, Plots
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
begin
x0 = 0
x1 = 1
ncell = 100
dx = (x1 - x0) / ncell
deg = 7 # polynomial degree
nsp = deg + 1
γ = 5 / 3
cfl = 0.01
dt = cfl * dx
t = 0.0
end
ps = FRPSpace1D(x0, x1, ncell, deg)
ℓ = FR.basis_norm(ps.deg)
u = zeros(ncell, nsp, 3)
for i = 1:ncell, ppp1 = 1:nsp
if ps.x[i] <= 0.5
prim = [1.0, 0.0, 0.5]
else
prim = [0.125, 0.0, 0.625]
end
u[i, ppp1, :] .= prim_conserve(prim, γ)
end
tspan = (0.0, 0.15)
prob = FREulerProblem(u, tspan, ps, γ, :dirichlet)
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Midpoint(), saveat = tspan[2], adaptive = false, dt = dt)
@showprogress for iter = 1:nt
@inbounds @threads for i = 1:ps.nx
ũ = ps.iV * itg.u[i, :, 1]
su = (ũ[end]^2) / (sum(ũ .^ 2) + 1e-6)
isd = shock_detector(log10(su), ps.deg)
λ = dt * exp(0.875 / 1 * (ps.deg)) * 0.15
if isd
for s = 1:3
û = ps.iV * itg.u[i, :, s]
KB.modal_filter!(û, λ; filter = :l2)
#KB.modal_filter!(û, ℓ; filter = :lasso)
#KB.modal_filter!(û, 4; filter = :exp)
#KB.modal_filter!(û, 6; filter = :houli)
itg.u[i, :, s] .= ps.V * û
end
end
end
step!(itg)
end
begin
x = zeros(ncell * nsp)
w = zeros(ncell * nsp, 3)
for i = 1:ncell
idx0 = (i - 1) * nsp
for j = 1:nsp
idx = idx0 + j
x[idx] = ps.xpg[i, j]
w[idx, :] .= itg.u[i, j, :]
end
end
sol = zeros(ncell * nsp, 3)
for i in axes(sol, 1)
sol[i, :] .= conserve_prim(w[i, :], γ)
sol[i, end] = 1 / sol[i, end]
end
plot(x, sol[:, 1], label = "ρ", xlabel = "x")
plot!(x, sol[:, 2], label = "u", xlabel = "x")
plot!(x, sol[:, 3], label = "T", xlabel = "x")
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2503 | using KitBase, FluxReconstruction, OrdinaryDiffEq, LinearAlgebra, Plots
using KitBase.ProgressMeter: @showprogress
begin
x0 = 0
x1 = 1
ncell = 100
dx = (x1 - x0) / ncell
deg = 2 # polynomial degree
nsp = deg + 1
γ = 5 / 3
cfl = 0.05
dt = cfl * dx
t = 0.0
end
ps = FRPSpace1D(x0, x1, ncell, deg)
u = zeros(ncell, nsp, 3)
for i = 1:ncell, ppp1 = 1:nsp
if ps.x[i] <= 0.5
prim = [1.0, 0.0, 0.5]
else
prim = [0.3, 0.0, 0.625]
end
#prim = [1 + 0.1*sin(2π * ps.xpg[i, ppp1]), 1.0, 1.0]
u[i, ppp1, :] .= prim_conserve(prim, γ)
end
function dudt!(du, u, p, t)
du .= 0.0
nx, nsp, J, ll, lr, lpdm, dgl, dgr, γ = p
ncell = size(u, 1)
nsp = size(u, 2)
f = zeros(ncell, nsp, 3)
for i = 1:ncell, j = 1:nsp
f[i, j, :] .= euler_flux(u[i, j, :], γ)[1] ./ J[i]
end
u_face = zeros(ncell, 3, 2)
f_face = zeros(ncell, 3, 2)
for i = 1:ncell, j = 1:3
# right face of element i
u_face[i, j, 1] = dot(u[i, :, j], lr)
f_face[i, j, 1] = dot(f[i, :, j], lr)
# left face of element i
u_face[i, j, 2] = dot(u[i, :, j], ll)
f_face[i, j, 2] = dot(f[i, :, j], ll)
end
f_interaction = zeros(nx + 1, 3)
for i = 2:nx
fw = @view f_interaction[i, :]
flux_hll!(fw, u_face[i-1, :, 1], u_face[i, :, 2], γ, 1.0)
end
fw = @view f_interaction[1, :]
flux_hll!(fw, u_face[nx, :, 1], u_face[1, :, 2], γ, 1.0)
fw = @view f_interaction[nx+1, :]
flux_hll!(fw, u_face[nx, :, 1], u_face[1, :, 2], γ, 1.0)
rhs1 = zeros(ncell, nsp, 3)
for i = 1:ncell, ppp1 = 1:nsp, k = 1:3
rhs1[i, ppp1, k] = dot(f[i, :, k], lpdm[ppp1, :])
end
idx = 2:ncell-1 # ending points are Dirichlet
for i in idx, ppp1 = 1:nsp, k = 1:3
du[i, ppp1, k] = -(
rhs1[i, ppp1, k] +
(f_interaction[i, k] / J[i] - f_face[i, k, 2]) * dgl[ppp1] +
(f_interaction[i+1, k] / J[i] - f_face[i, k, 1]) * dgr[ppp1]
)
end
end
tspan = (0.0, 0.15)
p = (ps.nx, ps.deg + 1, ps.J, ps.ll, ps.lr, ps.dl, ps.dhl, ps.dhr, γ)
prob = ODEProblem(dudt!, u, tspan, p)
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Midpoint(), saveat = tspan[2], adaptive = false, dt = dt)
@showprogress for iter = 1:nt
step!(itg)
end
sol = zero(itg.u)
for i in axes(sol, 1), j in axes(sol, 2)
sol[i, j, :] .= conserve_prim(itg.u[i, j, :], γ)
sol[i, j, end] = 1 / sol[i, j, end]
end
plot(ps.x, sol[:, 2, :])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 13090 | using KitBase, FluxReconstruction, OrdinaryDiffEq, LinearAlgebra, Plots, OffsetArrays
using ProgressMeter: @showprogress
using Base.Threads: @threads
begin
x0 = 0
x1 = 1
nx = 15
y0 = 0
y1 = 1
ny = 15
deg = 2
nsp = deg + 1
inK = 1
γ = 5 / 3
knudsen = 0.001
muref = ref_vhs_vis(knudsen, 1.0, 0.5)
cfl = 0.1
dx = (x1 - x0) / nx
dy = (y1 - y0) / ny
dt = cfl * min(dx, dy) / (3.0)
t = 0.0
tmax = 0.15
tspan = (0.0, tmax)
nt = tmax ÷ dt |> Int
end
ps = FRPSpace2D(x0, x1, nx, y0, y1, ny, deg, 1, 1)
μᵣ = ref_vhs_vis(knudsen, 1.0, 0.5)
gas = Gas(knudsen, 0.0, 1.0, 1.0, γ, 0.81, 1.0, 0.5, μᵣ)
u0 = OffsetArray{Float64}(undef, 4, nsp, nsp, 0:ny+1, 0:nx+1)
#for i = 1:nsp, j = 1:nsp, k = 0:ny+1, l = 0:nx+1
for i = 0:nx+1, j = 0:ny+1, k = 1:nsp, l = 1:nsp
u0[:, l, k, j, i] .= prim_conserve([1.0, 0.0, 0.0, 1.0], gas.γ)
#ρ = max(exp(-50 * ((ps.xpg[l, k, j, i, 1] - 0.5)^2 + (ps.xpg[l, k, j, i, 2] - 0.5)^2)), 1e-2)
#u0[:, i, j, k, l] .= prim_conserve([ρ, 0.0, 0.0, 1.0], gas.γ)
#=if ps.x[i, j] < 0.5
prim = [1.0, 0.0, 0.0, 0.5]
else
prim = [0.3, 0.0, 0.0, 0.625]
end
u0[:, l, k, j, i] .= prim_conserve(prim, gas.γ)=#
end
function KitBase.flux_gks!(
fw::AbstractVector{T1},
w::AbstractVector{T2},
inK::Real,
γ::Real,
μᵣ::Real,
ω::Real,
sw = zero(w)::AbstractVector{T2},
) where {T1<:AbstractFloat,T2<:Real}
prim = conserve_prim(w, γ)
Mu, Mv, Mxi, MuL, MuR = gauss_moments(prim, inK)
tau = vhs_collision_time(prim, μᵣ, ω)
a = pdf_slope(prim, sw, inK)
∂ft = -prim[1] .* moments_conserve_slope(a, Mu, Mv, Mxi, 1, 0)
A = pdf_slope(prim, ∂ft, inK)
Muv = moments_conserve(Mu, Mv, Mxi, 1, 0, 0)
Mau = moments_conserve_slope(a, Mu, Mv, Mxi, 2, 0)
Mtu = moments_conserve_slope(A, Mu, Mv, Mxi, 1, 0)
@. fw = prim[1] * (Muv - tau * Mau - tau * Mtu)
return nothing
end
function KitBase.flux_gks!(
fw::X,
wL::Y,
wR::Y,
inK::Real,
γ::Real,
μᵣ::Real,
ω::Real,
dt::Real,
swL = zero(wL)::Y,
swR = zero(wR)::Y,
) where {X<:AbstractArray{<:AbstractFloat,1},Y<:AbstractArray{<:AbstractFloat,1}}
primL = conserve_prim(wL, γ)
primR = conserve_prim(wR, γ)
Mu1, Mv1, Mxi1, MuL1, MuR1 = gauss_moments(primL, inK)
Mu2, Mv2, Mxi2, MuL2, MuR2 = gauss_moments(primR, inK)
w =
primL[1] .* moments_conserve(MuL1, Mv1, Mxi1, 0, 0, 0) .+
primR[1] .* moments_conserve(MuR2, Mv2, Mxi2, 0, 0, 0)
prim = conserve_prim(w, γ)
tau =
vhs_collision_time(prim, μᵣ, ω) +
2.0 * dt * abs(primL[1] / primL[end] - primR[1] / primR[end]) /
(primL[1] / primL[end] + primR[1] / primR[end])
if minimum(swL .* swR) < 0
#swL .= 0.0
#swR .= 0.0
end
faL = pdf_slope(primL, swL, inK)
sw = -primL[1] .* moments_conserve_slope(faL, Mu1, Mv1, Mxi1, 1, 0)
faTL = pdf_slope(primL, sw, inK)
faR = pdf_slope(primR, swR, inK)
sw = -primR[1] .* moments_conserve_slope(faR, Mu2, Mv1, Mxi2, 1, 0)
faTR = pdf_slope(primR, sw, inK)
Mu, Mv, Mxi, MuL, MuR = gauss_moments(prim, inK)
# time-integration constants
Mt = zeros(5)
Mt[4] = dt#tau * (1.0 - exp(-dt / tau))
Mt[5] = -tau * dt * exp(-dt / tau) + tau * Mt[4]
Mt[1] = dt - Mt[4]
Mt[2] = -tau * Mt[1] + Mt[5]
Mt[3] = 0.5 * dt^2 - tau * Mt[1]
# flux related to central distribution
Muv = moments_conserve(Mu, Mv, Mxi, 1, 0, 0)
fw .= Mt[1] .* prim[1] .* Muv
# flux related to upwind distribution
MuvL = moments_conserve(MuL1, Mv1, Mxi1, 1, 0, 0)
MauL = moments_conserve_slope(faL, MuL1, Mv1, Mxi1, 2, 0)
MauLT = moments_conserve_slope(faTL, MuL1, Mv1, Mxi1, 1, 0)
MuvR = moments_conserve(MuR2, Mv2, Mxi2, 1, 0, 0)
MauR = moments_conserve_slope(faR, MuR2, Mv2, Mxi2, 2, 0)
MauRT = moments_conserve_slope(faTR, MuR2, Mv2, Mxi2, 1, 0)
@. fw +=
Mt[4] * primL[1] * MuvL - tau * Mt[4] * primL[1] * MauL -
tau * Mt[4] * primL[1] * MauLT + Mt[4] * primR[1] * MuvR -
tau * Mt[4] * primR[1] * MauR - tau * Mt[4] * primR[1] * MauRT
fw ./= dt
return nothing
end
function dudt!(du, u, p, t)
boundary!(u, p, 1.0)
fx,
fy,
ux_face,
uy_face,
fx_face,
fy_face,
fx_interaction,
fy_interaction,
rhs1,
rhs2,
ps,
gas,
dt = p
nx = size(u, 5) - 2
ny = size(u, 4) - 2
nr = size(u, 3)
ns = size(u, 2)
@inbounds for i = 1:nx
for j = 1:ny, k = 1:nr, l = 1:ns
fw = @view fx[:, l, k, j, i]
flux_gks!(fw, u[:, l, k, j, i], gas.K, gas.γ, gas.μᵣ, gas.ω, zeros(4))
fw ./= ps.J[i, j][1]
#fx[:, l, k, j, i] .= euler_flux(u[:, l, k, j, i], gas.γ)[1] ./ ps.J[i, j][1]
end
end
@inbounds @threads for i = 1:nx
for j = 1:ny, k = 1:nr, l = 1:ns
fw = @view fy[:, l, k, j, i]
ul = local_frame(u[:, l, k, j, i], 0.0, 1.0)
flux_gks!(fw, ul, gas.K, gas.γ, gas.μᵣ, gas.ω, zeros(4))
fy[:, l, k, j, i] .= global_frame(fw, 0.0, 1.0) ./ ps.J[i, j][2]
#fy[:, l, k, j, i] .= euler_flux(u[:, l, k, j, i], gas.γ)[2] ./ ps.J[i, j][2]
end
end
@inbounds for i = 0:nx+1
for j = 1:ny, l = 1:ns, m = 1:4
ux_face[m, 1, l, j, i] = dot(u[m, l, :, j, i], ps.ll)
ux_face[m, 2, l, j, i] = dot(u[m, l, :, j, i], ps.lr)
fx_face[m, 1, l, j, i] = dot(fx[m, l, :, j, i], ps.ll)
fx_face[m, 2, l, j, i] = dot(fx[m, l, :, j, i], ps.lr)
end
end
@inbounds for i = 1:nx
for j = 0:ny+1, k = 1:nr, m = 1:4
uy_face[m, 1, k, j, i] = dot(u[m, :, k, j, i], ps.ll)
uy_face[m, 2, k, j, i] = dot(u[m, :, k, j, i], ps.lr)
fy_face[m, 1, k, j, i] = dot(fy[m, :, k, j, i], ps.ll)
fy_face[m, 2, k, j, i] = dot(fy[m, :, k, j, i], ps.lr)
end
end
@inbounds for i = 1:nx+1
for j = 1:ny, l = 1:ns
swL = zeros(4)
swR = zeros(4)
for m in eachindex(swL)
swL[m] = dot(u[m, l, :, j, i-1], ps.dll) / ps.J[i-1, j][1]
swR[m] = dot(u[m, l, :, j, i], ps.dlr) / ps.J[i, j][1]
end
fw = @view fx_interaction[:, l, j, i]
flux_gks!(
fw,
ux_face[:, 2, l, j, i-1],
ux_face[:, 1, l, j, i],
gas.K,
gas.γ,
gas.μᵣ,
gas.ω,
dt,
swL,
swR,
)
#=flux_hll!(
fw,
ux_face[:, 2, l, j, i-1],
ux_face[:, 1, l, j, i],
gas.γ,
1.0,
)=#
end
end
@inbounds for i = 1:nx
for j = 1:ny+1, k = 1:nr
swL = zeros(4)
swR = zeros(4)
for m in eachindex(swL)
swL[m] = dot(u[m, :, k, j-1, i], ps.dll) / ps.J[i, j-1][2]
swR[m] = dot(u[m, :, k, j, i], ps.dlr) / ps.J[i, j][2]
end
fw = @view fy_interaction[:, k, j, i]
uL = local_frame(uy_face[:, 2, k, j-1, i], 0.0, 1.0)
uR = local_frame(uy_face[:, 1, k, j, i], 0.0, 1.0)
flux_gks!(fw, uL, uR, gas.K, gas.γ, gas.μᵣ, gas.ω, dt, swL, swR)
#=flux_hll!(
fw,
uL,
uR,
gas.γ,
1.0,
)=#
fy_interaction[:, k, j, i] .= global_frame(fy_interaction[:, k, j, i], 0.0, 1.0)
end
end
@inbounds for i = 1:nx, j = 1:ny, k = 1:nr, l = 1:ns, m = 1:4
rhs1[m, l, k, j, i] = dot(fx[m, l, :, j, i], ps.dl[k, :])
rhs2[m, l, k, j, i] = dot(fy[m, :, k, j, i], ps.dl[l, :])
end
@inbounds for i = 1:nx, j = 1:ny, k = 1:nr, l = 1:ns, m = 1:4
du[m, l, k, j, i] = -(
rhs1[m, l, k, j, i] +
rhs2[m, l, k, j, i] +
(fx_interaction[m, l, j, i] / ps.J[i, j][1] - fx_face[m, 1, l, j, i]) *
ps.dhl[k] +
(fx_interaction[m, l, j, i+1] / ps.J[i, j][1] - fx_face[m, 2, l, j, i]) *
ps.dhr[k] +
(fy_interaction[m, k, j, i] / ps.J[i, j][2] - fy_face[m, 1, k, j, i]) *
ps.dhl[l] +
(fy_interaction[m, k, j+1, i] / ps.J[i, j][2] - fy_face[m, 2, k, j, i]) *
ps.dhr[l]
)
end
du[:, :, :, :, 0] .= 0.0
du[:, :, :, :, nx+1] .= 0.0
du[:, :, :, 0, :] .= 0.0
du[:, :, :, ny+1, :] .= 0.0
return nothing
end
function boundary!(u, p, λ0)
gas = p[end-1]
nx = size(u, 5) - 2
ny = size(u, 4) - 2
nr = size(u, 3)
ns = size(u, 2)
pb = zeros(4)
for j = 1:ny, k = 1:nr, l = 1:ns
prim = conserve_prim(u[:, l, k, j, 1], gas.γ)
pb[end] = 2 * λ0 - prim[end]
tmp = (prim[end] - λ0) / λ0
pb[1] = (1.0 - tmp) / (1.0 + tmp) * prim[1]
pb[2] = -prim[2]
pb[3] = -prim[3]
u[:, l, nr+1-k, j, 0] .= prim_conserve(pb, gas.γ)
end
for j = 1:ny, k = 1:nr, l = 1:ns
prim = conserve_prim(u[:, l, k, j, nx], gas.γ)
pb[end] = 2 * λ0 - prim[end]
tmp = (prim[end] - λ0) / λ0
pb[1] = (1 - tmp) / (1 + tmp) * prim[1]
pb[2] = -prim[2]
pb[3] = -prim[3]
u[:, l, nr+1-k, j, nx+1] .= prim_conserve(pb, gas.γ)
end
for i = 1:nx, k = 1:nr, l = 1:ns
prim = conserve_prim(u[:, l, k, 1, i], gas.γ)
pb[end] = 2 * λ0 - prim[end]
tmp = (prim[end] - λ0) / λ0
pb[1] = (1 - tmp) / (1 + tmp) * prim[1]
pb[2] = -prim[2]
pb[3] = -prim[3]
u[:, ns+1-l, k, 0, i] .= prim_conserve(pb, gas.γ)
end
for i = 1:nx, k = 1:nr, l = 1:ns
prim = conserve_prim(u[:, l, k, ny, i], gas.γ)
pb[end] = 2 * λ0 - prim[end]
tmp = (prim[end] - λ0) / λ0
pb[1] = (1 - tmp) / (1 + tmp) * prim[1]
pb[2] = 0.15#-prim[2] + 0.3
pb[3] = -prim[3]
u[:, ns+1-l, k, ny+1, i] .= prim_conserve(pb, gas.γ)
end
return nothing
end
begin
du = zero(u0)
fx = zero(u0)
fy = zero(u0)
ux_face = OffsetArray{Float64}(undef, 4, 2, ps.deg + 1, ps.ny, 0:ps.nx+1) |> zero
uy_face = OffsetArray{Float64}(undef, 4, 2, ps.deg + 1, 0:ps.ny+1, ps.nx) |> zero
fx_face = zero(ux_face)
fy_face = zero(uy_face)
fx_interaction = zeros(4, ps.deg + 1, ps.ny, ps.nx + 1)
fy_interaction = zeros(4, ps.deg + 1, ps.ny + 1, ps.nx)
rhs1 = zero(u0)
rhs2 = zero(u0)
end
p = (
fx,
fy,
ux_face,
uy_face,
fx_face,
fy_face,
fx_interaction,
fy_interaction,
rhs1,
rhs2,
ps,
gas,
dt,
)
#u = deepcopy(u0)
#dudt!(du, u, p, 0.0)
prob = ODEProblem(dudt!, u0, tspan, p)
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:100#nt
step!(itg)
end
contourf(ps.xpg[1:nx, 1, 1, 1, 1], ps.xpg[1, 1:ny, 1, 1, 2], itg.u[1, 1, 1, 1:ny, 1:nx])
contourf(ps.xpg[1:nx, 1, 1, 1, 1], ps.xpg[1, 1:ny, 1, 1, 2], itg.u[2, 1, 1, 1:ny, 1:nx])
contourf(ps.xpg[1:nx, 1, 1, 1, 1], ps.xpg[1, 1:ny, 1, 1, 2], itg.u[4, 1, 1, 1:ny, 1:nx])
plot(ps.xpg[1:nx, 1, 1, 1, 1], itg.u[1, 1, 1, ny÷2, 1:nx])
plot(ps.xpg[1:nx, 1, 1, 1, 1], itg.u[2, 1, 1, ny÷2, 1:nx])
plot(ps.xpg[1, 1:ny, 1, 1, 2], itg.u[1, 1, 1, 1:ny, nx÷2])
plot(ps.xpg[1, 1:ny, 1, 1, 2], itg.u[3, 1, 1, 1:ny, nx÷2])
begin
coord = zeros(nx * nsp, ny * nsp, 2)
prim = zeros(nx * nsp, ny * nsp, 4)
for i = 1:nx, j = 1:ny
idx0 = (i - 1) * nsp
idy0 = (j - 1) * nsp
for k = 1:nsp, l = 1:nsp
idx = idx0 + k
idy = idy0 + l
coord[idx, idy, 1] = ps.xpg[i, j, k, l, 1]
coord[idx, idy, 2] = ps.xpg[i, j, k, l, 2]
_w = itg.u[:, l, k, j, i]
prim[idx, idy, :] .= conserve_prim(_w, γ)
prim[idx, idy, 4] = 1 / prim[idx, idy, 4]
end
end
end
contourf(coord[:, 1, 1], coord[1, :, 2], prim[:, :, 2]')
plot(coord[:, 1, 1], prim[:, 1, 1])
plot(coord[:, 1, 1], prim[:, 1, 4])
begin
using PyCall
itp = pyimport("scipy.interpolate")
x_uni =
coord[1, 1, 1]:(coord[end, 1, 1]-coord[1, 1, 1])/(nx*nsp-1):coord[end, 1, 1] |>
collect
y_uni =
coord[1, 1, 2]:(coord[1, end, 2]-coord[1, 1, 2])/(ny*nsp-1):coord[1, end, 2] |>
collect
n_ref = itp.interp2d(coord[:, 1, 1], coord[1, :, 2], prim[:, :, 1], kind = "cubic")
n_uni = n_ref(x_uni, y_uni)
u_ref = itp.interp2d(coord[:, 1, 1], coord[1, :, 2], prim[:, :, 2], kind = "cubic")
u_uni = u_ref(x_uni, y_uni)
v_ref = itp.interp2d(coord[:, 1, 1], coord[1, :, 2], prim[:, :, 3], kind = "cubic")
v_uni = v_ref(x_uni, y_uni)
t_ref = itp.interp2d(coord[:, 1, 1], coord[1, :, 2], prim[:, :, 4], kind = "cubic")
t_uni = t_ref(x_uni, y_uni)
end
contourf(x_uni, y_uni, n_uni')
contourf(x_uni, y_uni, u_uni')
contourf(x_uni, y_uni, t_uni')
plot(x_uni[:, 1], n_uni[:, 1])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 10725 | using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
begin
set = Setup(
case = "shockvortex",
space = "2d0f0v",
flux = "hll",
collision = "nothing",
interpOrder = 3,
limiter = "positivity",
boundary = "fix",
cfl = 0.1,
maxTime = 1.0,
)
ps = FRPSpace2D(0.0, 2.0, 100, 0.0, 1.0, 50, set.interpOrder - 1, 1, 1)
vs = nothing
gas = Gas(Kn = 1e-6, Ma = 1.12, K = 1.0)
ib = nothing
ks = SolverSet(set, ps, vs, gas, ib)
end
function dudt!(du, u, p, t)
du .= 0.0
f,
u_face,
f_face,
fx_interaction,
fy_interaction,
rhs1,
rhs2,
iJ,
ll,
lr,
dhl,
dhr,
lpdm,
γ = p
nx = size(u, 1) - 2
ny = size(u, 2) - 2
nsp = size(u, 3)
@inbounds @threads for l = 1:nsp
for k = 1:nsp, j in axes(f, 2), i in axes(f, 1)
fg, gg = euler_flux(u[i, j, k, l, :], γ)
for s = 1:4
f[i, j, k, l, s, :] .= iJ[i, j][k, l] * [fg[s], gg[s]]
end
end
end
@inbounds @threads for m = 1:4
for l = 1:nsp, j in axes(u_face, 2), i in axes(u_face, 1)
u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)
for n = 1:2
f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
end
end
end
@inbounds @threads for k = 1:nsp
for j = 1:ny, i = 1:nx+1
fw = @view fx_interaction[i, j, k, :]
uL = @view u_face[i-1, j, 2, k, :]
uR = @view u_face[i, j, 4, k, :]
flux_hll!(fw, uL, uR, γ, 1.0)
end
end
@inbounds @threads for k = 1:nsp
for j = 1:ny+1, i = 1:nx
fw = @view fy_interaction[i, j, k, :]
uL = local_frame(u_face[i, j-1, 3, k, :], 0.0, 1.0)
uR = local_frame(u_face[i, j, 1, k, :], 0.0, 1.0)
flux_hll!(fw, uL, uR, γ, 1.0)
fw .= global_frame(fw, 0.0, 1.0)
end
end
@inbounds @threads for m = 1:4
for l = 1:nsp, k = 1:nsp, j = 1:ny, i = 1:nx
rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
end
end
@inbounds @threads for m = 1:4
for l = 1:nsp, k = 1:nsp, j = 1:ny, i = 1:nx
rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
end
end
@inbounds @threads for m = 1:4
for l = 1:nsp, k = 1:nsp, j = 1:ny, i = 1:nx
du[i, j, k, l, m] = -(
rhs1[i, j, k, l, m] +
rhs2[i, j, k, l, m] +
(
fx_interaction[i, j, l, m] * iJ[i, j][k, l][1, 1] -
f_face[i, j, 4, l, m, 1]
) * dhl[k] +
(
fx_interaction[i+1, j, l, m] * iJ[i, j][k, l][1, 1] -
f_face[i, j, 2, l, m, 1]
) * dhr[k] +
(
fy_interaction[i, j, k, m] * iJ[i, j][k, l][2, 2] -
f_face[i, j, 1, k, m, 2]
) * dhl[l] +
(
fy_interaction[i, j+1, k, m] * iJ[i, j][k, l][2, 2] -
f_face[i, j, 3, k, m, 2]
) * dhr[l]
)
end
end
return nothing
end
begin
f = OffsetArray{Float64}(
undef,
0:ks.ps.nx+1,
0:ks.ps.ny+1,
ks.ps.deg + 1,
ks.ps.deg + 1,
4,
2,
)
u_face = OffsetArray{Float64}(undef, 0:ks.ps.nx+1, 0:ks.ps.ny+1, 4, ks.ps.deg + 1, 4)
f_face = OffsetArray{Float64}(undef, 0:ks.ps.nx+1, 0:ks.ps.ny+1, 4, ks.ps.deg + 1, 4, 2)
fx_interaction = zeros(ks.ps.nx + 1, ks.ps.ny, ks.ps.deg + 1, 4)
fy_interaction = zeros(ks.ps.nx, ks.ps.ny + 1, ks.ps.deg + 1, 4)
rhs1 = zeros(ks.ps.nx, ks.ps.ny, ks.ps.deg + 1, ks.ps.deg + 1, 4)
rhs2 = zeros(ks.ps.nx, ks.ps.ny, ks.ps.deg + 1, ks.ps.deg + 1, 4)
end
p = (
f,
u_face,
f_face,
fx_interaction,
fy_interaction,
rhs1,
rhs2,
ps.iJ,
ps.ll,
ps.lr,
ps.dhl,
ps.dhr,
ps.dl,
ks.gas.γ,
)
tspan = (0.0, 0.5)
dt = 0.001
nt = tspan[2] ÷ dt |> Int
# initial condition
u0 = OffsetArray{Float64}(undef, 0:ps.nx+1, 0:ps.ny+1, ps.deg + 1, ps.deg + 1, 4)
for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
t1, t2 = ib_rh(ks.gas.Ma, ks.gas.γ)
if ps.x[i, j] <= ps.x1 * 0.25
prim = [t2[1], t1[2] - t2[2], 0.0, t2[3]]
else
prim = [t1[1], 0.0, 0.0, t1[3]]
s = prim[1]^(1 - ks.gas.γ) / (2 * prim[end])
κ = 0.2
μ = 0.204
rc = 0.05
x0 = 0.8
y0 = 0.5
r = sqrt((ps.xpg[i, j, k, l, 1] - x0)^2 + (ps.xpg[i, j, k, l, 2] - y0)^2)
η = r / rc
δu = κ * η * exp(μ * (1 - η^2)) * (ps.xpg[i, j, k, l, 2] - y0) / r
δv = -κ * η * exp(μ * (1 - η^2)) * (ps.xpg[i, j, k, l, 1] - x0) / r
δT = -(ks.gas.γ - 1) * κ^2 / (8 * μ * ks.gas.γ) * exp(2 * μ * (1 - η^2))
T0 = 1 / prim[end]
ρ = prim[1]^(ks.gas.γ - 1) * (T0 + δT) / T0^(1 / (ks.gas.γ - 1))
prim1 = [ρ, prim[2] + δu, prim[3] + δv, 1 / (1 / prim[4] + δT)]
if r <= rc * 8
prim .= prim1
end
end
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end
# alternative formulation from dsmc shock-vortex interaction paper
#=for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
t1, t2 = ib_rh(ks.gas.Ma, ks.gas.γ)
if ps.x[i, j] <= ps.x1 * 0.25
prim = [t2[1], t1[2] - t2[2], 0.0, t2[3]]
else
prim = [t1[1], 0.0, 0.0, t1[3]]
s = prim[1]^(1 - ks.gas.γ) / (2 * prim[end])
x0 = 1.0
y0 = 0.5
r = sqrt((ps.xpg[i, j, k, l, 1] - x0)^2 + (ps.xpg[i, j, k, l, 2] - y0)^2)
vm = 0.1
r1 = 0.07
r2 = 2 * r1
rset = r1 / (r1^2 - r2^2)
gammaset = (ks.gas.γ - 1) / ks.gas.γ
cst = 0.1#5
rho1 =
(
(ks.gas.γ - 1) / cst / ks.gas.γ *
vm^2 *
rset^2 *
(
(0.5 * r1^2 - 0.5 * r2^4 / r1^2 - 2 * r2^2 * log(r1)) -
(0.5 * r2^2 - 0.5 * r2^4 / r2^2 - 2 * r2^2 * log(r2))
) + 1^(ks.gas.γ - 1)
)^(1 / (ks.gas.γ - 1))
T1 =
1.0 +
2 *
gammaset *
rset^2 *
vm^2 *
(
(0.5 * r1^2 - 0.5 * r2^4 / r1^2 - 2 * r2^2 * log(r1)) -
(0.5 * r2^2 - 0.5 * r2^4 / r2^2 - 2 * r2^2 * log(r2))
)
if r <= r1
vθ = vm * r / r1
elseif r1 < r <= r2
vθ = vm * (r1) / (r1^2 - r2^2) * (r - r2^2 / r)
else
vθ = 0
end
@assert vθ >= 0
cosθ = (ps.xpg[i, j, k, l, 1] - x0) / r
sinθ = (ps.xpg[i, j, k, l, 2] - y0) / r
δu = vθ * sinθ
δv = -vθ * cosθ
prim[2:3] .= [δu, δv]
if r <= r1
prim[1] =
(
((ks.gas.γ - 1) / cst / ks.gas.γ * vm^2 / 2 / r1^2 * (r^2 - r1^2)) +
rho1^(ks.gas.γ - 1)
)^(1 / (ks.gas.γ - 1))
prim[4] = T1 + 2 * gammaset * vm^2 / r1^2 / 2 * (r^2 - r1^2)
prim[4] = 1 / prim[4]
elseif r1 < r <= r2
prim[1] =
(
(ks.gas.γ - 1) / cst / ks.gas.γ *
vm^2 *
rset^2 *
(
(0.5 * r^2 - 0.5 * r2^4 / r^2 - 2 * r2^2 * log(r)) -
(0.5 * r2^2 - 0.5 * r2^4 / r2^2 - 2 * r2^2 * log(r2))
) + 1^(ks.gas.γ - 1)
)^(1 / (ks.gas.γ - 1))
prim[4] =
1.0 +
2 *
gammaset *
rset^2 *
vm^2 *
(
(0.5 * r^2 - 0.5 * r2^4 / r^2 - 2 * r2^2 * log(r)) -
(0.5 * r2^2 - 0.5 * r2^4 / r2^2 - 2 * r2^2 * log(r2))
)
prim[4] = 1 / prim[4]
end
end
u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
end=#
prob = ODEProblem(dudt!, u0, tspan, p)
itg = init(prob, Midpoint(), save_everystep = false, adaptive = false, dt = dt)
@showprogress for iter = 1:100#nt
# limiter
@inbounds @threads for j = 1:ps.ny
for i = 1:ps.nx
ũ = @view itg.u[i, j, :, :, :]
positive_limiter(ũ, ks.gas.γ, ps.wp ./ 4, ps.ll, ps.lr)
end
end
step!(itg)
# filter
for i in axes(itg.u, 1), j in axes(itg.u, 2)
û = ps.iV * itg.u[i, j, 1:3, 1:3, 1][:]
su = û[end]^2 / sum(û .^ 2)
isShock = shock_detector(log10(su), ps.deg, -3.0 * log10(ps.deg), 9)
if isShock
for s = 1:4
û = ps.iV * itg.u[i, j, 1:3, 1:3, s][:]
FR.modal_filter!(û, 5e-4; filter = :l2)
uNode = reshape(ps.V * û, 3, 3)
itg.u[i, j, :, :, s] .= uNode
end
end
end
# boundary
itg.u[:, 0, :, :, :] .= itg.u[:, 1, :, :, :]
itg.u[:, ps.ny+1, :, :, :] .= itg.u[:, ps.ny, :, :, :]
itg.u[ps.nx+1, :, :, :, :] .= itg.u[ps.nx, :, :, :, :]
#itg.u[:, 0, :, 1:end, :] .= itg.u[:, 1, :, end:-1:1, :]
#itg.u[:, ps.ny+1, :, 1:end, :] .= itg.u[:, ps.ny, :, end:-1:1, :]
#itg.u[:, 0, :, 1:end, 3] .*= -1
#itg.u[:, ps.ny+1, :, end:-1:1, 3] .*= -1
end
begin
x = zeros(ps.nx * (ps.deg + 1), ps.ny * (ps.deg + 1))
y = zeros(ps.nx * (ps.deg + 1), ps.ny * (ps.deg + 1))
sol = zeros(ps.nx * (ps.deg + 1), ps.ny * (ps.deg + 1), 4)
for i = 1:ps.nx, j = 1:ps.ny
idx0 = (i - 1) * (ps.deg + 1)
idy0 = (j - 1) * (ps.deg + 1)
for k = 1:ps.deg+1, l = 1:ps.deg+1
idx = idx0 + k
idy = idy0 + l
x[idx, idy] = ps.xpg[i, j, k, l, 1]
y[idx, idy] = ps.xpg[i, j, k, l, 2]
sol[idx, idy, :] .= conserve_prim(itg.u[i, j, k, l, :], ks.gas.γ)
sol[idx, idy, 4] = 1 / sol[idx, idy, 4]
end
end
end
contourf(x[:, 1], y[1, :], sol[:, :, 1]', aspect_ratio = 1, legend = true)
plot(x[:, 1], sol[:, end÷2+1, 1])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 587 | using FluxReconstruction, Test
ps = FRPSpace1D(0, 1, 100, 2)
#--- values ---#
V = vandermonde_matrix(ps.deg, ps.xpl)
ψf = vandermonde_matrix(ps.deg, [-1.0, 1.0])
lf = zeros(2, ps.deg + 1)
for i in axes(lf, 1)
lf[i, :] .= V' \ ψf[i, :]
end
@test lf[1, :] ≈ ps.ll
@test lf[2, :] ≈ ps.lr
#--- derivatives ---#
Vr = ∂vandermonde_matrix(ps.deg, ps.xpl)
∂l = zeros(ps.deg + 1, ps.deg + 1)
for i = 1:ps.deg+1
∂l[i, :] .= V' \ Vr[i, :]
end
@test ∂l ≈ ps.dl
dVf = ∂vandermonde_matrix(ps.deg, [-1.0, 1.0])
∂lf = zeros(2, ps.deg + 1)
for i = 1:2
∂lf[i, :] .= V' \ dVf[i, :]
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1502 | module FluxReconstruction
const FR = FluxReconstruction
using Base.Threads: @threads
using CUDA
using GSL
using LinearAlgebra
using NonlinearSolve
using OrdinaryDiffEq
using PyCall
using KitBase
using KitBase: AV, AM, AA, advection_flux
using KitBase.FastGaussQuadrature
using KitBase.FiniteMesh.DocStringExtensions
using KitBase.OffsetArrays
using KitBase.SpecialFunctions
export FR
export AbstractElementShape,
Line,
Quad,
Tri,
Hex,
Wed,
Pyr,
Tet
export shock_detector,
positive_limiter
export legendre_point,
lagrange_point,
∂legendre,
∂radau,
∂sd,
∂huynh,
∂lagrange,
standard_lagrange,
simplex_basis,
∂simplex_basis,
vandermonde_matrix,
∂vandermonde_matrix,
correction_field,
JacobiP,
∂JacobiP
export tri_quadrature, triface_quadrature
export FRPSpace1D,
FRPSpace2D,
UnstructFRPSpace,
TriFRPSpace,
global_sp,
global_fp,
rs_ab,
xy_rs,
rs_xy,
rs_jacobi,
neighbor_fpidx
export interp_face!
export poly_derivative!
export FREulerProblem
include("data.jl")
include("dissipation.jl")
include("Polynomial/polynomial.jl")
include("Transform/transform.jl")
include("Quadrature/quadrature.jl")
include("struct.jl")
include("Geometry/geometry.jl")
include("tools.jl")
include("interpolate.jl")
include("derivative.jl")
include("Equation/equation.jl")
include("integrator.jl")
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 407 | const AbstractTensor3{T} = AbstractArray{T,3}
const AbstractTensor5{T} = AbstractArray{T,5}
abstract type AbstractElementShape end
struct Line <: AbstractElementShape end
struct Quad <: AbstractElementShape end
struct Tri <: AbstractElementShape end
struct Hex <: AbstractElementShape end
struct Wed <: AbstractElementShape end
struct Pyr <: AbstractElementShape end
struct Tet <: AbstractElementShape end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 222 | function poly_derivative!(
df::T1,
f::T1,
pdm::T2,
) where {T1<:AbstractVector,T2<:AbstractMatrix}
@assert length(f) == size(pdm, 1)
for i in eachindex(df)
df[i] = dot(f, pdm[i, :])
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 6349 | """
$(SIGNATURES)
Detect if the solution belongs to a strong discontinuity
_P. O. Persson and J. Peraire. Sub-cell shock capturing for discontinuous Galerkin methods. 44th AIAA Aerospace Sciences Meeting and Exhibit, 2006._
- @arg Se = log10(<(u - û)²>/<u²>), u is the solution based on orthogonal polynomials, and û is the same solution with one lower truncated order
- @arg deg: polynomial degree of freedom
- @arg S0: reference point of Se
- @arg κ: empirical parameter that needs to be chosen sufficiently large so as to obtain a sharp but smooth shock profile
"""
function shock_detector(Se, deg, S0 = -3.0 * log10(deg), κ = 4.0)
if Se < S0 - κ
σ = 1.0
elseif S0 - κ <= Se < S0 + κ
σ = 0.5 * (1.0 - sin(0.5 * π * (Se - S0) / κ))
else
σ = 0.0
end
return σ < 0.99 ? true : false
end
"""
$(SIGNATURES)
Slope limiter to preserve positivity
_R. Vandenhoeck and A. Lani. Implicit high-order flux reconstruction solver for high-speed compressible flows. Computer Physics Communications 242: 1-24, 2019."_
- @arg u: conservative variables with solution points in dim1 and states in dim2
- @arg γ: specific heat ratio
- @arg weights: quadrature weights for computing mean value
- @arg ll&lr: Langrange polynomials at left/right edge
- @arg t0=1.0: minimum limiting slope
"""
function positive_limiter(
u::AbstractVector{T},
weights,
ll,
lr,
t0 = 1.0,
) where {T<:AbstractFloat}
um = sum(u .* weights) / sum(weights)
ub = [dot(u, ll), dot(u, lr)]
ϵ = min(1e-13, um)
θ = min(minimum(ub), minimum(u))
t = min((um - ϵ) / (um - θ + 1e-8), 1.0)
@assert 0 < t <= 1 "incorrect range of limiter parameter t"
for i in axes(u, 1)
u[i] = t * (u[i] - um) + um
end
return nothing
end
function positive_limiter(
u::AbstractMatrix{T},
γ,
weights,
ll,
lr,
t0 = 1.0,
) where {T<:AbstractFloat}
# mean values
u_mean = [sum(u[:, j] .* weights) for j in axes(u, 2)]
t_mean = 1.0 / conserve_prim(u_mean, γ)[end]
p_mean = 0.5 * u_mean[1] * t_mean
# boundary values
ρb = [dot(u[:, 1], ll), dot(u[:, 1], lr)]
mb = [dot(u[:, 2], ll), dot(u[:, 2], lr)]
eb = [dot(u[:, 3], ll), dot(u[:, 3], lr)]
# density corrector
ϵ = min(1e-13, u_mean[1], p_mean)
ρ_min = min(minimum(ρb), minimum(u[:, 1])) # density minumum can emerge at both solution and flux points
t1 = min((u_mean[1] - ϵ) / (u_mean[1] - ρ_min + 1e-8), 1.0)
@assert 0 < t1 <= 1 "incorrect range of limiter parameter t"
for i in axes(u, 1)
u[i, 1] = t1 * (u[i, 1] - u_mean[1]) + u_mean[1]
end
# energy corrector
tj = Float64[]
for i = 1:2 # flux points
prim = conserve_prim([ρb[i], mb[i], eb[i]], γ)
if prim[end] < ϵ
prob = NonlinearProblem{false}(
tj_equation,
1.0,
([ρb[i], mb[i], eb[i]], u_mean, γ, ϵ),
)
sol = solve(prob, NewtonRaphson(), tol = 1e-9)
push!(tj, sol.u)
end
end
for i in axes(u, 1) # solution points
prim = conserve_prim(u[i, :], γ)
if prim[end] < ϵ
prob = NonlinearProblem{false}(tj_equation, 1.0, (u[i, :], u_mean, γ, ϵ))
sol = solve(prob, NewtonRaphson(), tol = 1e-9)
push!(tj, sol.u)
end
end
if length(tj) > 0
t2 = minimum(tj, t0)
for j in axes(u, 2), i in axes(u, 1)
u[i, j] = t2 * (u[i, j] - u_mean[j]) + u_mean[j]
end
end
return nothing
end
function positive_limiter(
u::AbstractArray{T,3},
γ,
weights,
ll,
lr,
t0 = 1.0,
) where {T<:AbstractFloat}
# mean values
u_mean = [sum(u[:, :, j] .* weights) for j in axes(u, 2)]
t_mean = 1.0 / conserve_prim(u_mean, γ)[end]
p_mean = 0.5 * u_mean[1] * t_mean
# boundary values
ρb = zeros(4, length(ll))
mxb = zeros(4, length(ll))
myb = zeros(4, length(ll))
eb = zeros(4, length(ll))
for j in axes(ρb, 2)
ρb[1, j] = dot(u[j, :, 1], ll)
ρb[2, j] = dot(u[:, j, 1], lr)
ρb[3, j] = dot(u[j, :, 1], lr)
ρb[4, j] = dot(u[:, j, 1], ll)
mxb[1, j] = dot(u[j, :, 2], ll)
mxb[2, j] = dot(u[:, j, 2], lr)
mxb[3, j] = dot(u[j, :, 2], lr)
mxb[4, j] = dot(u[:, j, 2], ll)
myb[1, j] = dot(u[j, :, 3], ll)
myb[2, j] = dot(u[:, j, 3], lr)
myb[3, j] = dot(u[j, :, 3], lr)
myb[4, j] = dot(u[:, j, 3], ll)
eb[1, j] = dot(u[j, :, 4], ll)
eb[2, j] = dot(u[:, j, 4], lr)
eb[3, j] = dot(u[j, :, 4], lr)
eb[4, j] = dot(u[:, j, 4], ll)
end
# density corrector
ϵ = min(1e-13, u_mean[1], p_mean)
ρ_min = min(minimum(ρb), minimum(u[:, :, 1])) # density minumum can emerge at both solution and flux points
t1 = min((u_mean[1] - ϵ) / (u_mean[1] - ρ_min + 1e-8), 1.0)
@assert 0 < t1 <= 1 "incorrect range of limiter parameter t"
for j in axes(u, 2), i in axes(u, 1)
u[i, j, 1] = t1 * (u[i, j, 1] - u_mean[1]) + u_mean[1]
end
# energy corrector
tj = Float64[]
for j = 1:length(ll), i = 1:4
prim = conserve_prim([ρb[i, j], mxb[i, j], myb[i, j], eb[i, j]], γ)
if prim[end] < ϵ
prob = NonlinearProblem{false}(
tj_equation,
1.0,
([ρb[i, j], mxb[i, j], myb[i, j], eb[i, j]], u_mean, γ, ϵ),
)
sol = solve(prob, NewtonRaphson(), tol = 1e-9)
push!(tj, sol.u)
end
end
for j in axes(u, 2), i in axes(u, 1) # solution points
prim = conserve_prim(u[i, j, :], γ)
if prim[end] < ϵ
prob = NonlinearProblem{false}(tj_equation, 1.0, (u[i, j, :], u_mean, γ, ϵ))
sol = solve(prob, NewtonRaphson(), tol = 1e-9)
push!(tj, sol.u)
end
end
if length(tj) > 0
t2 = minimum(tj, t0)
for k in axes(u, 3), j in axes(u, 2), i in axes(u, 1)
u[i, j, k] = t2 * (u[i, j, k] - u_mean[k]) + u_mean[k]
end
end
return nothing
end
function tj_equation(t, p)
ũ, u_mean, γ, ϵ = p
u_temp = [t * (ũ[i] - u_mean[i]) + u_mean[i] for i in eachindex(u_mean)]
prim_temp = conserve_prim(u_temp, γ)
return 0.5 * prim_temp[1] / prim_temp[end] - ϵ
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 171 | function integrator(dudt::Function, u0, tspan, p, solver, args...; kwargs...)
prob = ODEProblem(dudt, u0, tspan, p)
return init(prob, alg, args...; kwargs...)
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 328 | function interp_face!(fδ, f::T, ll::T1, lr::T1) where {T<:AbstractVector,T1<:AbstractVector}
fδ[1] = dot(f, ll)
fδ[2] = dot(f, lr)
end
function interp_face!(fδ, f::T, ll::T1, lr::T1) where {T<:AbstractMatrix,T1<:AbstractVector}
@views for i in axes(f, 1)
interp_face!(fδ[i, :], f[i, :], ll, lr)
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 7899 | abstract type AbstractStructFRSpace <: KitBase.AbstractStructPhysicalSpace end
abstract type AbstractUnstructFRSpace <: KitBase.AbstractUnstructPhysicalSpace end
"""
$(TYPEDEF)
1D physical space for flux reconstruction method
# Fields
$(FIELDS)
"""
struct FRPSpace1D{
A,
I<:Integer,
B<:AbstractVector{<:AbstractFloat},
C<:AbstractMatrix{<:AbstractFloat},
} <: AbstractStructFRSpace
base::A
deg::I
J::B
np::I
xpl::B
xpg::C
wp::B
dl::C
ll::B
lr::B
dll::B
dlr::B
dhl::B
dhr::B
V::C
iV::C
end
function FRPSpace1D(x0, x1, nx::Integer, deg::Integer, ng = 0::Integer, correction = :radau)
ps = PSpace1D(x0, x1, nx, ng)
J = [ps.dx[i] / 2 for i in eachindex(ps.dx)]
r = legendre_point(deg) .|> eltype(ps.x)
xi = push!(ps.x - 0.5 * ps.dx, ps.x[end] + 0.5 * ps.dx[end]) .|> eltype(ps.x)
xp = global_sp(xi, r)
wp = gausslegendre(deg + 1)[2]
ll = lagrange_point(r, -1.0)
lr = lagrange_point(r, 1.0)
lpdm = ∂lagrange(r)
V = vandermonde_matrix(deg, r) |> Array
iV = inv(V)
dVf = ∂vandermonde_matrix(deg, [-1.0, 1.0])
∂lf = zeros(2, deg + 1)
for i = 1:2
∂lf[i, :] .= V' \ dVf[i, :]
end
dll = ∂lf[1, :]
dlr = ∂lf[2, :]
fc = eval(Symbol("∂" * String(correction)))
dhl, dhr = fc(deg, r)
#dhl, dhr = ∂radau(deg, r)
return FRPSpace1D{typeof(ps),typeof(deg),typeof(J),typeof(xp)}(
ps,
deg,
J,
deg + 1,
r,
xp,
wp,
lpdm,
ll,
lr,
dll,
dlr,
dhl,
dhr,
V,
iV,
)
end
FRPSpace1D(; x0, x1, nx, deg, ng = 0, correction = :radau, kwargs...) =
FRPSpace1D(x0, x1, nx, deg, ng, correction)
"""
$(TYPEDEF)
2D physical space for flux reconstruction method
# Fields
$(FIELDS)
"""
struct FRPSpace2D{
A,
I<:Integer,
B,
C<:AbstractVector{<:AbstractFloat},
D<:AbstractArray{<:AbstractFloat,5},
E<:AbstractMatrix{<:AbstractFloat},
} <: AbstractStructFRSpace
base::A
deg::I
J::B
iJ::B
Ji::B
np::I
xpl::C
xpg::D
wp::E
dl::E
ll::C
lr::C
dll::C
dlr::C
dhl::C
dhr::C
V::E
iV::E
end
function FRPSpace2D(base::AbstractPhysicalSpace2D, deg::Integer)
# solution points in 1D standard element
r = legendre_point(deg) .|> eltype(base.x)
# Jacobian and its inverse
J = rs_jacobi(r, base.vertices)
iJ = deepcopy(J)
for i in axes(iJ, 1), j in axes(iJ, 2)
for k = 1:deg+1, l = 1:deg+1
iJ[i, j][k, l] .= inv(J[i, j][k, l])
end
end
# interface flux points
ri = zeros(eltype(base.x), 4, deg + 1)
ri[1, :] .= r
ri[2, :] .= 1.0
ri[3, :] .= r[end:-1:1]
ri[4, :] .= 0.0
si = zeros(eltype(base.x), 4, deg + 1)
si[1, :] .= 0.0
si[2, :] .= r
si[3, :] .= 1.0
si[4, :] .= r[end:-1:1]
# Jacobian of flux points
Ji = rs_jacobi(ri, si, base.vertices)
# solution points in global coordinates
xpg = OffsetArray{eltype(base.x)}(
undef,
axes(base.x, 1),
axes(base.y, 2),
1:deg+1,
1:deg+1,
1:2,
)
for i in axes(xpg, 1), j in axes(xpg, 2), k = 1:deg+1, l = 1:deg+1
@. xpg[i, j, k, l, :] =
(r[k] - 1.0) * (r[l] - 1.0) / 4 * base.vertices[i, j, 1, :] +
(r[k] + 1.0) * (1.0 - r[l]) / 4 * base.vertices[i, j, 2, :] +
(r[k] + 1.0) * (r[l] + 1.0) / 4 * base.vertices[i, j, 3, :] +
(1.0 - r[k]) * (r[l] + 1.0) / 4 * base.vertices[i, j, 4, :]
end
# quadrature weights
w = gausslegendre(deg + 1)[2] .|> eltype(base.x)
wp = [w[i] * w[j] for i = 1:deg+1, j = 1:deg+1]
# Lagrange polynomials
ll, lr, lpdm = standard_lagrange(r)
V = vandermonde_matrix(deg, r)
dVf = ∂vandermonde_matrix(deg, [-1.0, 1.0])
∂lf = zeros(eltype(base.x), 2, deg + 1)
for i = 1:2
∂lf[i, :] .= V' \ dVf[i, :]
end
dll = ∂lf[1, :]
dlr = ∂lf[2, :]
dhl, dhr = ∂radau(deg, r)
# 2D Vandermonde matrix
r2d = zeros(eltype(r), length(r), length(r))
for j in axes(r2d, 2)
r2d[:, j] .= r
end
s2d = deepcopy(r2d)
for i in axes(s2d, 1)
s2d[i, :] .= r
end
V = vandermonde_matrix(Quad, deg, r2d[:], s2d[:])
iV = inv(V)
return FRPSpace2D{typeof(base),typeof(deg),typeof(J),typeof(r),typeof(xpg),typeof(wp)}(
base,
deg,
J,
iJ,
Ji,
(deg + 1)^2,
r,
xpg,
wp,
lpdm,
ll,
lr,
dll,
dlr,
dhl,
dhr,
V,
iV,
)
end
function FRPSpace2D(
x0::Real,
x1::Real,
nx::Integer,
y0::Real,
y1::Real,
ny::Integer,
deg::Integer,
ngx = 0::Integer,
ngy = 0::Integer,
)
ps = PSpace2D(x0, x1, nx, y0, y1, ny, ngx, ngy)
return FRPSpace2D(ps, deg)
end
FRPSpace2D(; x0, x1, nx, y0, y1, ny, deg, ngx = 0, ngy = 0, kwargs...) =
FRPSpace2D(x0, x1, nx, y0, y1, ny, deg, ngx, ngy)
"""
$(TYPEDEF)
Unstructued physical space for flux reconstruction method
# Fields
$(FIELDS)
"""
struct UnstructFRPSpace{
A,
H,
G<:Integer,
B<:AbstractMatrix{<:AbstractFloat},
F<:AbstractArray{<:AbstractFloat,3},
E<:AbstractVector{<:AbstractFloat},
I<:AbstractArray{<:AbstractFloat,4},
J,
} <: AbstractUnstructFRSpace
#--- general ---#
base::A # basic unstructured mesh info that contains:
#=
cells::A # all information: cell, line, vertex
points::B # locations of vertex points
cellid::C # node indices of elements
cellType::D # inner/boundary cell
cellNeighbors::C # neighboring cells id
cellFaces::C # cell edges id
cellCenter::B # cell center location
cellArea::E # cell size
cellNormals::F # cell unit normal vectors
facePoints::C # ids of two points at edge
faceCells::C # ids of two cells around edge
faceCenter::B # edge center location
faceType::D # inner/boundary face
faceArea::E # face area
=#
#--- FR specific ---#
J::H # Jacobi
deg::G # polynomial degree
np::G # number of solution points
xpl::B # local coordinates of solution points
xpg::F # global coordinates of solution points
wp::E # weights of solution points
xfl::F # local coordinates of flux points
xfg::I # global coordinates of flux points
wf::B # weights of flux points
V::B # Vandermonde matrix
ψf::F # Vandermonde matrix along faces
Vr::B # ∂V/∂r
Vs::B # ∂V/∂s
∂l::F # ∇l
lf::F # Lagrange polynomials along faces
ϕ::F # correction field
fpn::J # adjacent flux points index in neighbor cell
end
function TriFRPSpace(file::T, deg::Integer) where {T<:AbstractString}
ps = UnstructPSpace(file)
J = rs_jacobi(ps.cellid, ps.points)
np = (deg + 1) * (deg + 2) ÷ 2
xpl, wp = tri_quadrature(deg)
V = vandermonde_matrix(Tri, deg, xpl[:, 1], xpl[:, 2])
Vr, Vs = ∂vandermonde_matrix(Tri, deg, xpl[:, 1], xpl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
ϕ = correction_field(deg, V)
xfl, wf = triface_quadrature(deg)
ψf = zeros(3, deg + 1, np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(Tri, deg, xfl[i, :, 1], xfl[i, :, 2])
end
lf = zeros(3, deg + 1, np)
for i = 1:3, j = 1:deg+1
lf[i, j, :] .= V' \ ψf[i, j, :]
end
xpg = global_sp(ps.points, ps.cellid, deg)
xfg = global_fp(ps.points, ps.cellid, deg)
ncell = size(ps.cellid, 1)
fpn = [neighbor_fpidx([i, j, k], ps, xfg) for i = 1:ncell, j = 1:3, k = 1:deg+1]
return UnstructFRPSpace(
ps,
J,
deg,
np,
xpl,
xpg,
wp,
xfl,
xfg,
wf,
V,
ψf,
Vr,
Vs,
∂l,
lf,
ϕ,
fpn,
)
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1587 | # ------------------------------------------------------------
# Mimic inheritance of common fields
# ------------------------------------------------------------
function Base.getproperty(x::AbstractStructFRSpace, name::Symbol)
options =
union(fieldnames(PSpace1D), fieldnames(PSpace2D), fieldnames(KitBase.CSpace2D))
if name in options
return getfield(x.base, name)
else
return getfield(x, name)
end
end
function Base.getproperty(x::AbstractUnstructFRSpace, name::Symbol)
if name in fieldnames(UnstructPSpace)
return getfield(x.base, name)
else
return getfield(x, name)
end
end
function Base.propertynames(x::AbstractStructFRSpace, private::Bool = false)
public = fieldnames(typeof(x))
true ?
(
(
public ∪
union(fieldnames(PSpace1D), fieldnames(PSpace2D), fieldnames(KitBase.CSpace2D))
)...,
) : public
end
function Base.propertynames(x::AbstractUnstructFRSpace, private::Bool = false)
public = fieldnames(typeof(x))
true ? ((public ∪ fieldnames(UnstructPSpace))...,) : public
end
# ------------------------------------------------------------
# Accuracy analysis
# ------------------------------------------------------------
function L1_error(u::T, ue::T, Δx) where {T<:AbstractArray}
return sum(abs.(u .- ue) .* Δx)
end
function L2_error(u::T, ue::T, Δx) where {T<:AbstractArray}
return sqrt(sum((abs.(u .- ue) .* Δx) .^ 2))
end
function L∞_error(u::T, ue::T, Δx) where {T<:AbstractArray}
return maximum(abs.(u .- ue) .* Δx)
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 4576 | function FRAdvectionProblem(u::Matrix, tspan, ps::AbstractStructFRSpace, a, bc::Symbol)
f = zero(u)
rhs = zero(u)
ncell = size(u, 1)
u_face = zeros(eltype(u), ncell, 2)
f_face = zeros(eltype(u), ncell, 2)
f_interaction = zeros(eltype(u), ncell + 1)
p = (
f,
u_face,
f_face,
f_interaction,
rhs,
ps.J,
ps.ll,
ps.lr,
ps.dl,
ps.dhl,
ps.dhr,
a,
bc,
)
return ODEProblem(frode_advection!, u, tspan, p)
end
function FRAdvectionProblem(u::CuMatrix, tspan, ps::AbstractStructFRSpace, a, bc::Symbol)
f = zero(u)
rhs = zero(u)
ncell = size(u, 1)
u_face = zeros(eltype(u), ncell, 2) |> CuArray
f_face = zeros(eltype(u), ncell, 2) |> CuArray
f_interaction = zeros(eltype(u), ncell + 1) |> CuArray
p = (
f,
u_face,
f_face,
f_interaction,
rhs,
ps.J |> CuArray,
ps.ll |> CuArray,
ps.lr |> CuArray,
ps.dl |> CuArray,
ps.dhl |> CuArray,
ps.dhr |> CuArray,
a,
bc,
)
return ODEProblem(frode_advection!, u, tspan, p)
end
function frode_advection!(du::Matrix, u, p, t)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, a, bc = p
ncell = size(u, 1)
nsp = size(u, 2)
advection_dflux!(f, u, a, J)
u_face .= hcat(u * ll, u * lr)
f_face .= hcat(f * ll, f * lr)
advection_iflux!(f_interaction, f_face, u_face)
rhs1 .= f * lpdm'
scalar_rhs!(du, rhs1, f_face, f_interaction, dgl, dgr)
bs = string(bc) * "_advection!"
bf = Symbol(bs) |> eval
bf(du, u, p)
return nothing
end
function frode_advection!(du, u, p, t)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, a, bc = p
ncell = size(u, 1)
nsp = size(u, 2)
@cuda advection_dflux!(f, u, a, J)
u_face .= hcat(u * ll, u * lr)
f_face .= hcat(f * ll, f * lr)
@cuda advection_iflux!(f_interaction, f_face, u_face)
rhs1 .= f * lpdm'
@cuda scalar_rhs!(du, rhs1, f_face, f_interaction, dgl, dgr)
bs = string(bc) * "_advection!"
bf = Symbol(bs) |> eval
CUDA.@allowscalar bf(du, u, p)
return nothing
end
function advection_dflux!(f::Array, u, a, J)
@threads for j in axes(f, 2)
for i in axes(f, 1)
@inbounds f[i, j] = advection_flux(u[i, j], a) / J[i]
end
end
return nothing
end
function advection_dflux!(f, u, a, J)
idx = (blockIdx().x - 1) * blockDim().x + threadIdx().x
idy = (blockIdx().y - 1) * blockDim().y + threadIdx().y
strx = blockDim().x * gridDim().x
stry = blockDim().y * gridDim().y
for j = idy:stry:size(u, 2)
for i = idx:strx:size(u, 1)
@inbounds f[i, j] = advection_flux(u[i, j], a) / J[i]
end
end
return nothing
end
function advection_iflux!(f_interaction::Array, f_face, u_face)
@inbounds @threads for i = 2:length(f_interaction)-1
au = (f_face[i, 1] - f_face[i-1, 2]) / (u_face[i, 1] - u_face[i-1, 2] + 1e-8)
f_interaction[i] = (
0.5 * (f_face[i, 1] + f_face[i-1, 2]) -
0.5 * abs(au) * (u_face[i, 1] - u_face[i-1, 2])
)
end
return nothing
end
function advection_iflux!(f_interaction, f_face, u_face)
idx = (blockIdx().x - 1) * blockDim().x + threadIdx().x
strx = blockDim().x * gridDim().x
@inbounds for i = idx+1:strx:length(f_interaction)-1
au = (f_face[i, 1] - f_face[i-1, 2]) / (u_face[i, 1] - u_face[i-1, 2] + 1e-8)
f_interaction[i] = (
0.5 * (f_face[i, 1] + f_face[i-1, 2]) -
0.5 * abs(au) * (u_face[i, 1] - u_face[i-1, 2])
)
end
return nothing
end
function dirichlet_advection!(du::AbstractMatrix, u, p)
du[1, :] .= 0.0
du[end, :] .= 0.0
end
function period_advection!(du::AbstractMatrix, u, p)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, a = p
ncell, nsp = size(u)
au = (f_face[1, 1] - f_face[ncell, 2]) / (u_face[1, 1] - u_face[ncell, 2] + 1e-6)
f_interaction[1] = (
0.5 * (f_face[ncell, 2] + f_face[1, 1]) -
0.5 * abs(au) * (u_face[1, 1] - u_face[ncell, 2])
)
f_interaction[end] = f_interaction[1]
for ppp1 = 1:nsp
for i in [1, ncell]
@inbounds du[i, ppp1] = -(
rhs1[i, ppp1] +
(f_interaction[i] - f_face[i, 1]) * dgl[ppp1] +
(f_interaction[i+1] - f_face[i, 2]) * dgr[ppp1]
)
end
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1807 | function bgk!(du, u, p, t)
dx, e2f, f2e, velo, weights, δ, deg, ll, lr, lpdm, dgl, dgr = p
ncell = size(u, 1)
nu = size(u, 2)
nsp = size(u, 3)
M = similar(u, ncell, nu, nsp)
for i = 1:ncell, k = 1:nsp
w = moments_conserve(u[i, :, k], velo, weights)
prim = conserve_prim(w, 3.0)
M[i, :, k] .= maxwellian(velo, prim)
end
τ = 1e-2
f = similar(u)
for i = 1:ncell, j = 1:nu, k = 1:nsp
J = 0.5 * dx[i]
f[i, j, k] = velo[j] * u[i, j, k] / J
end
f_face = zeros(eltype(u), ncell, nu, 2)
#=for i = 1:ncell, j = 1:nu, k = 1:nsp
# right face of element i
f_face[i, j, 1] += f[i, j, k] * lr[k]
# left face of element i
f_face[i, j, 2] += f[i, j, k] * ll[k]
end=#
@views for i = 1:ncell, j = 1:nu
FluxRC.interp_interface!(f_face[i, j, :], f[i, j, :], ll, lr)
end
f_interaction = similar(u, nface, nu)
for i = 1:nface
@. f_interaction[i, :] =
f_face[f2e[i, 1], :, 1] * (1.0 - δ) + f_face[f2e[i, 2], :, 2] * δ
end
rhs1 = zeros(eltype(u), ncell, nu, nsp)
#for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp, k = 1:nsp
# rhs1[i, j, ppp1] += f[i, j, k] * lpdm[ppp1, k]
#end
@views for i = 1:ncell, j = 1:nu
FluxRC.poly_derivative!(rhs1[i, j, :], f[i, j, :], lpdm)
end
#@views for i = 1:ncell, j = 1:nu, k = 1:nsp
# rhs1[i, j, k] = dot(f[i, j, :], lpdm[k, :])
#end
for i = 1:ncell, j = 1:nu, ppp1 = 1:nsp
du[i, j, ppp1] =
-(
rhs1[i, j, ppp1] +
(f_interaction[e2f[i, 2], j] - f_face[i, j, 1]) * dgl[ppp1] +
(f_interaction[e2f[i, 1], j] - f_face[i, j, 2]) * dgr[ppp1]
) + (M[i, j, ppp1] - u[i, j, ppp1]) / τ
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2617 | function FREulerProblem(u::AbstractTensor3, tspan, ps::AbstractStructFRSpace, γ, bc::Symbol)
f = zero(u)
rhs = zero(u)
ncell = size(u, 1)
u_face = zeros(ncell, 2, 3)
f_face = zeros(ncell, 2, 3)
f_interaction = zeros(ncell + 1, 3)
p = (
f,
u_face,
f_face,
f_interaction,
rhs,
ps.J,
ps.ll,
ps.lr,
ps.dl,
ps.dhl,
ps.dhr,
γ,
bc,
)
return ODEProblem(frode_euler!, u, tspan, p)
end
function frode_euler!(du::AbstractTensor3, u, p, t)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, γ, bc = p
ncell = size(u, 1)
nsp = size(u, 2)
@inbounds @threads for j = 1:nsp
for i = 1:ncell
f[i, j, :] .= euler_flux(u[i, j, :], γ)[1] ./ J[i]
end
end
@inbounds @threads for j = 1:3
# left face of element i
u_face[:, 1, j] .= u[:, :, j] * ll
f_face[:, 1, j] .= f[:, :, j] * ll
# right face of element i
u_face[:, 2, j] .= u[:, :, j] * lr
f_face[:, 2, j] .= f[:, :, j] * lr
end
@inbounds @threads for i = 2:ncell
fw = @view f_interaction[i, :]
flux_hll!(fw, u_face[i-1, 2, :], u_face[i, 1, :], γ, 1.0)
end
@inbounds @threads for k = 1:3
rhs1[:, :, k] .= f[:, :, k] * lpdm'
end
@inbounds @threads for i = 2:ncell-1
for ppp1 = 1:nsp, k = 1:3
du[i, ppp1, k] = -(
rhs1[i, ppp1, k] +
(f_interaction[i, k] / J[i] - f_face[i, 1, k]) * dgl[ppp1] +
(f_interaction[i+1, k] / J[i] - f_face[i, 2, k]) * dgr[ppp1]
)
end
end
bs = string(bc) * "_euler!"
bf = Symbol(bs) |> eval
bf(du, u, p)
return nothing
end
function dirichlet_euler!(du::AbstractTensor3, u, p)
du[1, :, :] .= 0.0
du[end, :, :] .= 0.0
end
function period_euler!(du::AbstractTensor3, u, p)
f, u_face, f_face, f_interaction, rhs1, J, ll, lr, lpdm, dgl, dgr, γ, bc = p
ncell = size(u, 1)
nsp = size(u, 2)
fw = @view f_interaction[1, :]
flux_hll!(fw, u_face[ncell, 2, :], u_face[1, 1, :], γ, 1.0)
fw = @view f_interaction[ncell+1, :]
flux_hll!(fw, u_face[ncell, 2, :], u_face[1, 1, :], γ, 1.0)
@inbounds for i in [1, ncell]
for ppp1 = 1:nsp, k = 1:3
du[i, ppp1, k] = -(
rhs1[i, ppp1, k] +
(f_interaction[i, k] / J[i] - f_face[i, 1, k]) * dgl[ppp1] +
(f_interaction[i+1, k] / J[i] - f_face[i, 2, k]) * dgr[ppp1]
)
end
end
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1043 | function scalar_rhs!(du::AbstractMatrix, rhs1, f_face, f_interaction, dgl, dgr)
ncell, nsp = size(du)
@threads for ppp1 = 1:nsp
for i = 2:ncell-1
@inbounds du[i, ppp1] = -(
rhs1[i, ppp1] +
(f_interaction[i] - f_face[i, 1]) * dgl[ppp1] +
(f_interaction[i+1] - f_face[i, 2]) * dgr[ppp1]
)
end
end
return nothing
end
function scalar_rhs!(du::CuDeviceMatrix, rhs1, f_face, f_interaction, dgl, dgr)
idx = (blockIdx().x - 1) * blockDim().x + threadIdx().x
idy = (blockIdx().y - 1) * blockDim().y + threadIdx().y
strx = blockDim().x * gridDim().x
stry = blockDim().y * gridDim().y
ncell, nsp = size(du)
for ppp1 = idy:stry:nsp
for i = idx+1:strx:ncell-1
@inbounds du[i, ppp1] = -(
rhs1[i, ppp1] +
(f_interaction[i] - f_face[i, 1]) * dgl[ppp1] +
(f_interaction[i+1] - f_face[i, 2]) * dgr[ppp1]
)
end
end
return nothing
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 244 | # ============================================================
# Governing Equations
# ============================================================
include("eq_scalar.jl")
include("eq_advection.jl")
include("eq_euler.jl")
include("eq_bgk.jl")
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2534 | """
$(SIGNATURES)
Calculate Jacobians for elements
Isosceles right triangle element
```
3
|
|
|
|-------|
1 2
```
X = [x, y] = λ¹V¹ + λ²V² + λ³V³
λs are linear:
λ¹ = -(r+s)/2
λ² = (r+1)/2
λ³ = (s+1)/2
Jacobian:
[xr xs
yr ys]
Xᵣ = -V¹/2 + V²/2
Xₛ = -V¹/2 + V³/2
"""
function rs_jacobi(cells, points)
ncell = size(cells, 1)
J = [
begin
xr, yr = (points[cells[i, 2], 1:2] - points[cells[i, 1], 1:2]) ./ 2
xs, ys = (points[cells[i, 3], 1:2] - points[cells[i, 1], 1:2]) ./ 2
[xr xs; yr ys]
end for i = 1:ncell
]
return J
end
"""
$(SIGNATURES)
Quadrilateral element
```
4 3
|-------|
| |
| |
|-------|
1 2
```
X = λ¹V¹ + λ²V² + λ³V³ + λ⁴V⁴
λs are bilinear rectangle shape functions:
(http://people.ucalgary.ca/~aknigh/fea/fea/rectangles/r1.html)
λ¹ = (r-1)(s-1)/4
λ² = (r+1)(1-s)/4
λ³ = (r+1)(s+1)/4
λ⁴ = (1-r)(s+1)/4
Jacobian:
Xᵣ = (s-1)V¹/4 + (1-s)V²/4 + (s+1)V³/4 - (s+1)V⁴/4
Xₛ = (r-1)V¹/4 - (r+1)V²/4 + (r+1)V³/4 + (1-r)V⁴/4
Unlike linear simplex elements,
J varies from point to point within an element for a general linear quadrilateral.
As a special case, the Jacobian matrix is a constant for each element in rectangular mesh.
"""
function rs_jacobi(r::T, s::T, vertices::AbstractMatrix) where {T<:Real}
xr, yr = @. (s - 1.0) * vertices[1, :] / 4 +
(1.0 - s) * vertices[2, :] / 4 +
(s + 1.0) * vertices[3, :] / 4 - (s + 1.0) * vertices[4, :] / 4
xs, ys = @. (r - 1.0) * vertices[1, :] / 4 - (r + 1.0) * vertices[2, :] / 4 +
(r + 1.0) * vertices[3, :] / 4 +
(1.0 - r) * vertices[4, :] / 4
J = [xr xs; yr ys]
return J
end
rs_jacobi(r::T, s::T, vertices::AbstractMatrix) where {T<:AbstractVector} =
[rs_jacobi(r[i], s[i], vertices) for i in eachindex(r)]
rs_jacobi(r::T, s::T, vertices::AbstractMatrix) where {T<:AbstractMatrix} =
[rs_jacobi(r[i], s[i], vertices) for i in axes(r, 1), j in axes(s, 2)]
rs_jacobi(r, s, vertices::AbstractArray{<:AbstractFloat,4}) = [
rs_jacobi(r, s, @view vertices[i, j, :, :]) for i in axes(vertices, 1),
j in axes(vertices, 2)
]
# syntax sugar for inner points with same samplings in x and y
rs_jacobi(r::AbstractVector, vertices::AbstractMatrix) =
[rs_jacobi(r[i], r[j], vertices) for i in eachindex(r), j in eachindex(r)]
rs_jacobi(r, vertices::AbstractArray{<:AbstractFloat,4}) = [
rs_jacobi(r, @view vertices[i, j, :, :]) for i in axes(vertices, 1),
j in axes(vertices, 2)
]
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1569 | """
$(SIGNATURES)
global id
local rank
"""
function neighbor_fpidx(IDs, ps, fpg)
# id-th cell, fd-th face, jd-th point
id, fd, jd = IDs
# ending point ids of a face
if fd == 1
pids = [ps.cellid[id, 1], ps.cellid[id, 2]]
elseif fd == 2
pids = [ps.cellid[id, 2], ps.cellid[id, 3]]
elseif fd == 3
pids = [ps.cellid[id, 3], ps.cellid[id, 1]]
end
# global face index
faceids = ps.cellFaces[id, :]
function get_faceid()
for i in eachindex(faceids)
if sort(pids) == sort(ps.facePoints[faceids[i], :])
return faceids[i]
end
end
@warn "no face id found"
end
faceid = get_faceid()
# neighbor cell id
neighbor_cid = setdiff(ps.faceCells[faceid, :], id)[1]
# in case of boundary cell
if neighbor_cid <= 0
return neighbor_cid, -1, -1
end
# face rank in neighbor cell
if ps.cellid[neighbor_cid, 1] ∉ ps.facePoints[faceid, :]
neighbor_frk = 2
elseif ps.cellid[neighbor_cid, 2] ∉ ps.facePoints[faceid, :]
neighbor_frk = 3
elseif ps.cellid[neighbor_cid, 3] ∉ ps.facePoints[faceid, :]
neighbor_frk = 1
end
# point rank in neighbor cell
neighbor_nrk1 =
findall(x -> x == fpg[id, fd, jd, 1], fpg[neighbor_cid, neighbor_frk, :, 1])
neighbor_nrk2 =
findall(x -> x == fpg[id, fd, jd, 2], fpg[neighbor_cid, neighbor_frk, :, 2])
neighbor_nrk = intersect(neighbor_nrk1, neighbor_nrk2)[1]
return neighbor_cid, neighbor_frk, neighbor_nrk
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 3444 | """
$(SIGNATURES)
Calculate global coordinates of solution points
Line elements
"""
function global_sp(xi::AbstractVector{T}, r::AbstractVector{T}) where {T<:Real} # line elements
xsp = similar(xi, first(eachindex(xi)):last(eachindex(xi))-1, length(r))
for i in axes(xsp, 1), j in axes(r, 1)
xsp[i, j] = r_x(r[j], xi[i], xi[i+1])
end
return xsp
end
"""
$(SIGNATURES)
Quadrilateral elements
"""
function global_sp(
xi::AbstractArray{<:Real,2},
yi::AbstractArray{<:Real,2},
r::AbstractArray{<:Real,1},
)
xp = similar(
xi,
first(axes(xi, 1)):last(axes(xi, 1))-1,
first(axes(xi, 2)):last(axes(xi, 2)),
length(r),
length(r),
)
yp = similar(xp)
for i in axes(xp, 1), j in axes(xp, 2), k in axes(r, 1), l in axes(r, 1)
xp[i, j, k, l] = r_x(r[k], xi[i, j], xi[i+1, j])
yp[i, j, k, l] = r_x(r[l], yi[i, j], yi[i, j+1])
end
return xp, yp
end
"""
$(SIGNATURES)
Triangle elements
- @arg points: vetices of elements
- @arg cellid: point ids of elements
- @arg N: polynomial degree
The right triangle is used in the reference space
- 1, 2: bottom points
- 3: top point
"""
function global_sp(
points::AbstractMatrix{T1},
cellid::AbstractMatrix{T2},
N::Integer,
) where {T1<:Real,T2<:Integer}
pl, wl = tri_quadrature(N)
Np = size(wl, 1)
spg = zeros(eltype(points), size(cellid, 1), Np, 2)
for i in axes(spg, 1), j in axes(spg, 2)
id1, id2, id3 = cellid[i, :]
spg[i, j, :] .=
rs_xy(pl[j, :], points[id1, 1:2], points[id2, 1:2], points[id3, 1:2])
end
return spg
end
#--- deprecated codes for equilateral triangle element ---#
#=function global_sp(
points::AbstractMatrix{T1},
cellid::AbstractMatrix{T2},
rs::AbstractMatrix{T3},
) where {T1<:Real,T2<:Integer,T3<:Real}
r = rs[:, 1]
s = rs[:, 2]
xsp = similar(points, size(cellid, 1), size(rs, 1), size(rs, 2))
for i in axes(xsp, 1), j in axes(xsp, 2)
xsp[i, j, :] =
(-3.0 * r[j] + 2.0 - √3 * s[j]) / 6.0 .* points[cellid[i, 1], 1:2] +
(3.0 * r[j] + 2.0 - √3 * s[j]) / 6.0 .* points[cellid[i, 2], 1:2] +
(2.0 + 2.0 * √3 * s[j]) / 6.0 .* points[cellid[i, 3], 1:2]
end
return xsp
end=#
"""
$(SIGNATURES)
Calculate global coordinates of flux points
Triangle elements
"""
function global_fp(points, cellid, N)
pf, wf = triface_quadrature(N)
fpg = zeros(size(cellid, 1), 3, N + 1, 2)
for i in axes(fpg, 1)
id1, id2, id3 = cellid[i, :]
for j in axes(fpg, 2), k in axes(fpg, 3)
fpg[i, j, k, :] .=
rs_xy(pf[j, k, :], points[id1, 1:2], points[id2, 1:2], points[id3, 1:2])
end
end
return fpg
end
#--- deprecated face-indexed codes ---#
#=function global_fp(points, cellid, faceCells, facePoints, N)
pf, wf = triface_quadrature(N)
fpg = zeros(size(faceCells, 1), N+1, 2)
for i in axes(fpg, 1), j in axes(fpg, 2)
idc = ifelse(faceCells[i, 1] != -1, faceCells[i, 1], faceCells[i, 2])
id1, id2, id3 = cellid[idc, :]
if !(id3 in facePoints[i, :])
idf = 1
elseif !(id1 in facePoints[i, :])
idf = 2
elseif !(id2 in facePoints[i, :])
idf = 3
end
fpg[i, j, :] .= rs_xy(pf[idf, j, :], points[id1, 1:2], points[id2, 1:2], points[id3, 1:2])
end
return fpg
end=#
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2355 | """
$(SIGNATURES)
Transfer coordinate r -> x from standard to real elements
"""
r_x(r, vl, vr) = ((1.0 - r) / 2.0) * vl + ((1.0 + r) / 2.0) * vr
"""
$(SIGNATURES)
Transfer coordinate r -> x from standard to real elements
Triangle element
"""
function rs_xy(
r,
s,
v1::AbstractVector{T},
v2::AbstractVector{T},
v3::AbstractVector{T},
) where {T<:Real}
return @. -(r + s) / 2 * v1 + (r + 1) / 2 * v2 + (s + 1) / 2 * v3
end
"""
$(SIGNATURES)
Triangle element
"""
function rs_xy(
v::AbstractVector{T},
v1::AbstractVector{T},
v2::AbstractVector{T},
v3::AbstractVector{T},
) where {T<:Real}
r, s = v
return rs_xy(r, s, v1, v2, v3)
end
"""
$(SIGNATURES)
Quadrilateral element
"""
function rs_xy(
r,
s,
v1::AbstractVector{T},
v2::AbstractVector{T},
v3::AbstractVector{T},
v4::AbstractVector{T},
) where {T<:Real}
return @. (r - 1.0) * (s - 1.0) / 4.0 * v1 +
(r + 1.0) * (1.0 - s) / 4.0 * v2 +
(r + 1.0) * (s + 1.0) / 4.0 * v3 +
(1.0 - r) * (s + 1.0) / 4.0 * v4
end
"""
$(SIGNATURES)
Transfer coordinates (x, y) -> (r,s) from equilateral to right triangle
"""
function xy_rs(x::T, y::T) where {T}
L1 = (sqrt(3.0) * y + 1.0) / 3.0
L2 = (-3.0 * x - sqrt(3.0) * y + 2.0) / 6.0
L3 = (3.0 * x - sqrt(3.0) * y + 2.0) / 6.0
r = -L2 + L3 - L1
s = -L2 - L3 + L1
return r, s
end
"""
$(SIGNATURES)
"""
function xy_rs(x::AbstractVector{T}, y::AbstractVector{T}) where {T}
Np = length(x)
r = zeros(Np)
s = zeros(Np)
for n = 1:Np
r[n], s[n] = xy_rs(x[n], y[n])
end
return r, s
end
"""
$(SIGNATURES)
"""
function xy_rs(coords::AbstractMatrix{T}) where {T<:Real}
return xy_rs(coords[:, 1], coords[:, 2])
end
"""
$(SIGNATURES)
Transfer coordinates (r,s) -> (a,b) in a triangle
"""
function rs_ab(r::T, s::T) where {T<:Real}
a = ifelse(s != 1.0, 2.0 * (1.0 + r) / (1.0 - s) - 1.0, -1.0)
b = 1.0 * s
return a, b
end
"""
$(SIGNATURES)
"""
function rs_ab(r::AbstractVector{T}, s::AbstractVector{T}) where {T<:Real}
a = zero(r)
b = zero(s)
for n in eachindex(a)
a[n], b[n] = rs_ab(r[n], s[n])
end
return a, b
end
"""
$(SIGNATURES)
"""
function rs_ab(coords::AbstractMatrix{T}) where {T<:Real}
return rs_ab(coords[:, 1], coords[:, 2])
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 252 | # ============================================================
# Geometric Methods
# ============================================================
include("geo_transform.jl")
include("geo_points.jl")
include("geo_jacobi.jl")
include("geo_neighbor.jl")
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1390 | """
$(SIGNATURES)
Construct exponential filter for nodal solution
- @arg N: number of coefficients
- @arg Nc: cutoff location
- @arg s: order of filter (must be even)
- @arg V: Vandermonde matrix
"""
function filter_exp(N, s, V, Nc = 0, invV = inv(V))
nv = size(V, 1)
if nv == N + 1
filterdiag = KitBase.filter_exp1d(N, s, Nc)
elseif nv == (N + 1) * (N + 2) ÷ 2
filterdiag = filter_exp2d(N, s, Nc)
end
F = V * diagm(filterdiag) * invV
return F
end
"""
$(SIGNATURES)
Construct exponential filter for modal solution
- @arg N: degree of polynomials
- @arg s: order of filter (must be even)
- @arg Nc: cutoff location
"""
function filter_exp2d(Norder, sp, Nc = 0)
alpha = -log(eps())
filterdiag = ones((Norder + 1) * (Norder + 2) ÷ 2)
sk = 1
for i = 0:Norder
for j = 0:Norder-i
if i + j >= Nc
filterdiag[sk] = exp(-alpha * ((i + j - Nc) / (Norder - Nc))^sp)
end
sk += 1
end
end
return filterdiag
end
"""
$(SIGNATURES)
Calculate norm of polynomial basis
"""
function basis_norm(deg)
NxHat = 100
xHat = range(-1, stop = 1, length = NxHat) |> collect
dxHat = xHat[2] - xHat[1]
nLocal = deg + 1
PhiL1 = zeros(nLocal)
for i = 1:nLocal
PhiL1[i] = dxHat * sum(abs.(JacobiP(xHat, 0, 0, i - 1)))
end
return PhiL1
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2871 | """
$(SIGNATURES)
Evaluate Jacobi polynomial P_n^(α,β)(x)
Note that the order of arguments and return values are different from Jacobi.jl
"""
function JacobiP(x::T, alpha, beta, N) where {T<:Real}
xp = x
PL = zeros(N + 1)
# P₀(x) and P₁(x)
gamma0 =
2^(alpha + beta + 1) / (alpha + beta + 1) * gamma(alpha + 1) * gamma(beta + 1) /
gamma(alpha + beta + 1)
PL[1] = 1.0 / sqrt(gamma0)
if N == 0
return PL[1]
end
gamma1 = (alpha + 1) * (beta + 1) / (alpha + beta + 3) * gamma0
PL[2] = ((alpha + beta + 2) * xp / 2 + (alpha - beta) / 2) / sqrt(gamma1)
if N == 1
P = PL[2]
return P
end
# forward recurrence using the symmetry of the recurrence
aold = 2 / (2 + alpha + beta) * sqrt((alpha + 1) * (beta + 1) / (alpha + beta + 3))
for i = 1:N-1
h1 = 2 * i + alpha + beta
anew =
2 / (h1 + 2) * sqrt(
(i + 1) * (i + 1 + alpha + beta) * (i + 1 + alpha) * (i + 1 + beta) /
(h1 + 1) / (h1 + 3),
)
bnew = -(alpha^2 - beta^2) / h1 / (h1 + 2)
PL[i+2] = 1 / anew * (-aold * PL[i] + (xp - bnew) * PL[i+1])
aold = anew
end
P = PL[N+1]
return P
end
"""
$(SIGNATURES)
"""
function JacobiP(x::AbstractArray, alpha, beta, N)
xp = copy(x)
PL = zeros(N + 1, length(xp))
# P₀(x) and P₁(x)
gamma0 =
2^(alpha + beta + 1) / (alpha + beta + 1) * gamma(alpha + 1) * gamma(beta + 1) /
gamma(alpha + beta + 1)
PL[1, :] .= 1.0 / sqrt(gamma0)
if N == 0
P = PL[:]
return P
end
gamma1 = (alpha + 1) * (beta + 1) / (alpha + beta + 3) * gamma0
@. PL[2, :] = ((alpha + beta + 2) * xp / 2 + (alpha - beta) / 2) / sqrt(gamma1)
if N == 1
P = PL[N+1, :]
return P
end
# forward recurrence using the symmetry of the recurrence
aold = 2 / (2 + alpha + beta) * sqrt((alpha + 1) * (beta + 1) / (alpha + beta + 3))
for i = 1:N-1
h1 = 2 * i + alpha + beta
anew =
2 / (h1 + 2) * sqrt(
(i + 1) * (i + 1 + alpha + beta) * (i + 1 + alpha) * (i + 1 + beta) /
(h1 + 1) / (h1 + 3),
)
bnew = -(alpha^2 - beta^2) / h1 / (h1 + 2)
@. PL[i+2, :] = 1 / anew * (-aold * PL[i, :] + (xp - bnew) * PL[i+1, :])
aold = anew
end
P = PL[N+1, :]
return P
end
"""
$(SIGNATURES)
"""
function ∂JacobiP(r::T, alpha, beta, N) where {T<:Real}
dP = 0.0
if N != 0
dP = sqrt(N * (N + alpha + beta + 1)) * JacobiP(r, alpha + 1, beta + 1, N - 1)
end
return dP
end
"""
$(SIGNATURES)
"""
function ∂JacobiP(r::AbstractArray{T}, alpha, beta, N) where {T<:Real}
dP = zero(r)
if N != 0
dP .= sqrt(N * (N + alpha + beta + 1)) .* JacobiP(r, alpha + 1, beta + 1, N - 1)
end
return dP
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2038 | """
$(SIGNATURES)
Calculate Legendre polynomials of solution points sp at location x
"""
function lagrange_point(sp::AbstractVector{T}, x::Real) where {T<:Real}
l = similar(sp)
nsp = length(sp)
for k = 1:nsp
tmp = 1.0
for j = 1:nsp
if j != k
tmp *= (x - sp[j]) / (sp[k] - sp[j])
end
end
l[k] = tmp
end
return l
end
function lagrange_point(sp, x::AbstractVector{T}) where {T<:Real}
lp = zeros(eltype(sp), axes(x, 1), axes(sp, 1))
for i in axes(lp, 1)
lp[i, :] .= lagrange_point(sp, x[i])
end
return lp
end
"""
$(SIGNATURES)
Calculate derivatives of Lagrange polynomials dlⱼ(rᵢ)
"""
function ∂lagrange(sp::T) where {T<:AbstractVector{<:Real}}
nsp = length(sp)
lpdm = similar(sp, nsp, nsp)
for k = 1:nsp, m = 1:nsp
lsum = 0.0
for l = 1:nsp
tmp = 1.0
for j = 1:nsp
if j != k && j != l
tmp *= (sp[m] - sp[j]) / (sp[k] - sp[j])
end
end
if l != k
lsum += tmp / (sp[k] - sp[l])
end
end
lpdm[m, k] = lsum
end
return lpdm
end
# ------------------------------------------------------------
# Vandermonde matrix based evaluation
# ------------------------------------------------------------
"""
$(SIGNATURES)
"""
function ∂lagrange(V, Vr)
Np = size(V, 1)
∂l = zeros(Np, Np)
for i = 1:Np
∂l[i, :] .= V' \ Vr[i, :]
end
return ∂l
end
"""
$(SIGNATURES)
"""
function ∂lagrange(V, Vr, Vs)
Np = size(V, 1)
∂l = zeros(Np, Np, 2)
for i = 1:Np
∂l[i, :, 1] .= V' \ Vr[i, :]
∂l[i, :, 2] .= V' \ Vs[i, :]
end
return ∂l
end
"""
$(SIGNATURES)
One-shot calculation of derivatives of Lagrange polynomials and the values at cell edge
"""
function standard_lagrange(x)
ll = lagrange_point(x, -1.0)
lr = lagrange_point(x, 1.0)
lpdm = ∂lagrange(x)
return ll, lr, lpdm
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1557 | """
$(SIGNATURES)
Calculate Legendre points of polynomial degree p
"""
legendre_point(p::Integer) = gausslegendre(p + 1)[1]
"""
$(SIGNATURES)
Calculate derivatives of Legendre polynomials of degree p at location x
"""
∂legendre(p::Integer, x) = last(sf_legendre_Pl_deriv_array(p, x)[2])
function ∂legendre(p::Integer, x::AV)
Δ = similar(x)
for i in eachindex(Δ)
Δ[i] = ∂legendre(p, x[i])
end
return Δ
end
"""
$(SIGNATURES)
Calculate derivatives of Radau polynomials (correction functions for nodal DG) of degree p at location x
"""
function ∂radau(p::Integer, x::Union{Real,AV})
Δ = ∂legendre(p, x)
Δ_plus = ∂legendre(p + 1, x)
dgl = @. (-1.0)^p * 0.5 * (Δ - Δ_plus)
dgr = @. 0.5 * (Δ + Δ_plus)
return dgl, dgr
end
"""
$(SIGNATURES)
Calculate derivatives of spectral difference correction functions of degree p at location x
"""
function ∂sd(p::Integer, x::Union{Real,AV})
Δ_minus = ∂legendre(p - 1, x)
Δ = ∂legendre(p, x)
Δ_plus = ∂legendre(p + 1, x)
y = (p * Δ_minus + (p + 1) * Δ_plus) / (2 * p + 1)
dgl = @. (-1.0)^p * 0.5 * (Δ - y)
dgr = @. 0.5 * (Δ + y)
return dgl, dgr
end
"""
$(SIGNATURES)
Calculate derivatives of Huynh's correction functions of degree p at location x
"""
function ∂huynh(p::Integer, x::Union{Real,AV})
Δ_minus = ∂legendre(p - 1, x)
Δ = ∂legendre(p, x)
Δ_plus = ∂legendre(p + 1, x)
y = ((p + 1) * Δ_minus + p * Δ_plus) / (2 * p + 1)
dgl = @. (-1.0)^p * 0.5 * (Δ - y)
dgr = @. 0.5 * (Δ + y)
return dgl, dgr
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 635 | function correction_field(N, V)
pl, wl = tri_quadrature(N)
pf, wf = triface_quadrature(N)
Np = (N + 1) * (N + 2) ÷ 2
ψf = zeros(3, N + 1, Np)
for i = 1:3
ψf[i, :, :] .= vandermonde_matrix(Tri, N, pf[i, :, 1], pf[i, :, 2])
end
σ = zeros(3, N + 1, Np)
for k = 1:Np
for j = 1:N+1
for i = 1:3
σ[i, j, k] = wf[i, j] * ψf[i, j, k]
end
end
end
V = vandermonde_matrix(Tri, N, pl[:, 1], pl[:, 2])
ϕ = zeros(3, N + 1, Np)
for f = 1:3, j = 1:N+1, i = 1:Np
ϕ[f, j, i] = sum(σ[f, j, :] .* V[i, :])
end
return ϕ
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 284 | # ============================================================
# Polynomial Methods
# ============================================================
include("poly_filter.jl")
include("poly_legendre.jl")
include("poly_jacobi.jl")
include("poly_lagrange.jl")
include("poly_triangle.jl")
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2589 | """
$(SIGNATURES)
Calculate quadrature points in a triangle
@arg deg: polynomial degree
@arg vertices: vertex coordinates
- for a equilateral triangle, the vertices are ([-1.0, -1 / √3], [1.0, -1 / √3], [0.0, 2 / √3])
- for a right triangle, the vertices take ([-1.0, -1.0], [1.0, -1.0], [-1.0, 1.0])
@arg if transform equals to true, then we transform the coordinates from x-y to r-s plane
"""
function tri_quadrature(
deg;
vertices = ([-1.0, -1 / √3], [1.0, -1 / √3], [0.0, 2 / √3]),
transform = true,
)
pushfirst!(pyimport("sys")."path", @__DIR__)
py"""
import qpmin
def create_quadrature(n):
if n == 1:
scheme = qpmin.williams_shunn_jameson_1()
elif n == 2:
scheme = qpmin.williams_shunn_jameson_2()
elif n == 3:
scheme = qpmin.williams_shunn_jameson_3()
elif n == 4:
scheme = qpmin.williams_shunn_jameson_4()
elif n == 5:
scheme = qpmin.williams_shunn_jameson_5()
elif n == 6:
scheme = qpmin.williams_shunn_jameson_6()
elif n == 7:
scheme = qpmin.williams_shunn_jameson_7()
elif n == 8:
scheme = qpmin.williams_shunn_jameson_8()
else:
print("Not a valid polynomial degree")
return scheme.points, scheme.weights
"""
# trilinear coordinates (三线坐标)
points0, weights = py"create_quadrature"(deg + 1)
# cartesian coordinates of vertices
p1, p2, p3 = vertices
a = norm(p2 .- p3)
b = norm(p3 .- p1)
c = norm(p2 .- p1)
points = similar(points0, size(points0, 2), 2)
for i in axes(points, 1)
x, y, z = points0[:, i]
# trilinear -> cartesian
points[i, :] .= (a * x .* p1 + b * y .* p2 + c * z .* p3) / (a * x + b * y + c * z)
end
if transform == true
r, s = xy_rs(points)
points .= hcat(r, s)
end
return points, weights
end
"""
$(SIGNATURES)
Calculate quadrature points along a face of right triangle
- face 1: 1 -> 2
- face 2: 2 -> 3
- face 3: 3 -> 1
Face 2 is assumed to be hypotenuse
@arg N: polynomial degree
"""
function triface_quadrature(N)
Δf = [1.0, √2, 1.0]
pf = Array{Float64}(undef, 3, N + 1, 2)
wf = Array{Float64}(undef, 3, N + 1)
p0, w0 = gausslegendre(N + 1)
pf[1, :, 1] .= p0
pf[2, :, 1] .= p0[end:-1:1]
pf[3, :, 1] .= -1.0
pf[1, :, 2] .= -1.0
pf[2, :, 2] .= p0
pf[3, :, 2] .= p0[end:-1:1]
wf[1, :] .= w0 .* Δf[1]
wf[2, :] .= w0 .* Δf[2]
wf[3, :] .= w0 .* Δf[3]
return pf, wf
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 2539 | # ============================================================
# Transformation Methods between nodal and modal formulations
# ============================================================
include("transform_triangle.jl")
"""
$(SIGNATURES)
Compute Vandermonde matrix for node-mode transform
Vû = u
- @arg N: polynomial degree
- @arg r: local x axis
- @arg s: local y axis
"""
function vandermonde_matrix(N, r)
V1D = zeros(eltype(r), length(r), N + 1)
for j = 1:N+1
V1D[:, j] .= JacobiP(r, 0, 0, j - 1)
end
return V1D
end
"""
$(SIGNATURES)
"""
vandermonde_matrix(::Type{Line}, N, r) = vandermonde_matrix(N, r)
"""
$(SIGNATURES)
"""
function vandermonde_matrix(::Type{Tri}, N, r, s)
Np = (N + 1) * (N + 2) ÷ 2
V2D = zeros(eltype(r), length(r), Np)
a, b = rs_ab(r, s)
sk = 1
for i = 0:N
for j = 0:N-i
V2D[:, sk] .= simplex_basis(a, b, i, j)
sk += 1
end
end
return V2D
end
"""
$(SIGNATURES)
"""
function vandermonde_matrix(::Type{Quad}, N, r, s)
Np = (N + 1)^2
V = zeros(eltype(r), length(r), Np)
sk = 1
for i = 0:N
for j = 0:N
V[:, sk] = JacobiP(r, 0, 0, i) .* JacobiP(s, 0, 0, j)
sk += 1
end
end
return V
end
"""
$(SIGNATURES)
gradient of the modal basis (i,j) at (r,s) at order N
"""
function ∂vandermonde_matrix(N::T, r) where {T<:Integer}
Vr = zeros(length(r), N + 1)
for i = 0:N
Vr[:, i+1] .= ∂JacobiP(r, 0, 0, i)
end
return Vr
end
"""
$(SIGNATURES)
"""
∂vandermonde_matrix(::Type{Line}, N, r) = ∂vandermonde_matrix(N, r)
"""
$(SIGNATURES)
"""
function ∂vandermonde_matrix(::Type{Tri}, N::T, r, s) where {T<:Integer}
V2Dr = zeros(eltype(r), length(r), (N + 1) * (N + 2) ÷ 2)
V2Ds = zeros(eltype(r), length(r), (N + 1) * (N + 2) ÷ 2)
# tensor-product coordinates
a, b = rs_ab(r, s)
sk = 1
for i = 0:N
for j = 0:N-i
V2Dr[:, sk], V2Ds[:, sk] = ∂simplex_basis(a, b, i, j)
sk += 1
end
end
return V2Dr, V2Ds
end
"""
$(SIGNATURES)
"""
function ∂vandermonde_matrix(::Type{Quad}, N::T, r, s) where {T<:Integer}
V2Dr = zeros(eltype(r), length(r), (N + 1)^2)
V2Ds = zeros(eltype(r), length(r), (N + 1)^2)
sk = 1
for i = 0:N
for j = 0:N
V2Dr[:, sk] .= ∂JacobiP(r, 0, 0, i) .* JacobiP(s, 0, 0, j)
V2Ds[:, sk] .= JacobiP(r, 0, 0, i) .* ∂JacobiP(s, 0, 0, j)
sk += 1
end
end
return V2Dr, V2Ds
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 1700 | """
$(SIGNATURES)
Evaluate 2D orthonormal polynomial at simplex (a, b) of order (i, j)
Translated from Simplex2DP.m
"""
function simplex_basis(a::T, b::T, i, j) where {T<:Real}
# x, a, b, n
h1 = JacobiP(a, 0, 0, i)
h2 = JacobiP(b, 2 * i + 1, 0, j)
return sqrt(2.0) * h1 * h2 * (1 - b)^i
end
"""
$(SIGNATURES)
"""
simplex_basis(a::AbstractVector{T}, b::AbstractVector{T}, i, j) where {T<:Real} =
[simplex_basis(a[k], b[k], i, j) for k in eachindex(a)]
function ∂simplex_basis(a::T, b::T, id, jd) where {T<:Real}
#fa = jacobi(a, id, 0, 0)
#dfa = djacobi(a, id, 0, 0)
#gb = jacobi(b, jd, 2*id+1, 0)
#dgb = djacobi(b, jd, 2*id+1, 0)
fa = JacobiP(a, 0, 0, id)
dfa = ∂JacobiP(a, 0, 0, id)
gb = JacobiP(b, 2 * id + 1, 0, jd)
dgb = ∂JacobiP(b, 2 * id + 1, 0, jd)
# r-derivative
# d/dr = da/dr d/da + db/dr d/db = (2/(1-s)) d/da = (2/(1-b)) d/da
dmodedr = dfa * gb
if id > 0
dmodedr *= (0.5 * (1.0 - b))^(id - 1)
end
# s-derivative
# d/ds = ((1+a)/2)/((1-b)/2) d/da + d/db
dmodeds = dfa * (gb * (0.5 * (1.0 + a)))
if id > 0
dmodeds *= (0.5 * (1.0 - b))^(id - 1)
end
tmp = dgb * (0.5 * (1.0 - b))^id
if id > 0
tmp -= 0.5 * id * gb * ((0.5 * (1.0 - b))^(id - 1))
end
dmodeds += fa * tmp
# normalization
dmodedr *= 2^(id + 0.5)
dmodeds *= 2^(id + 0.5)
return dmodedr, dmodeds
end
function ∂simplex_basis(a::AbstractVector{T}, b::AbstractVector{T}, id, jd) where {T<:Real}
dmodedr = zero(a)
dmodeds = zero(b)
for i in eachindex(a)
dmodedr[i], dmodeds[i] = ∂simplex_basis(a[i], b[i], id, jd)
end
return dmodedr, dmodeds
end
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 989 | using Test, FluxReconstruction, KitBase
cd(@__DIR__)
include("test_triangle.jl")
let u = rand(3), u0 = rand(3)
FR.L1_error(u, u0, 0.1)
FR.L2_error(u, u0, 0.1)
FR.L∞_error(u, u0, 0.1)
end
shock_detector(-Inf, 3)
shock_detector(log10(0.1), 3)
shock_detector(log10(1e5), 3)
deg = 5
ps2 = FRPSpace2D(0.0, 1.0, 20, 0.0, 1.0, 20, deg, 1, 1)
rs_jacobi(ps2.xpl, [0 0; √3 -1; √3+1 √3-1; 1 √3])
rs_jacobi(ps2.xpl, rand(3, 3, 4, 2))
ps1 = TriFRPSpace("../assets/linesource.msh", 2)
ps = FRPSpace1D(0.0, 1.0, 20, deg)
positive_limiter(ones(6), 1 / 6, ps.ll, ps.lr)
positive_limiter(ones(6, 3), 5 / 3, 1 / 6, ps.ll, ps.lr)
let u = rand(deg + 1)
ℓ = FR.basis_norm(deg)
# 2D exponential filter
FR.filter_exp(2, 10, Array(ps.V))
end
let u = rand(deg + 1, deg + 1)
modal_filter!(u, 1e-6, 1e-6; filter = :l2)
modal_filter!(u, 1e-6, 1e-6; filter = :l2opt)
end
f = randn(5, deg + 1)
fδ = randn(5, 2)
FR.interp_face!(fδ, f, ps.ll, ps.lr)
FR.standard_lagrange(ps.xpl)
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | code | 506 | deg = 3
pl, wl = tri_quadrature(deg)
V = vandermonde_matrix(Tri, deg, pl[:, 1], pl[:, 2])
Vr, Vs = ∂vandermonde_matrix(Tri, deg, pl[:, 1], pl[:, 2])
∂l = ∂lagrange(V, Vr, Vs)
a, b = rs_ab(pl[:, 1], pl[:, 2])
p1 = [-1.0, -1 / √3]
p2 = [1.0, -1 / √3]
p3 = [0.0, 2 / √3]
p = (p1, p2, p3)
points, weights = tri_quadrature(3, vertices = p)
@test points == pl
@test weights == wl
r, s = xy_rs(points)
a, b = rs_ab(r, s)
V = vandermonde_matrix(Tri, 3, r, s)
#using Plots
#scatter(points[:, 1], points[:, 2])
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.1.7 | aecb840b8b6830d65d3ff520e8d517ab7f15b13d | docs | 1428 | # FluxReconstruction.jl

[](https://codecov.io/gh/vavrines/FluxReconstruction.jl)
**FluxReconstruction** is a lightweight [Julia](https://julialang.org) implementation of the [flux reconstruction](https://arc.aiaa.org/doi/10.2514/6.2007-4079) method proposed by Huynh.
It is built in conjunction with the [SciML](https://github.com/SciML/DifferentialEquations.jl) and [Kinetic](https://github.com/vavrines/Kinetic.jl) ecosystems.
## Installation
FluxReconstruction is a registered package in the official [Julia package registry](https://github.com/JuliaRegistries/General).
We recommend installing it with the built-in Julia package manager, which automatically locates a stable release and all its dependencies.
From the Julia REPL, you can get in the package manager (by pressing `]`) and add the package.
```julia
julia> ]
(v1.9) pkg> add FluxReconstruction
```
## Physics
FluxReconstruction focuses on numerical solutions of transport equations.
Any advection-diffusion-type equation can be solved within the framework.
A partial list of current supported models include
- advection-diffusion equation
- Burgers equation
- Euler equations
- Navier-Stokes equations
- Boltzmann equation
| FluxReconstruction | https://github.com/vavrines/FluxReconstruction.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 2240 | """
FITSHeaders
A package implementing methods to store and parse FITS header cards.
"""
module FITSHeaders
export
# Quick FITS keyword:
@Fits_str,
FitsKey,
# FITS cards and headers:
FitsCard,
FitsHeader,
# Cards types:
FitsCardType,
FITS_LOGICAL,
FITS_INTEGER,
FITS_FLOAT,
FITS_STRING,
FITS_COMPLEX,
FITS_COMMENT,
FITS_UNDEFINED,
FITS_END,
# Sizes:
FITS_CARD_SIZE,
FITS_BLOCK_SIZE,
FITS_SHORT_KEYWORD_SIZE
using Requires
# Enumeration of keyword value type identifiers.
@enum FitsCardType::Cint begin
FITS_LOGICAL = 0
FITS_INTEGER = 1
FITS_FLOAT = 2
FITS_STRING = 3
FITS_COMPLEX = 4
FITS_COMMENT = 5
FITS_UNDEFINED = 6 # no value given
FITS_END = 7 # END card
end
# Julia types for card values.
const FitsInteger = Int64
const FitsFloat = Float64
const FitsComplex = Complex{FitsFloat}
# Types equivalent to undefined FITS card value.
const Undef = typeof(undef)
const Undefined = Union{Missing,Undef}
# Allowed types for FITS card names.
const CardName = Union{AbstractString,Symbol}
# Allowed types for FITS card values (including commentary cards).
const CardValue = Union{Real,AbstractString,Complex,Undefined,Nothing}
# Allowed types for FITS card comments.
const CardComment = Union{AbstractString,Nothing}
# Signature of pairs that may possibly be converted into FITS cards.
#
#NOTE: The value type is purposely unspecific to allow for collections of card
# pairs mixing different value types.
const CardPair{K<:CardName,V} = Pair{K,V}
include("parser.jl")
import .Parser:
@Fits_str,
FITS_CARD_SIZE,
FITS_BLOCK_SIZE,
FITS_SHORT_KEYWORD_SIZE,
FitsKey,
check_short_keyword,
check_keyword,
try_parse_keyword,
is_structural,
is_comment,
is_naxis,
is_end,
keyword
include("cards.jl")
import .Cards:
FitsCard
include("headers.jl")
import .Headers:
FitsHeader,
FullName
function __init__()
@require MappedBuffers="010f96a2-bf57-4630-84b9-647e6f9999c4" begin
FITSHeaders.Parser.PointerCapability(::Type{<:MappedBuffers.MappedBuffer}) =
FITSHeaders.Parser.PointerFull()
end
end
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 22027 | """
FITSHeaders.Cards
A sub-module of the `FITSHeaders` package implementing the methods and properties
for FITS header cards.
"""
module Cards
export FitsCard
using ..FITSHeaders
using ..FITSHeaders:
CardName,
CardValue,
CardComment,
FitsInteger,
FitsFloat,
FitsComplex,
Undef,
Undefined
import ..FITSHeaders:
FitsCardType
using ..FITSHeaders.Parser:
EMPTY_STRING,
ByteBuffer,
check_keyword,
get_units_part,
get_unitless_part,
make_string,
parse_complex_value,
parse_float_value,
parse_integer_value,
parse_logical_value,
parse_string_value,
scan_card
import ..FITSHeaders.Parser:
is_structural,
is_comment,
is_naxis,
is_end
using Dates, TypeUtils
# Extended union of possible card values. Any of these shall extend the
# `to_value` method.
const CardValueExt = Union{CardValue,DateTime}
const END_STRING = "END"
const UNDEF_INTEGER = zero(FitsInteger)
const UNDEF_COMPLEX = FitsComplex(NaN,NaN)
const UNDEF_FLOAT = FitsComplex(NaN,0.0)
const UNDEF_STRING = EMPTY_STRING
"""
card = FitsCard(key => (val, com))
builds a FITS header card associating keyword `key` with value `val` and
comment string `com`. The value `val` may be:
- a boolean to yield a card of type `FITS_LOGICAL`;
- an integer to yield a card of type `FITS_INTEGER`;
- a real to yield a card of type `FITS_FLOAT`;
- a complex to yield a card of type `FITS_COMPLEX`;
- a string to yield a card of type `FITS_STRING`;
- `nothing` to yield a card of type `FITS_COMMENT`;
- `undef` or `missing` to yield a card of type `FITS_UNDEFINED`.
The comment may be omitted for a normal FITS card and the value may be omitted
for a commentary FITS card:
card = FitsCard(key => val::Number)
card = FitsCard(key => str::AbstractString)
In the 1st case, the comment is assumed to be empty. In the 2nd case, the
string `str` is assumed to be the card comment if `key` is `"COMMENT"` or
`"HISTORY"` and the card value otherwise.
FITS cards have properties:
card.type # type of card: FITS_LOGICAL, FITS_INTEGER, etc.
card.key # quick key of card: Fits"BITPIX", Fits"HIERARCH", etc.
card.name # name of card
card.value # callable object representing the card value
card.comment # comment of card
card.units # units of card value
card.unitless # comment of card without the units part if any
As the values of FITS keywords have different types, `card.value` does not
yield a Julia value but a callable object. Called without any argument, this
object yields the actual card value:
card.value() -> val::Union{Bool,$FitsInteger,$FitsFloat,$FitsComplex,String,Nothing,$Undef}
but such a call is not *type-stable* as indicated by the type assertion with an
`Union{...}` above. For a type-stable result, the card value can be converted
to a given data type `T`:
card.value(T)
convert(T, card.value)
both yield the value of `card` converted to type `T`. For readability, `T` may
be an abstract type: `card.value(Integer)` yields the same result as
`card.value($FitsInteger)`, `card.value(Real)` or `card.value(AbstractFloat)`
yield the same result as `card.value($FitsFloat)`, `card.value(Complex)` yields
the same result as `card.value($FitsComplex)`, and `card.value(AbstractString)`
yields the same result as `card.value(String)`.
To make things easier, a few properties are aliases that yield the card value
converted to a specific type:
card.logical :: Bool # alias for card.value(Bool)
card.integer :: $FitsInteger # alias for card.value(Integer)
card.float :: $FitsFloat # alias for card.value(Real)
card.complex :: $FitsComplex # alias for card.value(Complex)
card.string :: String # alias for card.value(String)
Conversion is automatically attempted if the actual card value is of a
different type, throwing an error if the conversion is not possible or inexact.
`valtype(card)` yields the type of the value of `card`. `isassigned(card)`
yields whether `card` has a value (that is whether it is neither a commentary
card nor a card with an undefined value).
"""
struct FitsCard
key::FitsKey
type::FitsCardType
value_integer::FitsInteger
value_complex::FitsComplex
value_string::String
name::String
comment::String
FitsCard(key::FitsKey, name::AbstractString, val::Bool, com::AbstractString) =
new(key, FITS_LOGICAL, val, UNDEF_COMPLEX, UNDEF_STRING, name, com)
FitsCard(key::FitsKey, name::AbstractString, val::Integer, com::AbstractString) =
new(key, FITS_INTEGER, val, UNDEF_COMPLEX, UNDEF_STRING, name, com)
FitsCard(key::FitsKey, name::AbstractString, val::Real, com::AbstractString) =
new(key, FITS_FLOAT, UNDEF_INTEGER, val, UNDEF_STRING, name, com)
FitsCard(key::FitsKey, name::AbstractString, val::Complex, com::AbstractString) =
new(key, FITS_COMPLEX, UNDEF_INTEGER, val, UNDEF_STRING, name, com)
FitsCard(key::FitsKey, name::AbstractString, val::AbstractString, com::AbstractString) =
new(key, FITS_STRING, UNDEF_INTEGER, UNDEF_COMPLEX, val, name, com)
FitsCard(key::FitsKey, name::AbstractString, ::Undefined, com::AbstractString) =
new(key, FITS_UNDEFINED, UNDEF_INTEGER, UNDEF_COMPLEX, UNDEF_STRING, name, com)
FitsCard(key::FitsKey, name::AbstractString, ::Nothing, com::AbstractString) =
new(key, key === Fits"END" ? FITS_END : FITS_COMMENT,
UNDEF_INTEGER, UNDEF_COMPLEX, UNDEF_STRING, name, com)
end
# Constructor for imutable type does not need to return a new object.
FitsCard(A::FitsCard) = A
Base.convert(::Type{T}, A::FitsCard) where {T<:FitsCard} = A
"""
FitsCard(buf; offset=0)
yields a `FitsCard` object built by parsing the FITS header card stored in the
string or vector of bytes `buf`. Keyword `offset` can be used to specify the
number of bytes to skip at the beginning of `buf`, so that it is possible to
extract a specific FITS header card, not just the first one. At most, the
$FITS_CARD_SIZE first bytes after the offset are scanned to build the
`FitsCard` object. The next FITS card to parse is then at `offset +
$FITS_CARD_SIZE` and so on.
The considered card may be shorter than $FITS_CARD_SIZE bytes, the result being
exactly the same as if the missing bytes were spaces. If there are no bytes
left, a `FitsCard` object equivalent to the final `END` card of a FITS header
is returned.
"""
function FitsCard(buf::ByteBuffer; offset::Int = 0)
type, key, name_rng, val_rng, com_rng = scan_card(buf, offset)
name = type == FITS_END ? END_STRING : make_string(buf, name_rng)
com = make_string(buf, com_rng)
if type == FITS_LOGICAL
return FitsCard(key, name, parse_logical_value(buf, val_rng), com)
elseif type == FITS_INTEGER
return FitsCard(key, name, parse_integer_value(buf, val_rng), com)
elseif type == FITS_FLOAT
return FitsCard(key, name, parse_float_value(buf, val_rng), com)
elseif type == FITS_STRING
return FitsCard(key, name, parse_string_value(buf, val_rng), com)
elseif type == FITS_COMPLEX
return FitsCard(key, name, parse_complex_value(buf, val_rng), com)
elseif type == FITS_UNDEFINED
return FitsCard(key, name, undef, com)
else # must be commentary or END card
return FitsCard(key, name, nothing, com)
end
end
is_structural(card::FitsCard) = is_structural(card.key)
is_comment(card::FitsCard) = is_comment(card.type)
is_naxis(card::FitsCard) = is_naxis(card.key)
is_end(card::FitsCard) = is_end(card.type)
# This version shall print something equivalent to Julia code to produce the
# same object. We try to use the most concise syntax.
function Base.show(io::IO, A::FitsCard)
print(io, "FitsCard(\"")
print(io, A.name, "\"")
if A.type != FITS_END
if A.type == FITS_COMMENT
if A.key === Fits"COMMENT" || A.key === Fits"HISTORY"
print(io, " => ")
show(io, A.comment)
else
print(io, " => (nothing, ")
show(io, A.comment)
print(io, "=> (nothing, ")
end
else
commented = !isempty(A.comment)
if commented
print(io, " => (")
else
print(io, " => ")
end
if A.type == FITS_LOGICAL
print(io, A.logical ? "true" : "false")
elseif A.type == FITS_INTEGER
show(io, A.integer)
elseif A.type == FITS_FLOAT
show(io, A.float)
elseif A.type == FITS_COMPLEX
show(io, A.complex)
elseif A.type == FITS_STRING
show(io, A.string)
elseif A.type == FITS_UNDEFINED
print(io, "undef")
end
if commented
print(io, ", ")
show(io, A.comment)
print(io, ")")
end
end
end
print(io, ")")
end
# This version is for the REPL. We try to approximate FITS syntax.
function Base.show(io::IO, mime::MIME"text/plain", A::FitsCard)
print(io, "FitsCard: ")
print(io, A.name)
if A.type != FITS_END
if A.key === Fits"HIERARCH"
print(io, ' ')
else
n = ncodeunits(A.name)
while n < FITS_SHORT_KEYWORD_SIZE
print(io, ' ')
n += 1
end
end
end
if A.type == FITS_COMMENT
print(io, A.comment)
elseif A.type != FITS_END
print(io, "= ")
if A.type == FITS_LOGICAL
print(io, A.logical ? 'T' : 'F')
elseif A.type == FITS_INTEGER
show(io, A.integer)
elseif A.type == FITS_FLOAT
show(io, A.float)
elseif A.type == FITS_COMPLEX
print(io, "(")
show(io, real(A.complex))
print(io, ", ")
show(io, imag(A.complex))
print(io, ")")
elseif A.type == FITS_STRING
q = '\''
print(io, q)
for c in A.string
if c == q
print(io, q, q)
else
print(io, c)
end
end
print(io, q)
elseif A.type == FITS_UNDEFINED
print(io, "<undefined>")
end
if !isempty(A.comment)
print(io, " / ", A.comment)
end
end
end
# Callable object representing a FITS card value.
struct FitsCardValue
parent::FitsCard
end
Base.parent(A::FitsCardValue) = getfield(A, :parent)
(A::FitsCardValue)() = get_value(parent(A))
(A::FitsCardValue)(::Type{T}) where {T} = get_value(T, parent(A))
Base.show(io::IO, A::FitsCardValue) = show(io, A())
Base.show(io::IO, mime::MIME"text/plain", A::FitsCardValue) = show(io, mime, A())
# General conversion rules.
Base.convert(::Type{T}, A::FitsCardValue) where {T<:FitsCardValue} = A
Base.convert(::Type{T}, A::FitsCardValue) where {T} = A(T)
# Explict conversion rules are to avoid ambiguities.
Base.convert(::Type{T}, A::FitsCardValue) where {T<:Number} = A(T)
for T in (Integer, Real, AbstractFloat, Complex,
AbstractString, String, Nothing, Undef)
@eval Base.convert(::Type{$T}, A::FitsCardValue) = A($T)
end
# `apply(f, A, B)` apply binary operator `f` to `A` and `B` at least one being
# a card value.
function apply(f, A::FitsCardValue, B::FitsCardValue)
A = parent(A)
type = get_type(A)
type == FITS_LOGICAL ? apply(f, get_value_logical( A), B) :
type == FITS_INTEGER ? apply(f, get_value_integer( A), B) :
type == FITS_FLOAT ? apply(f, get_value_float( A), B) :
type == FITS_STRING ? apply(f, get_value_string( A), B) :
type == FITS_COMPLEX ? apply(f, get_value_complex( A), B) :
type == FITS_UNDEFINED ? apply(f, undef, B) : apply(f, nothing, B)
end
function apply(f, A::FitsCardValue, B::Any)
A = parent(A)
type = get_type(A)
type == FITS_LOGICAL ? f(get_value_logical( A), B) :
type == FITS_INTEGER ? f(get_value_integer( A), B) :
type == FITS_FLOAT ? f(get_value_float( A), B) :
type == FITS_STRING ? f(get_value_string( A), B) :
type == FITS_COMPLEX ? f(get_value_complex( A), B) :
type == FITS_UNDEFINED ? f(undef, B) : f(nothing, B)
end
function apply(f, A::Any, B::FitsCardValue)
B = parent(B)
type = get_type(B)
type == FITS_LOGICAL ? f(A, get_value_logical(B)) :
type == FITS_INTEGER ? f(A, get_value_integer(B)) :
type == FITS_FLOAT ? f(A, get_value_float( B)) :
type == FITS_STRING ? f(A, get_value_string( B)) :
type == FITS_COMPLEX ? f(A, get_value_complex(B)) :
type == FITS_UNDEFINED ? f(A, undef) : f(A, nothing)
end
for op in (:(==), :(<))
@eval begin
Base.$op(A::FitsCardValue, B::FitsCardValue) = apply($op, A, B)
Base.$op(A::FitsCardValue, B::Any) = apply($op, A, B)
Base.$op(A::Any, B::FitsCardValue) = apply($op, A, B)
end
end
# Conversion rules for a date. The FITS standard imposes ISO-8601 formatting
# for a date and time.
(A::FitsCardValue)(::Type{DateTime}) = parse(DateTime, A(String), ISODateTimeFormat)
Base.convert(::Type{DateTime}, A::FitsCardValue) = A(DateTime)
Dates.DateTime(A::FitsCardValue) = A(DateTime)
# If the FitsCard structure changes, it should be almost sufficient to change
# the following simple accessors.
get_type( A::FitsCard) = getfield(A, :type)
get_key( A::FitsCard) = getfield(A, :key)
get_name( A::FitsCard) = getfield(A, :name)
get_comment( A::FitsCard) = getfield(A, :comment)
get_value_logical(A::FitsCard) = !iszero(getfield(A, :value_integer))
get_value_integer(A::FitsCard) = getfield(A, :value_integer)
get_value_complex(A::FitsCard) = getfield(A, :value_complex)
get_value_float( A::FitsCard) = real(get_value_complex(A))
get_value_string( A::FitsCard) = getfield(A, :value_string)
get_value( A::FitsCard) = begin
type = get_type(A)
type == FITS_LOGICAL ? get_value_logical(A) :
type == FITS_INTEGER ? get_value_integer(A) :
type == FITS_FLOAT ? get_value_float( A) :
type == FITS_STRING ? get_value_string( A) :
type == FITS_COMPLEX ? get_value_complex(A) :
type == FITS_UNDEFINED ? undef :
nothing # FITS_COMMENT or FITS_END
end
get_value(::Type{Undef}, A::FitsCard) =
get_type(A) == FITS_UNDEFINED ? undef : conversion_error(Undef, A)
get_value(::Type{Nothing}, A::FitsCard) =
((get_type(A) == FITS_COMMENT)|(get_type(A) == FITS_END)) ? nothing : conversion_error(Nothing, A)
get_value(::Type{String}, A::FitsCard) =
get_type(A) == FITS_STRING ? get_value_string(A) : conversion_error(String, A)
get_value(::Type{Bool}, A::FitsCard) = begin
type = get_type(A)
type == FITS_LOGICAL ? get_value_logical(A) :
type == FITS_INTEGER ? convert(Bool, get_value_integer(A)) :
type == FITS_FLOAT ? convert(Bool, get_value_float( A)) :
type == FITS_COMPLEX ? convert(Bool, get_value_complex(A)) :
conversion_error(Bool, A)
end
get_value(::Type{FitsInteger}, A::FitsCard) = begin
type = get_type(A)
type == FITS_INTEGER ? get_value_integer(A) :
type == FITS_LOGICAL ? convert(FitsInteger, get_value_logical(A)) :
type == FITS_FLOAT ? convert(FitsInteger, get_value_float( A)) :
type == FITS_COMPLEX ? convert(FitsInteger, get_value_complex(A)) :
conversion_error(FitsInteger, A)
end
get_value(::Type{FitsFloat}, A::FitsCard) = begin
type = get_type(A)
type == FITS_FLOAT ? get_value_float( A) :
type == FITS_LOGICAL ? convert(FitsFloat, get_value_logical(A)) :
type == FITS_INTEGER ? convert(FitsFloat, get_value_integer(A)) :
type == FITS_COMPLEX ? convert(FitsFloat, get_value_complex(A)) :
conversion_error(FitsFloat, A)
end
get_value(::Type{FitsComplex}, A::FitsCard) = begin
type = get_type(A)
type == FITS_COMPLEX ? get_value_complex(A) :
type == FITS_FLOAT ? convert(FitsComplex, get_value_float( A)) :
type == FITS_LOGICAL ? convert(FitsComplex, get_value_logical(A)) :
type == FITS_INTEGER ? convert(FitsComplex, get_value_integer(A)) :
conversion_error(FitsComplex, A)
end
get_value(::Type{Integer}, A::FitsCard) = get_value(FitsInteger, A)
get_value(::Type{Real}, A::FitsCard) = get_value(FitsFloat, A)
get_value(::Type{AbstractFloat}, A::FitsCard) = get_value(FitsFloat, A)
get_value(::Type{Complex}, A::FitsCard) = get_value(FitsComplex, A)
get_value(::Type{AbstractString}, A::FitsCard) = get_value(String, A)
get_value(::Type{T}, A::FitsCard) where {T<:Number} = begin
type = get_type(A)
type == FITS_LOGICAL ? convert(T, get_value_logical(A)) :
type == FITS_INTEGER ? convert(T, get_value_integer(A)) :
type == FITS_FLOAT ? convert(T, get_value_float( A)) :
type == FITS_COMPLEX ? convert(T, get_value_complex(A)) :
conversion_error(T, A)
end
get_value(::Type{T}, A::FitsCard) where {T} = conversion_error(T, A) # catch errors
@noinline conversion_error(::Type{T}, A::FitsCard) where {T} =
error("value of FITS keyword \"$(get_name(A))\" cannot be converted to `$T`")
# Properties.
Base.propertynames(A::FitsCard) =
(:type, :key, :name, :value, :comment, :logical, :integer, :float, :complex,
:string, :units, :unitless)
Base.getproperty(A::FitsCard, sym::Symbol) = getproperty(A, Val(sym))
Base.getproperty(A::FitsCard, ::Val{:type }) = get_type(A)
Base.getproperty(A::FitsCard, ::Val{:key }) = get_key(A)
Base.getproperty(A::FitsCard, ::Val{:name }) = get_name(A)
Base.getproperty(A::FitsCard, ::Val{:value }) = FitsCardValue(A)
Base.getproperty(A::FitsCard, ::Val{:comment }) = get_comment(A)
Base.getproperty(A::FitsCard, ::Val{:logical }) = get_value(Bool, A)
Base.getproperty(A::FitsCard, ::Val{:integer }) = get_value(FitsInteger, A)
Base.getproperty(A::FitsCard, ::Val{:float }) = get_value(FitsFloat, A)
Base.getproperty(A::FitsCard, ::Val{:string }) = get_value(String, A)
Base.getproperty(A::FitsCard, ::Val{:complex }) = get_value(FitsComplex, A)
Base.getproperty(A::FitsCard, ::Val{:units }) = get_units_part(get_comment(A))
Base.getproperty(A::FitsCard, ::Val{:unitless}) = get_unitless_part(get_comment(A))
@noinline Base.setproperty!(A::FitsCard, sym::Symbol, x) =
error("attempt to set read-only property of FITS card")
"""
FitsCardType(T)
yields the FITS header card type code corresponding to Julia type `T`, one of:
`FITS_LOGICAL`, `FITS_INTEGER`, `FITS_FLOAT`, `FITS_COMPLEX`, `FITS_STRING`,
`FITS_COMMENT`, or `FITS_UNDEFINED`.
"""
FitsCardType(::Type{<:Bool}) = FITS_LOGICAL
FitsCardType(::Type{<:Integer}) = FITS_INTEGER
FitsCardType(::Type{<:AbstractFloat}) = FITS_FLOAT
FitsCardType(::Type{<:Complex}) = FITS_COMPLEX
FitsCardType(::Type{<:AbstractString}) = FITS_STRING
FitsCardType(::Type{<:Nothing}) = FITS_COMMENT
FitsCardType(::Type{<:Undefined}) = FITS_UNDEFINED
"""
FitsCardType(card::FitsCard)
card.type
yield the type code of the FITS header card `card`, one of: `FITS_LOGICAL`,
`FITS_INTEGER`, `FITS_FLOAT`, `FITS_COMPLEX`, `FITS_STRING`, `FITS_COMMENT`, or
`FITS_UNDEFINED`.
"""
FitsCardType(A::FitsCard) = get_type(A)
Base.isassigned(A::FitsCard) =
(A.type != FITS_COMMENT) & (A.type != FITS_UNDEFINED) & (A.type != FITS_END)
Base.isinteger(A::FitsCard) =
(A.type == FITS_INTEGER) | (A.type == FITS_LOGICAL)
Base.isreal(A::FitsCard) =
(A.type == FITS_FLOAT) |
(A.type == FITS_INTEGER) |
(A.type == FITS_LOGICAL) |
(A.type == FITS_COMPLEX && iszero(imag(get_value_complex(A))))
"""
valtype(x::Union{FitsCard,FitsCardType}) -> T
yields the Julia type `T` corresponding to a given FITS card or card type.
"""
@inline Base.valtype(A::FitsCard) = valtype(A.type)
Base.valtype(t::FitsCardType) =
t === FITS_LOGICAL ? Bool :
t === FITS_INTEGER ? FitsInteger :
t === FITS_FLOAT ? FitsFloat :
t === FITS_STRING ? String :
t === FITS_COMPLEX ? FitsComplex :
t === FITS_COMMENT ? Nothing :
t === FITS_UNDEFINED ? Undef :
t === FITS_END ? Nothing :
throw(ArgumentError("unexpected FITS card type"))
# FITS cards can be specified as pairs and conversely.
Base.convert(::Type{T}, A::FitsCard) where {T<:Pair} = T(A)
Base.convert(::Type{T}, pair::Pair) where {T<:FitsCard} = T(pair)
Base.Pair(A::FitsCard) = Pair(A.name, (A.value(), A.comment))
Base.Pair{K}(A::FitsCard) where {K} = Pair(as(K, A.name), (A.value(), A.comment))
Base.Pair{K,V}(A::FitsCard) where {K,V} = Pair(as(K, A.name), as(V, (A.value(), A.comment)))
FitsCard(pair::Pair{<:CardName, <:Any}) = build_card(pair...)
# Private helper function to build a FitsCard instance.
build_card(name::CardName, x) = build_card(check_keyword(name)..., x)
build_card(key::FitsKey, name::AbstractString, x::Tuple{CardValueExt,CardComment}) =
FitsCard(key, name, to_value(x[1]), to_comment(x[2]))
build_card(key::FitsKey, name::AbstractString, x::Tuple{CardValueExt}) =
FitsCard(key, name, to_value(x[1]), to_comment())
build_card(key::FitsKey, name::AbstractString, x::CardValueExt) =
FitsCard(key, name, to_value(x), to_comment())
build_card(key::FitsKey, name::AbstractString, x::AbstractString) =
is_comment(key) ? FitsCard(key, name, nothing, x) : FitsCard(key, name, x, to_comment())
@noinline build_card(key::FitsKey, name::AbstractString, x::X) where {X} =
throw(ArgumentError("invalid value and/or comment of type `$X` for FITS keyword `$name`"))
# Yield a bare card value. See alias `CardValueExt`.
to_value(val::CardValue) = val
to_value(val::DateTime) = Dates.format(val, ISODateTimeFormat)
# Yield a string from any instance of CardComment.
to_comment() = to_comment(nothing)
to_comment(com::AbstractString) = com
to_comment(com::Nothing) = EMPTY_STRING
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 18957 | module Headers
export FitsHeader
using ..FITSHeaders
using ..FITSHeaders: try_parse_keyword, is_comment
using ..FITSHeaders.Parser: full_name
using TypeUtils
using Base: @propagate_inbounds
using Base.Order: Ordering, Forward, Reverse
"""
FitsHeader(args...) -> hdr
yields a FITS header object initialized with records `args..`.
A FITS header object behaves as a vector of [`FitsCard`](@ref) elements with
integer or keyword (string) indices. When indexed by keywords, a FITS header
object is similar to a dictionary except that the order of records is preserved
and that commentary and continuation records (with keywords `"COMMENT"`,
`"HISTORY"`, `""`, or `"CONTINUE"`) may appear more than once.
To update or append a record to the FITS header `hdr`, call one of:
hdr[key] = x
push!(hdr, key => x)
where `x` is the value and/or comment of the record. If the keyword `key`
already exists in `hdr`, the record is updated, otherwise a new record is
appended. Commentary and continuation records are however always appended.
More generally, the `push!` method can be called as:
push!(hdr, rec)
where `rec` is a [`FitsCard`](@ref) object or anything, such as `key => x`,
that can be converted into an instance of this type.
To modify any existing record including commentary and continuation ones, use
the syntax:
hdr[i] = rec
where `i` is a linear (integer) index whule `rec` is a above.
Searching for the index `i` of an existing record in FITS header object `hdr`
can be done by the usual methods:
findfirst(what, hdr)
findlast(what, hdr)
findnext(what, hdr, start)
findprev(what, hdr, start)
which all return a valid integer index if a record matching `what` is found and
`nothing` otherwise. The matching pattern `what` can be a keyword (string), a
FITS card (an instance of [`FitsCard`](@ref) whose name is used as a matching
pattern), or a predicate function which takes a FITS card argument and returns
whether it matches. The find methods just yield `nothing` for any unsupported
kind of pattern.
"""
struct FitsHeader <: AbstractVector{FitsCard}
cards::Vector{FitsCard}
index::Dict{String,Int} # index to first (and unique for non-commentary and
# non-continuation keywords) entry with given
# keyword
# Build empty header or filled by keywords.
FitsHeader(; kwds...) =
merge!(new(FitsCard[], Dict{String,Int}()), values(kwds))
# Copy constructor.
FitsHeader(hdr::FitsHeader) = new(copy(hdr.cards), copy(hdr.index))
end
FitsHeader(args...) = merge!(FitsHeader(), args...)
FitsHeader(rec::Union{FitsCard,Pair}) = push!(FitsHeader(), FitsCard(rec))
Base.copy(hdr::FitsHeader) = FitsHeader(hdr)
Base.convert(::Type{<:FitsHeader}, hdr::FitsHeader) = hdr
Base.convert(::Type{<:FitsHeader}, iter) = FitsHeader(iter)
function Base.sizehint!(hdr::FitsHeader, n::Integer)
sizehint!(hdr.cards, n)
sizehint!(hdr.index, n)
return hdr
end
function Base.empty!(hdr::FitsHeader)
if length(hdr) > 0
empty!(hdr.cards)
empty!(hdr.index)
end
return hdr
end
Base.merge(hdr::FitsHeader, args...) = merge!(copy(hdr), args...)
Base.merge!(dest::FitsHeader) = dest
Base.merge!(dest::FitsHeader, A, B...) = merge!(merge!(dest, A), B...)
Base.merge!(dest::FitsHeader, other::Union{Pair,FitsCard}) = push!(dest, other)
function Base.merge!(dest::FitsHeader, other::FitsHeader)
if (len = length(other)) > 0
sizehint!(dest, length(dest) + len)
for card in other
push!(dest, card)
end
end
return dest
end
function Base.merge!(dest::FitsHeader, other::NamedTuple)
if (len = length(other)) > 0
sizehint!(dest, length(dest) + len)
for key in keys(other)
push!(dest, FitsCard(key => other[key]))
end
end
return dest
end
# By default, assume an iterable object.
function Base.merge!(dest::FitsHeader, other)
if has_length(other)
(len = length(other)) > 0 || return dest
sizehint!(dest, length(dest) + len)
end
for item ∈ other
push!(dest, FitsCard(item))
end
return dest
end
# Implement part of the abstract dictionary API.
Base.keys(hdr::FitsHeader) = keys(hdr.index)
function Base.getkey(hdr::FitsHeader, name::AbstractString, def)
c = try_parse_keyword(name)
c isa Char && return def # illegal FITS keyword
key, pfx = c
return getkey(hdr.index, full_name(pfx, name), def)
end
# Implement abstract array API.
Base.IndexStyle(::Type{<:FitsHeader}) = IndexLinear()
for func in (:length, :size, :axes)
@eval Base.$func(hdr::FitsHeader) = $func(hdr.cards)
end
Base.firstindex(hdr::FitsHeader) = 1
Base.lastindex(hdr::FitsHeader) = length(hdr)
@inline function Base.getindex(hdr::FitsHeader, i::Int)
@boundscheck checkbounds(hdr, i)
@inbounds getindex(hdr.cards, i)
end
@inline function Base.setindex!(hdr::FitsHeader, rec, i::Int)
@boundscheck checkbounds(hdr, i)
unsafe_setindex!(hdr, as(FitsCard, rec), i)
return hdr
end
# This unsafe method assumes that index i is valid.
function unsafe_setindex!(hdr::FitsHeader, new_card::FitsCard, i::Int)
@inbounds old_card = hdr.cards[i]
if !have_same_name(new_card, old_card)
# The name of the i-th card will change. We have to update the index
# accordingly.
#
# We first determine whether the index has to be updated for the name
# of the new card without touching the structure until the index has
# been updated for the name of the old card.
update_index_at_new_name = false
j = findfirst(new_card, hdr)
if j == nothing
# No other card exists in the header with this name.
update_index_at_new_name = true
elseif i != j
# The card name must be unique. Throwing an error here is painless
# because the structure has not yet been modified.
is_unique(new_card) && throw(ArgumentError(
"FITS keyword \"$(new_card.name)\" already exists at index $j"))
# Index must be updated for the new card name if new card will be
# the first one occurring in the header with this name.
update_index_at_new_name = i < j
end
# Now, do update index for the name of the old card.
if is_unique(old_card)
# There should be no other cards with the same name as the old
# card. Remove this name from the index.
delete!(hdr.index, old_card.name)
elseif findfirst(old_card, hdr) == i
# More than one card with the same name as the old card are allowed
# and the old card is the first with this name. Update the index
# with the next card with this name if one such exists in the
# index; otherwise, delete the name from the index.
k = findnext(old_card, hdr, i+1)
if k === nothing
delete!(hdr.index, old_card.name)
else
hdr.index[old_card.name] = k
end
end
if update_index_at_new_name
hdr.index[new_card.name] = i
end
end
# Remplace the old card by the new one.
@inbounds hdr.cards[i] = new_card
end
Base.setindex!(hdr::FitsHeader, val, name::AbstractString) = push!(hdr, name => val)
function Base.getindex(hdr::FitsHeader, name::AbstractString)
card = get(hdr, name, nothing)
card === nothing ? throw(KeyError(name)) : card
end
function Base.get(hdr::FitsHeader, i::Integer, def)
i = as(Int, i)
checkbounds(Bool, hdr, i) ? (@inbounds hdr[i]) : def
end
function Base.get(hdr::FitsHeader, name::AbstractString, def)
# NOTE: Call findfirst() to deal with HIERARCH convention.
i = findfirst(name, hdr)
i === nothing ? def : (@inbounds hdr[i])
end
Base.get(hdr::FitsHeader, key, def) = def
Base.haskey(hdr::FitsHeader, i::Integer) = checkbounds(Bool, hdr, i)
Base.haskey(hdr::FitsHeader, key::AbstractString) = findfirst(key, hdr) !== nothing
Base.haskey(hdr::FitsHeader, key) = false
"""
push!(hdr::FitsHeader, rec) -> hdr
appends a new record `rec` into the FITS header `hdr` or, if the keyword of the
card must be unique and a record with the same name already exists in `hdr`,
replaces the existing record.
This is strictly equivalent to:
hdr[key] = x
with `key` the name of the record, and `x` its associated value and/or comment.
Note that commentary and continuation records (with keywords `"COMMENT"`,
`"HISTORY"`, `""`, or `"CONTINUE"`) are always appended.
"""
function Base.push!(hdr::FitsHeader, card::FitsCard)
# Replace existing card with the same keyword if it must be unique.
# Otherwise, push a new card.
i = findfirst(card, hdr)
if i == nothing
# No card exists with this name, push a new one and index it.
hdr.index[card.name] = lastindex(push!(hdr.cards, card))
elseif is_unique(card)
# A card with this name must be unique, replace existing card.
@inbounds hdr.cards[i] = card
else
# Append the commentary or continuation card to the header.
push!(hdr.cards, card)
end
return hdr
end
Base.push!(hdr::FitsHeader, rec) = push!(hdr, as(FitsCard, rec))
"""
FITSHeaders.FullName(str) -> obj
yields the full name of a FITS header record given the, possibly shortened,
name `str`. The returned object has 2 properties: `obj.name` is the full name
and `obj.key` is the quick key uniquely representing the 8 first characters of
the full name.
The `"HIERARCH "` prefix being optional to match a FITS keyword, and the quick
key being useful to accelerate comparisons. `FullName` is a guarantee to have
the full name and the quick key built from a, possibly shortened, keyword name.
"""
struct FullName
key::FitsKey # quick key
name::String # full name
end
function FullName(str::AbstractString)
c = try_parse_keyword(str)
if c isa Char
# When parsing fails, return an instance that is unmatchable by any
# valid FITS card.
return FullName(zero(FitsKey), as(String, str))
else
key, pfx = c
return FullName(key, full_name(pfx, str))
end
end
# Yield whether name is a unique FITS keyword.
is_unique(obj::Union{FitsCard,FullName}) = is_unique(obj.key)
is_unique(key::FitsKey) =
(key !== Fits"COMMENT") &
(key !== Fits"HISTORY") &
(key !== Fits"CONTINUE") &
(key !== Fits"")
# Generic matcher to implement matching by regular expressions for example.
struct Matches{T} <: Function
pattern::T
end
(obj::Matches{Regex})(card::FitsCard) = match(obj.pattern, card.name) !== nothing
"""
findfirst(what, hdr::FitsHeader) -> i :: Union{Int,Nothing}
finds the first occurence of a record in FITS header `hdr` matching the pattern
`what`.
"""
Base.findfirst(what, hdr::FitsHeader) = nothing
"""
findlast(what, hdr::FitsHeader) -> i :: Union{Int,Nothing}
find the last occurence of a record in FITS header `hdr` matching the pattern
`what`.
"""
Base.findlast(what, hdr::FitsHeader) = nothing
"""
findnext(what, hdr::FitsHeader, start) -> i :: Union{Int,Nothing}
find the next occurence of a record in FITS header `hdr` matching the pattern
`what` at or after index `start`.
""" Base.findnext
"""
findprev(what, hdr::FitsHeader, start) -> i :: Union{Int,Nothing}
find the previous occurence of a record in FITS header `hdr` matching the
pattern `what` at or before index `start`.
""" Base.findprev
Base.findfirst(pat::Union{FitsCard,FullName}, hdr::FitsHeader) =
get(hdr.index, pat.name, nothing)
function Base.findlast(pat::Union{FitsCard,FullName}, hdr::FitsHeader)
first = findfirst(pat, hdr)
first === nothing && return nothing
is_unique(pat) && return first
# Enter slow part...
@inbounds for i ∈ lastindex(hdr):-1:first+1
have_same_name(pat, hdr.cards[i]) && return i
end
return first
end
# String and card patterns are treated specifically because the dictionary
# storing the header index can be directly used. Other patterns are converted
# to predicate functions.
Base.findfirst(func::Function, hdr::FitsHeader) =
unsafe_findnext(func, hdr, firstindex(hdr))
Base.findlast(func::Function, hdr::FitsHeader) =
unsafe_findprev(func, hdr, lastindex(hdr))
for func in (:findfirst, :findlast)
@eval begin
function Base.$func(str::AbstractString, hdr::FitsHeader)
pat = FullName(str)
return iszero(pat.key) ? nothing : $func(pat, hdr)
end
function Base.$func(pat::Regex, hdr::FitsHeader)
return $func(Matches(pat), hdr)
end
end
end
# NOTE: First stage of `findnext` and `findprev` avoids costly conversion if
# result can be decided without actually searching. Need to specify type of
# `what` in function signature to avoid ambiguities.
for T in (Any, AbstractString, FullName, FitsCard, Function)
@eval begin
function Base.findnext(what::$T, hdr::FitsHeader, start::Integer)
start = as(Int, start)
start > lastindex(hdr) && return nothing
start < firstindex(hdr) && throw(BoundsError(hdr, start))
return unsafe_findnext(what, hdr, start)
end
function Base.findprev(what::$T, hdr::FitsHeader, start::Integer)
start = as(Int, start)
start < firstindex(hdr) && return nothing
start > lastindex(hdr) && throw(BoundsError(hdr, start))
return unsafe_findprev(what, hdr, start)
end
end
end
for func in (:unsafe_findnext, :unsafe_findprev)
@eval begin
function $func(str::AbstractString, hdr::FitsHeader, start::Int)
pat = FullName(str)
return iszero(pat.key) ? nothing : $func(pat, hdr, start)
end
function $func(pat::Regex, hdr::FitsHeader, start::Int)
return $func(Matches(pat), hdr, start)
end
end
end
# By default, find nothing.
unsafe_findnext(pat, hdr::FitsHeader, start::Int) = nothing
unsafe_findprev(pat, hdr::FitsHeader, start::Int) = nothing
function unsafe_findnext(pat::Union{FitsCard,FullName}, hdr::FitsHeader, start::Int)
first = findfirst(pat, hdr)
first === nothing && return nothing
start ≤ first && return first
is_unique(pat) && return nothing
# Enter slow part...
@inbounds for i ∈ start:lastindex(hdr)
have_same_name(pat, hdr.cards[i]) && return i
end
return nothing
end
function unsafe_findprev(pat::Union{FitsCard,FullName}, hdr::FitsHeader, start::Int)
first = findfirst(pat, hdr)
first === nothing && return nothing
start < first && return nothing
is_unique(pat) && return first
# Enter slow part...
@inbounds for i ∈ start:-1:first+1
have_same_name(pat, hdr.cards[i]) && return i
end
return first
end
function unsafe_findnext(func::Function, hdr::FitsHeader, start::Int)
@inbounds for i ∈ start:lastindex(hdr)
func(hdr.cards[i]) && return i
end
return nothing
end
function unsafe_findprev(func::Function, hdr::FitsHeader, start::Int)
@inbounds for i ∈ start:-1:firstindex(hdr)
func(hdr.cards[i]) && return i
end
return nothing
end
function have_same_name(A::Union{FitsCard,FullName}, B::FitsCard)
A.key === B.key || return false
A.key === Fits"HIERARCH" || return true
A.name === B.name || isequal(A.name, B.name)
end
"""
eachmatch(what, hdr::FitsHeader)
yields an iterator over the records of `hdr` matching `what`.
For example:
@inbounds for rec in eachmatch(what, hdr)
... # do something
end
is equivalent to:
i = findfirst(what, hdr)
@inbounds while i !== nothing
rec = hdr[i]
... # do something
i = findnext(what, hdr, i+1)
end
while:
@inbounds for rec in reverse(eachmatch(what, hdr))
... # do something
end
is equivalent to:
i = findlast(what, hdr)
@inbounds while i !== nothing
rec = hdr[i]
... # do something
i = findprev(what, hdr, i-1)
end
"""
Base.eachmatch(what, hdr::FitsHeader) = HeaderIterator(what, hdr)
struct HeaderIterator{O<:Ordering,P}
pattern::P
header::FitsHeader
HeaderIterator(ord::O, pat::P, hdr::FitsHeader) where {O,P} =
new{O,P}(pat, hdr)
end
HeaderIterator(pat, hdr::FitsHeader) = HeaderIterator(Forward, pat, hdr)
HeaderIterator(ord::Ordering, pat::AbstractString, hdr::FitsHeader) =
HeaderIterator(ord, FullName(pat), hdr)
HeaderIterator(ord::Ordering, pat::Regex, hdr::FitsHeader) =
HeaderIterator(ord, Matches(pat), hdr)
Base.IteratorEltype(::Type{<:HeaderIterator}) = Base.HasEltype()
Base.eltype(::Type{<:HeaderIterator}) = FitsCard
# Extend length for HeaderIterator but pretend its size is unknown because the
# implementation of the length method is rather inefficient.
Base.IteratorSize(::Type{<:HeaderIterator}) = Base.SizeUnknown()
function Base.length(iter::HeaderIterator)
n = 0
for rec in iter
n += 1
end
return n
end
Base.reverse(iter::HeaderIterator{typeof(Forward)}) =
HeaderIterator(Reverse, iter.pattern, iter.header)
Base.reverse(iter::HeaderIterator{typeof(Reverse)}) =
HeaderIterator(Forward, iter.pattern, iter.header)
# Iterate over entries in forward order.
function Base.iterate(iter::HeaderIterator{typeof(Forward)})
j = findfirst(iter.pattern, iter.header)
j === nothing ? nothing : ((@inbounds iter.header[j]), j+1)
end
function Base.iterate(iter::HeaderIterator{typeof(Forward)}, i::Int)
j = findnext(iter.pattern, iter.header, i)
j === nothing ? nothing : ((@inbounds iter.header[j]), j+1)
end
# Iterate over entries in reverse order.
function Base.iterate(iter::HeaderIterator{typeof(Reverse)})
j = findlast(iter.pattern, iter.header)
j === nothing ? nothing : ((@inbounds iter.header[j]), j-1)
end
function Base.iterate(iter::HeaderIterator{typeof(Reverse)}, i::Int)
j = findprev(iter.pattern, iter.header, i)
j === nothing ? nothing : ((@inbounds iter.header[j]), j-1)
end
"""
collect(what, hdr::FitsHeader; order::Ordering = Forward)
yields a vector of the records of `hdr` matching `what` and sorted according to
`order` (`Base.Order.Forward` or `Base.Order.Reverse`).
"""
function Base.collect(what, hdr::FitsHeader; order::Ordering = Forward)
iter = HeaderIterator(order, what, hdr)
dest = FitsCard[]
has_length(iter) && sizehint!(dest, length(iter))
for rec in iter
push!(dest, rec)
end
return dest
end
function Base.filter(what, hdr::FitsHeader; order::Ordering = Forward)
iter = HeaderIterator(order, what, hdr)
dest = FitsHeader()
has_length(iter) && sizehint!(dest, length(iter))
for rec in iter
push!(dest, rec)
end
return dest
end
has_length(iter) = Base.IteratorSize(iter) isa Union{Base.HasShape,Base.HasLength}
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 51378 | """
FITSHeaders.Parser
A sub-module of the `FITSHeaders` package implementing methods for parsing FITS
header cards.
"""
module Parser
using ..FITSHeaders
using ..FITSHeaders:
FitsInteger,
FitsFloat,
FitsComplex
using Compat
using Base: @propagate_inbounds
# To create a byte buffer to be converted to a string, it is faster to call
# StringVector(n) rather than Vector{UInt8}(undef,n).
using Base: StringVector
const EMPTY_STRING = ""
@inline is_little_endian() = (ENDIAN_BOM === 0x04030201)
@inline is_big_endian() = (ENDIAN_BOM === 0x01020304)
is_little_endian() || is_big_endian() || error("unsupported byte order")
"""
FITS_CARD_SIZE
is the number of bytes per FITS header card.
"""
const FITS_CARD_SIZE = 80
"""
FITS_BLOCK_SIZE
is the number of bytes per FITS header/data block.
"""
const FITS_BLOCK_SIZE = 36*FITS_CARD_SIZE # 2880
"""
FITS_SHORT_KEYWORD_SIZE
is the number of bytes in a short FITS keyword, that is all FITS keyword but
the `HIERARCH` ones. If a FITS keyword is shorther than this, it is equivalent
to pad it with ASCII spaces (hexadecimal code 0x20).
"""
const FITS_SHORT_KEYWORD_SIZE = 8
"""
FITSHeaders.Parser.PointerCapability(T) -> Union{PointerNone,PointerFull}
yields whether `Base.unsafe_convert(Ptr{UInt8},obj)` and
`Base.cconvert(Ptr{UInt8},obj)` are fully implemented for an object `obj` of
type `T`. This also means that the object is stored in memory for some
contiguous range of addresses.
"""
abstract type PointerCapability end
struct PointerNone <: PointerCapability end
struct PointerFull <: PointerCapability end
PointerCapability(A::Any) = PointerCapability(typeof(A))
PointerCapability(::Type{<:Union{Array,String,SubString{String}}}) = PointerFull()
PointerCapability(::Type) = PointerNone()
"""
FITSHeaders.Parser.ByteString
is the union of types of strings that can be considered as vectors of bytes to
implement fast parsing methods (see [`FITSHeaders.Parser.ByteBuffer`](@ref)).
FITS header cards consist in character from the restricted set of ASCII
characters from `' '` to `'~'` (hexadecimal codes 0x20 to 0x7E). Hence Julia
strings (encoded in ASCII or in UTF8) can be treated as vectors of bytes.
"""
const ByteString = Union{String,SubString{String}}
"""
FITSHeaders.Parser.ByteVector
is an alias for types that can be considered as vectors of bytes to
implement fast parsing methods (see [`FITSHeaders.Parser.ByteBuffer`](@ref)).
"""
const ByteVector = AbstractVector{UInt8}
"""
FITSHeaders.Parser.ByteBuffer
is the union of types that can be considered as buffers of bytes and that can
treated as vectors of bytes to parse FITS header cards using the following
helper functions (assuming `A isa ByteBuffer` holds):
first_byte_index(A) # yields the index of the first byte in A
last_byte_index(A) # yields the index of the last byte in A
byte_index_range(A) # yields the range of byte indices in A
get_byte(A,i) # yields the i-th byte from A
See [`FITSHeaders.Parser.ByteString`](@ref) and [`FITSHeaders.Parser.ByteVector`](@ref).
"""
const ByteBuffer = Union{ByteString,ByteVector}
"""
FITSHeaders.Parser.get_byte(T = UInt8, A, i)
yields the `i`-th byte of `A` which may be a vector of bytes or a string.
Optional first argument `T` is to specify the data type of the returned value.
When parsing a FITS header or keyword, it is possible to specify the index `n`
of the last available byte in `A` and call:
FITSHeaders.Parser.get_byte(T = UInt8, A, i, n)
which yields the `i`-th byte of `A` if `i ≤ n` and `0x20` (an ASCII space)
otherwise.
This function propagates the `@inbounds` macro.
"""
@inline @propagate_inbounds get_byte(A::ByteVector, i::Int) = getindex(A, i)
@inline @propagate_inbounds get_byte(A::ByteString, i::Int) = codeunit(A, i)::UInt8
@inline @propagate_inbounds get_byte(A, i::Int, n::Int) = (i ≤ n ? get_byte(A, i) : 0x20)
@inline @propagate_inbounds get_byte(::Type{T}, args...) where {T<:Unsigned} = get_byte(args...) % T
"""
FITSHeaders.Parser.first_byte_index(A)
yields the index of the first byte in `A`.
"""
@inline first_byte_index(A::ByteString) = firstindex(A)
@inline first_byte_index(A::ByteVector) = firstindex(A)
"""
FITSHeaders.Parser.last_byte_index(A)
yields the index of the last byte in `A`.
"""
@inline last_byte_index(A::ByteString) = ncodeunits(A) + (firstindex(A) - 1)
@inline last_byte_index(A::ByteVector) = lastindex(A)
"""
FITSHeaders.Parser.byte_index_range(A)
yields the range of byte indices in `A`.
"""
@inline byte_index_range(buf::ByteBuffer) = first_byte_index(buf):last_byte_index(buf)
# Yields an empty index range starting at given index.
empty_range(i::Int = 1) = i:i-1
@inline function check_byte_index(buf::ByteBuffer, i::Int)
i_first, i_last = first_byte_index(buf), last_byte_index(buf)
(i_first ≤ i ≤ i_last) || throw(BoundsError(buf, i))
end
@inline function check_byte_index(buf::ByteBuffer, rng::AbstractUnitRange{Int},
n::Int = last_byte_index(buf))
check_byte_index(buf, first(rng), last(rng), n)
end
@inline function check_byte_index(buf::ByteBuffer, i::Int, j::Int,
n::Int = last_byte_index(buf))
((i > j) | ((i ≥ first_byte_index(buf)) & (j ≤ n))) || throw(BoundsError(buf, i:j))
end
"""
FitsKey(buf, off=0, i_last=last_byte_index(buf))
encodes the, at most, first $FITS_SHORT_KEYWORD_SIZE bytes (or ASCII
characters) of `buf`, starting at offset `off`, in a 64-bit integer value which
is exactly equal to the first $FITS_SHORT_KEYWORD_SIZE bytes of a FITS keyword
as stored in a FITS header. Argument `buf` may be a string or a vector of
bytes.
Optional argument `i_last` is the index of the last byte available in `buf`. If
fewer than $FITS_SHORT_KEYWORD_SIZE bytes are available (that is, if `off +
$FITS_SHORT_KEYWORD_SIZE > i_last`), the result is as if `buf` has been padded
with ASCII spaces (hexadecimal code 0x20).
The only operation that makes sense with an instance of `FitsKey` is comparison
for equality for fast searching of keywords in a FITS header.
The caller may use `@inbounds` macro if it is certain that bytes in the range
`off+1:i_last` are in bounds for `buf`.
For the fastest, but unsafe, computations call:
FitsKey(Val(:full), buf, off)
FitsKey(Val(:pad), buf, off, i_last)
where first argument should be `Val(:full)` if there are at least
$FITS_SHORT_KEYWORD_SIZE bytes available after `off`, and `Val(:pad)`
otherwise. These variants do not perfom bounds checking, it is the caller's
responsibility to insure that the arguments are consistent.
"""
struct FitsKey
val::UInt64
end
@assert sizeof(FitsKey) == FITS_SHORT_KEYWORD_SIZE
Base.convert(::Type{FitsKey}, x::FitsKey) = x
Base.convert(::Type{FitsKey}, x::Integer) = FitsKey(x)
"""
FitsKey()
zero(FitsKey)
yield a null FITS key, that is whose bytes are all 0. This can be asserted by
calling `issero` on the returned key. Since any valid FITS key cannot contain
null bytes, a null FITS key may be useful for searching keys.
"""
FitsKey() = FitsKey(zero(UInt64))
# NOTE: Other constructors are implemented in parser.jl
Base.iszero(key::FitsKey) = iszero(key.val)
Base.zero(::Union{FitsKey,Type{FitsKey}}) = FitsKey()
Base.:(==)(a::FitsKey, b::FitsKey) = a.val === b.val
Base.convert(::Type{T}, key::FitsKey) where {T<:Integer} = convert(T, key.val)
Base.UInt64(key::FitsKey) = key.val
function Base.String(key::FitsKey)
buf = StringVector(FITS_SHORT_KEYWORD_SIZE)
len = @inbounds decode!(buf, key; offset = 0)
return String(resize!(buf, len))
end
Base.show(io::IO, mime::MIME"text/plain", key::FitsKey) = show(io, key)
function Base.show(io::IO, key::FitsKey)
# FIXME: Improve the following test.
flag = true
for i in 0:sizeof(FitsKey)-1
flag &= is_restricted_ascii((key.val >> (i<<3)) % UInt8)
end
if flag
# Can be printed as a regular FITS keyword.
buf = Vector{UInt8}(undef, FITS_SHORT_KEYWORD_SIZE + 6)
buf[1] = 'F'
buf[2] = 'i'
buf[3] = 't'
buf[4] = 's'
buf[5] = '"'
len = @inbounds decode!(buf, key; offset = 5) + 1
buf[len] = '"'
if len < length(buf)
write(io, view(buf, Base.OneTo(len)))
else
write(io, buf)
end
else
# Certainly not a regular FITS keyword.
write(io, "FitsKey(", repr(key.val), ")")
end
return nothing # do not return the number of bytes written
end
# Decode FITS quick key. Returns index of last non-space character which is
# also the length if the buffer has 1-based indices.
@inline function decode!(buf::AbstractVector{UInt8},
key::FitsKey;
offset::Int = 0)
i_first = (offset + firstindex(buf))::Int
i_last = (i_first + (FITS_SHORT_KEYWORD_SIZE - 1))::Int
I = i_first:i_last
@boundscheck ((offset ≥ 0) & (i_last ≤ lastindex(buf))) || throw(BoundsError(buf, I))
val = key.val
shft = is_little_endian() ? 0 : 8*(FITS_SHORT_KEYWORD_SIZE-1)
incr = is_little_endian() ? +8 : -8
i_last = offset
@inbounds for i in I
byte = (val >> shft) % UInt8
shft += incr
if byte != 0x20
i_last = i
end
buf[i] = byte
end
return i_last
end
"""
@Fits_str
A macro to construct a 64-bit quick key equivalent to the FITS keyword given in
argument and as it is stored in the header of a FITS file. The argument must be
a short FITS keyword (e.g., not a `HIERARCH` one) specified as a literal string
of, at most, $FITS_SHORT_KEYWORD_SIZE ASCII characters with no trailing spaces.
For example `Fits"SIMPLE"` or `Fits"NAXIS2"`.
The result is the same as that computed by `FitsKey` but since the quick key is
given by a string macro, it is like a constant computed at compile time with no
runtime penalty.
"""
macro Fits_str(str::String)
FitsKey(check_short_keyword(str))
end
"""
FITSHeaders.check_short_keyword(str) -> str
returns the string `str` throwing an exception if `str` is not a short FITS
keyword consisting in, at most, $FITS_SHORT_KEYWORD_SIZE ASCII characters from
the restricted set of upper case letters (bytes 0x41 to 0x5A), decimal digits
(hexadecimal codes 0x30 to 0x39), hyphen (hexadecimal code 0x2D), or underscore
(hexadecimal code 0x5F).
"""
function check_short_keyword(str::ByteString)
rng = byte_index_range(str)
@inbounds for i in rng
is_keyword(get_byte(str, i)) || error("invalid character in short FITS keyword \"$str\"")
end
length(rng) ≤ FITS_SHORT_KEYWORD_SIZE || error("too many characters in FITS keyword \"$str\"")
return str
end
equal(b::UInt8, c::Char) = equal(b, UInt8(c))
equal(b::T, c::T) where {T} = b === c
between(x::UInt8, lo::Char, hi::Char) = between(x, UInt8(lo), UInt8(hi))
between(x::T, lo::T, hi::T) where {T} = (lo ≤ x) & (x ≤ hi)
const C_RESTRICTED_ASCII = 0x01 << 0
const C_KEYWORD = 0x01 << 1
const C_DIGIT = 0x01 << 2
const C_UPPERCASE = 0x01 << 3
const C_LOWERCASE = 0x01 << 4
const C_STARTS_LOGICAL = 0x01 << 5
const C_STARTS_NUMBER = 0x01 << 6
function build_ctype()
code = zeros(UInt8, 256)
firstindex(code) === 1 || throw(AssertionError("firstindex(code) === 1"))
typemin(UInt8) === 0x00 || throw(AssertionError("typemin(UInt8) === 0x00"))
typemax(UInt8) === 0xFF || throw(AssertionError("typemax(UInt8) === 0xFF"))
typemin(Char) == Char(0) || throw(AssertionError("typemin(Char) == Char(0)"))
promote_type(UInt8, Int) === Int || throw(AssertionError("promote_type(UInt8, Int) === Int"))
for c in ' ':'~'
code[c%UInt8 + 1] |= C_RESTRICTED_ASCII
end
for c in '0':'9'
code[c%UInt8 + 1] |= C_DIGIT|C_KEYWORD|C_STARTS_NUMBER
end
for c in 'A':'Z'
code[c%UInt8 + 1] |= C_UPPERCASE|C_KEYWORD
end
for c in 'a':'z'
code[c%UInt8 + 1] |= C_LOWERCASE
end
code['T'%UInt8 + 1] |= C_STARTS_LOGICAL
code['F'%UInt8 + 1] |= C_STARTS_LOGICAL
code['.'%UInt8 + 1] |= C_STARTS_NUMBER
code['+'%UInt8 + 1] |= C_STARTS_NUMBER
code['-'%UInt8 + 1] |= C_KEYWORD|C_STARTS_NUMBER
code['_'%UInt8 + 1] |= C_KEYWORD
return code
end
const C_TYPE = build_ctype()
c_type(c::UInt8) = @inbounds C_TYPE[c + 1]
c_type(c::Char) = ifelse(c%UInt < length(C_TYPE), c_type(c%UInt8), zero(eltype(C_TYPE)))
is_digit(c::Union{Char,UInt8}) = between(c, '0', '9')
is_uppercase(c::Union{Char,UInt8}) = between(c, 'A', 'Z')
is_lowercase(c::Union{Char,UInt8}) = between(c, 'a', 'z')
is_space(c::Union{Char,UInt8}) = equal(c, ' ')
is_space(c1::T, c2::T) where {T<:Union{Char,UInt8}} = is_space(c1) & is_space(c2)
@inline is_space(c1::T, c2::T, c3::T...) where {T<:Union{Char,UInt8}} = is_space(c1, c2) & is_space(c3...)
is_quote(c::Union{Char,UInt8}) = equal(c, '\'')
is_equals_sign(c::Union{Char,UInt8}) = equal(c, '=')
is_hyphen(c::Union{Char,UInt8}) = equal(c, '-')
is_underscore(c::Union{Char,UInt8}) = equal(c, '_')
is_comment_separator(c::Union{Char,UInt8}) = equal(c, '/')
is_opening_parenthesis(c::Union{Char,UInt8}) = equal(c, '(')
is_closing_parenthesis(c::Union{Char,UInt8}) = equal(c, ')')
is_restricted_ascii(c::Union{Char,UInt8}) = between(c, ' ', '~')
is_keyword(c::Union{Char,UInt8}) = (c_type(c) & C_KEYWORD) == C_KEYWORD
starts_logical(c::Union{Char,UInt8}) = (c_type(c) & C_STARTS_LOGICAL) == C_STARTS_LOGICAL
starts_number(c::Union{Char,UInt8}) = (c_type(c) & C_STARTS_NUMBER) == C_STARTS_NUMBER
@inline function FitsKey(buf::ByteBuffer, off::Int = 0)
i_last = last_byte_index(buf)
@boundscheck check_byte_index(buf, off+1, min(off+FITS_SHORT_KEYWORD_SIZE, i_last), i_last)
off + FITS_SHORT_KEYWORD_SIZE ≤ i_last ? FitsKey(Val(:full), buf, off) :
FitsKey(Val(:pad), buf, off, i_last)
end
@inline function FitsKey(buf::ByteBuffer, off::Int, i_last::Int)
@boundscheck check_byte_index(buf, off+1, min(off+FITS_SHORT_KEYWORD_SIZE, i_last))
off + FITS_SHORT_KEYWORD_SIZE ≤ i_last ? FitsKey(Val(:full), buf, off) :
FitsKey(Val(:pad), buf, off, i_last)
end
@inline FitsKey(val::Val{:full}, buf::ByteBuffer, off::Int) =
FitsKey(PointerCapability(buf), val, buf, off)
@inline FitsKey(::PointerFull, ::Val{:full}, buf::Vector{UInt8}, off::Int) =
GC.@preserve buf unsafe_load(Base.unsafe_convert(Ptr{FitsKey}, buf) + off)
@inline function FitsKey(::PointerCapability, ::Val{:full}, buf::ByteBuffer, off::Int)
@inbounds begin
@static if is_little_endian()
# Little-endian byte order.
k = (get_byte(UInt64, buf, off + 1) << 0) |
(get_byte(UInt64, buf, off + 2) << 8) |
(get_byte(UInt64, buf, off + 3) << 16) |
(get_byte(UInt64, buf, off + 4) << 24) |
(get_byte(UInt64, buf, off + 5) << 32) |
(get_byte(UInt64, buf, off + 6) << 40) |
(get_byte(UInt64, buf, off + 7) << 48) |
(get_byte(UInt64, buf, off + 8) << 56)
else
# Big-endian byte order.
k = (get_byte(UInt64, buf, off + 1) << 56) |
(get_byte(UInt64, buf, off + 2) << 48) |
(get_byte(UInt64, buf, off + 3) << 40) |
(get_byte(UInt64, buf, off + 4) << 32) |
(get_byte(UInt64, buf, off + 5) << 24) |
(get_byte(UInt64, buf, off + 6) << 16) |
(get_byte(UInt64, buf, off + 7) << 8) |
(get_byte(UInt64, buf, off + 8) << 0)
end
end
return FitsKey(k)
end
@inline function FitsKey(::Val{:pad}, buf::ByteBuffer, off::Int, i_last::Int)
@inbounds begin
@static if is_little_endian()
# Little-endian byte order.
k = (get_byte(UInt64, buf, off + 1, i_last) << 0) |
(get_byte(UInt64, buf, off + 2, i_last) << 8) |
(get_byte(UInt64, buf, off + 3, i_last) << 16) |
(get_byte(UInt64, buf, off + 4, i_last) << 24) |
(get_byte(UInt64, buf, off + 5, i_last) << 32) |
(get_byte(UInt64, buf, off + 6, i_last) << 40) |
(get_byte(UInt64, buf, off + 7, i_last) << 48) |
(get_byte(UInt64, buf, off + 8, i_last) << 56)
else
# Big-endian byte order.
k = (get_byte(UInt64, buf, off + 1, i_last) << 56) |
(get_byte(UInt64, buf, off + 2, i_last) << 48) |
(get_byte(UInt64, buf, off + 3, i_last) << 40) |
(get_byte(UInt64, buf, off + 4, i_last) << 32) |
(get_byte(UInt64, buf, off + 5, i_last) << 24) |
(get_byte(UInt64, buf, off + 6, i_last) << 16) |
(get_byte(UInt64, buf, off + 7, i_last) << 8) |
(get_byte(UInt64, buf, off + 8, i_last) << 0)
end
end
return FitsKey(k)
end
"""
FITSHeaders.is_structural(A::Union{FitsKey,FitsCard})
yields whether `A` is a structural FITS keyword or card.
"""
function is_structural(key::FitsKey)
# NOTE This version takes 4.5ns to 7.2ns compared to 30ns with a set of all
# such keys.
b = (is_little_endian() ? key.val : (key.val >> 56)) % UInt8
b == UInt8('N') ? is_structural_N(key) :
b == UInt8('B') ? is_structural_B(key) :
b == UInt8('S') ? is_structural_S(key) :
b == UInt8('X') ? is_structural_X(key) :
b == UInt8('T') ? is_structural_T(key) :
b == UInt8('E') ? is_structural_E(key) :
b == UInt8('P') ? is_structural_P(key) :
b == UInt8('G') ? is_structural_G(key) : false
end
# Yeild whether key is a structural key starting with a `T`, a `E`, etc.
is_structural_B(key::FitsKey) = (key === Fits"BITPIX")
is_structural_S(key::FitsKey) = (key === Fits"SIMPLE")
is_structural_E(key::FitsKey) = (key === Fits"EXTEND") | (key === Fits"END")
is_structural_X(key::FitsKey) = (key === Fits"XTENSION")
is_structural_P(key::FitsKey) = (key === Fits"PCOUNT")
is_structural_G(key::FitsKey) = (key === Fits"GCOUNT")
is_structural_N(key::FitsKey) = is_naxis(key)
is_structural_T(key::FitsKey) = begin
key === Fits"TFIELDS" && return true
mask = (is_little_endian() ? 0x000000FFFFFFFFFF : 0xFFFFFFFFFF000000)
root = (key.val & mask)
if (root == (Fits"TFORM".val & mask)) | (root == (Fits"TTYPE".val & mask))
# Get the 3 trailing bytes.
b1, b2, b3 = if is_little_endian()
(key.val >> 40) % UInt8,
(key.val >> 48) % UInt8,
(key.val >> 56) % UInt8
else
(key.val >> 16) % UInt8,
(key.val >> 8) % UInt8,
(key.val ) % UInt8
end
return is_indexed(b1, b2, b3)
end
mask = (is_little_endian() ? 0x00000000FFFFFFFF : 0xFFFFFFFF00000000)
if (key.val & mask) == (Fits"TDIM".val & mask)
# Get the 4 trailing bytes.
b1, b2, b3, b4 = if is_little_endian()
(key.val >> 32) % UInt8,
(key.val >> 40) % UInt8,
(key.val >> 48) % UInt8,
(key.val >> 56) % UInt8
else
(key.val >> 24) % UInt8,
(key.val >> 16) % UInt8,
(key.val >> 8) % UInt8,
(key.val ) % UInt8
end
# NOTE: Last byte must be a space because the maximum number of columns
# is 999.
return is_space(b4) && is_indexed(b1, b2, b3)
end
return false
end
"""
FITSHeaders.Parser.is_indexed(b...)
yields whether trailing bytes `b...` of a FITS keyword indicate an indexed
keyword.
"""
is_indexed() = false
is_indexed(b1::UInt8) = is_digit(b1)
@inline is_indexed(b1::UInt8, b2::UInt8...) =
is_indexed(b1) & (is_space(b2...) | is_indexed(b2...))
"""
FITSHeaders.is_comment(A::Union{FitsCardType,FitsCard})
yields whether `A` indicates a, possibly non-standard, commentary FITS keyword.
FITSHeaders.is_comment(key::FitsKey)
yields whether `key` is `Fits"COMMENT"` or `Fits"HISTORY"` which corresponds to
a standard commentary FITS keyword.
"""
is_comment(key::FitsKey) = (key == Fits"COMMENT") | (key == Fits"HISTORY")
is_comment(type::FitsCardType) = type === FITS_COMMENT
"""
FITSHeaders.is_naxis(A::Union{FitsKey,FitsCard})
yields whether `A` is a FITS "NAXIS" or "NAXIS#" keyword or card with`#`
denoting a decimal number.
"""
function is_naxis(key::FitsKey)
mask = (is_little_endian() ? 0x000000FFFFFFFFFF : 0xFFFFFFFFFF000000)
if (key.val & mask) == (Fits"NAXIS".val & mask)
# Get the 3 trailing bytes.
b1, b2, b3 = if is_little_endian()
(key.val >> 40) % UInt8,
(key.val >> 48) % UInt8,
(key.val >> 56) % UInt8
else
(key.val >> 16) % UInt8,
(key.val >> 8) % UInt8,
(key.val ) % UInt8
end
return is_space(b1) ? is_space(b2, b3) : is_indexed(b1, b2, b3)
end
return false
end
"""
FITSHeaders.is_end(A::Union{FitsKey,FitsCardType,FitsCard})
yields whether `A` indicates the END FITS keyword.
"""
is_end(key::FitsKey) = (key == Fits"END")
is_end(type::FitsCardType) = type === FITS_END
for sym in (:logical, :integer, :float, :string, :complex)
parse_func = Symbol("parse_$(sym)_value")
try_parse_func = Symbol("try_parse_$(sym)_value")
mesg = "failed to parse value of $sym FITS card"
@eval begin
@inline function $parse_func(buf::ByteBuffer, rng::AbstractUnitRange{Int})
val = $try_parse_func(buf, rng)
isnothing(val) && throw(ArgumentError($mesg))
return val
end
$try_parse_func(buf::ByteBuffer) =
@inbounds $try_parse_func(buf, byte_index_range(buf))
end
end
function try_parse_logical_value(buf::ByteBuffer,
rng::AbstractUnitRange{Int})
i = first(rng)
last(rng) == i || return nothing
@boundscheck check_byte_index(buf, i)
@inbounds b = get_byte(buf, i)
return equal(b, 'T') ? true : equal(b, 'F') ? false : nothing
end
function try_parse_integer_value(buf::ByteBuffer,
rng::AbstractUnitRange{Int})
len = length(rng)
len > 0 || return nothing
@boundscheck check_byte_index(buf, rng)
@inbounds begin
# Proceed as if the value was negative to avoid overflows, because
# abs(typemin(Int)) > typemax(Int).
i_first, i_last = first(rng), last(rng)
b = get_byte(buf, i_first)
negate = true
if equal(b, '-')
negate = false
i_first += 1
elseif equal(b, '+')
i_first += 1
end
i_first ≤ i_last || return nothing # no digits
val = zero(FitsInteger)
off = oftype(val, '0')
ten = oftype(val, 10)
for i in i_first:i_last
b = get_byte(buf, i)
is_digit(b) || return nothing
val = ten*val - (oftype(val, b) - off)
val ≤ zero(val) || return nothing # integer overflow
end
return negate ? -val : val
end
end
# Replace 'd' or 'D' by 'e' and leave other characters unchanged.
filter_character_in_float_value(c::Union{UInt8,Char}) =
ifelse(equal(c, 'D')|equal(c, 'd'), oftype(c, 'e'), c)
function try_parse_float_value(buf::ByteBuffer,
rng::AbstractUnitRange{Int})
len = length(rng)
len > 0 || return nothing
@boundscheck check_byte_index(buf, rng)
# Use a temporary array to copy the range of bytes replacing 'd' and 'D' by 'e'.
wrk = StringVector(len)
off = first(rng) - firstindex(wrk)
@inbounds for i in eachindex(wrk)
wrk[i] = filter_character_in_float_value(get_byte(buf, off + i))
end
return tryparse(FitsFloat, String(wrk))
end
function try_parse_string_value(buf::ByteBuffer,
rng::AbstractUnitRange{Int})
len = length(rng)
len > 0 || return nothing
@boundscheck check_byte_index(buf, rng)
@inbounds begin
# Check whether we do have a quoted string.
i_first, i_last = first(rng), last(rng)
(len ≥ 2 &&
is_quote(get_byte(buf, i_first)) &&
is_quote(get_byte(buf, i_last))) || return nothing
i_first += 1 # remove opening quote
i_last -= 1 # remove closing quote
# Get rid of trailing spaces.
while i_last ≥ i_first && is_space(get_byte(buf, i_last))
i_last -= 1
end
i_last ≥ i_first || return EMPTY_STRING
# Copy the string into a temporary buffer taking care of escaped
# quotes. Trailing spaces have already been stripped, so it is not
# necessary to treat spaces specially.
#
# NOTE: We cannot use a simple for-loop because indices may have to be
# incremented inside the loop.
wrk = StringVector(i_last - i_first + 1)
i = i_first - 1
j = firstindex(wrk) - 1
while i < i_last
b = get_byte(buf, i += 1)
if is_quote(b)
# Next character must aslo be a quote.
i < i_last || return nothing # error
b = get_byte(buf, i += 1)
is_quote(b) || return nothing # error
end
wrk[j += 1] = b
end
len = j - firstindex(wrk) + 1
len > 0 || return EMPTY_STRING
return String(resize!(wrk, len))
end
end
function try_parse_complex_value(buf::ByteBuffer,
rng::AbstractUnitRange{Int})
len = length(rng)
len > 0 || return nothing
@boundscheck check_byte_index(buf, rng)
@inbounds begin
# Check whether we do have a string like "(re,im)", hence with at least
# 5 characters, starting with '(' and ending with ')'.
i_first, i_last = first(rng), last(rng)
(len ≥ 5 &&
is_opening_parenthesis(get_byte(buf, i_first)) &&
is_closing_parenthesis(get_byte(buf, i_last))) || return nothing
i_first += 1 # remove opening parenthesis
i_last -= 1 # remove closing parenthesis
# Search for the ',' separator and parse the real and imaginary parts.
for i ∈ i_first:i_last
if equal(get_byte(buf, i += 1), ',')
re = @inbounds try_parse_float_value(buf, i_first : i - 1)
re === nothing && break
im = @inbounds try_parse_float_value(buf, i + 1 : i_last)
im === nothing && break
return FitsComplex(re, im)
end
end
return nothing
end
end
"""
FITSHeaders.Parser.make_string(buf, rng) -> str::String
yields a string from the bytes of `buf` in the range of indices `rng`.
"""
@inline function make_string(buf::ByteBuffer, rng::AbstractUnitRange{Int})
len = length(rng)
iszero(len) && return EMPTY_STRING
@boundscheck check_byte_index(buf, rng)
return unsafe_make_string(PointerCapability(buf), buf, rng)
end
function unsafe_make_string(::PointerFull, buf::ByteBuffer,
rng::AbstractUnitRange{Int})
# Directly build a string from the buffer.
len = length(rng)
off = first(rng) - 1
obj = Base.cconvert(Ptr{UInt8}, buf) # object to be preserved
ptr = Base.unsafe_convert(Ptr{UInt8}, obj) + off
return GC.@preserve obj unsafe_string(ptr, len)
end
function unsafe_make_string(::PointerCapability, buf::ByteBuffer,
rng::AbstractUnitRange{Int})
# Use a temporary workspace to copy the range of bytes.
len = length(rng)
wrk = StringVector(len)
off = first(rng) - firstindex(wrk)
@inbounds for i in eachindex(wrk)
wrk[i] = get_byte(buf, off + i)
end
return String(wrk)
end
"""
FITSHeaders.Parser.scan_card(A, off=0) -> type, key, name_rng, val_rng, com_rng
parses a FITS header card `A` as it is written in a FITS file. `A` may be a
string or a vector of bytes. Optional argument `off` is an offset in bytes
where to start the parsing. At most, $FITS_CARD_SIZE bytes after `off` are
considered in `A` which may thus belong to a larger piece of data (e.g., a FITS
header). The result is a 5-tuple:
- `type::FitsCardType` is the type of the card value.
- `key::FitsKey` is the quick key corresponding to the short keyword of the
card.
- `name_rng` is the range of bytes containing the keyword name without trailing
spaces.
- `val_rng` is the range of bytes containing the unparsed value part, without
leading and trailing spaces but with parenthesis or quote delimiters for a
complex or a string card. This range is empty for a commentary card, the
`END` card, or if the card has an undefined value.
- `com_rng` is the range of bytes containing the comment part without
non-significant spaces.
"""
function scan_card(buf::ByteBuffer, off::Int = 0)
off ≥ 0 || throw(ArgumentError("offset must be nonnegative"))
i_first = off + first_byte_index(buf)
i_last = min(last_byte_index(buf), i_first - 1 + FITS_CARD_SIZE)
if i_first > i_last
# Empty range, return the parameters of an END card to reflect that
# except that the name range is empty.
rng = empty_range(i_first)
return FITS_END, Fits"END", rng, rng, rng
end
@inbounds begin # NOTE: above settings warrant that
key, name_rng, i_next = scan_keyword_part(buf, i_first:i_last)
if !is_comment(key)
# May be a non-commentary FITS card.
if key == Fits"END"
# Remaining part shall contains only spaces
com_rng = trim_leading_spaces(buf, i_next:i_last)
isempty(com_rng) || nonspace_in_end_card(get_byte(buf, first(com_rng)))
val_rng = empty_range(i_last)
return FITS_END, key, name_rng, val_rng, com_rng
elseif i_first ≤ i_next ≤ i_last - 1 &&
is_equals_sign(get_byte(buf, i_next)) &&
is_space(get_byte(buf, i_next + 1))
# Value marker found, scan for the value and comment parts.
type, val_rng, com_rng = scan_value_comment_parts(buf, i_next+2:i_last)
return type, key, name_rng, val_rng, com_rng
end
end
# Commentary card: no value and a comment in bytes 9-80.
val_rng = empty_range(i_next)
com_rng = trim_trailing_spaces(buf, i_next:i_last)
return FITS_COMMENT, key, name_rng, val_rng, com_rng
end
end
"""
FITSHeaders.Parser.scan_short_keyword_part(A, rng) -> name_rng
scans the first bytes of `A` in the index range `rng` for a valid short FITS
keyword and returns the index range to this keyword. A short FITS keyword
consists in, at most, $FITS_SHORT_KEYWORD_SIZE ASCII characters from the
restricted set of upper case letters (bytes 0x41 to 0x5A), decimal digits
(hexadecimal codes 0x30 to 0x39), hyphen (hexadecimal code 0x2D), or underscore
(hexadecimal code 0x5F). Trailing spaces are ignored.
The following relations hold:
first(name_rng) == first(rng)
length(name_rng) ≤ min(length(rng), $FITS_SHORT_KEYWORD_SIZE)
In case scanning shall be pursued, the next token to scan starts at or after
index:
i_next = first(name_rng) + $FITS_SHORT_KEYWORD_SIZE
"""
@inline function scan_short_keyword_part(buf::ByteBuffer, rng::AbstractUnitRange{Int})
@boundscheck check_byte_index(buf, rng)
@inbounds begin
i_first = first(rng)
i_last = min(i_first + (FITS_SHORT_KEYWORD_SIZE - 1), last(rng))
nspaces = 0
for i in i_first:i_last
b = get_byte(buf, i)
if is_space(b)
nspaces += 1
elseif is_keyword(b)
iszero(nspaces) || bad_character_in_keyword(' ')
else
bad_character_in_keyword(b)
end
end
return i_first : i_last - nspaces
end
end
"""
FITSHeaders.Parser.scan_keyword_part(A, rng) -> key, name_rng, i_next
parses a the keyword part of FITS header card stored in bytes `rng` of `A`.
Returns `key` the keyword quick key, `name_rng` the byte index range for the
keyword name (with leading "HIERARCH "` and trailing spaces removed), and
`i_next` the index of the first byte where next token (value marker of comment)
may start.
"""
function scan_keyword_part(buf::ByteBuffer, rng::AbstractUnitRange{Int})
# Scan for the short FITS keyword part.
name_rng = scan_short_keyword_part(buf, rng)
# Retrieve limits for byte indices and index of next token assuming a short
# FITS keyword for now.
i_first, i_last = first(rng), last(rng)
i_next = i_first + FITS_SHORT_KEYWORD_SIZE
# NOTE: scan_short_keyword_part() has already checked the range for us.
@inbounds begin
# Compute fast code equivalent to the short FITS keyword.
off = i_first - 1
key = off + FITS_SHORT_KEYWORD_SIZE ≤ i_last ? FitsKey(Val(:full), buf, off) :
FitsKey(Val(:pad), buf, off, i_last)
if key == Fits"HIERARCH" && i_first ≤ i_next ≤ i_last - 2 && is_space(get_byte(buf, i_next))
# Parse HIERARCH keyword. Errors are deferred until the value
# marker "= " is eventually found.
i_error = i_first - 1 # index of first bad character
nspaces = 1 # to count consecutive spaces
i_mark = i_first - 1 # index where long FITS keyword may end
for i in i_next+1:i_last
b = get_byte(buf, i)
if is_space(b)
nspaces += 1
elseif is_keyword(b)
# Update last index of long keyword to that of the last non-space.
i_mark = i
if (nspaces > 1) & (i_error < i_first)
# Having more than one consecutive space is forbidden.
i_error = i
end
nspaces = 0
elseif is_equals_sign(b)
if i_mark ≥ i_first && i < i_last && is_space(get_byte(buf, i+1))
# Value marker found. The index for the next token is
# that of the = sign.
if i_error ≥ i_first
# Some illegal character was found.
bad_character_in_keyword(get_byte(buf, i_error))
end
return key, i_first:i_mark, i
else
# This is not a long keyword, it will result in a
# commentary HIERARCH card.
break
end
elseif i_error < i_first
i_error = i
end
end
end
end
# Short FITS keyword.
return key, name_rng, i_next
end
"""
FITSHeaders.Parser.full_name(pfx, name::AbstractString)
yields `"HIERARCH "*name` if `pfx` is true, `name` otherwise. The result is a
`String`.
"""
full_name(pfx::Bool, name::AbstractString)::String =
pfx ? "HIERARCH "*name : String(name)
"""
FITSHeaders.keyword(name) -> full_name
yields the full FITS keyword corresponding to `name`, throwing an exception if
`name` is not a valid FITS keyword. The result is equal to either `name` or
to `"HIERARCH "*name`.
Examples:
``` jldoctest
julia> FITSHeaders.keyword("GIZMO")
"GIZMO"
julia> FITSHeaders.keyword("HIERARCH GIZMO")
"HIERARCH GIZMO"
julia> FITSHeaders.keyword("GIZ MO")
"HIERARCH GIZ MO"
julia> FITSHeaders.keyword("VERYLONGNAME")
"HIERARCH VERYLONGNAME"
```
where the 1st one is a short FITS keyword (with less than
$FITS_SHORT_KEYWORD_SIZE characters), the 3rd one is explictely a `HIERARCH`
keyword, while the 3rd and 4th ones are automatically turned into `HIERARCH`
keywords because the 3rd one contains a space and because the 4th one is longer
than $FITS_SHORT_KEYWORD_SIZE characters.
See also [`FITSHeaders.check_keyword`](@ref) and
[`FITSHeaders.Parser.full_name`](@ref).
"""
keyword(name::Symbol) = keyword(String(name))
function keyword(name::AbstractString)
c = try_parse_keyword(name)
c isa Char && bad_character_in_keyword(c)
key, pfx = c
return full_name(pfx, name)
end
"""
FITSHeaders.check_keyword(name) -> key, full_name
checks the FITS keyword `name` and returns the corresponding quick key and full
keyword name throwing an exception if `name` is not a valid FITS keyword. The
full keyword name is a `string` instance either equal to `name` or to `"HIERARCH "*name`.
See also [`FITSHeaders.keyword`](@ref), [`FITSHeaders.parse_keyword`](@ref), and
[`FITSHeaders.Parser.full_name`](@ref).
"""
check_keyword(name::Symbol) = check_keyword(String(name))
function check_keyword(name::AbstractString)
c = try_parse_keyword(name)
c isa Char && bad_character_in_keyword(c)
key, pfx = c
return key, full_name(pfx, name)
end
"""
FITSHeaders.try_parse_keyword(str)
parses the FITS keyword given by string `str`. In case of parsing error, the
result is the first illegal character encountered in `str`. Otherwise, the
result is the 2-tuple `(key,pfx)` with `key` the quick key of the keyword and
`pfx` a boolean indicating whether the `"HIERARCH "` prefix should be prepended
to `str` to form the full keyword name. If the string has more than
$FITS_SHORT_KEYWORD_SIZE characters or if any single space separator occurs in
the string, a `HIERARCH` keyword is assumed even though the string does not
start with `"HIERARCH "`. Leading and trailing spaces are not allowed.
The returned `key` is `Fits"HIERARCH"` in 4 cases:
- The string starts with `"HIERARCH "` followed by a name, possibly split in
several words and possibly longer than $FITS_SHORT_KEYWORD_SIZE characters,
`pfx` is `false`.
- The string does not starts with `"HIERARCH "` but consists in at least two
space-separated words, `pfx` is true.
- The string does not starts with `"HIERARCH "` but is longer than
$FITS_SHORT_KEYWORD_SIZE characters, `pfx` is true.
- The string is `"HIERARCH"`, `pfx` is `false`.
"""
function try_parse_keyword(str::Union{String,SubString{String}})
# NOTE: `str` is encoded in UTF-8 with codeunits that are bytes. Since FITS
# keywords must only consist in restricted ASCII characters (bytes less or
# equal that 0x7F), we can access the string as a vector of bytes.
# Moreover, if an illegal codeunit is encountered, its index is also the
# correct index of the offending ASCII (byte less or equal that 0x7F) or
# UTF8 character (byte greater that 0x7F).
@inbounds begin
# Compute quick key of the short FITS keyword, this is a cheap way to
# figure out whether the sequence of bytes starts with "HIERARCH". This
# does not check for the validity of the leading bytes, unless the key
# is Fits"HIERARCH".
len = ncodeunits(str)
key = len ≥ FITS_SHORT_KEYWORD_SIZE ? FitsKey(Val(:full), str, 0) :
FitsKey(Val(:pad), str, 0, len)
any_space = false # any space found so far?
pfx = false # must add "HIERARCH " prefix?
i = 1 # starting index
if key == Fits"HIERARCH"
# String starts with "HIERARCH". There are 3 possibilities:
#
# 1. The string is exactly "HIERARCH".
#
# 2. The string starts with "HIERARCH " and is thus a regular
# HIERARCH keyword.
#
# 2. The string starts with "HIERARCHx" where x is any valid
# non-space character. The string is thus too long to be a
# simple FITS keyword and the HIERARCH convention must be used.
# The prefix "HIERARCH " must be prepended for that.
#
# Which of these apply requires to look at next character. In any
# case, the leading FITS_SHORT_KEYWORD_SIZE bytes are valid, so we
# increment index i to not re-check this part.
i += FITS_SHORT_KEYWORD_SIZE
# If at least one more byte is available, we are in cases 2 or 3; in
# case 1 otherwise.
if i ≤ len
b = get_byte(str, i)
if is_space(b)
# Case 2: the sequence starts with "HIERARCH ".
any_space = true
elseif is_keyword(b)
# Case 3: the keyword is too long and a "HIERARCH " prefix
# must be prepended.
pfx = true
else
return str[i] # illegal character
end
i += 1
end
elseif len ≥ 1
# We must verify that the first byte is valid (not a space).
b = get_byte(str, i)
is_keyword(b) || return str[i] # illegal character
i += 1
# A long keyword implies using the HIERARCH convention.
if len > FITS_SHORT_KEYWORD_SIZE
key = Fits"HIERARCH"
pfx = true
end
end
# Check remaining bytes.
while i ≤ len
b = get_byte(str, i)
if is_space(b)
# It is an error to have 2 or more consecutive spaces.
any_space && return str[i] # illegal character
any_space = true
# Keyword must be a HIERARCH one because it has at least one
# space separator. If this was not already detected, the
# "HIERARCH " is missing.
if key != Fits"HIERARCH"
key = Fits"HIERARCH"
pfx = true
end
elseif is_keyword(b)
# Not a space.
any_space = false
else
return str[i] # illegal character
end
i += 1
end
any_space && return ' ' # illegal character
return key, pfx
end
end
"""
FITSHeaders.Parser.scan_value_comment_parts(buf, rng) -> type, val_rng, com_rng
scans the range `rng` of bytes to find the value and comment of a FITS card
stored in `buf`. If `rng` is not empty, `first(rng)` shall be the index of the
first byte where the value may be found, that is right after the value
indicator `"= "`, and `last(rng)` shall be the index of the last byte to scan.
For speed, these are not checked. The result is a tuple with `type` the type of
the FITS card value, `val_rng` the index range for the unparsed value part, and
`com_rng` the index range of the comment part without leading spaces.
"""
function scan_value_comment_parts(buf::ByteBuffer, rng::AbstractUnitRange{Int})
# Skip leading spaces.
i, k = first(rng), last(rng)
@inbounds while i ≤ k && is_space(get_byte(buf, i))
i += 1
end
if i > k
# There were only spaces: the value is undefined and the comment is
# empty.
return FITS_UNDEFINED, i:k, i:k
end
# Guess card type based on first non-space byte.
b = get_byte(buf, i)
if starts_number(b)
# Integer or float value.
type = equal(b, '.') ? FITS_FLOAT : FITS_INTEGER
for j in i+1:k
b = get_byte(buf, j)
if is_digit(b)
continue
elseif is_space(b) | is_comment_separator(b)
return type, i:j-1, scan_comment_part(buf, j:k)
else
type = FITS_FLOAT
end
end
# Value with no comment.
return type, i:k, k+1:k
elseif is_quote(b)
# Quoted string value. Find the closing quote. NOTE: The search loop
# cannot be a for-loop because running index j has to be incremented
# twice when an escaped quote is encountered.
j = i
while j < k
j += 1
if is_quote(get_byte(buf, j))
j += 1
if j > k || !is_quote(get_byte(buf, j))
# Closing quote found.
return FITS_STRING, i:j-1, scan_comment_part(buf, j:k)
end
end
end
error("no closing quote in string value of FITS header card")
elseif equal(b, 'F') | equal(b, 'T')
return FITS_LOGICAL, i:i, scan_comment_part(buf, i+1:k)
elseif is_opening_parenthesis(b)
# Complex value.
for j in i+1:k
if is_closing_parenthesis(get_byte(buf, j))
return FITS_COMPLEX, i:j, scan_comment_part(buf, j+1:k)
end
end
error("no closing parenthesis in complex value of FITS header card")
elseif is_comment_separator(b)
# Comment marker found before value, the value is undefined.
return FITS_UNDEFINED, i:i-1, scan_comment_part(buf, i:k)
else
error("unexpected character in FITS header card")
end
end
"""
FITSHeaders.Parser.scan_comment_part(buf, rng) -> com_rng
scans the range `rng` of bytes to find the comment part of a FITS card stored
in `buf`. If `rng` is not empty, `first(rng)` shall be the index of the first
byte where the comment separator may be found, that is right after the last
byte of the value part, and `last(rng)` shall be the index of the last byte to
scan. For speed, these are not checked. The result is the index range for the
comment part.
This method honors the bound-checking state.
"""
@inline function scan_comment_part(buf::ByteBuffer, rng::AbstractUnitRange{Int})
@boundscheck check_byte_index(buf, rng)
@inbounds begin
# Find beginning of comment skipping all spaces before and after the
# comment separator.
i_first, i_last = first(rng), last(rng)
while i_first ≤ i_last
b = get_byte(buf, i_first)
i_first += 1
if is_comment_separator(b)
# Skip spaces after the comment separator.
while i_first ≤ i_last && is_space(get_byte(buf, i_first))
i_first += 1
end
# Skip trailing spaces.
while i_last ≥ i_first && is_space(get_byte(buf, i_last))
i_last -= 1
end
return i_first:i_last
elseif !is_space(b)
error("non-space before comment separator in FITS header card")
end
end
return empty_range(i_first)
end
end
# Units in comments.
function scan_units_marks(str::Union{String,SubString{String}})
@inbounds begin
# It is assumed that leading spaces have been trimmed.
i_first, i_last = first_byte_index(str), last_byte_index(str)
if i_first ≤ i_last && get_byte(str, i_first) == UInt8('[')
i = i_first
while i < i_last
i += 1
if get_byte(str, i) == UInt8(']')
return i_first:i
end
end
end
return empty_range(i_first) # yields i_first:i_first-1
end
end
# Yields the units part of a parsed comment.
function get_units_part(str::Union{String,SubString{String}})
@inbounds begin
rng = scan_units_marks(str)
i_first, i_last = first(rng), last(rng)
if i_first < i_last # is there at least 2 bytes (ASCII characters)?
i_first += 1 # skip opening [
i_last -= 1 # skip closing ]
# Trim leading spaces.
while i_first ≤ i_last && is_space(get_byte(str, i_first))
i_first += 1
end
# Trim trailing spaces.
while i_first ≤ i_last && is_space(get_byte(str, i_last))
i_last -= 1
end
if i_first ≤ i_last
return SubString(str, i_first, i_last)
end
end
return SubString(str, empty_range(first(rng)))
end
end
# Yields the unitless part of a parsed comment.
function get_unitless_part(str::Union{String,SubString{String}})
@inbounds begin
rng = scan_units_marks(str)
i_first, i_last = first(rng), last(rng)
if i_first > i_last
# No units.
return SubString(str, first_byte_index(str), last_byte_index(str))
else
# There are units.
#
# NOTE: In fact, scan_units_marks() warrants that last(rng)+1 is
# always the first byte of the unitless part whether there
# are units or not, so the code could be simplified.
i_first = i_last + 1
i_last = last_byte_index(str)
# Trim leading spaces.
while i_first ≤ i_last && is_space(get_byte(str, i_first))
i_first += 1
end
if i_first > i_last
# Empty unitless part.
i_first = first_byte_index(str)
i_last = i_first - 1
end
return SubString(str, i_first, i_last)
end
end
end
"""
FITSHeaders.Parser.trim_leading_spaces(buf[, rng]) -> sub_rng
yields the range `sub_rng` of byte indices in `buf` (a string or a vector of
bytes) without the leading spaces in `buf`. Optional argument `rng` is to
specify the range of byte indices to consider in `buf`. If `rng` is not
provided, all the bytes of `buf` are considered. If `rng` is provided,
`sub_rng` is such that:
first(sub_rng) ≥ first(rng)
last(sub_rng) == last(rng)
""" trim_leading_spaces
@inline function unsafe_trim_leading_spaces(buf::ByteBuffer, rng::AbstractUnitRange{Int})
i_first, i_last = first(rng), last(rng)
@inbounds while i_first ≤ i_last && is_space(get_byte(buf, i_first))
i_first += 1
end
return i_first:i_last
end
"""
FITSHeaders.Parser.trim_trailing_spaces(buf[, rng]) -> sub_rng
yields the range `sub_rng` of byte indices in `buf` (a string or a vector of
bytes) without the trailing spaces in `buf`. Optional argument `rng` is to
specify the range of byte indices to consider in `buf`. If `rng` is not
provided, all the bytes of `buf` are considered. If `rng` is provided,
`sub_rng` is such that:
first(sub_rng) == first(rng)
last(sub_rng) ≤ last(rng)
""" trim_trailing_spaces
@inline function unsafe_trim_trailing_spaces(buf::ByteBuffer, rng::AbstractUnitRange{Int})
i_first, i_last = first(rng), last(rng)
@inbounds while i_last ≥ i_first && is_space(get_byte(buf, i_last))
i_last -= 1
end
return i_first:i_last
end
# Implement higher level "safe" methods.
for func in (:trim_leading_spaces, :trim_trailing_spaces)
unsafe_func = Symbol("unsafe_$func")
@eval begin
$func(buf::ByteBuffer) = $unsafe_func(buf, byte_index_range(buf))
function $func(buf::ByteBuffer, rng::AbstractUnitRange{Int})
@boundscheck check_byte_index(buf, rng)
return $unsafe_func(buf, rng)
end
end
end
# Human readable Representation of a character.
repr_char(b::UInt8) = is_restricted_ascii(b) ? repr(Char(b)) : repr(b)
repr_char(c::Char) = (is_restricted_ascii(c) || ! isascii(c)) ? repr(c) : repr(UInt8(c))
@noinline nonspace_in_end_card(c::Union{Char,UInt8}) =
error("invalid non-space character $(repr_char(c)) in FITS END card")
@noinline bad_character_in_keyword(c::Union{Char,UInt8}) =
is_space(c) ? error("extra space character in FITS keyword") :
error("invalid character $(repr_char(c)) in FITS keyword")
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 1867 | module BenchmarkingFITSHeaders
using FITSHeaders
using BenchmarkTools
let s = "SIMPLE = T / this is a FITS file "
print("- parsing logical FITS card: ")
@btime FitsCard($s)
end
let s = "BITPIX = -32 / number of bits per data pixel "
print("- parsing integer FITS card: ")
@btime FitsCard($s)
end
let s = "HIERARCH ESO OBS EXECTIME = +2919 / Expected execution time "
print("- parsing HIERARCH FITS card:")
@btime FitsCard($s)
end
let s = "CRVAL3 = 0.96 / CRVAL along 3rd axis "
print("- parsing float FITS card: ")
@btime FitsCard($s)
end
let s = "COMPLEX = (-2.7,+3.1d5) / some other complex value "
print("- parsing complex FITS card: ")
@btime FitsCard($s)
end
let s = "EXTNAME = 'SCIDATA ' / a simple string "
print("- parsing string FITS card: ")
@btime FitsCard($s)
end
let s = "REMARK = 'Joe''s taxi' / a string with an embedded quote "
print("- parsing string with quotes:")
@btime FitsCard($s)
end
let s = "COMMENT Some comments (with leading spaces that should not be removed) "
print("- parsing COMMENT FITS card: ")
@btime FitsCard($s)
end
let s = "HISTORY A new history starts here... "
print("- parsing HISTORY FITS card: ")
@btime FitsCard($s)
end
let s = " "
print("- parsing blank FITS card: ")
@btime FitsCard($s)
end
let s = "END "
print("- parsing END FITS card: ")
@btime FitsCard($s)
end
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | code | 62294 | module TestingFITSHeaders
using TypeUtils
using Dates
using Test
using FITSHeaders
using FITSHeaders:
FitsInteger, FitsFloat, FitsComplex,
is_structural, is_comment, is_naxis, is_end
@static if ENDIAN_BOM == 0x04030201
const BYTE_ORDER = :little_endian
order_bytes(x) = bswap(x)
elseif ENDIAN_BOM == 0x01020304
const BYTE_ORDER = :big_endian
order_bytes(x) = x
else
error("unsupported byte order")
end
# Returns is only defined for Julia ≥ 1.7
struct Returns{V} <: Function; val::V; end
(obj::Returns)(args...; kwds...) = obj.val
make_FitsKey(str::AbstractString) =
FitsKey(reinterpret(UInt64,UInt8[c for c in str])[1])
function make_byte_vector(str::AbstractString)
@assert codeunit(str) === UInt8
vec = Array{UInt8}(undef, ncodeunits(str))
I, = axes(vec)
k = firstindex(str) - first(I)
for i in I
vec[i] = codeunit(str, i + k)
end
return vec
end
function make_discontinuous_byte_vector(str::AbstractString)
@assert codeunit(str) === UInt8
arr = Array{UInt8}(undef, 2, ncodeunits(str))
I, J = axes(arr)
i = last(I)
k = firstindex(str) - first(J)
for j in J
arr[i,j] = codeunit(str, j + k)
end
return view(arr, i, :)
end
_load(::Type{T}, buf::Vector{UInt8}, off::Integer = 0) where {T} =
GC.@preserve buf unsafe_load(Base.unsafe_convert(Ptr{T}, buf) + off)
_store!(::Type{T}, buf::Vector{UInt8}, x, off::Integer = 0) where {T} =
GC.@preserve buf unsafe_store!(Base.unsafe_convert(Ptr{T}, buf) + off, as(T, x))
@testset "FITSHeaders.jl" begin
@testset "Assertions" begin
# Check that `unsafe_load` and `unsafe_store!` are unaligned operations
# and that in `pointer + offset` expression the offset is in bytes (not
# in number of elements).
let buf = UInt8[b for b in 0x00:0xFF],
ptr = Base.unsafe_convert(Ptr{UInt64}, buf)
@test _load(UInt64, buf, 0) === order_bytes(0x0001020304050607)
@test _load(UInt64, buf, 1) === order_bytes(0x0102030405060708)
@test _load(UInt64, buf, 2) === order_bytes(0x0203040506070809)
@test _load(UInt64, buf, 3) === order_bytes(0x030405060708090A)
@test _load(UInt64, buf, 4) === order_bytes(0x0405060708090A0B)
@test _load(UInt64, buf, 5) === order_bytes(0x05060708090A0B0C)
@test _load(UInt64, buf, 6) === order_bytes(0x060708090A0B0C0D)
@test _load(UInt64, buf, 7) === order_bytes(0x0708090A0B0C0D0E)
val = order_bytes(0x0102030405060708)
for i in 0:7
_store!(UInt64, fill!(buf, 0x00), val, i)
for j in 0:7
@test _load(UInt64, buf, j) === (val >> (8*(j - i)))
end
end
end
@test sizeof(FitsKey) == 8
@test FITS_SHORT_KEYWORD_SIZE == 8
@test FITS_CARD_SIZE == 80
@test FITS_BLOCK_SIZE == 2880
end
@testset "FitsCardType" begin
@test FitsCardType(Bool) === FITS_LOGICAL
@test FitsCardType(Int16) === FITS_INTEGER
@test FitsCardType(Float32) === FITS_FLOAT
@test FitsCardType(ComplexF64) === FITS_COMPLEX
@test FitsCardType(String) === FITS_STRING
@test FitsCardType(Nothing) === FITS_COMMENT
@test FitsCardType(UndefInitializer) === FITS_UNDEFINED
@test FitsCardType(Missing) === FITS_UNDEFINED
end
@testset "Keywords" begin
@test iszero(FitsKey())
@test zero(FitsKey()) === FitsKey()
@test zero(FitsKey) === FitsKey()
@test convert(Integer, FitsKey()) === zero(UInt64)
@test convert(FitsKey, 1234) === FitsKey(1234)
@test convert(FitsKey, FitsKey(1234)) === FitsKey(1234)
@test UInt64(FitsKey()) === zero(UInt64)
@test Fits"SIMPLE" == make_FitsKey("SIMPLE ")
@test Fits"SIMPLE" === make_FitsKey("SIMPLE ")
@test Fits"BITPIX" === make_FitsKey("BITPIX ")
@test Fits"NAXIS" === make_FitsKey("NAXIS ")
@test Fits"COMMENT" === make_FitsKey("COMMENT ")
@test Fits"HISTORY" === make_FitsKey("HISTORY ")
@test Fits"HIERARCH" === make_FitsKey("HIERARCH")
@test Fits"" === make_FitsKey(" ")
@test Fits"END" === make_FitsKey("END ")
@test String(Fits"") == ""
@test String(Fits"SIMPLE") == "SIMPLE"
@test String(Fits"HIERARCH") == "HIERARCH"
@test repr(Fits"") == "Fits\"\""
@test repr(Fits"SIMPLE") == "Fits\"SIMPLE\""
@test repr(Fits"HIERARCH") == "Fits\"HIERARCH\""
@test repr("text/plain", Fits"") == "Fits\"\""
@test repr("text/plain", Fits"SIMPLE") == "Fits\"SIMPLE\""
@test repr("text/plain", Fits"HIERARCH") == "Fits\"HIERARCH\""
@test string(FitsKey()) == "FitsKey(0x0000000000000000)"
@test string(Fits"SIMPLE") == "Fits\"SIMPLE\""
@test string(Fits"HISTORY") == "Fits\"HISTORY\""
@test_throws Exception FITSHeaders.keyword("SIMPLE#")
@test_throws Exception FITSHeaders.keyword(" SIMPLE")
@test_throws Exception FITSHeaders.keyword("SIMPLE ")
@test_throws Exception FITSHeaders.keyword("SImPLE")
@test_throws Exception FITSHeaders.keyword("TOO MANY SPACES")
@test_throws Exception FITSHeaders.keyword("HIERARCH A") # more than one space
@test_throws Exception FITSHeaders.keyword("HIERARCH+ A") # invalid character
# Short FITS keywords.
@test FITSHeaders.try_parse_keyword("SIMPLE") == (Fits"SIMPLE", false)
@test FITSHeaders.keyword("SIMPLE") == "SIMPLE"
@test FITSHeaders.keyword(:SIMPLE) == "SIMPLE"
@test FITSHeaders.try_parse_keyword("HISTORY") == (Fits"HISTORY", false)
@test FITSHeaders.keyword("HISTORY") == "HISTORY"
# Keywords longer than 8-characters are HIERARCH ones.
@test FITSHeaders.try_parse_keyword("LONG-NAME") == (Fits"HIERARCH", true)
@test FITSHeaders.keyword("LONG-NAME") == "HIERARCH LONG-NAME"
@test FITSHeaders.try_parse_keyword("HIERARCHY") == (Fits"HIERARCH", true)
@test FITSHeaders.keyword("HIERARCHY") == "HIERARCH HIERARCHY"
# Keywords starting by "HIERARCH " are HIERARCH ones.
for key in ("HIERARCH GIZMO", "HIERARCH MY GIZMO", "HIERARCH MY BIG GIZMO")
@test FITSHeaders.try_parse_keyword(key) == (Fits"HIERARCH", false)
@test FITSHeaders.keyword(key) === key # should return the same object
end
# Keywords with multiple words are HIERARCH ones whatever their lengths.
for key in ("A B", "A B C", "SOME KEY", "TEST CASE")
@test FITSHeaders.try_parse_keyword(key) == (Fits"HIERARCH", true)
@test FITSHeaders.keyword(key) == "HIERARCH "*key
end
# The following cases are consequences of the implemented scanner.
@test FITSHeaders.try_parse_keyword("HIERARCH") == (Fits"HIERARCH", false)
@test FITSHeaders.keyword("HIERARCH") == "HIERARCH"
@test FITSHeaders.try_parse_keyword("HIERARCH SIMPLE") == (Fits"HIERARCH", false)
@test FITSHeaders.keyword("HIERARCH SIMPLE") == "HIERARCH SIMPLE"
@test is_structural(Fits"SIMPLE")
@test is_structural(Fits"BITPIX")
@test is_structural(Fits"NAXIS")
@test is_structural(Fits"NAXIS1")
@test is_structural(Fits"NAXIS999")
@test is_structural(Fits"XTENSION")
@test is_structural(Fits"TFIELDS")
@test !is_structural(Fits"TTYPE")
@test is_structural(Fits"TTYPE1")
@test is_structural(Fits"TTYPE999")
@test !is_structural(Fits"TFORM")
@test is_structural(Fits"TFORM1")
@test is_structural(Fits"TFORM999")
@test !is_structural(Fits"TDIM")
@test is_structural(Fits"TDIM1")
@test is_structural(Fits"TDIM999")
@test is_structural(Fits"PCOUNT")
@test is_structural(Fits"GCOUNT")
@test is_structural(Fits"END")
@test !is_structural(Fits"COMMENT")
@test !is_structural(Fits"HISTORY")
@test !is_structural(Fits"HIERARCH")
@test !is_comment(Fits"SIMPLE")
@test !is_comment(Fits"BITPIX")
@test !is_comment(Fits"NAXIS")
@test !is_comment(Fits"NAXIS1")
@test !is_comment(Fits"NAXIS999")
@test !is_comment(Fits"XTENSION")
@test !is_comment(Fits"TFIELDS")
@test !is_comment(Fits"TTYPE")
@test !is_comment(Fits"TTYPE1")
@test !is_comment(Fits"TTYPE999")
@test !is_comment(Fits"TFORM")
@test !is_comment(Fits"TFORM1")
@test !is_comment(Fits"TFORM999")
@test !is_comment(Fits"TDIM")
@test !is_comment(Fits"TDIM1")
@test !is_comment(Fits"TDIM999")
@test !is_comment(Fits"PCOUNT")
@test !is_comment(Fits"GCOUNT")
@test !is_comment(Fits"END")
@test is_comment(Fits"COMMENT")
@test is_comment(Fits"HISTORY")
@test !is_comment(Fits"HIERARCH")
@test !is_naxis(Fits"SIMPLE")
@test !is_naxis(Fits"BITPIX")
@test is_naxis(Fits"NAXIS")
@test is_naxis(Fits"NAXIS1")
@test is_naxis(Fits"NAXIS999")
@test !is_naxis(Fits"XTENSION")
@test !is_naxis(Fits"TFIELDS")
@test !is_naxis(Fits"TTYPE")
@test !is_naxis(Fits"TTYPE1")
@test !is_naxis(Fits"TTYPE999")
@test !is_naxis(Fits"TFORM")
@test !is_naxis(Fits"TFORM1")
@test !is_naxis(Fits"TFORM999")
@test !is_naxis(Fits"TDIM")
@test !is_naxis(Fits"TDIM1")
@test !is_naxis(Fits"TDIM999")
@test !is_naxis(Fits"PCOUNT")
@test !is_naxis(Fits"GCOUNT")
@test !is_naxis(Fits"END")
@test !is_naxis(Fits"COMMENT")
@test !is_naxis(Fits"HISTORY")
@test !is_naxis(Fits"HIERARCH")
@test !is_end(Fits"SIMPLE")
@test !is_end(Fits"BITPIX")
@test !is_end(Fits"NAXIS")
@test !is_end(Fits"NAXIS1")
@test !is_end(Fits"NAXIS999")
@test !is_end(Fits"XTENSION")
@test !is_end(Fits"TFIELDS")
@test !is_end(Fits"TTYPE")
@test !is_end(Fits"TTYPE1")
@test !is_end(Fits"TTYPE999")
@test !is_end(Fits"TFORM")
@test !is_end(Fits"TFORM1")
@test !is_end(Fits"TFORM999")
@test !is_end(Fits"TDIM")
@test !is_end(Fits"TDIM1")
@test !is_end(Fits"TDIM999")
@test !is_end(Fits"PCOUNT")
@test !is_end(Fits"GCOUNT")
@test is_end(Fits"END")
@test !is_end(Fits"COMMENT")
@test !is_end(Fits"HISTORY")
@test !is_end(Fits"HIERARCH")
end
@testset "Parser" begin
# Byte order.
@test FITSHeaders.Parser.is_big_endian() === (BYTE_ORDER === :big_endian)
@test FITSHeaders.Parser.is_little_endian() === (BYTE_ORDER === :little_endian)
# Character classes according to FITS standard.
for b in 0x00:0xFF
c = Char(b)
@test FITSHeaders.Parser.is_digit(c) === ('0' ≤ c ≤ '9')
@test FITSHeaders.Parser.is_uppercase(c) === ('A' ≤ c ≤ 'Z')
@test FITSHeaders.Parser.is_lowercase(c) === ('a' ≤ c ≤ 'z')
@test FITSHeaders.Parser.is_space(c) === (c == ' ')
@test FITSHeaders.Parser.is_quote(c) === (c == '\'')
@test FITSHeaders.Parser.is_equals_sign(c) === (c == '=')
@test FITSHeaders.Parser.is_hyphen(c) === (c == '-')
@test FITSHeaders.Parser.is_underscore(c) === (c == '_')
@test FITSHeaders.Parser.is_comment_separator(c) === (c == '/')
@test FITSHeaders.Parser.is_opening_parenthesis(c) === (c == '(')
@test FITSHeaders.Parser.is_closing_parenthesis(c) === (c == ')')
@test FITSHeaders.Parser.is_restricted_ascii(c) === (' ' ≤ c ≤ '~')
@test FITSHeaders.Parser.is_keyword(c) ===
(('0' ≤ c ≤ '9') | ('A' ≤ c ≤ 'Z') | (c == '-') | (c == '_'))
end
# Trimming of spaces.
for str in ("", " a string ", "another string", " yet another string ")
@test SubString(str, FITSHeaders.Parser.trim_leading_spaces(str)) == lstrip(str)
@test SubString(str, FITSHeaders.Parser.trim_trailing_spaces(str)) == rstrip(str)
rng = firstindex(str):ncodeunits(str)
@test SubString(str, FITSHeaders.Parser.trim_leading_spaces(str, rng)) == lstrip(str)
@test SubString(str, FITSHeaders.Parser.trim_trailing_spaces(str, rng)) == rstrip(str)
end
# Representation of a character.
@test FITSHeaders.Parser.repr_char(' ') == repr(' ')
@test FITSHeaders.Parser.repr_char(0x20) == repr(' ')
@test FITSHeaders.Parser.repr_char('\0') == repr(0x00)
@test FITSHeaders.Parser.repr_char(0x00) == repr(0x00)
@test FITSHeaders.Parser.repr_char('i') == repr('i')
@test FITSHeaders.Parser.repr_char(0x69) == repr('i')
# FITS logical value.
@test FITSHeaders.Parser.try_parse_logical_value("T") === true
@test FITSHeaders.Parser.try_parse_logical_value("F") === false
@test FITSHeaders.Parser.try_parse_logical_value("t") === nothing
@test FITSHeaders.Parser.try_parse_logical_value("f") === nothing
@test FITSHeaders.Parser.try_parse_logical_value("true") === nothing
@test FITSHeaders.Parser.try_parse_logical_value("false") === nothing
# FITS integer value.
for val in (zero(Int64), typemin(Int64), typemax(Int64))
str = "$val"
@test FITSHeaders.Parser.try_parse_integer_value(str) == val
if val > 0
# Add a few leading zeros.
str = "000$val"
@test FITSHeaders.Parser.try_parse_integer_value(str) == val
end
@test FITSHeaders.Parser.try_parse_integer_value(" "*str) === nothing
@test FITSHeaders.Parser.try_parse_integer_value(str*" ") === nothing
end
# FITS float value;
for val in (0.0, 1.0, -1.0, float(π))
str = "$val"
@test FITSHeaders.Parser.try_parse_float_value(str) ≈ val
@test FITSHeaders.Parser.try_parse_integer_value(" "*str) === nothing
@test FITSHeaders.Parser.try_parse_integer_value(str*" ") === nothing
end
# FITS complex value;
@test FITSHeaders.Parser.try_parse_float_value("2.3d4") ≈ 2.3e4
@test FITSHeaders.Parser.try_parse_float_value("-1.09D3") ≈ -1.09e3
@test FITSHeaders.Parser.try_parse_complex_value("(2.3d4,-1.8)") ≈ complex(2.3e4,-1.8)
@test FITSHeaders.Parser.try_parse_complex_value("(-1.09e5,7.6D2)") ≈ complex(-1.09e5,7.6e2)
# FITS string value;
@test FITSHeaders.Parser.try_parse_string_value("''") == ""
@test FITSHeaders.Parser.try_parse_string_value("'''") === nothing
@test FITSHeaders.Parser.try_parse_string_value("''''") == "'"
@test FITSHeaders.Parser.try_parse_string_value("'Hello!'") == "Hello!"
@test FITSHeaders.Parser.try_parse_string_value("'Hello! '") == "Hello!"
@test FITSHeaders.Parser.try_parse_string_value("' Hello!'") == " Hello!"
@test FITSHeaders.Parser.try_parse_string_value("' Hello! '") == " Hello!"
@test FITSHeaders.Parser.try_parse_string_value("' Hello! '") == " Hello!"
@test FITSHeaders.Parser.try_parse_string_value("'Joe''s taxi'") == "Joe's taxi"
@test FITSHeaders.Parser.try_parse_string_value("'Joe's taxi'") === nothing
@test FITSHeaders.Parser.try_parse_string_value("'Joe'''s taxi'") === nothing
# Units.
let com = ""
@test FITSHeaders.Parser.get_units_part(com) == ""
@test FITSHeaders.Parser.get_unitless_part(com) == ""
end
let com = "some comment"
@test FITSHeaders.Parser.get_units_part(com) == ""
@test FITSHeaders.Parser.get_unitless_part(com) == "some comment"
end
let com = "[]some comment"
@test FITSHeaders.Parser.get_units_part(com) == ""
@test FITSHeaders.Parser.get_unitless_part(com) == "some comment"
end
let com = "[] some comment"
@test FITSHeaders.Parser.get_units_part(com) == ""
@test FITSHeaders.Parser.get_unitless_part(com) == "some comment"
end
let com = "[some units]some comment"
@test FITSHeaders.Parser.get_units_part(com) == "some units"
@test FITSHeaders.Parser.get_unitless_part(com) == "some comment"
end
let com = "[ some units ] some comment"
@test FITSHeaders.Parser.get_units_part(com) == "some units"
@test FITSHeaders.Parser.get_unitless_part(com) == "some comment"
end
let com = "[some comment"
@test FITSHeaders.Parser.get_units_part(com) == ""
@test FITSHeaders.Parser.get_unitless_part(com) == "[some comment"
end
end
@testset "Cards from strings" begin
# Errors...
@test_throws Exception FitsCard("END nothing allowed here")
@test_throws Exception FitsCard("VALUE = # / invalid character")
@test_throws Exception FitsCard("VALUE = .-123 / invalid number")
@test_throws Exception FitsCard("VALUE = -12x3 / invalid number")
@test_throws Exception FitsCard("VALUE = (1,3.0 / unclosed complex")
@test_throws Exception FitsCard("VALUE = (1,) / bad complex")
@test_throws Exception FitsCard("VALUE = (,1) / bad complex")
@test_throws Exception FitsCard("VALUE = 'hello / unclosed string")
@test_throws Exception FitsCard("VALUE = 'Joe's taxi' / unescaped quote")
# Logical FITS cards.
let card = FitsCard("SIMPLE = T / this is a FITS file ")
@test :type ∈ propertynames(card)
@test :name ∈ propertynames(card)
@test :key ∈ propertynames(card)
@test :value ∈ propertynames(card)
@test :comment ∈ propertynames(card)
@test :units ∈ propertynames(card)
@test :unitless ∈ propertynames(card)
@test :logical ∈ propertynames(card)
@test :integer ∈ propertynames(card)
@test :float ∈ propertynames(card)
@test :complex ∈ propertynames(card)
@test :string ∈ propertynames(card)
@test card.type === FITS_LOGICAL
@test FitsCardType(card) === FITS_LOGICAL
@test card.key == Fits"SIMPLE"
@test card.name == "SIMPLE"
@test card.comment == "this is a FITS file"
@test card.value() isa Bool
@test card.value() == true
@test card.value() === card.logical
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === true
@test isinteger(card) === true
@test isreal(card) === true
@test_throws Exception card.key = Fits"HISTORY"
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test card.value(Bool) === convert(Bool, card.value())
@test card.value(Int16) === convert(Int16, card.value())
@test card.value(Integer) === convert(FitsInteger, card.value())
@test card.value(Real) === convert(FitsFloat, card.value())
@test card.value(AbstractFloat) === convert(FitsFloat, card.value())
@test card.value(Complex) === convert(FitsComplex, card.value())
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(typeof(card.value), card.value) === card.value
@test convert(valtype(card), card.value) === card.value()
@test convert(Bool, card.value) === card.value(Bool)
@test convert(Int16, card.value) === card.value(Int16)
@test convert(Integer, card.value) === card.value(Integer)
@test convert(Real, card.value) === card.value(Real)
@test convert(AbstractFloat, card.value) === card.value(AbstractFloat)
@test convert(Complex, card.value) === card.value(Complex)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
end
# Integer valued cards.
let card = FitsCard("BITPIX = -32 / number of bits per data pixel ")
@test card.type == FITS_INTEGER
@test card.key == Fits"BITPIX"
@test card.name == "BITPIX"
@test card.comment == "number of bits per data pixel"
@test card.value() isa FitsInteger
@test card.value() == -32
@test card.value() === card.integer
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === true
@test isinteger(card) === true
@test isreal(card) === true
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test card.value(Int16) === convert(Int16, card.value())
@test card.value(Integer) === convert(FitsInteger, card.value())
@test card.value(Real) === convert(FitsFloat, card.value())
@test card.value(AbstractFloat) === convert(FitsFloat, card.value())
@test card.value(Complex) === convert(FitsComplex, card.value())
@test_throws InexactError card.value(Bool)
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test convert(Int16, card.value) === card.value(Int16)
@test convert(Integer, card.value) === card.value(Integer)
@test convert(Real, card.value) === card.value(Real)
@test convert(AbstractFloat, card.value) === card.value(AbstractFloat)
@test convert(Complex, card.value) === card.value(Complex)
@test_throws InexactError convert(Bool, card.value)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
end
let card = FitsCard("NAXIS = 3 / number of axes ")
@test card.type == FITS_INTEGER
@test card.key == Fits"NAXIS"
@test card.name == "NAXIS"
@test card.comment == "number of axes"
@test card.units == ""
@test card.unitless == "number of axes"
@test card.value() isa FitsInteger
@test card.value() == 3
@test card.value() === card.integer
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === true
@test isinteger(card) === true
@test isreal(card) === true
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test card.value(Int16) === convert(Int16, card.value())
@test card.value(Integer) === convert(FitsInteger, card.value())
@test card.value(Real) === convert(FitsFloat, card.value())
@test card.value(AbstractFloat) === convert(FitsFloat, card.value())
@test card.value(Complex) === convert(FitsComplex, card.value())
@test_throws InexactError card.value(Bool)
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test convert(Int16, card.value) === card.value(Int16)
@test convert(Integer, card.value) === card.value(Integer)
@test convert(Real, card.value) === card.value(Real)
@test convert(AbstractFloat, card.value) === card.value(AbstractFloat)
@test convert(Complex, card.value) === card.value(Complex)
@test_throws InexactError convert(Bool, card.value)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
end
# COMMENT and HISTORY.
let card = FitsCard("COMMENT Some comments (with leading spaces that should not be removed) ")
@test card.type == FITS_COMMENT
@test card.key == Fits"COMMENT"
@test card.name == "COMMENT"
@test card.comment == " Some comments (with leading spaces that should not be removed)"
@test card.value() isa Nothing
@test card.value() === nothing
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test_throws Exception card.value(Bool)
@test_throws Exception card.value(Int16)
@test_throws Exception card.value(Integer)
@test_throws Exception card.value(Real)
@test_throws Exception card.value(AbstractFloat)
@test_throws Exception card.value(Complex)
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test_throws Exception convert(Bool, card.value)
@test_throws Exception convert(Int16, card.value)
@test_throws Exception convert(Integer, card.value)
@test_throws Exception convert(Real, card.value)
@test_throws Exception convert(AbstractFloat, card.value)
@test_throws Exception convert(Complex, card.value)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
# is_comment(), is_end(), ...
@test is_comment(card) === true
@test is_comment(card.type) === true
@test is_comment(card.key) === true # standard comment
@test is_end(card) === false
@test is_end(card.type) === false
@test is_end(card.key) === false
@test is_structural(card) == false
@test is_naxis(card) == false
end
let card = FitsCard("HISTORY A new history starts here... ")
@test card.type == FITS_COMMENT
@test card.key == Fits"HISTORY"
@test card.name == "HISTORY"
@test card.comment == "A new history starts here..."
@test card.value() isa Nothing
@test card.value() === nothing
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test_throws Exception card.value(Bool)
@test_throws Exception card.value(Int16)
@test_throws Exception card.value(Integer)
@test_throws Exception card.value(Real)
@test_throws Exception card.value(AbstractFloat)
@test_throws Exception card.value(Complex)
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test_throws Exception convert(Bool, card.value)
@test_throws Exception convert(Int16, card.value)
@test_throws Exception convert(Integer, card.value)
@test_throws Exception convert(Real, card.value)
@test_throws Exception convert(AbstractFloat, card.value)
@test_throws Exception convert(Complex, card.value)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
# is_comment(), is_end(), ...
@test is_comment(card) === true
@test is_comment(card.type) === true
@test is_comment(card.key) === true # standard comment
@test is_end(card) === false
@test is_end(card.type) === false
@test is_end(card.key) === false
@test is_structural(card) == false
@test is_naxis(card) == false
end
# Non standard commentary card.
let card = FitsCard("NON-STANDARD COMMENT" => (nothing, "some comment"))
@test card.type == FITS_COMMENT
@test card.key == Fits"HIERARCH"
@test card.name == "HIERARCH NON-STANDARD COMMENT"
@test card.comment == "some comment"
@test card.value() isa Nothing
@test card.value() === nothing
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test_throws Exception card.value(Bool)
@test_throws Exception card.value(Int16)
@test_throws Exception card.value(Integer)
@test_throws Exception card.value(Real)
@test_throws Exception card.value(AbstractFloat)
@test_throws Exception card.value(Complex)
@test_throws Exception card.value(String)
@test_throws Exception card.value(AbstractString)
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test_throws Exception convert(Bool, card.value)
@test_throws Exception convert(Int16, card.value)
@test_throws Exception convert(Integer, card.value)
@test_throws Exception convert(Real, card.value)
@test_throws Exception convert(AbstractFloat, card.value)
@test_throws Exception convert(Complex, card.value)
@test_throws Exception convert(String, card.value)
@test_throws Exception convert(AbstractString, card.value)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
# is_comment(), is_end(), ...
@test is_comment(card) === true
@test is_comment(card.type) === true
@test is_comment(card.key) === false # non-standard comment
@test is_end(card) === false
@test is_end(card.type) === false
@test is_end(card.key) === false
@test is_structural(card) == false
@test is_naxis(card) == false
end
# String valued card.
let card = FitsCard("REMARK = 'Joe''s taxi' / a string with an embedded quote ")
@test card.type == FITS_STRING
@test card.key == Fits"REMARK"
@test card.name == "REMARK"
@test card.comment == "a string with an embedded quote"
@test card.value() isa String
@test card.value() == "Joe's taxi"
@test card.value() === card.string
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === false
# Convert callable value object by calling the object itself.
@test card.value(valtype(card)) === card.value()
@test_throws Exception card.value(Bool)
@test_throws Exception card.value(Int16)
@test_throws Exception card.value(Integer)
@test_throws Exception card.value(Real)
@test_throws Exception card.value(AbstractFloat)
@test_throws Exception card.value(Complex)
@test card.value(String) === convert(String, card.value())
@test card.value(AbstractString) === convert(AbstractString, card.value())
# Convert callable value object by calling `convert`.
@test convert(valtype(card), card.value) === card.value()
@test_throws Exception convert(Bool, card.value)
@test_throws Exception convert(Int16, card.value)
@test_throws Exception convert(Integer, card.value)
@test_throws Exception convert(Real, card.value)
@test_throws Exception convert(AbstractFloat, card.value)
@test_throws Exception convert(Complex, card.value)
@test convert(String, card.value) === card.value(String)
@test convert(AbstractString, card.value) === card.value(AbstractString)
# Various string representations.
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
# is_comment(), is_end(), ...
@test is_comment(card) == false
@test is_comment(card.type) == false
@test is_comment(card.key) == false
@test is_end(card) == false
@test is_end(card.type) == false
@test is_end(card.key) == false
@test is_structural(card) == false
@test is_naxis(card) == false
end
#
let card = FitsCard("EXTNAME = 'SCIDATA ' ")
@test card.type == FITS_STRING
@test card.key == Fits"EXTNAME"
@test card.name == "EXTNAME"
@test card.comment == ""
@test isinteger(card) === false
@test isassigned(card) === true
@test card.value() isa String
@test card.value() == "SCIDATA"
@test card.value() === card.string
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === false
end
#
let card = FitsCard("CRPIX1 = 1. ")
@test card.type == FITS_FLOAT
@test card.key == Fits"CRPIX1"
@test card.name == "CRPIX1"
@test card.comment == ""
@test card.value() isa FitsFloat
@test card.value() ≈ 1.0
@test card.value() === card.float
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === true
end
#
let card = FitsCard("CRVAL3 = 0.96 / CRVAL along 3rd axis ")
@test card.type == FITS_FLOAT
@test card.key == Fits"CRVAL3"
@test card.name == "CRVAL3"
@test card.comment == "CRVAL along 3rd axis"
@test card.value() isa FitsFloat
@test card.value() ≈ 0.96
@test card.value() === card.float
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === true
end
#
let card = FitsCard("HIERARCH ESO OBS EXECTIME = +2919 / Expected execution time ")
@test card.type == FITS_INTEGER
@test card.key == Fits"HIERARCH"
@test card.name == "HIERARCH ESO OBS EXECTIME"
@test card.comment == "Expected execution time"
@test card.value() isa FitsInteger
@test card.value() == +2919
@test card.value() === card.integer
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === true
@test isreal(card) === true
end
# FITS cards with undefined value.
let card = FitsCard("DUMMY = / no value given ")
@test card.type == FITS_UNDEFINED
@test card.key == Fits"DUMMY"
@test card.name == "DUMMY"
@test card.comment == "no value given"
@test card.value() === undef
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
end
let card = FitsCard("HIERARCH DUMMY = / no value given ")
@test card.type == FITS_UNDEFINED
@test card.key == Fits"HIERARCH"
@test card.name == "HIERARCH DUMMY"
@test card.comment == "no value given"
@test card.value() === undef
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
end
# Complex valued cards.
let card = FitsCard("COMPLEX = (1,0) / [km/s] some complex value ")
@test card.type == FITS_COMPLEX
@test card.key == Fits"COMPLEX"
@test card.name == "COMPLEX"
@test card.comment == "[km/s] some complex value"
@test card.units == "km/s"
@test card.unitless == "some complex value"
@test card.value() isa FitsComplex
@test card.value() ≈ complex(1,0)
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === iszero(imag(card.value()))
end
let card = FitsCard("COMPLEX = (-2.7,+3.1d5) / some other complex value ")
@test card.type == FITS_COMPLEX
@test card.key == Fits"COMPLEX"
@test card.name == "COMPLEX"
@test card.comment == "some other complex value"
@test card.value() isa FitsComplex
@test card.value() ≈ complex(-2.7,+3.1e5)
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test card.value(Complex{Float32}) === Complex{Float32}(card.value())
@test convert(Complex{Float32}, card.value) === Complex{Float32}(card.value())
@test_throws InexactError card.value(Float64)
@test_throws InexactError convert(Float32, card.value)
@test isassigned(card) === true
@test isinteger(card) === false
@test isreal(card) === iszero(imag(card.value()))
end
# END card.
let card = FitsCard("END ")
@test card.type == FITS_END
@test card.key == Fits"END"
@test card.name == "END"
@test card.comment == ""
@test card.value() isa Nothing
@test card.value() === nothing
@test valtype(card) === typeof(card.value())
@test card.value(valtype(card)) === card.value()
@test repr(card) isa String
@test repr("text/plain", card) isa String
@test repr(card.value) isa String
@test repr("text/plain", card.value) isa String
@test isassigned(card) === false
@test isinteger(card) === false
@test isreal(card) === false
@test is_comment(card) == false
@test is_comment(card.type) == false
@test is_comment(card.key) == false
@test is_end(card) == true
@test is_end(card.type) == true
@test is_end(card.key) == true
@test is_structural(card) == true
@test is_naxis(card) == false
end
end
@testset "Cards from bytes" begin
# Logical FITS cards.
str = "SIMPLE = T / this is a FITS file "
for buf in (make_byte_vector(str), make_discontinuous_byte_vector(str))
card = FitsCard(buf)
@test card.type == FITS_LOGICAL
@test card.key == Fits"SIMPLE"
@test card.name == "SIMPLE"
@test card.comment == "this is a FITS file"
@test card.value() isa Bool
@test card.value() == true
@test card.value() === card.logical
@test valtype(card) === typeof(card.value())
end
# "END", empty string "" or out of range offset yield an END card.
let card = FitsCard("END")
@test card.type === FITS_END
@test card.key === Fits"END"
end
let card = FitsCard("")
@test card.type === FITS_END
@test card.key === Fits"END"
end
let card = FitsCard("xEND"; offset=1)
@test card.type === FITS_END
@test card.key === Fits"END"
end
let card = FitsCard("SOMETHING"; offset=250)
@test card.type === FITS_END
@test card.key === Fits"END"
end
end
@testset "Cards from pairs" begin
# Badly formed cards.
@test_throws ArgumentError FitsCard(:GIZMO => [])
@test_throws ArgumentError FitsCard("GIZMO" => ("comment",2))
@test_throws Exception FitsCard(:Gizmo => 1)
@test_throws Exception FitsCard("Gizmo" => 1)
# Well formed cards and invariants.
@test FitsCard(:GIZMO => 1) isa FitsCard
@test FitsCard(:GIZMO => 1).type === FITS_INTEGER
@test FitsCard(:GIZMO => 1) === FitsCard("GIZMO" => 1)
@test FitsCard(:GIZMO => 1) === FitsCard("GIZMO" => (1,))
@test FitsCard(:GIZMO => 1) === FitsCard("GIZMO" => (1,nothing))
@test FitsCard(:GIZMO => 1) === FitsCard("GIZMO" => (1,""))
@test FitsCard(:COMMENT => "Hello world!") isa FitsCard
@test FitsCard(:COMMENT => "Hello world!").type === FITS_COMMENT
@test FitsCard(:COMMENT => "Hello world!") === FitsCard("COMMENT" => "Hello world!")
@test FitsCard(:COMMENT => "Hello world!") === FitsCard("COMMENT" => (nothing, "Hello world!"))
# Logical FITS cards.
com = "some comment"
pair = "SIMPLE" => (true, com)
card = FitsCard(pair)
@test FitsCard(card) === card
@test convert(FitsCard, card) === card
@test convert(FitsCard, pair) == card
@test convert(Pair, card) == pair
@test Pair(card) == pair
@test Pair{String}(card) === pair
@test Pair{String,Tuple{Bool,String}}(card) === pair
@test Pair{String,Tuple{Int,String}}(card) === (card.name => (card.value(Int), card.comment))
@test card.type === FITS_LOGICAL
@test card.key === Fits"SIMPLE"
@test card.name === "SIMPLE"
@test card.value() === true
@test card.comment == com
@test_throws ErrorException card.value(FitsCard)
card = FitsCard("TWO KEYS" => (π, com))
@test card.type === FITS_FLOAT
@test card.key === Fits"HIERARCH"
@test card.name == "HIERARCH TWO KEYS"
@test card.value() ≈ π
@test card.comment == com
card = convert(FitsCard, "HIERARCH NAME" => ("some name", com))
@test card.type === FITS_STRING
@test card.key === Fits"HIERARCH"
@test card.name == "HIERARCH NAME"
@test card.value() == "some name"
@test card.comment == com
card = convert(FitsCard, "HIERARCH COMMENT" => (nothing, com))
@test card.type === FITS_COMMENT
@test card.key === Fits"HIERARCH"
@test card.name == "HIERARCH COMMENT"
@test card.value() === nothing
@test card.comment == com
card = convert(FitsCard, "COMMENT" => com)
@test card.type === FITS_COMMENT
@test card.key === Fits"COMMENT"
@test card.name == "COMMENT"
@test card.value() === nothing
@test card.comment == com
card = convert(FitsCard, "REASON" => undef)
@test card.type === FITS_UNDEFINED
@test card.key === Fits"REASON"
@test card.name == "REASON"
@test card.value() === undef
@test card.comment == ""
card = convert(FitsCard, "REASON" => (missing, com))
@test card.type === FITS_UNDEFINED
@test card.key === Fits"REASON"
@test card.name == "REASON"
@test card.value() === undef
@test card.comment == com
# Dates.
date = now()
card = FitsCard("DATE-OBS" => date)
@test card.type === FITS_STRING
@test card.key === Fits"DATE-OBS"
@test card.name == "DATE-OBS"
@test card.value() == Dates.format(date, ISODateTimeFormat)
@test card.value(DateTime) === date
@test convert(DateTime, card.value) === date
@test DateTime(card.value) === date
@test card.comment == ""
card = FitsCard("DATE-OBS" => (date))
@test card.type === FITS_STRING
@test card.key === Fits"DATE-OBS"
@test card.name == "DATE-OBS"
@test card.value() == Dates.format(date, ISODateTimeFormat)
@test card.value(DateTime) === date
@test convert(DateTime, card.value) === date
@test DateTime(card.value) === date
@test card.comment == ""
card = FitsCard("DATE-OBS" => (date, com))
@test card.type === FITS_STRING
@test card.key === Fits"DATE-OBS"
@test card.name == "DATE-OBS"
@test card.value() == Dates.format(date, ISODateTimeFormat)
@test card.value(DateTime) === date
@test convert(DateTime, card.value) === date
@test DateTime(card.value) === date
@test card.comment == com
end
@testset "Operations on card values" begin
A = FitsCard("KEY_A" => true).value
B = FitsCard("KEY_B" => 42).value
C = FitsCard("KEY_C" => 24.0).value
D = FitsCard("KEY_D" => "hello").value
@test A == A()
@test A() == A
@test A == true
@test A != false
@test A > false
@test A ≥ true
@test A ≤ true
@test B == B()
@test B() == B
@test B == 42
@test B != 41
@test B > Int16(41)
@test B ≥ Int16(42)
@test B ≤ Int16(42)
@test C == C()
@test C() == C
@test C == C
@test C == 24
@test C != 25
@test C > 23
@test C ≥ 24
@test C ≤ 24
@test D == D()
@test D() == D
@test D == "hello"
@test D != "Hello"
@test A == A
@test A != B
@test A != C
@test A != D
@test B != A
@test B == B
@test B != C
@test B != D
@test C != A
@test C != B
@test C == C
@test C != D
@test D != A
@test D != B
@test D != C
@test D == D
@test B > A
@test B ≥ A
@test B > C
@test B ≥ C
end
@testset "Headers" begin
dims = (4,5,6,7)
h = FitsHeader("SIMPLE" => (true, "FITS file"),
"BITPIX" => (-32, "bits per pixels"),
"NAXIS" => (length(dims), "number of dimensions"))
@test length(h) == 3
@test sort(collect(keys(h))) == ["BITPIX", "NAXIS", "SIMPLE"]
# Same object:
@test convert(FitsHeader, h) === h
# Same contents but different objects:
hp = convert(FitsHeader, h.cards); @test hp !== h && hp == h
hp = FitsHeader(h); @test hp !== h && hp == h
hp = copy(h); @test hp !== h && hp == h
@test length(empty!(hp)) == 0
@test haskey(h, "NAXIS")
@test !haskey(h, "NO-SUCH-KEY")
@test haskey(h, firstindex(h))
@test !haskey(h, lastindex(h) + 1)
@test get(h, "NAXIS", π) isa FitsCard
@test get(h, "illegal keyword!", π) === π
@test get(h, +, π) === π
@test getkey(h, "illegal keyword!", π) === π
@test getkey(h, "NAXIS", π) == "NAXIS"
@test IndexStyle(h) === IndexLinear()
@test h["SIMPLE"] === h[1]
@test h[1].key === Fits"SIMPLE"
@test h[1].value() == true
@test h["BITPIX"] === h[2]
@test h[2].key === Fits"BITPIX"
@test h[2].value() == -32
@test h["NAXIS"] === h[3]
@test h[3].key === Fits"NAXIS"
@test h[3].value() == length(dims)
# Build 2 another headers, one with just the dimensions, the other with
# some other records, then merge these headers.
h1 = FitsHeader(h["NAXIS"])
for i in eachindex(dims)
push!(h1, "NAXIS$i" => (dims[i], "length of dimension # $i"))
end
h2 = FitsHeader(COMMENT = "Some comment.",
BSCALE = (1.0, "Scaling factor."),
BZERO = (0.0, "Bias offset."))
h2["CCD GAIN"] = (3.2, "[ADU/e-] detector gain")
h2["HIERARCH CCD BIAS"] = -15
h2["COMMENT"] = "Another comment."
h2["COMMENT"] = "Yet another comment."
@test merge!(h) === h
hp = merge(h, h1, h2)
@test merge!(h, h1, h2) === h
@test hp == h && hp !== h
@test merge!(hp, h1) == h # re-merging existing unique cards does not change anything
empty!(h1)
empty!(h2)
empty!(hp)
@test length(eachmatch("COMMENT", h)) == 3
@test count(Returns(true), eachmatch("COMMENT", h)) == 3
coms = collect("COMMENT", h)
@test length(coms) == 3
@test coms isa Vector{FitsCard}
@test coms[1].comment == "Some comment."
@test coms[2].comment == "Another comment."
@test coms[3].comment == "Yet another comment."
iter = eachmatch("COMMENT", h)
@test reverse(reverse(iter)) === iter
@test collect(iter) == coms
@test collect(reverse(iter)) == reverse(coms)
# Test indexing by integer/name.
i = findfirst("BITPIX", h)
@test i isa Integer && h[i].name == "BITPIX"
@test h["BITPIX"] === h[i]
@test h["BSCALE"].value(Real) ≈ 1
@test h["BSCALE"].comment == "Scaling factor."
# Test HIERARCH records.
@test get(h, 0, nothing) === nothing
@test get(h, 1, nothing) === h[1]
card = get(h, "HIERARCH CCD GAIN", nothing)
@test card isa FitsCard
if card !== Nothing
@test card.key === Fits"HIERARCH"
@test card.name == "HIERARCH CCD GAIN"
@test card.value() ≈ 3.2
@test card.units == "ADU/e-"
@test card.unitless == "detector gain"
end
card = get(h, "CCD BIAS", nothing)
@test card isa FitsCard
if card !== Nothing
@test card.key === Fits"HIERARCH"
@test card.name == "HIERARCH CCD BIAS"
@test card.value() == -15
end
# Change existing record, by name and by index for a short and for a
# HIERARCH keyword.
n = length(h)
h["BSCALE"] = (1.1, "better value")
@test length(h) == n
@test h["BSCALE"].value(Real) ≈ 1.1
@test h["BSCALE"].comment == "better value"
i = findfirst("BITPIX", h)
@test i isa Integer
h[i] = (h[i].name => (-64, h[i].comment))
@test h["BITPIX"].value() == -64
i = findfirst("CCD BIAS", h)
h[i] = ("CCD LOW BIAS" => (h[i].value(), h[i].comment))
@test h[i].name == "HIERARCH CCD LOW BIAS"
# It is forbidden to have more than one non-unique keyword.
i = findfirst("BITPIX", h)
@test_throws ArgumentError h[i+1] = h[i]
# Replace a card by comment appering earlier than any other comment. Do
# this in a temporary copy to avoid corrupting the header.
let hp = copy(h)
n = length(eachmatch("COMMENT", hp))
i = findfirst("COMMENT", hp)
hp[i-1] = ("COMMENT" => (nothing, "Some early comment."))
@test findfirst("COMMENT", hp) == i - 1
@test length(eachmatch("COMMENT", hp)) == n + 1
@test hp[i-1].type == FITS_COMMENT
end
# Replace existing card by another one with another name. Peek the
# first of a non-unique record to check that the index is correctly
# updated.
for i in 1:3 # we need a number of commentary records
h["HISTORY"] = "History record number $i."
h["OTHER$i"] = (i, "Something else.")
if i == 1
# Check findlast/findfirst on a commentary keyword that has a
# single occurence.
@test findlast("HISTORY", h) == length(h) - 1
@test findfirst("HISTORY", h) == length(h) - 1
end
end
n = length(eachmatch("HISTORY", h))
@test n ≥ 3
while n > 0
i = findfirst("HISTORY", h)
@test i isa Integer
h[i] = ("SOME$i" => (42, h[i].comment))
n -= 1
@test length(eachmatch("HISTORY", h)) == n
end
@test findfirst("HISTORY", h) === nothing
# Append non-existing record.
n = length(h)
h["GIZMO"] = ("Joe's taxi", "what?")
@test length(h) == n+1
@test h["GIZMO"].value() == "Joe's taxi"
@test h["GIZMO"].comment == "what?"
# Test search failure when: (i) keyword is valid but does not exists,
# (ii) keyword is invalid, and (iii) pattern is unsupported.
@test findfirst("NON-EXISTING KEYWORD", h) === nothing
@test findfirst("Invalid keyword", h) === nothing
@test findfirst(π, h) === nothing
@test findfirst(π, h) === nothing
@test findlast(π, h) === nothing
@test findnext(π, h, firstindex(h)) === nothing
@test findprev(π, h, lastindex(h)) === nothing
@test_throws BoundsError findnext(π, h, firstindex(h) - 1)
@test_throws BoundsError findprev(π, h, lastindex(h) + 1)
@test_throws BoundsError findnext("SIMPLE", h, firstindex(h) - 1)
@test_throws BoundsError findprev("SIMPLE", h, lastindex(h) + 1)
@test findnext(π, h, lastindex(h) + 1) === nothing
@test findprev(π, h, firstindex(h) - 1) === nothing
@test findnext("SIMPLE", h, lastindex(h) + 1) === nothing
@test findprev("SIMPLE", h, firstindex(h) - 1) === nothing
# Forward search.
i = findfirst("COMMENT", h)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Some comment."
i = findnext(h[i], h, i + 1)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Another comment."
i = findnext(h[i], h, i + 1)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Yet another comment."
@test findnext(h[i], h, i + 1) isa Nothing
# Backward search.
i = findlast("COMMENT", h)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Yet another comment."
i = findprev("COMMENT", h, i - 1)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Another comment."
i = findprev(h[i], h, i - 1)
@test i isa Integer
@test h[i].type === FITS_COMMENT
@test h[i].comment == "Some comment."
@test findprev(h[i], h, i - 1) isa Nothing
# Check that non-commentary records are unique.
for i in eachindex(h)
card = h[i]
card.type === FITS_COMMENT && continue
@test findnext(card, h, i + 1) isa Nothing
end
# Search with a predicate.
@test findfirst(card -> card.type === FITS_END, h) === nothing
@test findlast(card -> card.name == "BITPIX", h) === 2
# Apply a filter.
hp = filter(card -> match(r"^NAXIS[0-9]*$", card.name) !== nothing, h)
@test hp isa FitsHeader
@test startswith(first(hp).name, "NAXIS")
@test startswith(last(hp).name, "NAXIS")
# Search by regular expressions.
n = length(dims)
pat = r"^NAXIS[0-9]*$"
i = findfirst(pat, h)
@test h[i].name == "NAXIS"
i = findnext(pat, h, i+1)
@test h[i].name == "NAXIS1"
i = findnext(pat, h, i+1)
@test h[i].name == "NAXIS2"
i = findlast(pat, h)
@test h[i].name == "NAXIS$(n)"
i = findprev(pat, h, i-1)
@test h[i].name == "NAXIS$(n - 1)"
i = findnext(pat, h, i-1)
@test h[i].name == "NAXIS$(n - 2)"
let hp = filter(pat, h)
@test hp isa FitsHeader
@test startswith(first(hp).name, "NAXIS")
@test startswith(last(hp).name, "NAXIS")
end
let v = collect(pat, h)
@test v isa Vector{FitsCard}
@test startswith(first(v).name, "NAXIS")
@test startswith(last(v).name, "NAXIS")
end
end
end
end # module
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | docs | 2993 | # User visible changes in `FITSHeaders` package
# Version 0.4.1
- Update compatibility for `TypeUtils`.
# Version 0.4.0
- Package renamed as `FITSHeaders`.
- Undefined FITS card value is `undef` (was `missing`). When creating a FITS
card, `missing` is considered as `undef`.
- Comparison operators (`==`, `!=`, `<`, `>`, `≤`, and `≥`) can be applied to
FITS card values. The other operand may also be a card value.
- Logical value stored as an integer in `FitsCard`. This is an internal change.
# Version 0.3.11
- Update doc.
- Submitted as an official Julia package.
## Version 0.3.10
- Extend `haskey` for `FitsHeader` objects.
## Version 0.3.9
- `"TFIELDS"`, `"TFORM#"`, `"TTYPE#"`, and `"TDIM#"` are also structural keywords.
## Version 0.3.8
- New non-exported methods: `BaseFITS.is_structural` and `BaseFITS.is_naxis`
to respectively check whether a FITS card or keyword is a structural or axis
one.
## Version 0.3.7
- Package `AsType` is now [`TypeUtils`](https://github.com/emmt/TypeUtils.jl).
## Version 0.3.6
- Package is compatible with Julia 1.0.
- Avoid returning number of bytes written in `show`.
- Date-time format is ISO-8601 as specified by FITS standard.
## Version 0.3.5
- Fix creating FITS cards from pairs of type `Pair{<:CardName,<:Any}` which may
be the type of the objects in some collections, such as vectors, used to
represent FITS header. Non-exported `BaseFITS.CardPair{K<:CardName,V}` is an
alias for such pair types.
## Version 0.3.4
- *Provide support for dates:* Card values of type `Dates.DateTime` are
automatically converted into string values and, conversely, calling
`card.value(DateTime)`, `convert(DataTime,card.value)`, and
`DateTime(card.value)` attempts to convert the string value of `card` into a
date.
## Version 0.3.3
- Use `AsType` package.
- Remove `CompatHelper`.
## Version 0.3.2
- Fix silly bug in keyword comparison.
## Version 0.3.1
- Use quick table for character class.
## Version 0.3.0
- Package renamed `BaseFITS.jl`.
- `FitsHeader` can be built from list of header cards, list of pairs, and named
tuples. Here "list" means any iterable producing items of a given type. The
same types are allowed for `merge` and `merge!` applied to a FITS header.
- Non-exported constants `CarName`, `CardValue`, `CardComment`, and `Undefined`
to help converting a pair into a FITS header card.
- `BaseFITS.keyword` and `BaseFITS.check_keyword` can take a symbolic name as
argument.
## Version 0.2.1
- Can search cards in FITS header by regular expressions.
- Implement merging of headers with `merge` and `merge!`.
- `length(eachmatch(pat,hdr::FitsHeader))` yields number of matches.
- Some bug fixes.
## Version 0.2.0
- Package renamed `FITSBase.jl`.
- To avoid collisions with `FITSIO.jl` types are prefixed by `Fits` instead of
`FITS`.
## Version 0.1.1
- Package name `FITSCards.jl`.
- Add `FITSHeader` structure.
- New card properties: `card.units` and `card.unitless`.
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 0.4.1 | 5a8540e7601cbd07f583ef49e01fdaca32b9c171 | docs | 17274 | # FITSHeaders [](https://github.com/emmt/FITSHeaders.jl/actions/workflows/CI.yml?query=branch%3Amain) [](https://codecov.io/gh/emmt/FITSHeaders.jl)
`FITSHeaders` is a pure [Julia](https://julialang.org/) package for managing basic
FITS structures such as FITS headers. [FITS (for *Flexible Image Transport
System*)](https://fits.gsfc.nasa.gov/fits_standard.html) is a data file format
widely used in astronomy. A FITS file is a concatenation of *Header Data Units*
(HDUs) that consist in a header part and a data part. The header of a HDU is a
collection of so-called *FITS cards*. Each such card is stored in textual form
and associates a keyword with a value and/or a comment.
The `FITSHeaders` package is intended to provide:
- Methods for fast parsing of a FITS header or of a piece of a FITS header
(that is a single FITS header card).
- An expressive API for creating FITS cards and accessing their components
(keyword, value, and comment), possibly, in a *type-stable* way.
- Methods for easy and efficient access to the records of a FITS header.
## Building FITS cards
A FITS header card associates a keyword (or a name) with a value and a comment
(both optional). A FITS header card can be efficiently stored as an instance of
`FitsCard` built by:
``` julia
card = FitsCard(key => (val, com))
```
with `key` the card name, `val` its value, and `com` its comment. The value
`val` may be:
- a boolean to yield a card of type `FITS_LOGICAL`;
- an integer to yield a card of type `FITS_INTEGER`;
- a non-integer real to yield a card of type `FITS_FLOAT`;
- a complex to yield a card of type `FITS_COMPLEX`;
- a string to yield a card of type `FITS_STRING`;
- `nothing` to yield a card of type `FITS_COMMENT`;
- `undef` or `missing` to yield a card of type `FITS_UNDEFINED`.
The comment may be omitted for a normal FITS card and the value may be omitted
for a commentary FITS card:
``` julia
card = FitsCard(key => val::Number)
card = FitsCard(key => str::AbstractString)
```
In the 1st case, the comment is assumed to be empty. In the 2nd case, the
string `str` is assumed to be the card comment if `key` is `"COMMENT"` or
`"HISTORY"` and the card value otherwise.
Conversely, `Pair(card)` yields the pair `key => (val, com)`. The `convert` method
is extended by the `FITSHeaders` package to perform these conversions.
If the string value of a FITS card is too long, it shall be split across
several consecutive `CONTINUE` cards when writing a FITS file. Likewise, if the
comment of a commentary keyword (`"COMMENT"` or `"HISTORY"`) is too long, it
shall be split across several consecutive cards with the same keyword when
writing a FITS file.
## FITS cards properties
FITS cards have the following properties (among others):
``` julia
card.type # type of card: FITS_LOGICAL, FITS_INTEGER, etc.
card.key # quick key of card: Fits"BITPIX", Fits"HIERARCH", etc.
card.name # name of card
card.value # callable object representing the card value
card.comment # comment of card
card.units # units of card value
card.unitless # comment of card without the units part if any
```
As the values of FITS keywords have different types, `card.value` does not
yield a Julia value but a callable object. Called without any argument, this
object yields the actual card value:
``` julia
card.value() -> val::Union{Bool,Int64,Float64,ComplexF64,String,Nothing,UndefInitializer}
```
but such a call is not *type-stable* as indicated by the union `Union{...}` in
the above type assertion. For a type-stable result, the card value can be
converted to a given data type `T`:
``` julia
card.value(T)
convert(T, card.value)
```
both yield the value of `card` converted to type `T`. For readability, `T` may
be an abstract type: `card.value(Integer)` yields the same result as
`card.value(Int64)`, `card.value(Real)` or `card.value(AbstractFloat)` yield
the same result as `card.value(Float64)`, `card.value(Complex)` yields the same
result as `card.value(ComplexF64)`, and `card.value(AbstractString)` yields the
same result as `card.value(String)`.
To make things easier, a few additional properties are aliases that yield the
card value converted to a specific type:
``` julia
card.logical :: Bool # alias for card.value(Bool)
card.integer :: Int64 # alias for card.value(Integer)
card.float :: Float64 # alias for card.value(Real)
card.complex :: ComplexF64 # alias for card.value(Complex)
card.string :: String # alias for card.value(String)
```
When the actual card value is of a different type than the one requested, an
error is thrown if the conversion is not possible or inexact.
`valtype(card)` yields the Julia type of the value of `card` while
`isassigned(card)` yields whether `card` has a value (that is whether it is
neither a commentary card nor a card with an undefined value).
## FITS keywords
There are two kinds of FITS keywords:
- Short FITS keywords are words with at most 8 ASCII characters from the
restricted set of upper case letters (bytes 0x41 to 0x5A), decimal digits
(hexadecimal codes 0x30 to 0x39), hyphen (hexadecimal code 0x2D), or
underscore (hexadecimal code 0x5F). In a FITS file, keywords shorter than 8
characters are right-padded with ordinary spaces (hexadecimal code 0x20).
- `HIERARCH` FITS keywords start with the string `"HIERARCH "` (with a single
trailing space) followed by one or more words composed from the same
restricted set of ASCII characters as short keywords and separated by a
single space.
Keywords longer than 8 characters or composed of several words can only be
represented as `HIERARCH` FITS keywords. To simplify the representation of FITS
cards as pairs, the `FitsCard` constructor automatically converts long keywords
or multi-word keywords into a `HIERARCH` FITS keyword by prefixing the keyword
with the string `"HIERARCH "` for example:
``` julia
julia> card = FitsCard("VERY-LONG-NAME" => (2, "keyword is longer than 8 characters"))
FitsCard: HIERARCH VERY-LONG-NAME = 2 / keyword is longer than 8 characters
julia> card.name
"HIERARCH VERY-LONG-NAME"
julia> FitsCard("SOME KEY" => (3, "keyword has 8 characters but 2 words"))
FitsCard: HIERARCH SOME KEY = 3 / keyword has 8 characters but 2 words
julia> card.name
"HIERARCH SOME KEY"
```
This rule is only applied to the construction of FITS cards from pairs. When
parsing a FITS header card from a file, the `"HIERARCH "` prefix must be
present.
The non-exported method `FITSHeaders.keyword` may be used to apply this rule:
``` julia
julia> FITSHeaders.keyword("VERY-LONG-NAME")
"HIERARCH VERY-LONG-NAME"
julia> FITSHeaders.keyword("SOME KEY")
"HIERARCH SOME KEY"
julia> FITSHeaders.keyword("NAME")
"NAME"
julia> FITSHeaders.keyword("HIERARCH NAME")
"HIERARCH NAME"
```
## Quick FITS keys
In `FITSHeaders`, a key of type `FitsKey` is a 64-bit value computed from a FITS
keyword. The key of a short FITS keyword is unique and exactly matches the
first 8 bytes of the keyword as it is stored in a FITS file. Thus quick keys
provide fast means to compare and search FITS keywords. The constructor
`FitsKey(name)` yields the quick key of the string `name`. A quick key may be
literally expressed by using the `@Fits_str` macro in Julia code. For example:
``` julia
card.key == Fits"NAXIS"
```
is faster than, say `card.name == "NAXIS"`, to check whether the name of the
FITS header card `card` is `"NAXIS"`. This is because, the comparison is
performed on a single integer (not on several characters) and expression
`Fits"...."` is a constant computed at compile time with no run-time penalty.
Compared to `FitsKey(name)`, `Fits"...."` checks the validity of the characters
composing the literal short keyword (again this is done at compile time so
without run-time penalty) and, for readability, does not allow for trailing
spaces.
For a `HIERARCH` keyword, the quick key is equal to the constant
`Fits"HIERARCH"` whatever the other part of the keyword.
## Parsing of FITS header cards
Each FITS header card is stored in a FITS file as 80 consecutive bytes from the
restricted set of ASCII characters from `' '` to `'~'` (hexadecimal codes 0x20
to 0x7E). Hence Julia strings (whether they are encoded in ASCII or in UTF8)
can be treated as vectors of bytes. The parsing methods provided by the
`FITSHeaders` package exploit this to deal with FITS headers and cards stored as
either vectors of bytes (of type `AbstractVector{UInt8}`) or as Julia strings
(of type `String` or `SubString{String}`).
A `FitsCard` object can be built by parsing a FITS header card as it is stored
in a FITS file:
``` julia
card = FitsCard(buf; offset=0)
```
where `buf` is either a string or a vector of bytes. Keyword `offset` can be
used to specify the number of bytes to skip at the beginning of `buf`, so that
it is possible to extract a specific FITS header card, not just the first one.
At most, the 80 first bytes after the offset are scanned to build the
`FitsCard` object. The next FITS card to parse is then at `offset + 80` and so
on.
The considered card may be shorter than 80 bytes, the result being exactly the
same as if the missing bytes were spaces. If there are no bytes left, a
`FitsCard` object equivalent to the final `END` card of a FITS header is
returned.
## FITS headers
The `FITSHeaders` package provides objects of type `FitsHeader` to store,
possibly partial, FITS headers.
### Building a FITS header
To build a FITS header initialized with records `args..`, call:
``` julia
hdr = FitsHeader(args...)
```
where `args...` is a variable number of records in any form allowed by the
`FitsCard` constructor, it can also be a vector or a tuple of records. For
example:
``` julia
dims = (384, 288)
hdr = FitsHeader("SIMPLE" => true,
"BITPIX" => (-32, "32-bit floats"),
"NAXIS" => (length(dims), "number of dimensions"),
ntuple(i -> "NAXIS$i" => dims[i], length(dims))...,
"COMMENT" => "A comment.",
"COMMENT" => "Another comment.",
"DATE" => ("2023-02-01", "1st of February, 2023"),
"COMMENT" => "Yet another comment.")
```
Method `keys` can be applied to get the list of keywords in a FITS header:
``` julia
julia> keys(hdr)
KeySet for a Dict{String, Int64} with 7 entries. Keys:
"COMMENT"
"BITPIX"
"SIMPLE"
"NAXIS2"
"NAXIS1"
"NAXIS"
"DATE"
```
### Retrieving records from a FITS header
A FITS header object behaves as a vector of `FitsCard` elements with integer or
keyword (string) indices. When indexed by keywords, a FITS header object is
similar to a dictionary except that the order of records is preserved and that
commentary and continuation records (with keywords `"COMMENT"`, `"HISTORY"`,
`""`, or `"CONTINUE"`) may appear more than once.
An integer (linear) index `i` or a string index `key` can be used to retrieve
a given record:
``` julia
hdr[i] # i-th record
hdr[key] # first record whose name matches `key`
```
For example (with `hdr` as built above):
``` julia
julia> hdr[2]
FitsCard: BITPIX = -32 / 32-bit floats
julia> hdr["NAXIS"]
FitsCard: NAXIS = 2 / number of dimensions
julia> hdr["COMMENT"]
FitsCard: COMMENT A comment.
```
Note that, when indexing by name, the first matching record is returned. This
may be a concern for non-unique keywords as in the last above example. All
matching records can be collected into a vector of `FitsCard` elements by:
``` julia
collect(key, hdr) # all records whose name matches `key`
```
For example:
``` julia
julia> collect("COMMENT", hdr)
3-element Vector{FitsCard}:
FitsCard: COMMENT A comment.
FitsCard: COMMENT Another comment.
FitsCard: COMMENT Yet another comment.
julia> collect(rec -> startswith(rec.name, "NAXIS"), hdr)
3-element Vector{FitsCard}:
FitsCard: NAXIS = 2 / number of dimensions
FitsCard: NAXIS1 = 384
FitsCard: NAXIS2 = 288
julia> collect(r"^NAXIS[0-9]+$", hdr)
2-element Array{FitsCard,1}:
FitsCard("NAXIS1" => 384)
FitsCard("NAXIS2" => 288)
```
This behavior is different from that of `filter` which yields another FITS
header instance:
``` julia
julia> filter(rec -> startswith(rec.name, "NAXIS"), hdr)
3-element FitsHeader:
FitsCard: NAXIS = 2 / number of dimensions
FitsCard: NAXIS1 = 384
FitsCard: NAXIS2 = 288
```
For more control, searching for the index `i` of an existing record in FITS
header object `hdr` can be done by the usual methods:
``` julia
findfirst(what, hdr)
findlast(what, hdr)
findnext(what, hdr, start)
findprev(what, hdr, start)
```
which all return a valid integer index if a record matching `what` is found and
`nothing` otherwise. The matching pattern `what` can be a keyword (string), a
FITS card (an instance of `FitsCard` whose name is used as a matching pattern),
a regular expression, or a predicate function which takes a FITS card argument
and shall return whether it matches. The find methods just yield `nothing` for
any unsupported kind of pattern.
The `eachmatch` method is a simple mean to iterate over matching records:
``` julia
eachmatch(what, hdr)
```
yields an iterator over the records of `hdr` matching `what`. For example:
``` julia
@inbounds for rec in eachmatch(what, hdr)
... # do something
end
```
is a shortcut for:
``` julia
i = findfirst(what, hdr)
@inbounds while i !== nothing
rec = hdr[i]
... # do something
i = findnext(what, hdr, i+1)
end
```
while:
``` julia
@inbounds for rec in reverse(eachmatch(what, hdr))
... # do something
end
```
is equivalent to:
``` julia
i = findlast(what, hdr)
@inbounds while i !== nothing
rec = hdr[i]
... # do something
i = findprev(what, hdr, i-1)
end
```
If it is not certain that a record exists or to avoid throwing a `KeyError`
exception, use the `get` method. For example:
``` julia
julia> get(hdr, "BITPIX", nothing)
FitsCard: BITPIX = -32 / 32-bit floats
julia> get(hdr, "GIZMO", missing)
missing
```
### Modifying a FITS header
A record `rec` may be pushed to a FITS header `hdr` to modify the header:
``` julia
push!(hdr, rec)
```
where `rec` may have any form allowed by the `FitsCard` constructor. If the
keyword is `"COMMENT"`, `"HISTORY"`, `""`, or `"CONTINUE"`, `rec` is appended
to the end of the list of records stored by `hdr`. For other keywords which
must be unique, if a record of the same name exists in `hdr`, it is replaced by
`rec`; otherwise, it is appended to the end of the list of records stored by
`hdr`.
The `setindex!` method may be used with a keyword (string) index. For example,
the two following statements are equivalent:
``` julia
hdr[key] = (val, com)
push!(hdr, key => (val, com))
```
The `setindex!` method may also be used with a linear (integer) index.. For
example:
``` julia
hdr[i] = rec
```
replaces the `i`-th record in `hdr` by `rec`. With an integer index, the rule
for unique / non-unique keywords is not applied, so this indexing should be
restricted to editing the value and/or comment of an existing entry. The
following example illustrates how this can be used to modify the comment of the
BITPIX record:
``` julia
julia> if (i = findfirst("BITPIX", hdr)) != nothing
hdr[i] = ("BITPIX" => (hdr[i].value(), "A better comment."))
end
"BITPIX" => (-32, "A better comment.")
```
## Timings
`FITSHeaders` is ought to be fast. Below are times and memory allocations for
parsing 80-byte FITS cards measured with Julia 1.8.5 on a Linux laptop with an
Intel Core i7-5500U CPU:
- parsing logical FITS card: 114.588 ns (2 allocations: 64 bytes)
- parsing integer FITS card: 118.519 ns (2 allocations: 72 bytes)
- parsing HIERARCH FITS card: 142.462 ns (2 allocations: 88 bytes)
- parsing float FITS card: 274.119 ns (4 allocations: 152 bytes)
- parsing complex FITS card: 424.060 ns (6 allocations: 248 bytes)
- parsing string FITS card: 155.694 ns (4 allocations: 144 bytes)
- parsing string with quotes: 169.223 ns (4 allocations: 168 bytes)
- parsing COMMENT FITS card: 90.615 ns (2 allocations: 112 bytes)
- parsing HISTORY FITS card: 100.591 ns (2 allocations: 72 bytes)
- parsing blank FITS card: 78.261 ns (0 allocations: 0 bytes)
- parsing END FITS card: 82.286 ns (0 allocations: 0 bytes)
The benchmark code is in file [`test/benchmarks.jl`](test/benchmarks.jl). The
HIERARCH card has an integer value. The float and complex valued cards take
more time to parse because parsing a floating-point value is more complex than
parsing, say, an integer and because the string storing the floating-point
value must be copied to replace letters `d` and `D`, allowed in FITS standard
to indicate the exponent, by an `e`.
For comparison, just extracting the keyword, value, and comment parts from a
80-characters FITS card by calling the functions `fits_get_keyname` and
`fits_parse_value` of CFITSIO library takes about 150 ns on the same machine.
This does not includes the allocation of the buffers to store these 3 parts
(about 120 ns for this) and the parsing of the value which are all included in
the timings of the `FISCard` constructor above.
| FITSHeaders | https://github.com/emmt/FITSHeaders.jl.git |
|
[
"MIT"
] | 2.0.0 | cdf3c2ce48c06a2106c0196d9814d9630a991d12 | code | 719 | using CountDownLatches
using Documenter
DocMeta.setdocmeta!(
CountDownLatches,
:DocTestSetup,
:(using CountDownLatches);
recursive = true,
)
makedocs(;
modules = [CountDownLatches],
authors = "Octogonapus <[email protected]> and contributors",
repo = "https://github.com/Octogonapus/CountDownLatches.jl/blob/{commit}{path}#{line}",
sitename = "CountDownLatches.jl",
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
canonical = "https://Octogonapus.github.io/CountDownLatches.jl",
assets = String[],
),
pages = ["Home" => "index.md"],
)
deploydocs(; repo = "github.com/Octogonapus/CountDownLatches.jl", devbranch = "main")
| CountDownLatches | https://github.com/Octogonapus/CountDownLatches.jl.git |
|
[
"MIT"
] | 2.0.0 | cdf3c2ce48c06a2106c0196d9814d9630a991d12 | code | 1600 | module CountDownLatches
export CountDownLatch, await, count_down, get_count
"""
CountDownLatch(count::I) where {I<:Integer}
A `CountDownLatch` that starts at some initial non-negative `count`. This latch can be counted down and waited on.
"""
mutable struct CountDownLatch{I<:Integer}
count::Threads.Atomic{I}
condition::Threads.Condition
function CountDownLatch(count::I) where {I<:Integer}
if count < 0
throw(ArgumentError("Count ($count) must not be negative."))
end
new{I}(Threads.Atomic{I}(I(count)), Threads.Condition(ReentrantLock()))
end
end
"""
await(latch::CountDownLatch)
Waits until the `latch` has counted down to `<= 0`.
"""
function await(latch::CountDownLatch)
# Check the count early to possibly avoid a call to lock
if get_count(latch) <= 0
return
end
lock(latch.condition) do
while get_count(latch) > 0
wait(latch.condition)
end
end
end
"""
count_down(latch::CountDownLatch)
Counts down the `latch` once. This may cause the count to become negative. Any tasks that were blocked in `await` will
be woken if the count becomes `<= 0`.
"""
function count_down(latch::CountDownLatch{I}) where {I<:Integer}
Threads.atomic_sub!(latch.count, I(1))
lock(latch.condition) do
notify(latch.condition, nothing; all = true, error = false)
end
nothing
end
"""
get_count(latch::CountDownLatch)
Returns the current count of the `latch`. This count may be negative.
"""
function get_count(latch::CountDownLatch)
latch.count[]
end
end
| CountDownLatches | https://github.com/Octogonapus/CountDownLatches.jl.git |
|
[
"MIT"
] | 2.0.0 | cdf3c2ce48c06a2106c0196d9814d9630a991d12 | code | 1832 | using CountDownLatches
using Test
using ThreadPools
@testset "create a latch with a negative count" begin
@test_throws ArgumentError CountDownLatch(-1)
end
@testset "count down from 1" begin
latch = CountDownLatch(1)
count_down(latch)
await(latch)
@test get_count(latch) == 0
end
@testset "count down from 1 two times" begin
latch = CountDownLatch(1)
count_down(latch)
count_down(latch)
await(latch)
@test get_count(latch) == -1
end
@testset "wait for another thread to count down from 1" begin
latch = CountDownLatch(1)
t = Threads.@spawn begin
count_down(latch)
end
await(latch)
@test get_count(latch) == 0
@test istaskdone(t)
end
@testset "mutual count down" begin
latch1 = CountDownLatch(1)
latch2 = CountDownLatch(1)
latch3 = CountDownLatch(1)
t = Threads.@spawn begin
count_down(latch2)
await(latch1)
count_down(latch3)
end
await(latch2)
count_down(latch1)
await(latch3)
@test get_count(latch1) == 0
@test get_count(latch2) == 0
@test get_count(latch3) == 0
@test istaskdone(t)
end
@testset "wait for another thread to count down from 2" begin
latch = CountDownLatch(2)
t = Threads.@spawn begin
count_down(latch)
count_down(latch)
end
await(latch)
@test get_count(latch) == 0
@test istaskdone(t)
end
@testset "wait for this thread to count down from 2 using ThreadPools" begin
latch = CountDownLatch(2)
this_thread_id = Threads.threadid()
@tspawnat this_thread_id begin
# I would like to assert that await() was called but this is the best I can come up with
@test get_count(latch) == 1
count_down(latch)
end
count_down(latch)
await(latch)
@test get_count(latch) == 0
end
| CountDownLatches | https://github.com/Octogonapus/CountDownLatches.jl.git |
|
[
"MIT"
] | 2.0.0 | cdf3c2ce48c06a2106c0196d9814d9630a991d12 | docs | 1343 | # CountDownLatches
[](https://Octogonapus.github.io/CountDownLatches.jl/stable)
[](https://Octogonapus.github.io/CountDownLatches.jl/dev)
[](https://github.com/Octogonapus/CountDownLatches.jl/actions)
[](https://codecov.io/gh/Octogonapus/CountDownLatches.jl)
[](https://github.com/invenia/BlueStyle)
This package implements a multithreading primitive called a `CountDownLatch` that holds an internal count.
The latch's count can be decremented by multiple threads.
Threads may also wait on the latch's count to become zero.
## Example
In this example, the main thread will be blocked by `await` until the spawned thread counts the latch down.
This is clearly a contrived example, but imagine that there is much more code before `count_down` and before `await`.
```julia
latch = CountDownLatch(1)
Threads.@spawn begin
# Decrease the latch's count by one
count_down(latch)
end
# Wait until the latch's count become zero
await(latch)
```
| CountDownLatches | https://github.com/Octogonapus/CountDownLatches.jl.git |
|
[
"MIT"
] | 2.0.0 | cdf3c2ce48c06a2106c0196d9814d9630a991d12 | docs | 128 | ```@meta
CurrentModule = CountDownLatches
```
# CountDownLatches
```@index
```
```@autodocs
Modules = [CountDownLatches]
```
| CountDownLatches | https://github.com/Octogonapus/CountDownLatches.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1506 | using Comrade
using Distributions
using BenchmarkTools
using Pyehtim
# To download the data visit https://doi.org/10.25739/g85n-f134
obs = ehtim.obsdata.load_uvfits(joinpath(@__DIR__, "..", "examples", "Data", "SR1_M87_2017_096_hi_hops_netcal_StokesI.uvfits"))
obsavg = scan_average(obs)
amp = extract_table(obsavg, VisibilityAmplitudes())
function model(θ, p)
(;rad, wid, a, b, f, sig, asy, pa, x, y) = θ
ring = f*smoothed(stretched(MRing((a,), (b,)), μas2rad(rad), μas2rad(rad)), μas2rad(wid))
g = (1-f)*shifted(rotated(stretched(Gaussian(), μas2rad(sig)*asy, μas2rad(sig)), pa), μas2rad(x), μas2rad(y))
return ring + g
end
prior = (
rad = Uniform(10.0, 30.0),
wid = Uniform(1.0, 10.0),
a = Uniform(-0.5, 0.5), b = Uniform(-0.5, 0.5),
f = Uniform(0.0, 1.0),
sig = Uniform((1.0), (60.0)),
asy = Uniform(0.0, 0.9),
pa = Uniform(0.0, 1π),
x = Uniform(-(80.0), (80.0)),
y = Uniform(-(80.0), (80.0))
)
# Now form the posterior
skym = SkyModel(model, prior, imagepixels(μas2rad(150.0), μas2rad(150.0), 128, 128))
θ = (rad= 22.0, wid= 3.0, a = 0.0, b = 0.15, f=0.8, sig = 20.0, asy=0.2, pa=π/2, x=20.0, y=20.0)
m = model(θ, nothing)
post = VLBIPosterior(skym, amp)
tpost = asflat(post)
x0 = prior_sample(tpost)
ℓ = logdensityof(tpost)
@benchmark ℓ($x0)
# 38.1 μs
using Enzyme
@benchmark Enzyme.gradient(Enzyme.Reverse, $(Const(tpost)), $x0)
#107.3 μs
# Now we do the eht-imaging benchmarks
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1964 | # THis is because we are on a headless system
# see https://github.com/jheinen/GR.jl/issues/510
# ENV["GKS_WSTYPE"]="nul"
using Documenter, Pkg
using DocumenterVitepress
using Comrade, ComradeBase, AdvancedHMC, Dynesty, Optimization,
PolarizedTypes
using Pyehtim, VLBISkyModels, InteractiveUtils
using AbstractMCMC, Random, HypercubeTransform
deployconfig = Documenter.auto_detect_deploy_system()
Documenter.post_status(deployconfig; type="pending", repo="github.com/ptiede/Comrade.jl.git")
TUTORIALS = [
"Overview" => "tutorials/index.md",
"Beginner" =>[
"tutorials/beginner/LoadingData.md",
"tutorials/beginner/GeometricModeling.md"
],
"Intermediate" => [
"tutorials/intermediate/ClosureImaging.md",
"tutorials/intermediate/StokesIImaging.md",
"tutorials/intermediate/PolarizedImaging.md"
],
"Advanced" => [
"tutorials/advanced/HybridImaging.md",
]
]
makedocs(;
modules=[ComradeBase, Comrade],
repo="https://github.com/ptiede/Comrade.jl/blob/{commit}{path}#{line}",
sitename="Comrade.jl",
format = MarkdownVitepress(
repo="https://github.com/ptiede/Comrade.jl",
devurl = "dev",
devbranch = "main",
),
pages=Any[
"Home" => "index.md",
"introduction.md",
"benchmarks.md",
"vlbi_imaging_problem.md",
"conventions.md",
"Tutorials" => TUTORIALS,
"Extensions" => [
"ext/optimization.md",
"ext/ahmc.md",
"ext/dynesty.md",
"ext/pigeons.md"
],
"base_api.md",
"api.md"
],
draft = false,
source = "src",
build = "build",
clean = true
)
deploydocs(;
repo="github.com/ptiede/Comrade.jl",
push_preview=true,
devbranch = "main",
target = "build"
)
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1270 | using Pkg; Pkg.activate(@__DIR__)
using Literate
preprocess(path, str) = replace(str, "__DIR = @__DIR__" => "__DIR = \"$(dirname(path))\"")
get_example_path(p) = joinpath(@__DIR__, "..", "examples", p)
OUTPUT = joinpath(@__DIR__, "src", "tutorials")
TUTORIALS = [
"beginner/LoadingData/main.jl",
"beginner/GeometricModeling/main.jl",
"intermediate/ClosureImaging/main.jl",
"intermediate/StokesIImaging/main.jl",
"intermediate/PolarizedImaging/main.jl",
"advanced/HybridImaging/main.jl",
]
withenv("JULIA_DEBUG"=>"Literate") do
for (d, paths) in (("", TUTORIALS),),
(i,p) in enumerate(paths)
name = "$((rsplit(p, "/")[2]))"
d = "$((rsplit(p, "/")[1]))"
p_ = get_example_path(p)
@info p_
jl_expr = "using Literate;"*
"preprocess(path, str) = replace(str, \"__DIR = @__DIR__\" => \"__DIR = \\\"\$(dirname(path))\\\"\");"*
"Literate.markdown(\"$(p_)\", \"$(joinpath(OUTPUT, d))\";"*
"name=\"$name\", execute=false, flavor=Literate.DocumenterFlavor(),"*
"preprocess=Base.Fix1(preprocess, \"$(p_)\"))"
cm = `julia --project=$(@__DIR__) -e $(jl_expr)`
run(cm)
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 11337 | # # Hybrid Imaging of a Black Hole
# In this tutorial, we will use **hybrid imaging** to analyze the 2017 EHT data.
# By hybrid imaging, we mean decomposing the model into simple geometric models, e.g., rings
# and such, plus a rasterized image model to soak up the additional structure.
# This approach was first developed in [`BB20`](https://iopscience.iop.org/article/10.3847/1538-4357/ab9c1f)
# and applied to EHT 2017 data. We will use a similar model in this tutorial.
# ## Introduction to Hybrid modeling and imaging
# The benefit of using a hybrid-based modeling approach is the effective compression of
# information/parameters when fitting the data. Hybrid modeling requires the user to
# incorporate specific knowledge of how you expect the source to look like. For instance
# for M87, we expect the image to be dominated by a ring-like structure. Therefore, instead
# of using a high-dimensional raster to recover the ring, we can use a ring model plus
# a raster to soak up the additional degrees of freedom.
# This is the approach we will take in this tutorial to analyze the April 6 2017 EHT data
# of M87.
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
ENV["GKSwstype"] = "nul" #hide
# ## Loading the Data
# To get started we will load Comrade
using Comrade
# ## Load the Data
using Pyehtim
# For reproducibility we use a stable random number genreator
using StableRNGs
rng = StableRNG(11)
# To download the data visit https://doi.org/10.25739/g85n-f134
# To load the eht-imaging obsdata object we do:
obs = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
# Now we do some minor preprocessing:
# - Scan average the data since the data have been preprocessed so that the gain phases
# coherent.
obs = scan_average(obs).add_fractional_noise(0.02)
# For this tutorial we will once again fit complex visibilities since they
# provide the most information once the telescope/instrument model are taken
# into account.
dvis = extract_table(obs, Visibilities())
# ## Building the Model/Posterior
# Now we build our intensity/visibility model. That is, the model that takes in a
# named tuple of parameters and perhaps some metadata required to construct the model.
# For our model, we will use a raster or `ContinuousImage` model, an `m-ring` model,
# and a large asymmetric Gaussian component to model the unresolved short-baseline flux.
function sky(θ, metadata)
(;c, σimg, f, r, σ, ma, mp, fg) = θ
(;ftot, grid) = metadata
## Form the image model
## First transform to simplex space first applying the non-centered transform
rast = (ftot*f*(1-fg)).*to_simplex(CenteredLR(), σimg.*c)
mimg = ContinuousImage(rast, grid, BSplinePulse{3}())
## Form the ring model
α = ma.*cos.(mp)
β = ma.*sin.(mp)
ring = smoothed(modify(MRing(α, β), Stretch(r), Renormalize((ftot*(1-f)*(1-fg)))), σ)
gauss = modify(Gaussian(), Stretch(μas2rad(250.0)), Renormalize(ftot*f*fg))
## We group the geometric models together for improved efficiency. This will be
## automated in future versions.
return mimg + (ring + gauss)
end
# Unlike other imaging examples
# (e.g., [Imaging a Black Hole using only Closure Quantities](@ref)) we also need to include
# a model for the instrument, i.e., gains as well. The gains will be broken into two components
# - Gain amplitudes which are typically known to 10-20%, except for LMT, which has amplitudes closer to 50-100%.
# - Gain phases which are more difficult to constrain and can shift rapidly.
using VLBIImagePriors
using Distributions
fgain(x) = exp(x.lg + 1im*x.gp)
G = SingleStokesGain(fgain)
intpr = (
lg= ArrayPrior(IIDSitePrior(ScanSeg(), Normal(0.0, 0.2)); LM = IIDSitePrior(ScanSeg(), Normal(0.0, 1.0))),
gp= ArrayPrior(IIDSitePrior(ScanSeg(), DiagonalVonMises(0.0, inv(π^2))); refant=SEFDReference(0.0))
)
intmodel = InstrumentModel(G, intpr)
# Before we move on, let's go into the `model` function a bit. This function takes two arguments
# `θ` and `metadata`. The `θ` argument is a named tuple of parameters that are fit
# to the data. The `metadata` argument is all the ancillary information we need to construct the model.
# For our hybrid model, we will need two variables for the metadata, a `grid` that specifies
# the locations of the image pixels and a `cache` that defines the algorithm used to calculate
# the visibilities given the image model. This is required since `ContinuousImage` is most easily
# computed using number Fourier transforms like the [`NFFT`](https://github.com/JuliaMath/NFFT.jl)
# or [FFT](https://github.com/JuliaMath/FFTW.jl).
# To combine the models, we use `Comrade`'s overloaded `+` operators, which will combine the
# images such that their intensities and visibilities are added pointwise.
# Now let's define our metadata. First we will define the cache for the image. This is
# required to compute the numerical Fourier transform.
fovxy = μas2rad(200.0)
npix = 32
g = imagepixels(fovxy, fovxy, npix, npix)
# Part of hybrid imaging is to force a scale separation between
# the different model components to make them identifiable.
# To enforce this we will set the raster component to have a
# correlation length of 5 times the beam size.
beam = beamsize(dvis)
rat = (beam/(step(g.X)))
cprior = GaussMarkovRandomField(5*rat, size(g))
# For the other parameters we use a uniform priors for the ring fractional flux `f`
# ring radius `r`, ring width `σ`, and the flux fraction of the Gaussian component `fg`
# and the amplitude for the ring brightness modes. For the angular variables `ξτ` and `ξ`
# we use the von Mises prior with concentration parameter `inv(π^2)` which is essentially
# a uniform prior on the circle. Finally for the standard deviation of the MRF we use a
# half-normal distribution. This is to ensure that the MRF has small differences from the
# mean image.
skyprior = (
c = cprior,
σimg = truncated(Normal(0.0, 0.1); lower=0.01),
f = Uniform(0.0, 1.0),
r = Uniform(μas2rad(10.0), μas2rad(30.0)),
σ = Uniform(μas2rad(0.1), μas2rad(10.0)),
ma = ntuple(_->Uniform(0.0, 0.5), 2),
mp = ntuple(_->DiagonalVonMises(0.0, inv(π^2)), 2),
fg = Uniform(0.0, 1.0),
)
# Now we form the metadata
skymetadata = (;ftot=1.1, grid = g)
skym = SkyModel(sky, skyprior, g; metadata=skymetadata)
# This is everything we need to specify our posterior distribution, which our is the main
# object of interest in image reconstructions when using Bayesian inference.
using Enzyme
post = VLBIPosterior(skym, intmodel, dvis; admode=set_runtime_activity(Enzyme.Reverse))
# To sample from our prior we can do
xrand = prior_sample(rng, post)
# and then plot the results
using DisplayAs #hide
import CairoMakie as CM
CM.activate!(type = "png", px_per_unit=1) #hide
gpl = imagepixels(μas2rad(200.0), μas2rad(200.0), 128, 128)
fig = imageviz(intensitymap(skymodel(post, xrand), gpl));
fig |> DisplayAs.PNG |> DisplayAs.Text #hide
# ## Reconstructing the Image
# To find the image we will demonstrate two methods:
# - Optimization to find the MAP (fast but often a poor estimator)
# - Sampling to find the posterior (slow but provides a substantially better estimator)
# For optimization we will use the `Optimization.jl` package and the LBFGS optimizer.
# To use this we use the [`comrade_opt`](@ref) function
using Optimization
using OptimizationOptimJL
xopt, sol = comrade_opt(post, LBFGS();
initial_params=xrand, maxiters=2000, g_tol=1e0)
# First we will evaluate our fit by plotting the residuals
using Plots
fig = residual(post, xopt);
fig |> DisplayAs.PNG |> DisplayAs.Text #hide
# These residuals suggest that we are substantially overfitting the data. This is a common
# side effect of MAP imaging. As a result if we plot the image we see that there
# is substantial high-frequency structure in the image that isn't supported by the data.
imageviz(intensitymap(skymodel(post, xopt), gpl), figure=(;resolution=(500, 400),))
# To improve our results we will now move to Posterior sampling. This is the main method
# we recommend for all inference problems in `Comrade`. While it is slower the results are
# often substantially better. To sample we will use the `AdvancedHMC` package.
using AdvancedHMC
chain = sample(rng, post, NUTS(0.8), 700; n_adapts=500, progress=false, initial_params=xopt);
# We then remove the adaptation/warmup phase from our chain
chain = chain[501:end]
# !!! warning
# This should be run for 4-5x more steps to properly estimate expectations of the posterior
#-
# Now lets plot the mean image and standard deviation images.
# To do this we first clip the first 250 MCMC steps since that is during tuning and
# so the posterior is not sampling from the correct sitesary distribution.
using StatsBase
msamples = skymodel.(Ref(post), chain[begin:2:end]);
# The mean image is then given by
imgs = intensitymap.(msamples, Ref(gpl))
fig = imageviz(mean(imgs), colormap=:afmhot, size=(400, 300));
fig |> DisplayAs.PNG |> DisplayAs.Text #hide
#-
fig = imageviz(std(imgs), colormap=:batlow, size=(400, 300));
fig |> DisplayAs.PNG |> DisplayAs.Text #hide
#-
#
# We can also split up the model into its components and analyze each separately
comp = Comrade.components.(msamples)
ring_samples = getindex.(comp, 2)
rast_samples = first.(comp)
ring_imgs = intensitymap.(ring_samples, Ref(gpl));
rast_imgs = intensitymap.(rast_samples, Ref(gpl));
ring_mean, ring_std = mean_and_std(ring_imgs);
rast_mean, rast_std = mean_and_std(rast_imgs);
fig = CM.Figure(; resolution=(400, 400));
axes = [CM.Axis(fig[i, j], xreversed=true, aspect=CM.DataAspect()) for i in 1:2, j in 1:2]
CM.image!(axes[1,1], ring_mean, colormap=:afmhot); axes[1,1].title = "Ring Mean"
CM.image!(axes[1,2], ring_std, colormap=:afmhot); axes[1,2].title = "Ring Std. Dev."
CM.image!(axes[2,1], rast_mean, colormap=:afmhot); axes[2,1].title = "Rast Mean"
CM.image!(axes[2,2], rast_std./rast_mean, colormap=:afmhot); axes[2,2].title = "Rast std/mean"
CM.hidedecorations!.(axes)
fig |> DisplayAs.PNG |> DisplayAs.Text
# Finally, let's take a look at some of the ring parameters
figd = CM.Figure(;resolution=(650, 400));
p1 = CM.density(figd[1,1], rad2μas(chain.sky.r)*2, axis=(xlabel="Ring Diameter (μas)",))
p2 = CM.density(figd[1,2], rad2μas(chain.sky.σ)*2*sqrt(2*log(2)), axis=(xlabel="Ring FWHM (μas)",))
p3 = CM.density(figd[1,3], -rad2deg.(chain.sky.mp.:1) .+ 360.0, axis=(xlabel = "Ring PA (deg) E of N",))
p4 = CM.density(figd[2,1], 2*chain.sky.ma.:2, axis=(xlabel="Brightness asymmetry",))
p5 = CM.density(figd[2,2], 1 .- chain.sky.f, axis=(xlabel="Ring flux fraction",))
figd |> DisplayAs.PNG |> DisplayAs.Text #hide
# Now let's check the residuals using draws from the posterior
p = Plots.plot();
for s in sample(chain, 10)
residual!(p, post, s, legend=false)
end
p |> DisplayAs.PNG |> DisplayAs.Text #hide
# And everything looks pretty good! Now comes the hard part: interpreting the results...
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 10565 | # # Geometric Modeling of EHT Data
# `Comrade` has been designed to work with the EHT and ngEHT.
# In this tutorial, we will show how to reproduce some of the results
# from [EHTC VI 2019](https://iopscience.iop.org/article/10.3847/2041-8213/ab1141).
# In EHTC VI, they considered fitting simple geometric models to the data
# to estimate the black hole's image size, shape, brightness profile, etc.
# In this tutorial, we will construct a similar model and fit it to the data in under
# 50 lines of code (sans comments). To start, we load Comrade and some other packages we need.
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
ENV["GKSwstype"] = "nul" #hide
using Comrade
using Pyehtim
# For reproducibility we use a stable random number genreator
using StableRNGs
rng = StableRNG(42)
#-
# The next step is to load the data. We will use the publically
# available M 87 data which can be downloaded
# from [cyverse](https://datacommons.cyverse.org/browse/iplant/home/shared/commons_repo/curated/EHTC_FirstM87Results_Apr2019).
# For an introduction to data loading, see [Loading Data into Comrade](@ref).
obs = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
# Now we will kill 0-baselines since we don't care about large-scale flux and
# since we know that the gains in this dataset are coherent across a scan, we make scan-average data
obs = Pyehtim.scan_average(obs.flag_uvdist(uv_min=0.1e9)).add_fractional_noise(0.02)
# Now we extract the data products we want to fit
dlcamp, dcphase = extract_table(obs, LogClosureAmplitudes(;snrcut=3.0), ClosurePhases(;snrcut=3.0))
# !!!warn
# We remove the low-snr closures since they are very non-gaussian. This can create rather
# large biases in the model fitting since the likelihood has much heavier tails that the
# usual Gaussian approximation.
#-
# For the image model, we will use a modified `MRing`, a
# infinitely thin delta ring with an azimuthal structure given by a Fourier expansion.
# To give the MRing some width, we will convolve the ring with a Gaussian and add an
# additional gaussian to the image to model any non-ring flux.
# Comrade expects that any model function must accept a named tuple and returns must always
# return an object that implements the [VLBISkyModels Interface](https://ehtjulia.github.io/VLBISkyModels.jl/stable/interface/)
#-
function sky(θ, p)
(;radius, width, ma, mp, τ, ξτ, f, σG, τG, ξG, xG, yG) = θ
α = ma.*cos.(mp .- ξτ)
β = ma.*sin.(mp .- ξτ)
ring = f*smoothed(modify(MRing(α, β), Stretch(radius, radius*(1+τ)), Rotate(ξτ)), width)
g = (1-f)*shifted(rotated(stretched(Gaussian(), σG, σG*(1+τG)), ξG), xG, yG)
return ring + g
end
# To construct our likelihood `p(V|M)` where `V` is our data and `M` is our model, we use the `RadioLikelihood` function.
# The first argument of `RadioLikelihood` is always a function that constructs our Comrade
# model from the set of parameters `θ`.
# We now need to specify the priors for our model. The easiest way to do this is to
# specify a NamedTuple of distributions:
using Distributions, VLBIImagePriors
prior = (
radius = Uniform(μas2rad(10.0), μas2rad(30.0)),
width = Uniform(μas2rad(1.0), μas2rad(10.0)),
ma = (Uniform(0.0, 0.5), Uniform(0.0, 0.5)),
mp = (Uniform(0, 2π), Uniform(0, 2π)),
τ = Uniform(0.0, 1.0),
ξτ= Uniform(0.0, π),
f = Uniform(0.0, 1.0),
σG = Uniform(μas2rad(1.0), μas2rad(100.0)),
τG = Uniform(0.0, 1.0),
ξG = Uniform(0.0, 1π),
xG = Uniform(-μas2rad(80.0), μas2rad(80.0)),
yG = Uniform(-μas2rad(80.0), μas2rad(80.0))
)
# Note that for `α` and `β` we use a product distribution to signify that we want to use a
# multivariate uniform for the mring components `α` and `β`. In general the structure of the
# variables is specified by the prior. Note that this structure must be compatible with the
# model definition `model(θ)`.
# We can now construct our Sky model, which typically takes a model, prior and the
# on sky grid. Note that since our model is analytic the grid is not directly used when
# computing visibilities.
skym = SkyModel(sky, prior, imagepixels(μas2rad(200.0), μas2rad(200.0), 128, 128))
# In this tutorial we will be using closure products as our data. As such we do not need to specify a
# instrument model, since for stokes I imaging, the likelihood is approximately invariant to the instrument
# model.
post = VLBIPosterior(skym, dlcamp, dcphase)
# !!! note
# When fitting visibilities a instrument is required, and a reader can refer to
# [Stokes I Simultaneous Image and Instrument Modeling](@ref).
# This constructs a posterior density that can be evaluated by calling `logdensityof`.
# For example,
logdensityof(post, (sky = (radius = μas2rad(20.0),
width = μas2rad(10.0),
ma = (0.3, 0.3),
mp = (π/2, π),
τ = 0.1,
ξτ= π/2,
f = 0.6,
σG = μas2rad(50.0),
τG = 0.1,
ξG = 0.5,
xG = 0.0,
yG = 0.0),))
# ## Reconstruction
# Now that we have fully specified our model, we now will try to find the optimal reconstruction
# of our model given our observed data.
# Currently, `post` is in **parameter** space. Often optimization and sampling algorithms
# want it in some modified space. For example, nested sampling algorithms want the
# parameters in the unit hypercube. To transform the posterior to the unit hypercube, we
# can use the `ascube` function
cpost = ascube(post)
# If we want to flatten the parameter space and move from constrained parameters to (-∞, ∞)
# support we can use the `asflat` function
fpost = asflat(post)
# These transformed posterior expect a vector of parameters. For example, we can draw from the
# prior in our usual parameter space
p = prior_sample(rng, post)
# and then transform it to transformed space using T
logdensityof(cpost, Comrade.TV.inverse(cpost, p))
logdensityof(fpost, Comrade.TV.inverse(fpost, p))
# note that the log densit is not the same since the transformation has causes a jacobian to ensure volume is preserved.
# ### Finding the Optimal Image
# Typically, most VLBI modeling codes only care about finding the optimal or best guess
# image of our posterior `post` To do this, we will use [`Optimization.jl`](https://docs.sciml.ai/Optimization/stable/) and
# specifically the [`BlackBoxOptim.jl`](https://github.com/robertfeldt/BlackBoxOptim.jl) package. For Comrade, this workflow is
# we use the [`comrade_opt`](@ref) function.
using Optimization
using OptimizationBBO
xopt, sol = comrade_opt(post, BBO_adaptive_de_rand_1_bin_radiuslimited(); maxiters=50_000);
# Given this we can now plot the optimal image or the *maximum a posteriori* (MAP) image.
using DisplayAs
import CairoMakie as CM
CM.activate!(type = "png", px_per_unit=1) #hide
g = imagepixels(μas2rad(200.0), μas2rad(200.0), 256, 256)
fig = imageviz(intensitymap(skymodel(post, xopt), g), colormap=:afmhot, size=(500, 400));
DisplayAs.Text(DisplayAs.PNG(fig))
# ### Quantifying the Uncertainty of the Reconstruction
# While finding the optimal image is often helpful, in science, the most important thing is to
# quantify the certainty of our inferences. This is the goal of Comrade. In the language
# of Bayesian statistics, we want to find a representation of the posterior of possible image
# reconstructions given our choice of model and the data.
#
# Comrade provides several sampling and other posterior approximation tools. To see the
# list, please see the Libraries section of the docs. For this example, we will be using
# [Pigeons.jl](https://github.com/Julia-Tempering/Pigeons.jl) which is a state-of-the-art
# parallel tempering sampler that enables global exploration of the posterior. For smaller dimension
# problems (< 100) we recommend using this sampler, especially if you have access to > 1 core.
using Pigeons
pt = pigeons(target=cpost, explorer=SliceSampler(), record=[traces, round_trip, log_sum_ratio], n_chains=16, n_rounds=8)
# That's it! To finish it up we can then plot some simple visual fit diagnostics.
# First we extract the MCMC chain for our posterior.
chain = sample_array(cpost, pt)
# First to plot the image we call
using DisplayAs #hide
imgs = intensitymap.(skymodel.(Ref(post), sample(chain, 100)), Ref(g))
fig = imageviz(imgs[end], colormap=:afmhot)
DisplayAs.Text(DisplayAs.PNG(fig))
# What about the mean image? Well let's grab 100 images from the chain, where we first remove the
# adaptation steps since they don't sample from the correct posterior distribution
meanimg = mean(imgs)
fig = imageviz(meanimg, colormap=:afmhot);
DisplayAs.Text(DisplayAs.PNG(fig))
# That looks similar to the EHTC VI, and it took us no time at all!. To see how well the
# model is fitting the data we can plot the model and data products
using Plots
p1 = Plots.plot(simulate_observation(post, xopt; add_thermal_noise=false)[1], label="MAP")
Plots.plot!(p1, dlcamp)
p2 = Plots.plot(simulate_observation(post, xopt; add_thermal_noise=false)[2], label="MAP")
Plots.plot!(p2, dcphase)
DisplayAs.Text(DisplayAs.PNG(Plots.plot(p1, p2, layout=(2,1))))
# We can also plot random draws from the posterior predictive distribution.
# The posterior predictive distribution create a number of synthetic observations that
# are marginalized over the posterior.
p1 = Plots.plot(dlcamp);
p2 = Plots.plot(dcphase);
uva = uvdist.(datatable(dlcamp))
uvp = uvdist.(datatable(dcphase))
for i in 1:10
mobs = simulate_observation(post, sample(chain, 1)[1])
mlca = mobs[1]
mcp = mobs[2]
Plots.scatter!(p1, uva, mlca[:measurement], color=:grey, label=:none, alpha=0.2)
Plots.scatter!(p2, uvp, atan.(sin.(mcp[:measurement]), cos.(mcp[:measurement])), color=:grey, label=:none, alpha=0.2)
end
p = Plots.plot(p1, p2, layout=(2,1));
DisplayAs.Text(DisplayAs.PNG(p))
# Finally, we can also put everything onto a common scale and plot the normalized residuals.
# The normalied residuals are the difference between the data
# and the model, divided by the data's error:
p = residual(post, chain[end]);
DisplayAs.Text(DisplayAs.PNG(p))
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 3251 | # # Loading Data into Comrade
# The VLBI field does not have a standardized data format, and the EHT uses a
# particular uvfits format similar to the optical interferometry oifits format.
# As a result, we reuse the excellent `eht-imaging` package to load data into `Comrade`.
# Once the data is loaded, we then convert the data into the tabular format `Comrade`
# expects. Note that this may change to a Julia package as the Julia radio
# astronomy group grows.
# To get started, we will load `Comrade` and `Plots` to enable visualizations of the data
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
ENV["GKSwstype"] = "nul" #hide
using Comrade
using Plots
# We also load Pyehtim since it loads eht-imaging into Julia using PythonCall and exports
# the variable ehtim
using Pyehtim
# To load the data we will use `eht-imaging`. We will use the 2017 public M87 data which can be downloaded from
# [cyverse](https://datacommons.cyverse.org/browse/iplant/home/shared/commons_repo/curated/EHTC_FirstM87Results_Apr2019)
obseht = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
# Now we will average the data over telescope scans. Note that the EHT data has been pre-calibrated so this averaging
# doesn't induce large coherence losses.
obs = Pyehtim.scan_average(obseht)
# !!! warning
# We use a custom scan-averaging function to ensure that the scan-times are homogenized.
#-
# We can now extract data products that `Comrade` can use
vis = extract_table(obs, Visibilities()) ## complex visibilites
amp = extract_table(obs, VisibilityAmplitudes()) ## visibility amplitudes
cphase = extract_table(obs, ClosurePhases(; snrcut=3.0)) ## extract minimal set of closure phases
lcamp = extract_table(obs, LogClosureAmplitudes(; snrcut=3.0)) ## extract minimal set of log-closure amplitudes
# For polarization we first load the data in the cirular polarization basis
# Additionally, we load the array table at the same time to load the telescope mounts.
obseht = Pyehtim.load_uvfits_and_array(
joinpath(__DIR, "..", "..", "Data", "polarized_gaussian_all_corruptions.uvfits"),
joinpath(__DIR, "..", "..", "Data", "array.txt"),
polrep="circ"
)
obs = Pyehtim.scan_average(obseht)
coh = extract_table(obs, Coherencies())
# !!! warning
# Always use our `extract_cphase` and `extract_lcamp` functions to find the closures
# eht-imaging will sometimes incorrectly calculate a non-redundant set of closures.
#-
# We can also recover the array used in the observation using
using DisplayAs
ac = arrayconfig(vis)
plot(ac) |> DisplayAs.PNG |> DisplayAs.Text # Plot the baseline coverage
# To plot the data we just call
l = @layout [a b; c d]
pv = plot(vis);
pa = plot(amp);
pcp = plot(cphase);
plc = plot(lcamp);
plot(pv, pa, pcp, plc; layout=l) |> DisplayAs.PNG |> DisplayAs.Text
# And also the coherency matrices
plot(coh) |> DisplayAs.PNG |> DisplayAs.Text
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 10373 | # # Imaging a Black Hole using only Closure Quantities
# In this tutorial, we will create a preliminary reconstruction of the 2017 M87 data on April 6
# using closure-only imaging. This tutorial is a general introduction to closure-only imaging in Comrade.
# For an introduction to simultaneous
# image and instrument modeling, see [Stokes I Simultaneous Image and Instrument Modeling](@ref)
# ## Introduction to Closure Imaging
# The EHT is one of the highest-resolution telescope ever created. Its resolution is equivalent
# to roughly tracking a hockey puck on the moon when viewing it from the earth. However,
# the EHT is also a unique interferometer. First, EHT data is incredibly sparse, the
# array is formed from only eight geographic locations around the planet. Second, the obseving
# frequency is much higher than traditional VLBI. Lastly, each site in the array is unique.
# They have different dishes, recievers, feeds, and electronics.
# Putting this all together implies that many of the common imaging techniques struggle to
# fit the EHT data and explore the uncertainty in both the image and instrument. One way to
# deal with some of these uncertainties is to not directly fit the data but instead fit
# closure quantities, which are independent of many of the instrumental effects that plague the
# data. The types of closure quantities are briefly described in [Introduction to the VLBI Imaging Problem](@ref).
#
# In this tutorial, we will do closure-only modeling of M87 to produce a posterior of images of M87.
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
ENV["GKSwstype"] = "nul"; #hide
# To get started, we will load Comrade
using Comrade
# Pyehtim loads eht-imaging using PythonCall this is necessary to load uvfits files
# currently.
using Pyehtim
# For reproducibility we use a stable random number genreator
using StableRNGs
rng = StableRNG(123)
# ## Load the Data
# To download the data visit https://doi.org/10.25739/g85n-f134
# To load the eht-imaging obsdata object we do:
obs = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
# Now we do some minor preprocessing:
# - Scan average the data since the data have been preprocessed so that the gain phases
# are coherent.
# - Add 2% systematic noise to deal with calibration issues such as leakage.
obs = scan_average(obs).add_fractional_noise(0.02)
# Now, we extract our closure quantities from the EHT data set. We flag now SNR points since
# the closure likelihood we use is only applicable to high SNR data.
dlcamp, dcphase = extract_table(obs, LogClosureAmplitudes(;snrcut=3), ClosurePhases(;snrcut=3))
# !!! note
# Fitting low SNR closure data is complicated and requires a more sophisticated likelihood.
# If low-SNR data is very important we recommend fitting visibilties with a instrumental model.
# ## Build the Model/Posterior
# For our model, we will be using an image model that consists of a raster of point sources,
# convolved with some pulse or kernel to make a `ContinuousImage`.
# To define this model we define the standard two argument function `sky` that defines the
# sky model we want to fit. The first argument are the model parameters, and are typically
# a NamedTuple. The second argument defines the metadata
# for the model that is typically constant. For our model the constant `metdata` will just
# by the mean or prior image.
function sky(θ, metadata)
(;fg, c, σimg) = θ
(;mimg) = metadata
## Apply the GMRF fluctuations to the image
rast = apply_fluctuations(CenteredLR(), mimg, σimg.*c.params)
m = ContinuousImage(((1-fg)).*rast, BSplinePulse{3}())
## Force the image centroid to be at the origin
x0, y0 = centroid(m)
## Add a large-scale gaussian to deal with the over-resolved mas flux
g = modify(Gaussian(), Stretch(μas2rad(250.0), μas2rad(250.0)), Renormalize(fg))
return shifted(m, -x0, -y0) + g
end
# Now, let's set up our image model. The EHT's nominal resolution is 20-25 μas. Additionally,
# the EHT is not very sensitive to a larger field of views; typically, 60-80 μas is enough to
# describe the compact flux of M87. Given this, we only need to use a small number of pixels
# to describe our image.
npix = 32
fovxy = μas2rad(150.0)
# To define the image model we need to specify both the grid we will be using and the
# FT algorithm we will use, in this case the NFFT which is the most efficient.
grid = imagepixels(fovxy, fovxy, npix, npix)
# Now we need to specify our image prior. For this work we will use a Gaussian Markov
# Random field prior
using VLBIImagePriors, Distributions
# Since we are using a Gaussian Markov random field prior we need to first specify our `mean`
# image. For this work we will use a symmetric Gaussian with a FWHM of 50 μas
fwhmfac = 2*sqrt(2*log(2))
mpr = modify(Gaussian(), Stretch(μas2rad(50.0)./fwhmfac))
imgpr = intensitymap(mpr, grid)
skymeta = (;mimg = imgpr./flux(imgpr));
# Now we can finally form our image prior. For this we use a heirarchical prior where the
# direct log-ratio image prior is a Gaussian Markov Random Field. The correlation length
# of the GMRF is a hyperparameter that is fit during imaging. We pass the data to the prior
# to estimate what the maximumal resolutoin of the array is and prevent the prior from allowing
# correlation lengths that are much small than the telescope beam size. Note that this GMRF prior
# has unit variance. For more information on the GMRF prior see the [`corr_image_prior`](@ref) doc string.
cprior = corr_image_prior(grid, dlcamp)
# Putting everything together the total prior is then our image prior, a prior on the
# standard deviation of the MRF, and a prior on the fractional flux of the Gaussian component.
prior = (c = cprior, σimg = Exponential(0.1), fg=Uniform(0.0, 1.0))
# We can then define our sky model.
skym = SkyModel(sky, prior, grid; metadata=skymeta)
# Since we are fitting closures we do not need to include an instrument model, since
# the closure likelihood is approximately independent of gains in the high SNR limit.
using Enzyme
post = VLBIPosterior(skym, dlcamp, dcphase; admode=set_runtime_activity(Enzyme.Reverse))
# ## Reconstructing the Image
# To reconstruct the image we will first use the MAP estimate. This is approach is basically
# a re-implentation of regularized maximum likelihood (RML) imaging. However, unlike traditional
# RML imaging we also fit the regularizer hyperparameters, thanks to our interpretation of
# as our imaging prior as a hierarchical model.
# To optimize our posterior `Comrade` provides the `comrade_opt` function. To use this
# functionality a user first needs to import `Optimization.jl` and the optimizer of choice.
# In this tutorial we will use Optim.jl's L-BFGS optimizer, which is defined in the sub-package
# OptimizationOptimJL. We also need to import Enzyme to allow for automatic differentiation.
using Optimization
using OptimizationOptimJL
xopt, sol = comrade_opt(post, LBFGS();
maxiters=1000, initial_params=prior_sample(rng, post))
# First we will evaluate our fit by plotting the residuals
using DisplayAs #hide
using Plots
p = residual(post, xopt)
DisplayAs.Text(DisplayAs.PNG(p)) #hide
# Now let's plot the MAP estimate.
import CairoMakie as CM
CM.activate!(type = "png", px_per_unit=1) #hide
g = imagepixels(μas2rad(150.0), μas2rad(150.0), 100, 100)
img = intensitymap(skymodel(post, xopt), g)
fig = imageviz(img, size=(600, 500));
DisplayAs.Text(DisplayAs.PNG(fig)) #hide
# That doesn't look great. This is pretty common for the sparse EHT data. In this case the
# MAP often drastically overfits the data, producing a image filled with artifacts. In addition,
# we note that the MAP itself is not invariant to the model parameterization. Namely, if we
# changed our prior to use a fully centered parameterization we would get a very different image.
# Fortunately, these issues go away when we sample from the posterior, and construct expectations
# of the posterior, like the mean image.
# To sample from the posterior we will use HMC and more specifically the NUTS algorithm. For information about NUTS
# see Michael Betancourt's [notes](https://arxiv.org/abs/1701.02434).
# !!! note
# For our `metric` we use a diagonal matrix due to easier tuning.
#-
using AdvancedHMC
chain = sample(rng, post, NUTS(0.8), 700; n_adapts=500, progress=false, initial_params=xopt);
# !!! warning
# This should be run for longer!
#-
# Now that we have our posterior, we can assess which parts of the image are strongly inferred by the
# data. This is rather unique to `Comrade` where more traditional imaging algorithms like CLEAN and RML are inherently
# unable to assess uncertainty in their reconstructions.
#
# To explore our posterior let's first create images from a bunch of draws from the posterior
msamples = skymodel.(Ref(post), chain[501:2:end]);
# The mean image is then given by
using StatsBase
imgs = intensitymap.(msamples, Ref(g))
mimg = mean(imgs)
simg = std(imgs)
fig = CM.Figure(;resolution=(700, 700));
axs = [CM.Axis(fig[i, j], xreversed=true, aspect=1) for i in 1:2, j in 1:2]
CM.image!(axs[1,1], mimg, colormap=:afmhot); axs[1, 1].title="Mean"
CM.image!(axs[1,2], simg./(max.(mimg, 1e-8)), colorrange=(0.0, 2.0), colormap=:afmhot);axs[1,2].title = "Std"
CM.image!(axs[2,1], imgs[1], colormap=:afmhot);
CM.image!(axs[2,2], imgs[end], colormap=:afmhot);
CM.hidedecorations!.(axs)
fig |> DisplayAs.PNG |> DisplayAs.Text
# Now let's see whether our residuals look better.
p = Plots.plot(layout=(2,1));
for s in sample(chain[501:end], 10)
residual!(post, s)
end
p |> DisplayAs.PNG |> DisplayAs.Text
# And viola, you have a quick and preliminary image of M87 fitting only closure products.
# For a publication-level version we would recommend
# 1. Running the chain longer and multiple times to properly assess things like ESS and R̂ (see [Geometric Modeling of EHT Data](@ref))
# 2. Fitting gains. Typically gain amplitudes are good to 10-20% for the EHT not the infinite uncertainty closures implicitly assume
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 19079 | # # Polarized Image and Instrumental Modeling
# In this tutorial, we will analyze a simulated simple polarized dataset to demonstrate
# Comrade's polarized imaging capabilities.
# ## Introduction to Polarized Imaging
# The EHT is a polarized interferometer. However, like all VLBI interferometers, it does not
# directly measure the Stokes parameters (I, Q, U, V). Instead, it measures components
# related to the electric field at the telescope along two *directions* using feeds.
# There are two types of feeds at telescopes: circular, which measure $R/L$ components of the
# electric field, and linear feeds, which measure $X/Y$ components of the electric field.
# Most sites in the EHT use circular feeds, meaning they measure the right (R) and left
# electric field (L) at each telescope. Although note that ALMA actually uses linear feeds.
# Currently Comrade has the ability to fit natively mixed polarization data however, the
# publically released EHT data has been converted to circular polarization.
# For a VLBI array whose feeds are purely circluar the **coherency matrices** are given by,
#
# ```math
# C_{ij} = \begin{pmatrix}
# RR^* & RL^*\\
# LR^* & LL^*
# \end{pmatrix}.
# ```
#
# These coherency matrices are the fundamental object in interferometry and what
# the telescope observes. For a perfect interferometer, these circular coherency matrices
# are related to the usual Fourier transform of the stokes parameters by
#
# ```math
# \begin{pmatrix}
# \tilde{I}\\ \tilde{Q} \\ \tilde{U} \\ \tilde{V}
# \end{pmatrix}
# =\frac{1}{2}
# \begin{pmatrix}
# RR^* + LL^* \\
# RL^* + LR^* \\
# i(LR^* - RL^*)\\
# RR^* - LL^*
# \end{pmatrix}.
# ```
#-
# !!! note
# In this tutorial, we stick to circular feeds but Comrade has the capabilities
# to model linear (XX,XY, ...) and mixed basis coherencies (e.g., RX, RY, ...).
#-
#
# In reality, the measure coherencies are corrupted by both the atmosphere and the
# telescope itself. In `Comrade` we use the RIME formalism [^1] to represent these corruptions,
# namely our measured coherency matrices $V_{ij}$ are given by
# ```math
# V_{ij} = J_iC_{ij}J_j^\dagger
# ```
# where $J$ is known as a *Jones matrix* and $ij$ denotes the baseline $ij$ with sites $i$ and $j$.
#-
# `Comrade` is highly flexible with how the Jones matrices are formed and provides several
# convenience functions that parameterize standard Jones matrices. These matrices include:
# - [`JonesG`](@ref) which builds the set of complex gain Jones matrices
# ```math
# G = \begin{pmatrix}
# g_a &0\\
# 0 &g_b\\
# \end{pmatrix}
# ```
# - [`JonesD`](@ref) which builds the set of complex d-terms Jones matrices
# ```math
# D = \begin{pmatrix}
# 1 & d_a\\
# d_b &1\\
# \end{pmatrix}
# ```
# - [`JonesR`](@ref) is the basis transform matrix $T$. This transformation is special and
# combines two things using the decomposition $T=FB$. The first, $B$, is the transformation from
# some reference basis to the observed coherency basis (this allows for mixed basis measurements).
# The second is the feed rotation, $F$, that transforms from some reference axis to the axis of the
# telescope as the source moves in the sky. The feed rotation matrix `F` for circular feeds
# in terms of the per station feed rotation angle $\varphi$ is
# ```math
# F = \begin{pmatrix}
# e^{-i\varphi} & 0\\
# 0 & e^{i\varphi}\\
# \end{pmatrix}
# ```
#-
#
# In the rest of the tutorial, we are going to solve for all of these instrument model terms in
# while re-creating the polarized image from the first [`EHT results on M87`](https://iopscience.iop.org/article/10.3847/2041-8213/abe71d).
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
# ## Load the Data
# To get started we will load Comrade
ENV["GKSwstype"] = "nul" #hide
using Comrade
# ## Load the Data
using Pyehtim
# For reproducibility we use a stable random number genreator
using StableRNGs
rng = StableRNG(42)
# Now we will load some synthetic polarized data.
fname = Base.download("https://de.cyverse.org/anon-files/iplant/home/shared/commons_repo/curated/EHTC_M87pol2017_Nov2023/hops_data/April11/SR2_M87_2017_101_lo_hops_ALMArot.uvfits",
joinpath(__DIR, "m87polarized.uvfits")
)
obs = Pyehtim.load_uvfits_and_array(
fname,
joinpath(__DIR, "..", "..", "Data", "array.txt"), polrep="circ")
# Notice that, unlike other non-polarized tutorials, we need to include a second argument.
# This is the **array file** of the observation and is required to determine the feed rotation
# of the array.
# Now we scan average the data since the data to boost the SNR and reduce the total data volume.
obs = scan_average(obs).add_fractional_noise(0.01).flag_uvdist(uv_min=0.1e9)
#-
# Now we extract our observed/corrupted coherency matrices.
dvis = extract_table(obs, Coherencies())
# ##Building the Model/Posterior
# To build the model, we first break it down into two parts:
# 1. **The image or sky model**. In Comrade, all polarized image models are written in terms of the Stokes parameters.
# In this tutorial, we will use a polarized image model based on Pesce (2021)[^2], and
# parameterizes each pixel in terms of the [`Poincare sphere`](https://en.wikipedia.org/wiki/Unpolarized_light#Poincar%C3%A9_sphere).
# This parameterization ensures that we have all the physical properties of stokes parameters.
# Note that we also have a parameterization in terms of hyperbolic trig functions `VLBISkyModels.PolExp2Map`
# 2. **The instrument model**. The instrument model specifies the model that describes the impact of instrumental and atmospheric effects.
# We will be using the $J = GDR$ decomposition we described above. However, to parameterize the
# R/L complex gains, we will be using a gain product and ratio decomposition. The reason for this decomposition
# is that in realistic measurements, the gain ratios and products have different temporal characteristics.
# Namely, many of the EHT observations tend to demonstrate constant R/L gain ratios across an
# nights observations, compared to the gain products, which vary every scan. Additionally,
# the gain ratios tend to be smaller (i.e., closer to unity) than the gain products.
# Using this apriori knowledge, we can build this into our model and reduce
# the total number of parameters we need to model.
# First we specify our sky model. As always `Comrade` requires this to be a two argument
# function where the first argument is typically a NamedTuple of parameters we will fit
# and the second are additional metadata required to build the model.
using StatsFuns: logistic
function sky(θ, metadata)
(;c, σ, p, p0, pσ, angparams) = θ
(;mimg, ftot) = metadata
## Build the stokes I model
rast = apply_fluctuations(CenteredLR(), mimg, σ.*c.params)
brast = baseimage(rast)
brast .= ftot.*brast
## The total polarization fraction is modeled in logit space so we transform it back
pim = logistic.(p0 .+ pσ.*p.params)
## Build our IntensityMap
pmap = PoincareSphere2Map(rast, pim, angparams)
## Construct the actual image model which uses a third order B-spline pulse
m = ContinuousImage(pmap, BSplinePulse{3}())
## Finally find the image centroid and shift it to be at the center
x0, y0 = centroid(pmap)
ms = shifted(m, -x0, -y0)
return ms
end
# Now, we define the model metadata required to build the model.
# We specify our image grid and cache model needed to define the polarimetric
# image model. Our image will be a 10x10 raster with a 60μas FOV.
using Distributions
using VLBIImagePriors
fovx = μas2rad(200.0)
fovy = μas2rad(200.0)
nx = ny = 32
grid = imagepixels(fovx, fovy, nx, ny)
fwhmfac = 2*sqrt(2*log(2))
mpr = modify(Gaussian(), Stretch(μas2rad(50.0)./fwhmfac))
mimg = intensitymap(mpr, grid)
# For the image metadata we specify the grid and the total flux of the image, which is 1.0.
# Note that we specify the total flux out front since it is degenerate with an overall shift
# in the gain amplitudes.
skymeta = (; mimg=mimg./flux(mimg), ftot=0.6)
# We use again use a GMRF prior similar to the [Imaging a Black Hole using only Closure Quantities](@ref) tutorial
# for the log-ratio transformed image. We use the same correlated image prior for the inverse-logit transformed
# total polarization. The mean total polarization fraction `p0` is centered at -2.0 with a standard deviation of 2.0
# which logit transformed puts most of the prior mass < 0.8 fractional polarization. The standard deviation of the
# total polarization fraction `pσ` again uses a Half-normal process. The angular parameters of the polarizaton are
# given by a uniform prior on the sphere.
cprior = corr_image_prior(grid, dvis)
skyprior = (
c = cprior,
σ = Exponential(0.1),
p = cprior,
p0 = Normal(-2.0, 2.0),
pσ = truncated(Normal(0.0, 1.0); lower=0.01),
angparams = ImageSphericalUniform(nx, ny),
)
skym = SkyModel(sky, skyprior, grid; metadata=skymeta)
# Now we build the instrument model. Due to the complexity of VLBI the instrument model is critical
# to the success of imaging and getting reliable results. For this example we will use the standard
# instrument model used in polarized EHT analyses expressed in the RIME formalism. Our Jones
# decomposition will be given by `GDR`, where `G` are the complex gains, `D` are the d-terms, and `R`
# is what we call the *ideal instrument response*, which is how an ideal interferometer using the
# feed basis we observe relative to some reference basis.
#
# Given the possible flexibility in different parameterizations of the individual Jones matrices
# each Jones matrix requires the user to specify a function that converts from parameters
# to specific parameterization f the jones matrices.
# For the complex gain matrix, we used the `JonesG` jones matrix. The first argument is now
# a function that converts from the parameters to the complex gain matrix. In this case, we
# will use a amplitude and phase decomposition of the complex gain matrix. Note that since
# the gain matrix is a diagonal 2x2 matrix the function must return a 2-element tuple.
# The first element of the tuple is the gain for the first polarization feed (R) and the
# second is the gain for the second polarization feed (L).
function fgain(x)
gR = exp(x.lgR + 1im*x.gpR)
gL = gR*exp(x.lgrat + 1im*x.gprat)
return gR, gL
end
G = JonesG(fgain)
# Similarly we provide a `JonesD` function for the leakage terms. Since we assume that we
# are in the small leakage limit, we will use the decomposition
# 1 d1
# d2 1
# Therefore, there are 2 free parameters for the JonesD our parameterization function
# must return a 2-element tuple. For d-terms we will use a re-im parameterization.
function fdterms(x)
dR = complex(x.dRx, x.dRy)
dL = complex(x.dLx, x.dLy)
return dR, dL
end
D = JonesD(fdterms)
# Finally we define our response Jones matrix. This matrix is a basis transform matrix
# plus the feed rotation angle for each station. These are typically set by the telescope
# so there are no free parameters, so no parameterization is necessary.
R = JonesR(;add_fr=true)
# Finally, we build our total Jones matrix by using the `JonesSandwich` function. The
# first argument is a function that specifies how to combine each Jones matrix. In this case
# we will use the standard decomposition J = adjoint(R)*G*D*R, where we need to apply the adjoint
# of the feed rotaion matrix `R` because the data has feed rotation calibration.
js(g,d,r) = adjoint(r)*g*d*r
J = JonesSandwich(js, G, D, R)
# !!! note
# This is a general note that for arrays with non-zero leakage, feed rotation calibration
# does not remove the impact of feed rotations on the instrument model. That is,
# when modeling feed rotation must be taken into account. This is because
# the R and D matrices are not commutative. Therefore, to recover the correct instrumental
# terms we must include the feed rotation calibration in the instrument model. This is not
# ideal when doing polarized modeling, especially for interferometers using a mixture of linear
# and circular feeds. For linear feeds R does not commute with G or D and applying feed rotation
# calibration before solving for gains can mix gains and leakage with feed rotation calibration terms
# breaking many of the typical assumptions about the stabilty of different instrument effects.
# For the instrument prior, we will use a simple IID prior for the complex gains and d-terms.
# The `IIDSitePrior` function specifies that each site has the same prior and each value is independent
# on some time segment. The current time segments are
# - `ScanSeg()` which specifies each scan has an independent value
# - `TrackSeg()` which says that the value is constant over the track.
# - `IntegSeg()` which says that the value changes each integration time
# For the released EHT data, the calibration procedure makes gains stable over each scan
# so we use `ScanSeg` for those quantities. The d-terms are typically stable over the track
# so we use `TrackSeg` for those.
intprior = (
lgR = ArrayPrior(IIDSitePrior(ScanSeg(), Normal(0.0, 0.2))),
lgrat= ArrayPrior(IIDSitePrior(ScanSeg(), Normal(0.0, 0.01))),
gpR = ArrayPrior(IIDSitePrior(ScanSeg(), DiagonalVonMises(0.0, inv(π^2))); refant=SEFDReference(0.0), phase=true),
gprat= ArrayPrior(IIDSitePrior(ScanSeg(), DiagonalVonMises(0.0, inv(0.1^2))); refant = SingleReference(:AA, 0.0), phase=false),
dRx = ArrayPrior(IIDSitePrior(TrackSeg(), Normal(0.0, 0.2))),
dRy = ArrayPrior(IIDSitePrior(TrackSeg(), Normal(0.0, 0.2))),
dLx = ArrayPrior(IIDSitePrior(TrackSeg(), Normal(0.0, 0.2))),
dLy = ArrayPrior(IIDSitePrior(TrackSeg(), Normal(0.0, 0.2))),
)
# Finally, we can build our instrument model which takes a model for the Jones matrix `J`
# and priors for each term in the Jones matrix.
intmodel = InstrumentModel(J, intprior)
# intmodel = InstrumentModel(JonesR(;add_fr=true))
# Putting it all together, we form our likelihood and posterior objects for optimization and
# sampling, and specifying to use Enzyme.Reverse with runtime activity for AD.
using Enzyme
post = VLBIPosterior(skym, intmodel, dvis; admode=set_runtime_activity(Enzyme.Reverse))
# ## Reconstructing the Image and Instrument Effects
# To sample from this posterior, it is convenient to move from our constrained parameter space
# to an unconstrained one (i.e., the support of the transformed posterior is (-∞, ∞)). This transformation is
# done using the `asflat` function.
tpost = asflat(post)
# We can also query the dimension of our posterior or the number of parameters we will sample.
# !!! warning
# This can often be different from what you would expect. This difference is especially true when using
# angular variables, where we often artificially increase the dimension
# of the parameter space to make sampling easier.
#-
# Now we optimize. Unlike other imaging examples, we move straight to gradient optimizers
# due to the higher dimension of the space. In addition the only AD package that can currently
# work with the polarized Comrade posterior is Enzyme.
using Optimization
using OptimizationOptimisers
xopt, sol = comrade_opt(post, Optimisers.Adam();
initial_params=prior_sample(rng, post), maxiters=25_000)
# Now let's evaluate our fits by plotting the residuals
using Plots
residual(post, xopt)
# These look reasonable, although there may be some minor overfitting.
# Let's compare our results to the ground truth values we know in this example.
# First, we will load the polarized truth
imgtrue = load_fits(joinpath(__DIR, "..", "..", "Data", "polarized_gaussian.fits"), IntensityMap{StokesParams})
# Select a reasonable zoom in of the image.
imgtruesub = regrid(imgtrue, imagepixels(fovx, fovy, nx*4, ny*4))
img = intensitymap(Comrade.skymodel(post, xopt), axisdims(imgtruesub))
#Plotting the results gives
import CairoMakie as CM
using DisplayAs #hide
fig = imageviz(img, adjust_length=true, colormap=:bone, pcolormap=:RdBu)
fig |> DisplayAs.PNG |> DisplayAs.Text
#-
# !!! note
# The image looks a little noisy. This is an artifact of the MAP image. To get a publication quality image
# we recommend sampling from the posterior and averaging the samples. The results will be essentially
# identical to the results from [EHTC VII](https://iopscience.iop.org/article/10.3847/2041-8213/abe71d).
# We can also analyze the instrument model. For example, we can look at the gain ratios and products.
# To grab the ratios and products we can use the `caltable` function which will return analyze the gprat array
# and convert it to a uniform table. We can then plot the gain phases and amplitudes.
gphase_ratio = caltable(xopt.instrument.gprat)
gamp_ratio = caltable(exp.(xopt.instrument.lgrat))
#-
# Plotting the phases first, we see large trends in the righ circular polarization phase. This is expected
# due to a lack of image centroid and the absense of absolute phase information in VLBI. However, the gain
# phase difference between the left and right circular polarization is stable and close to zero. This is
# expected since gain ratios are typically stable over the course of an observation and the constant
# offset was removed in the EHT calibration process.
gphaseR = caltable(xopt.instrument.gpR)
p = Plots.plot(gphaseR, layout=(3,3), size=(650,500));
Plots.plot!(p, gphase_ratio, layout=(3,3), size=(650,500));
p |> DisplayAs.PNG |> DisplayAs.Text
#-
# Moving to the amplitudes we see largely stable gain amplitudes on the right circular polarization except for LMT which is
# known and due to pointing issues during the 2017 observation. Again the gain ratios are stable and close to unity. Typically
# we expect that apriori calibration should make the gain ratios close to unity.
gampr = caltable(exp.(xopt.instrument.lgR))
p = Plots.plot(gampr, layout=(3,3), size=(650,500))
Plots.plot!(p, gamp_ratio, layout=(3,3), size=(650,500))
p |> DisplayAs.PNG |> DisplayAs.Text
#-
# To sample from the posterior, you can then just use the `sample` function from AdvancedHMC like in the
# other imaging examples. For example
# ```julia
# using AdvancedHMC
# chain = sample(rng, post, NUTS(0.8), 10_000, n_adapts=5000, progress=true, initial_params=xopt)
# ```
# [^1]: Hamaker J.P, Bregman J.D., Sault R.J. (1996) [https://articles.adsabs.harvard.edu/pdf/1996A%26AS..117..137H]
# [^2]: Pesce D. (2021) [https://ui.adsabs.harvard.edu/abs/2021AJ....161..178P/abstract]
#-
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 11877 | # # Stokes I Simultaneous Image and Instrument Modeling
# In this tutorial, we will create a preliminary reconstruction of the 2017 M87 data on April 6
# by simultaneously creating an image and model for the instrument. By instrument model, we
# mean something akin to self-calibration in traditional VLBI imaging terminology. However,
# unlike traditional self-cal, we will solve for the gains each time we update the image
# self-consistently. This allows us to model the correlations between gains and the image.
# To get started we load Comrade.
import Pkg #hide
__DIR = @__DIR__ #hide
pkg_io = open(joinpath(__DIR, "pkg.log"), "w") #hide
Pkg.activate(__DIR; io=pkg_io) #hide
Pkg.develop(; path=joinpath(__DIR, "..", "..", ".."), io=pkg_io) #hide
Pkg.instantiate(; io=pkg_io) #hide
Pkg.precompile(; io=pkg_io) #hide
close(pkg_io) #hide
using Comrade
using Pyehtim
using LinearAlgebra
# For reproducibility we use a stable random number genreator
using StableRNGs
rng = StableRNG(12)
# ## Load the Data
# To download the data visit https://doi.org/10.25739/g85n-f134
# First we will load our data:
obs = ehtim.obsdata.load_uvfits(joinpath(__DIR, "..", "..", "Data", "SR1_M87_2017_096_lo_hops_netcal_StokesI.uvfits"))
# obs = ehtim.obsdata.load_uvfits("~/Dropbox (Smithsonian External)/M872021Project/Data/2021/CASA/e21e18/V4/M87_calibrated_b3.uvf+EVPA_rotation+netcal_10savg+flag.uvfits")
# Now we do some minor preprocessing:
# - Scan average the data since the data have been preprocessed so that the gain phases
# coherent.
# - Add 1% systematic noise to deal with calibration issues that cause 1% non-closing errors.
obs = scan_average(obs).add_fractional_noise(0.02)
# Now we extract our complex visibilities.
dvis = extract_table(obs, Visibilities())
# ##Building the Model/Posterior
# Now, we must build our intensity/visibility model. That is, the model that takes in a
# named tuple of parameters and perhaps some metadata required to construct the model.
# For our model, we will use a raster or `ContinuousImage` for our image model.
# The model is given below:
# The model construction is very similar to [Imaging a Black Hole using only Closure Quantities](@ref),
# except we include a large scale gaussian since we want to model the zero baselines.
# For more information about the image model please read the closure-only example.
function sky(θ, metadata)
(;fg, c, σimg) = θ
(;ftot, mimg) = metadata
## Apply the GMRF fluctuations to the image
rast = apply_fluctuations(CenteredLR(), mimg, σimg.*c.params)
pimg = parent(rast)
@. pimg = (ftot*(1-fg))*pimg
m = ContinuousImage(rast, BSplinePulse{3}())
x0, y0 = centroid(m)
## Add a large-scale gaussian to deal with the over-resolved mas flux
g = modify(Gaussian(), Stretch(μas2rad(500.0), μas2rad(500.0)), Renormalize(ftot*fg))
return shifted(m, -x0, -y0) + g
end
# Now, let's set up our image model. The EHT's nominal resolution is 20-25 μas. Additionally,
# the EHT is not very sensitive to a larger field of view. Typically 60-80 μas is enough to
# describe the compact flux of M87. Given this, we only need to use a small number of pixels
# to describe our image.
npix = 32
fovx = μas2rad(200.0)
fovy = μas2rad(200.0)
# Now let's form our cache's. First, we have our usual image cache which is needed to numerically
# compute the visibilities.
grid = imagepixels(fovx, fovy, npix, npix)
# Now we need to specify our image prior. For this work we will use a Gaussian Markov
# Random field prior
# Since we are using a Gaussian Markov random field prior we need to first specify our `mean`
# image. This behaves somewhat similary to a entropy regularizer in that it will
# start with an initial guess for the image structure. For this tutorial we will use a
# a symmetric Gaussian with a FWHM of 50 μas
using VLBIImagePriors
using Distributions
fwhmfac = 2*sqrt(2*log(2))
mpr = modify(Gaussian(), Stretch(μas2rad(50.0)./fwhmfac))
mimg = intensitymap(mpr, grid)
# Now we can form our metadata we need to fully define our model.
# We will also fix the total flux to be the observed value 1.1. This is because
# total flux is degenerate with a global shift in the gain amplitudes making the problem
# degenerate. To fix this we use the observed total flux as our value.
skymeta = (;ftot = 1.1, mimg = mimg./flux(mimg))
# To make the Gaussian Markov random field efficient we first precompute a bunch of quantities
# that allow us to scale things linearly with the number of image pixels. The returns a
# functional that accepts a single argument related to the correlation length of the field.
# The second argument defines the underlying random field of the Markov process. Here
# we are using a zero mean and unit variance Gaussian Markov random field.
# For this tutorial we will use the first order random field
cprior = corr_image_prior(grid, dvis)
# Putting everything together the total prior is then our image prior, a prior on the
# standard deviation of the MRF, and a prior on the fractional flux of the Gaussian component.
prior = (
c = cprior,
σimg = truncated(Normal(0.0, 0.5); lower=0.0),
fg = Uniform(0.0, 1.0),
)
# Now we can construct our sky model.
skym = SkyModel(sky, prior, grid; metadata=skymeta)
# Unlike other imaging examples
# (e.g., [Imaging a Black Hole using only Closure Quantities](@ref)) we also need to include
# a model for the instrument, i.e., gains. The gains will be broken into two components
# - Gain amplitudes which are typically known to 10-20%, except for LMT, which has amplitudes closer to 50-100%.
# - Gain phases which are more difficult to constrain and can shift rapidly.
G = SingleStokesGain() do x
lg = x.lgμ + x.lgσ*x.lgz
gp = x.gp
return exp(lg + 1im*gp)
end
intpr = (
lgμ = ArrayPrior(IIDSitePrior(TrackSeg(), Normal(0.0, 0.2)); LM = IIDSitePrior(TrackSeg(), Normal(0.0, 1.0))),
lgσ = ArrayPrior(IIDSitePrior(TrackSeg(), Exponential(0.1))),
lgz = ArrayPrior(IIDSitePrior(ScanSeg(), Normal(0.0, 1.0))),
gp= ArrayPrior(IIDSitePrior(ScanSeg(), DiagonalVonMises(0.0, inv(π^2))); refant=SEFDReference(0.0), phase=true)
)
intmodel = InstrumentModel(G, intpr)
# To form the posterior we just combine the skymodel, instrument model and the data. Additionally,
# since we want to use gradients we need to specify the AD mode. Essentially for all modes we recommend
# using `Enzyme.set_runtime_activity(Enzyme.Reverse)`. Eventually as Comrade and Enzyme matures we will
# no need `set_runtime_activity`.
using Enzyme
post = VLBIPosterior(skym, intmodel, dvis; admode=set_runtime_activity(Enzyme.Reverse))
# done using the `asflat` function.
tpost = asflat(post)
ndim = dimension(tpost)
# We can now also find the dimension of our posterior or the number of parameters we are going to sample.
# !!! warning
# This can often be different from what you would expect. This is especially true when using
# angular variables where we often artificially increase the dimension
# of the parameter space to make sampling easier.
#-
# To initialize our sampler we will use optimize using Adam
using Optimization
using OptimizationOptimisers
xopt, sol = comrade_opt(post, Optimisers.Adam(); initial_params=prior_sample(rng, post), maxiters=20_000, g_tol=1e-1)
# !!! warning
# Fitting gains tends to be very difficult, meaning that optimization can take a lot longer.
# The upside is that we usually get nicer images.
#-
# First we will evaluate our fit by plotting the residuals
using Plots
using DisplayAs
residual(post, xopt) |> DisplayAs.PNG |> DisplayAs.Text
# These look reasonable, although there may be some minor overfitting. This could be
# improved in a few ways, but that is beyond the goal of this quick tutorial.
# Plotting the image, we see that we have a much cleaner version of the closure-only image from
# [Imaging a Black Hole using only Closure Quantities](@ref).
import CairoMakie as CM
CM.activate!(type = "png", px_per_unit=3) #hide
g = imagepixels(fovx, fovy, 128, 128)
img = intensitymap(skymodel(post, xopt), g)
imageviz(img, size=(500, 400))|> DisplayAs.PNG |> DisplayAs.Text
# Because we also fit the instrument model, we can inspect their parameters.
# To do this, `Comrade` provides a `caltable` function that converts the flattened gain parameters
# to a tabular format based on the time and its segmentation.
intopt = instrumentmodel(post, xopt)
gt = Comrade.caltable(angle.(intopt))
plot(gt, layout=(3,3), size=(600,500)) |> DisplayAs.PNG |> DisplayAs.Text
# The gain phases are pretty random, although much of this is due to us picking a random
# reference sites for each scan.
# Moving onto the gain amplitudes, we see that most of the gain variation is within 10% as expected
# except LMT, which has massive variations.
gt = Comrade.caltable(abs.(intopt))
plot(gt, layout=(3,3), size=(600,500)) |> DisplayAs.PNG |> DisplayAs.Text
# To sample from the posterior, we will use HMC, specifically the NUTS algorithm. For
# information about NUTS,
# see Michael Betancourt's [notes](https://arxiv.org/abs/1701.02434).
# However, due to the need to sample a large number of gain parameters, constructing the posterior
# is rather time-consuming. Therefore, for this tutorial, we will only do a quick preliminary
# run
#-
using AdvancedHMC
chain = sample(rng, post, NUTS(0.8), 1_000; n_adapts=500, progress=false, initial_params=xopt)
#-
# !!! note
# The above sampler will store the samples in memory, i.e. RAM. For large models this
# can lead to out-of-memory issues. To fix that you can include the keyword argument
# `saveto = DiskStore()` which periodically saves the samples to disk limiting memory
# useage. You can load the chain using `load_samples(diskout)` where `diskout` is
# the object returned from sample.
#-
# Now we prune the adaptation phase
chain = chain[501:end]
#-
# !!! warning
# This should be run for likely an order of magnitude more steps to properly estimate expectations of the posterior
#-
# Now that we have our posterior, we can put error bars on all of our plots above.
# Let's start by finding the mean and standard deviation of the gain phases
mchain = Comrade.rmap(mean, chain)
schain = Comrade.rmap(std, chain)
# Now we can use the measurements package to automatically plot everything with error bars.
# First we create a `caltable` the same way but making sure all of our variables have errors
# attached to them.
using Measurements
gmeas = instrumentmodel(post, (;instrument= map((x,y)->Measurements.measurement.(x,y), mchain.instrument, schain.instrument)))
ctable_am = caltable(abs.(gmeas))
ctable_ph = caltable(angle.(gmeas))
# Now let's plot the phase curves
plot(ctable_ph, layout=(4,3), size=(600,500)) |> DisplayAs.PNG |> DisplayAs.Text
#-
# and now the amplitude curves
plot(ctable_am, layout=(4,3), size=(600,500)) |> DisplayAs.PNG |> DisplayAs.Text
# Finally let's construct some representative image reconstructions.
samples = skymodel.(Ref(post), chain[begin:5:end])
imgs = intensitymap.(samples, Ref(g))
mimg = mean(imgs)
simg = std(imgs)
fig = CM.Figure(;resolution=(700, 700));
axs = [CM.Axis(fig[i, j], xreversed=true, aspect=1) for i in 1:2, j in 1:2]
CM.image!(axs[1,1], mimg, colormap=:afmhot); axs[1, 1].title="Mean"
CM.image!(axs[1,2], simg./(max.(mimg, 1e-8)), colorrange=(0.0, 2.0), colormap=:afmhot);axs[1,2].title = "Std"
CM.image!(axs[2,1], imgs[1], colormap=:afmhot);
CM.image!(axs[2,2], imgs[end], colormap=:afmhot);
CM.hidedecorations!.(axs)
fig |> DisplayAs.PNG |> DisplayAs.Text
# And viola, you have just finished making a preliminary image and instrument model reconstruction.
# In reality, you should run the `sample` step for many more MCMC steps to get a reliable estimate
# for the reconstructed image and instrument model parameters.
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 7725 | module ComradeAdvancedHMCExt
using Comrade
using AdvancedHMC
using AdvancedHMC: AbstractHMCSampler
using AbstractMCMC
using AbstractMCMC: Sample
using Accessors
using ArgCheck
using DocStringExtensions
using HypercubeTransform
using LogDensityProblems
using Printf
using Random
using StatsBase
using Serialization
function initialize_params(tpost, initial_params)
isnothing(initial_params) && return prior_sample(tpost)
return HypercubeTransform.inverse(tpost, initial_params)
end
# internal method that makes the HMCSampler
function make_sampler(rng, ∇ℓ, sampler::AdvancedHMC.AbstractHMCSampler, θ0)
metric = AdvancedHMC.make_metric(sampler, ∇ℓ)
hamil = AdvancedHMC.Hamiltonian(metric, ∇ℓ)
ϵ = AdvancedHMC.make_step_size(rng, sampler, hamil, θ0)
integr = AdvancedHMC.make_integrator(sampler, ϵ)
κ = AdvancedHMC.make_kernel(sampler, integr)
adaptor= AdvancedHMC.make_adaptor(sampler, metric, integr)
return AdvancedHMC.LogDensityModel(∇ℓ), HMCSampler(κ, metric, adaptor)
end
function AbstractMCMC.Sample(
rng::Random.AbstractRNG, tpost::Comrade.TransformedVLBIPosterior,
sampler::AbstractHMCSampler; initial_params=nothiing, kwargs...)
θ0 = initialize_params(tpost, initial_params)
model, smplr = make_sampler(rng, tpost, sampler, θ0)
return AbstractMCMC.Sample(rng, model, smplr; initial_params=θ0, kwargs...)
end
"""
sample(rng, post::VLBIPosterior, sampler::AbstractHMCSampler, nsamples, args...;saveto=MemoryStore(), initial_params=nothing, kwargs...)
Sample from the posterior `post` using the sampler `sampler` for `nsamples` samples. Additional
arguments are forwarded to AbstractMCMC.sample. If `saveto` is a DiskStore, the samples will be
saved to disk. If `initial_params` is not `nothing` then the sampler will start from that point.
## Arguments
- rng: The random number generator to use
- post: The posterior to sample from
- nsamples: The total number of samples
## Keyword Arguments
- `saveto`: If a DiskStore, the samples will be saved to disk, if [`MemoryStore`](@ref) the samples will be stored in memory/ram.
- `initial_params`: The initial parameters to start the sampler from. If `nothing` then the sampler will start from a random point in the prior.
- `kwargs`: Additional keyword arguments to pass to the sampler. Examples include `n_adapts` which is the total number of samples to use for adaptation.
To see the others see the AdvancedHMC documentation.
"""
function AbstractMCMC.sample(
rng::Random.AbstractRNG, post::Comrade.VLBIPosterior,
sampler::AbstractHMCSampler, nsamples, args...;
saveto=MemoryStore(), initial_params=nothing, kwargs...)
saveto isa DiskStore && return sample_to_disk(rng, post, sampler, nsamples, args...; outdir=saveto.name, output_stride=min(saveto.stride, nsamples), initial_params, kwargs...)
if isnothing(Comrade.admode(post))
throw(ArgumentError("You must specify an automatic differentiation type in VLBIPosterior with admode kwarg"))
else
tpost = asflat(post)
end
tpost = asflat(post)
θ0 = initialize_params(tpost, initial_params)
model, smplr = make_sampler(rng, tpost, sampler, θ0)
res = sample(rng, model, smplr, nsamples, args...;
initial_params=θ0, saveto=saveto, chain_type=Array, kwargs...)
stats = getproperty.(res, :stat)
samples = getproperty.(getproperty.(res, :z), :θ)
chain = transform.(Ref(tpost), samples)
return PosteriorSamples(chain, stats; metadata=Dict(:sampler=>:AHMC, :sampler_kwargs=>kwargs, :post=>tpost))
end
# Disk sampling stuff goes here
function initialize(rng::Random.AbstractRNG, tpost::Comrade.TransformedVLBIPosterior,
sampler::AbstractHMCSampler, nsamples, outbase, args...;
n_adapts = min(nsamples÷2, 1000),
initial_params=nothing, outdir = "Results",
output_stride=min(100, nsamples),
restart = false,
kwargs...)
if restart
@assert isfile(joinpath(outdir, "checkpoint.jls")) "Checkpoint file does not exist in $(outdir)"
tmp = deserialize(joinpath(outdir, "checkpoint.jls"))
(;pt, state, out, iter) = tmp
if iter*output_stride >= nsamples
@warn("Not sampling because the current number of samples is greater than the number you requested")
return pt, state, out, iter
end
if pt.c.coll.stop != nsamples
@warn("The number of samples wanted in the stored checkpoint does not match the number of samples requested."*
"Changing to the number you requested")
pt = @set pt.c.coll.stop = nsamples
end
@info "Resuming from checkpoint on iteration $iter"
return pt, state, out, iter
end
mkpath(joinpath(outdir, "samples"))
θ0 = initial_params
if isnothing(initial_params)
@warn "No starting location chosen, picking start from prior"
θ0 = prior_sample(rng, tpost)
end
t = Sample(rng, tpost, sampler; initial_params=θ0, n_adapts, kwargs...)(1:nsamples)
pt = Iterators.partition(t, output_stride)
nscans = nsamples÷output_stride + (nsamples%output_stride!=0 ? 1 : 0)
# Now save the output
out = Comrade.DiskOutput(abspath(outdir), nscans, output_stride, nsamples)
serialize(joinpath(outdir, "parameters.jls"), (;params=out))
tmp = @timed iterate(pt)
state, iter = _process_samples(pt, tpost, tmp.value, tmp.time, nscans, out, outbase, outdir, 1)
return pt, state, out, iter
end
function _process_samples(pt, tpost, next, time, nscans, out, outbase, outdir, iter)
(chain, state) = next
stats = getproperty.(chain, :stat)
samples = transform.(Ref(tpost), getproperty.(getproperty.(chain, :z), :θ))
s = PosteriorSamples(samples, stats; metadata=Dict(:sampler=>:AHMC))
@info("Scan $(iter)/$nscans statistics:\n"*
" Total time: $(time) seconds\n"*
" Mean tree depth: $(round(mean(samplerstats(s).tree_depth); digits=1))\n"*
" Mode tree depth: $(round(StatsBase.mode(samplerstats(s).tree_depth); digits=1))\n"*
" n-divergences: $(sum(samplerstats(s).numerical_error))/$(length(stats))\n"*
" Avg log-post: $(mean(samplerstats(s).log_density))\n")
serialize(outbase*(@sprintf "%05d.jls" iter), (samples=Comrade.postsamples(s), stats=Comrade.samplerstats(s)))
chain = nothing
samples = nothing
stats = nothing
GC.gc(true)
iter += 1
serialize(joinpath(outdir, "checkpoint.jls"), (;pt, state, out, iter))
return state, iter
end
function sample_to_disk(rng::Random.AbstractRNG, post::Comrade.VLBIPosterior,
sampler::AbstractHMCSampler, nsamples, args...;
n_adapts = min(nsamples÷2, 1000),
initial_params=nothing, outdir = "Results",
restart=false,
output_stride=min(100, nsamples),
kwargs...)
tpost = asflat(post)
nscans = nsamples÷output_stride + (nsamples%output_stride!=0 ? 1 : 0)
outbase = joinpath(outdir, "samples", "output_scan_")
pt, state, out, i = initialize(
rng, tpost, sampler, nsamples, outbase, args...;
n_adapts,
initial_params, restart, outdir, output_stride, kwargs...
)
tmp = @timed iterate(pt, state)
t = tmp.time
next = tmp.value
while !isnothing(next)
t = @elapsed begin
state, i = _process_samples(pt, tpost, next, t, nscans, out, outbase, outdir, i)
next = iterate(pt, state)
end
end
return out
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1983 | module ComradeDynestyExt
using AbstractMCMC
using Comrade
using Dynesty
using Random
"""
dysample(post::Comrade.VLBIPosterior, smplr::Dynesty.NestedSampler, args...; kwargs...)
dysample(post::Comrade.VLBIPosterior, smplr::Dynesty.DynamicNestedSampler, args...; kwargs...)
Sample the posterior `post` using `Dynesty.jl` `NestedSampler/DynamicNestedSampler` sampler.
The `args/kwargs`
are forwarded to `Dynesty` for more information see its [docs](https://github.com/ptiede/Dynesty.jl)
This returns a PosteriorSamples object.
The `samplerstats` includes additional information about the samples, like the log-likelihood,
evidence, evidence error, and the sample weights. The final element of the tuple is the original
dynesty output file.
To create equally weighted samples the user can use
```julia
using StatsBase
chain = sample(post, NestedSampler(dimension(post), 1000))
equal_weighted_chain = sample(chain, Weights(stats.weights), 10_000)
```
"""
function Dynesty.dysample(post::Comrade.VLBIPosterior,
sampler::Union{Dynesty.NestedSampler, DynamicNestedSampler};
kwargs...)
tpost = ascube(post)
ℓ = logdensityof(tpost)
res = dysample(ℓ, identity, Comrade.dimension(tpost), sampler; kwargs...)
# Make sure that res["sample"] is an array and use transpose
samples, weights = transpose(Dynesty.PythonCall.pyconvert(Array, res["samples"])),
exp.(Dynesty.PythonCall.pyconvert(Vector, res["logwt"] - res["logz"][-1]))
chain = transform.(Ref(tpost), eachcol(samples))
stats = (logl = Dynesty.PythonCall.pyconvert(Vector, res["logl"]),
weights = weights,
)
logz = Dynesty.PythonCall.pyconvert(Float64, res["logz"][-1])
logzerr = Dynesty.PythonCall.pyconvert(Float64, res["logzerr"][-1])
return PosteriorSamples(chain, stats; metadata=Dict(:sampler => :dynesty, :dynesty_output => res, :logz => logz, :logzerr => logzerr))
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 576 | module ComradeEnzymeExt
using Enzyme
using Comrade
using LogDensityProblems
LogDensityProblems.dimension(d::Comrade.TransformedVLBIPosterior) = dimension(d)
LogDensityProblems.capabilities(::Type{<:Comrade.TransformedVLBIPosterior}) = LogDensityProblems.LogDensityOrder{1}()
function LogDensityProblems.logdensity_and_gradient(d::Comrade.TransformedVLBIPosterior, x::AbstractArray)
mode = Enzyme.EnzymeCore.WithPrimal(Comrade.admode(d))
dx = zero(x)
(_, y) = autodiff(mode, Comrade.logdensityof, Active, Const(d), Duplicated(x, dx))
return y, dx
end
end | Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 3317 | module ComradeOptimizationExt
using Comrade
using Optimization
using Distributions
using LinearAlgebra
using HypercubeTransform
using LogDensityProblems
function Optimization.OptimizationFunction(post::Comrade.TransformedVLBIPosterior, args...; kwargs...)
ℓ(x,p=post) = -logdensityof(p, x)
if isnothing(Comrade.admode(post))
return SciMLBase.OptimizationFunction(ℓ, args...; kwargs...)
else
function grad(G, x, p)
(_, dx) = LogDensityProblems.logdensity_and_gradient(post, x)
dx .*= -1
G .= dx
return G
end
return SciMLBase.OptimizationFunction(ℓ, args...; grad=grad, kwargs...)
end
end
# """
# comrade_laplace(prob, opt, args...; kwargs...)
# Compute the Laplace or Quadratic approximation to the prob or posterior.
# The `args` and `kwargs` are passed the the SciMLBase.solve function.
# This will return a `Distributions.MvNormal` object that approximates
# the posterior in the transformed space.
# Note the quadratic approximation is in the space of the transformed posterior
# not the usual parameter space. This is better for constrained problems where
# we may run up against a boundary.
# """
# function Comrade.comrade_laplace(post::VLBIPosterior, opt, adtype=Val(:ForwardDiff))
# sol = solve(prob, opt, args...; kwargs...)
# f = Base.Fix2(prob.f, nothing)
# J = ForwardDiff.hessian(f, sol)
# @. J += 1e-5 # add offset to help with positive definitness
# h = J*sol
# return MvNormalCanon(h, Symmetric(J))
# end
"""
comrade_opt(post::VLBIPosterior, opt, args...; initial_params=nothing, kwargs...)
Optimize the posterior `post` using the `opt` optimizer.
!!! warning
To use use a gradient optimizer with AD, `VLBIPosterior` must be created with a specific `admode` specified.
The `admode` can be a union of `Nothing` and `<:EnzymeCore.Mode` types. We recommend
using `Enzyme.set_runtime_activity(Enzyme.Reverse)`.
## Arguments
- `post` : The posterior to optimize.
- `opt` : The optimizer to use. This can be any optimizer from `Optimization.jl`.
- `args` : Additional arguments passed to the `Optimization`, `solve` method
## Keyword Arguments
- `initial_params` : The initial parameters to start the optimization. If `nothing` then
the initial parameters are sampled from the prior. If not `nothing` then the initial
parameters are transformed to the transformed space.
- `kwargs` : Additional keyword arguments passed `Optimization.jl` `solve` method.
"""
function Comrade.comrade_opt(post::VLBIPosterior, opt, args...; initial_params=nothing, lb=nothing, ub=nothing, cube=false, kwargs...)
if isnothing(Comrade.admode(post)) || cube
tpost = ascube(post)
else
tpost = asflat(post)
end
f = OptimizationFunction(tpost)
if isnothing(initial_params)
initial_params = prior_sample(tpost)
else
initial_params = Comrade.inverse(tpost, initial_params)
end
if tpost.transform isa HypercubeTransform.AbstractHypercubeTransform
lb=fill(0.0001, dimension(tpost))
ub=fill(0.9999, dimension(tpost))
end
prob = OptimizationProblem(f, initial_params, tpost; lb, ub)
sol = solve(prob, opt, args...; kwargs...)
return transform(tpost, sol), sol
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 2444 | module ComradePigeonsExt
using Comrade
using Pigeons
using AbstractMCMC
using LogDensityProblems
using HypercubeTransform
using TransformVariables
using Random
Pigeons.initialization(tpost::Comrade.TransformedVLBIPosterior, rng::Random.AbstractRNG, ::Int) = prior_sample(rng, tpost)
struct PriorRef{P,T}
model::P
transform::T
end
function (p::PriorRef{P,<:TransformVariables.AbstractTransform})(x) where {P}
y, lj = TransformVariables.transform_and_logjac(p.transform, x)
logdensityof(p.model, y) + lj
end
function (p::PriorRef{P,<:HypercubeTransform.AbstractHypercubeTransform})(x) where {P}
for xx in x
(xx > 1 || xx < 0) && return convert(eltype(x), -Inf)
end
return zero(eltype(x))
end
Pigeons.default_explorer(::Comrade.TransformedVLBIPosterior{P,<:HypercubeTransform.AbstractHypercubeTransform}) where {P} =
SliceSampler()
Pigeons.default_explorer(::Comrade.TransformedVLBIPosterior{P,<:TransformVariables.AbstractTransform}) where {P} =
Pigeons.AutoMALA(;default_autodiff_backend = :Enzyme)
function Pigeons.default_reference(tpost::Comrade.TransformedVLBIPosterior)
t = tpost.transform
p = tpost.lpost.prior
return PriorRef(p, t)
end
function Pigeons.sample_iid!(target::Comrade.TransformedVLBIPosterior, replica, shared)
replica.state = Pigeons.initialization(target, replica.rng, replica.replica_index)
end
function Pigeons.sample_iid!(target::PriorRef{P, <:TransformVariables.AbstractTransform}, replica, shared) where {P}
replica.state .= Comrade.inverse(target.transform, rand(replica.rng, target.model))
end
function Pigeons.sample_iid!(::PriorRef{P,<:HypercubeTransform.AbstractHypercubeTransform}, replica, shared) where {P}
rand!(replica.rng, replica.state)
end
function Pigeons.sample_array(tpost::Comrade.TransformedVLBIPosterior, pt::Pigeons.PT)
samples = sample_array(pt)
tbl = mapreduce(hcat, eachslice(samples, dims=(3,), drop=true)) do arr
s = map(x->Comrade.transform(tpost, @view(x[begin:end-1])), eachrow(arr))
return s
end
sts = (logdensity= samples[:, end, :] |> vec,)
return Comrade.PosteriorSamples(tbl, sts; metadata=Dict(:sampler=>:Pigeons, :post=>tpost))
end
LogDensityProblems.dimension(t::PriorRef) = Comrade.dimension(t.transform)
LogDensityProblems.logdensity(t::PriorRef, x) = t(x)
LogDensityProblems.capabilities(::Type{<:PriorRef}) = LogDensityProblems.LogDensityOrder{0}()
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 18462 | module ComradePyehtimExt
using Comrade
using Pyehtim
using StructArrays: StructVector, StructArray, append!!
using LinearAlgebra
using StaticArraysCore
function build_arrayconfig(obs)
obsd = obs.data
obsc = obs.copy()
ra, dec = get_radec(obsc)
mjd = get_mjd(obsc)
source = get_source(obsc)
bw = get_bw(obsc)
angles = get_fr_angles(obsc)
tarr = Pyehtim.get_arraytable(obsc)
scans = get_scantable(obsc)
bw = get_bw(obsc)
elevation = StructArray(angles[1])
parallactic = StructArray(angles[2])
U = pyconvert(Vector, obsd["u"])
V = pyconvert(Vector, obsd["v"])
t1 = pyconvert(Vector{Symbol}, obsd["t1"])
t2 = pyconvert(Vector{Symbol}, obsd["t2"])
Ti= pyconvert(Vector, obsd["time"])
Fr= fill(pyconvert(eltype(U), obsc.rf), length(U))
sites = tuple.(t1, t2)
single_polbasis = (CirBasis(), CirBasis())
polbasis = fill(single_polbasis,length(U))
data = StructArray{Comrade.EHTArrayBaselineDatum{eltype(U), eltype(polbasis), eltype(elevation[1][1])}}(
(;U, V, Ti, Fr, sites, polbasis, elevation, parallactic)
)
return Comrade.EHTArrayConfiguration(bw, tarr, scans, mjd, ra, dec, source, :UTC, data)
end
function getvisfield(obs)
obsd = obs.data
vis = pyconvert(Vector{ComplexF64}, obsd["vis"])
err = pyconvert(Vector{Float64}, obsd["sigma"])
return vis, err
end
function getampfield(obs)
obsamps = obs.amp
erramp = pyconvert(Vector, obsamps["sigma"])
amps = pyconvert(Vector, obsamps["amp"])
return amps, erramp
end
function getcoherency(obs)
# check if the obs is in circular basis otherwise noise out
@assert((pyconvert(String, obs.polrep) == "circ"),
"obs is not in circular polarization.\n"*
"To fix read in the data using\n"*
" Pyehtim.load_uvfits_and_array(obsname, arrayname, polrep=\"circ\")\n"*
"Do not use\n obs.switch_polrep(\"circ\")\nsince missing hands will not be handled correctly."
)
c11 = pyconvert(Vector, obs.data["rrvis"])
c12 = pyconvert(Vector, obs.data["rlvis"])
c21 = pyconvert(Vector, obs.data["lrvis"])
c22 = pyconvert(Vector, obs.data["llvis"])
cohmat = StructArray{SMatrix{2,2,eltype(c11), 4}}((c11, c21, c12, c22))
# get uncertainties
e11 = copy(pyconvert(Vector, obs.data["rrsigma"]))
e12 = copy(pyconvert(Vector, obs.data["rlsigma"]))
e21 = copy(pyconvert(Vector, obs.data["lrsigma"]))
e22 = copy(pyconvert(Vector, obs.data["llsigma"]))
errmat = StructArray{SMatrix{2,2,eltype(e11), 4}}((e11, e21, e12, e22))
return cohmat, errmat
end
function getcpfield(obs)
# Here we just return the information needed to form
# the closure configuration
obscp = obs.cphase
time = pyconvert(Vector, obscp["time"])
freq = fill(get_rf(obs), length(time))
t1 = pyconvert(Vector{Symbol}, obscp["t1"])
t2 = pyconvert(Vector{Symbol}, obscp["t2"])
t3 = pyconvert(Vector{Symbol}, obscp["t3"])
noise = pyconvert(Vector, obscp["sigmacp"])
baseline = tuple.(t1, t2, t3)
return StructArray((;T=time, F=freq, noise, baseline))
end
function getlcampfield(obs)
# Here we just return the information needed to form
# the closure configuration
obslcamp = obs.logcamp
t1 = pyconvert(Vector{Symbol}, obslcamp["t1"])
t2 = pyconvert(Vector{Symbol}, obslcamp["t2"])
t3 = pyconvert(Vector{Symbol}, obslcamp["t3"])
time = pyconvert(Vector, obslcamp["time"])
t4 = pyconvert(Vector{Symbol}, obslcamp["t4"])
baseline = tuple.(t1, t2, t3, t4)
noise = pyconvert(Vector, obslcamp["sigmaca"])
freq = fill(get_rf(obs), length(time))
return StructArray((;T=time, F=freq, baseline, noise))
end
function get_arraytable(obs)
return StructArray(
sites = pyconvert(Vector{Symbol}, obs.tarr["site"]),
X = pyconvert(Vector, obs.tarr["x"]),
Y = pyconvert(Vector, obs.tarr["y"]),
Z = pyconvert(Vector, obs.tarr["z"]),
SEFD1 = pyconvert(Vector, obs.tarr["sefdr"]),
SEFD2 = pyconvert(Vector, obs.tarr["sefdl"]),
fr_parallactic = pyconvert(Vector, obs.tarr["fr_par"]),
fr_elevation = pyconvert(Vector, obs.tarr["fr_elev"]),
fr_offset = deg2rad.(pyconvert(Vector, obs.tarr["fr_off"])),
)
end
"""
extract_amp(obs)
Extracts the visibility amplitudes from an ehtim observation object.
Any valid keyword arguments to `add_amp` in ehtim can be passed through extract_amp.
Returns an EHTObservationTable with visibility amplitude data
"""
function Comrade.extract_amp(obsc; pol=:I, debias=false, kwargs...)
obs = obsc.copy()
obs.add_scans()
obs.reorder_tarr_snr()
obs.add_amp(;debias, kwargs...)
config = build_arrayconfig(obs)
amp, amperr = getampfield(obs)
T = Comrade.EHTVisibilityAmplitudeDatum{pol, eltype(amp), typeof(config[1])}
return Comrade.EHTObservationTable{T}(amp, amperr, config)
end
"""
extract_vis(obs; kwargs...)
Extracts the complex visibilities from an ehtim observation object
This grabs the raw `data` object from the obs object. Any keyword arguments are ignored.
Returns an EHTObservationTable with complex visibility data
"""
function Comrade.extract_vis(obsc; pol=:I, kwargs...)
obs = obsc.copy()
obs.add_scans()
obs.reorder_tarr_snr()
config = build_arrayconfig(obs)
vis, viserr = getvisfield(obs)
T = Comrade.EHTVisibilityDatum{pol, eltype(viserr), typeof(config[1])}
return Comrade.EHTObservationTable{T}(vis, viserr, config)
end
"""
extract_coherency(obs; kwargs...)
Extracts the coherency matrix from an ehtim observation object
This grabs the raw `data` object from the obs object. Any keyword arguments are ignored.
Returns an EHTObservationTable with coherency matrices
"""
function Comrade.extract_coherency(obsc; kwargs...)
obs = obsc.copy()
obs.add_scans()
obs.reorder_tarr_snr()
config = build_arrayconfig(obs)
vis, viserr = getcoherency(obs)
T = Comrade.EHTCoherencyDatum{eltype(real(vis[1])), typeof(config[1]), eltype(vis), eltype(viserr)}
return Comrade.EHTObservationTable{T}(vis, viserr, config)
end
function closure_designmat(type, closures, scanvis)
if type == :cphase
design_mat = closurephase_designmat(closures, scanvis)
elseif type == :lcamp
design_mat = closureamp_designmat(closures, scanvis)
else
throw(ArgumentError("Not a valid type of closure"))
end
end
function closurephase_designmat(cphase, scanvis)
antvis1, antvis2 = baseline(scanvis)
design_mat = zeros(length(cphase), length(scanvis))
#throw("here")
# fill in each row of the design matrix
for i in axes(design_mat, 2), j in axes(design_mat,1)
a1, a2, a3 = cphase[j].baseline
# check leg 1
((antvis1[i] == a1) & (antvis2[i] == a2)) && (design_mat[j,i] = 1.0)
((antvis1[i] == a2) & (antvis2[i] == a1)) && (design_mat[j,i] = -1.0)
#check leg 2
((antvis1[i] == a2) & (antvis2[i] == a3)) && (design_mat[j,i] = 1.0)
((antvis1[i] == a3) & (antvis2[i] == a2)) && (design_mat[j,i] = -1.0)
#check leg 3
((antvis1[i] == a3) & (antvis2[i] == a1)) && (design_mat[j,i] = 1.0)
((antvis1[i] == a1) & (antvis2[i] == a3)) && (design_mat[j,i] = -1.0)
end
return design_mat
end
function closureamp_designmat(lcamp, scanvis)
antvis1, antvis2 = baseline(scanvis)
design_mat = zeros(length(lcamp), length(scanvis))
# fill in each row of the design matrix
for i in axes(design_mat, 2), j in axes(design_mat,1)
a1, a2, a3, a4 = lcamp[j].baseline
av1 = antvis1[i]
av2 = antvis2[i]
# check leg 1
(((av1 == a1)&(av2 == a2)) || (av1 == a2)&(av2 == a1))&& (design_mat[j,i] = 1.0)
#check leg 2
(((av1 == a3)&(av2 == a4)) || (av1 == a4)&(av2 == a3))&& (design_mat[j,i] = 1.0)
#check leg 3
(((av1 == a1)&(av2 == a4)) || (av1 == a4)&(av2 == a1))&& (design_mat[j,i] = -1.0)
#check leg 4
(((av1 == a2)&(av2 == a3)) || (av1 == a3)&(av2 == a2))&& (design_mat[j,i] = -1.0)
end
return design_mat
end
function build_dmats(type::Symbol, closure, st)
S = eltype(closure.time)
dmat = Matrix{S}[]
for i in 1:length(st)
scanvis = st[i]
inds = findall(==(scanvis.time), closure.times)
if isnothing(inds)
inow = length(dmat)
# I want to construct block diagonal matrices for efficienty but we need
# to be careful with scan that can't form closures. This hack moves these
# scans into the preceding scan but fills it with zeros
if i > 1
dmat[inow] = hcat(dmat[inow], zeros(S, size(dmat[inow],1), length(scanvis.scan)))
else
push!(dmat, zeros(S, 1, length(scanvis.scan)))
end
continue
end
scancl = closures[inds]
if type == :cphase
dmatscan = closurephase_designmat(scancl, scanvis)
elseif type == :lcamp
dmatscan = closureamp_designmat(scancl, scanvis)
else
throw(ArgumentError("Not a valid type of closure"))
end
push!(dmat, dmatscan)
end
if iszero(dmat[1])
dmat[2] = hcat(zeros(S, size(dmat[2],1), size(dmat[1],2)), dmat[2])
dmat = dmat[2:end]
end
return dmat
end
function _ehtim_cphase(obsc; count="max", cut_trivial=false, uvmin=0.1e9, kwargs...)
obs = obsc.copy()
# cut 0 baselines since these are trivial triangles
if cut_trivial
obs = obs.flag_uvdist(uv_min=uvmin)
end
obs.reorder_tarr_snr()
obs.add_cphase(;count=count, kwargs...)
cphase = getcpfield(obs)
return cphase, Comrade.extract_vis(obs)
end
function _make_lcamp(obsc, count="max"; kwargs...)
obs = obsc.copy()
obs.reorder_tarr_snr()
obs.add_logcamp(;count=count, kwargs...)
data = getlcampfield(obs)
ra, dec = get_radec(obs)
mjd = get_mjd(obs)
source = get_source(obs)
bw = get_bw(obs)
return Comrade.EHTObservation(data = data, mjd = mjd,
config=nothing,
ra = ra, dec= dec,
bandwidth=bw,
source = source,
)
end
function _ehtim_lcamp(obsc; count="max", kwargs...)
obs = obsc.copy()
obs.reorder_tarr_snr()
obs.add_logcamp(;count=count, kwargs...)
lcamp = getlcampfield(obs)
return lcamp, Comrade.extract_vis(obs)
end
function _minimal_closure(type, closures, st)
# Determine the number of timestamps containing a closure triangle
S = eltype(closures.T)
# loop over all timestamps
dmat = Matrix{S}[]
for i in 1:length(st)
scanvis = st[i]
inds = findall(==(scanvis.time), closures.T)
if length(inds) == 0
inow = length(dmat)
# I want to construct block diagonal matrices for efficienty but we need
# to be careful with scan that can't form closures. This hack moves these
# scans into the preceding scan but fills it with zeros
if i > 1
dmat[inow] = hcat(dmat[inow], zeros(S, size(dmat[inow],1), length(scanvis.scan)))
else
push!(dmat, zeros(S, 1, length(scanvis.scan)))
end
continue
end
# Get our cphase scan
scancl = closures[inds]
# @info scancl
# sort by closure noise so we form a nice minimal set
snr = inv.(scancl.noise)
ind_snr = sortperm(snr)
scancl = scancl[ind_snr]
# initialize the design matrix
design_mat = closure_designmat(type, scancl, scanvis)
# determine the expected size of the minimal set
# this is needed to make sure we aren't killing too many triangles
nmin = rank(design_mat)
# print some info
# println("For timestamp $(scanvis.time):")
# get the current sites
# println("Observing sites are $(scancl.baseline)")
# println("scanvis sites ", sites(scanvis))
# println("Size of maximal set of closure products = $(length(scancl))")
# println("Size of minimal set of closure products = $(nmin)")
# println("...")
##########################################################
# start of loop to recover minimal set
##########################################################
dmat_min = minimal_closure_scan(type, scancl, scanvis, nmin)
push!(dmat, dmat_min)
end
# Now if the first scan can't form a closure we will have an extra row of zeros
# kill this
if iszero(dmat[1])
dmat[2] = hcat(zeros(S, size(dmat[2],1), size(dmat[1],2)), dmat[2])
dmat = dmat[2:end]
end
return dmat
end
function minimal_closure_scan(type, closures, scanvis, nmin::Int)
# make a mask to keep track of which clhases will stick around
scancl = deepcopy(closures)
keep = fill(true, length(closures))
# remember the original minimal set size
nmin0 = nmin
# perform the loop
count = 1
keep = fill(true, length(closures))
good = true
while good
# recreate the mask each time
closurekeep = closures[keep]
design_mat = closure_designmat(type, closurekeep, scanvis)
# determine the size of the minimal set
nmin = rank(design_mat)
#println(nmin0, " ", nmin, " ", size(design_mat, 1))
# Now decide whether to continue pruning
if (sum(keep) == nmin0) && (nmin == nmin0)
good = false
else
if nmin == nmin0
keep[count] = false
else
keep[count-1] = true
count -= 1
end
#(nmin == nmin0) && (keep[count] = false)
end
count += 1
count+1 > length(scancl) && break
end
# print out the size of the recovered set for double-checking
closurekeep = closures[keep]
dmat = closure_designmat(type, closurekeep, scanvis)
if length(closurekeep) != nmin
@error "minimal set not found $(length(closurekeep)) $(nmin)"
throw("No minimal set found at time $(scanvis.time)")
end
return dmat
end
"""
extract_cphase(obs)
Extracts the closure phases from an ehtim observation object
Any valid keyword arguments to `add_cphase` in ehtim can be passed through extract_cphase.
Returns an EHTObservation with closure phases datums
# Special Keyword arguments:
- count: How the closures are formed, the available options are "min-correct", "min", "max"
- cut_trivial: Cut the trivial triangles from the closures
- uvmin: The flag to decide what are trivial triangles. Any baseline with ||(u,v)|| < uvmin
are removed.
- kwargs...: Other arguments are forwarded to eht-imaging.
# Warning
The `count` keyword argument is treated specially in `Comrade`. The default option
is "min-correct" and should almost always be used.
This option construct a minimal set of closure phases that is valid even when
the array isn't fully connected. For testing and legacy reasons we `ehtim` other count
options are also included. However, the current `ehtim` count="min" option is broken
and does construct proper minimal sets of closure quantities if the array isn't fully connected.
"""
function Comrade.extract_cphase(obs; pol=:I, count="min", kwargs...)
# compute a maximum set of closure phases
obsc = obs.copy()
# reorder to maximize the snr
obsc.reorder_tarr_snr()
cphase, dvis = _ehtim_cphase(obsc; count="max", kwargs...)
#Now make the vis obs
st = timetable(dvis)
if count == "min"
dmat = _minimal_closure(:cphase, cphase, st)
elseif count == "max"
dmat = build_dmats(:cphase, cphase, st)
else
throw(ArgumentError("$(count) is not valid use 'min' or 'max'"))
end
clac = Comrade.ClosureConfig(arrayconfig(dvis), dmat, measurement(dvis), noise(dvis))
T = Comrade.EHTClosurePhaseDatum{pol, eltype(cphase.T), typeof(arrayconfig(dvis)[1])}
cp = Comrade.closure_phases(measurement(dvis), Comrade.designmat(clac))
cp_sig = abs2.(Comrade.noise(dvis)./Comrade.measurement(dvis))
cp_cov = Comrade.designmat(clac)*Diagonal(cp_sig)*transpose(Comrade.designmat(clac))
return Comrade.EHTObservationTable{T}(cp, cp_cov, clac)
end
"""
extract_lcamp(obs; kwargs...)
Extracts the log-closure amp. from an ehtim observation object
Any valid keyword arguments to `add_logcamp` in ehtim can be passed through extract_lcamp.
# Special Keyword arguments:
- count: How the closures are formed, the available options are "min-correct", "min", "max"
- kwargs...: Other arguments are forwarded to eht-imaging.
Returns an EHTObservation with log-closure amp. datums
# Warning
The `count` keyword argument is treated specially in `Comrade`. The default option
is "min-correct" and should almost always be used.
This option construct a minimal set of closure phases that is valid even when
the array isn't fully connected. For testing and legacy reasons we `ehtim` other count
options are also included. However, the current `ehtim` count="min" option is broken
and does construct proper minimal sets of closure quantities if the array isn't fully connected.
"""
function Comrade.extract_lcamp(obs; pol=:I, count="min", kwargs...)
# compute a maximum set of closure phases
obsc = obs.copy()
# reorder to maximize the snr
obsc.reorder_tarr_snr()
lcamp, dvis = _ehtim_lcamp(obsc; count="max", kwargs...)
#Now make the vis obs
st = timetable(dvis)
if count == "min"
dmat = _minimal_closure(:lcamp, lcamp, st)
elseif count == "max"
dmat = build_dmats(:lcamp, lcamp, st)
else
throw(ArgumentError("$(count) is not valid use 'min' or 'max'"))
end
clac = Comrade.ClosureConfig(arrayconfig(dvis), dmat, measurement(dvis), noise(dvis))
cldmat = Comrade.designmat(clac)
T = Comrade.EHTLogClosureAmplitudeDatum{pol, eltype(lcamp.T), typeof(arrayconfig(dvis)[1])}
lcamp = Comrade.logclosure_amplitudes(measurement(dvis), Comrade.designmat(clac))
lcamp_sig = abs2.(Comrade.noise(dvis)./Comrade.measurement(dvis))
lcamp_cov = cldmat*Diagonal(lcamp_sig)*transpose(cldmat)
return Comrade.EHTObservationTable{T}(lcamp, lcamp_cov, clac)
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 414 | module ComradeAHMC
using AbstractMCMC
using Reexport
@reexport using AdvancedHMC
using Comrade
using DocStringExtensions
using LogDensityProblems, LogDensityProblemsAD
using ArgCheck: @argcheck
using Random
using Accessors
using Printf
using StatsBase
using AbstractMCMC: Sample
using Serialization
function __init__()
@warn "ComradeDynesty is deprecated, AdvancedHMC.jl is now an extension."
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1836 | using Pyehtim, Comrade, ComradeAHMC, Distributions, VLBIImagePriors
using Enzyme
using Test
include(joinpath(@__DIR__, "../../../test/test_util.jl"))
@testset "ComradeAHMC.jl" begin
_, _, _, lcamp, cphase = load_data()
g = imagepixels(μas2rad(150.0), μas2rad(150.0), 256, 256)
skym = SkyModel(test_model, test_prior(), g)
post = VLBIPosterior(skym, lcamp, cphase)
x0 = (sky = (f1 = 1.0916271439905998,
σ1 = 8.230088139590025e-11,
τ1 = 0.49840994275315254,
ξ1 = -1.0489388962890198,
f2 = 0.553944311447593,
σ2 = 4.1283218512580634e-11,
τ2 = 0.5076731020106428,
ξ2 = -0.5376269092893298,
x = 1.451956089157719e-10,
y = 1.455983181049137e-10),)
s1 = AHMC(autodiff=Val(:Enzyme))
s2 = AHMC(autodiff=Val(:Enzyme))
s3 = AHMC()
hchain = sample(post, s1, 1_000; n_adapts=500, progress=false)
hchain = sample(post, s1, 1_000; n_adapts=500, progress=false, initial_params=x0)
hchain = sample(post, s2, 1_000; n_adapts=500, progress=false, initial_params=x0)
out = sample(post, s2, 1_000; n_adapts=500, saveto=ComradeAHMC.DiskStore(name=joinpath(@__DIR__, "Test")), initial_params=x0)
out = sample(post, s2, 1_200; n_adapts=500, saveto=ComradeAHMC.DiskStore(name=joinpath(@__DIR__, "Test")), initial_params=x0, restart=true)
c1 = load_table(out)
@test c1[201:451] == load_table(out, 201:451)
c1 = load_table(out; table="stats")
@test c1[1:451] == load_table(out, 1:451; table="stats")
c1 = load_table(joinpath(@__DIR__, "Test"))
sample(post, s2, 1_000; n_adapts=500, saveto=ComradeAHMC.DiskStore(name=joinpath(@__DIR__, "Test")), initial_params=x0, restart=true)
@test c1[201:451] == load_table(joinpath(@__DIR__, "Test"), 201:451)
rm("Test", recursive=true)
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 187 | module ComradeAdaptMCMC
using AdaptiveMCMC
using Comrade
using AbstractMCMC
using Random
function __init__()
@warn "ComradeAdaptMCMC is deprecated, use Pigeons insteads."
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 143 | using Pyehtim, Comrade, ComradeAdaptMCMC, Distributions, VLBIImagePriors
using Test
include(joinpath(@__DIR__, "../../../test/test_util.jl"))
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 204 | module ComradeDynesty
using Comrade
using Dynesty
using AbstractMCMC
using Reexport
using Random
function __init__()
@warn "ComradeDynesty is deprecated. Dynesty.jl is now an extension."
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 141 | using Pyehtim, Comrade, ComradeDynesty, Distributions, VLBIImagePriors
using Test
include(joinpath(@__DIR__, "../../../test/test_util.jl"))
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 209 | module ComradeNested
using Comrade
using AbstractMCMC
using Reexport
using Random
export resample_equal
function __init__()
@warn "ComradeNested is deprecated. Dynesty.jl is now an extension."
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1133 | using Pyehtim, Comrade, ComradeNested, Distributions, VLBIImagePriors
using Test
include(joinpath(@__DIR__, "../../../test/test_util.jl"))
@testset "ComradeNested.jl" begin
_, _, _, lcamp, cphase = load_data()
g = imagepixels(μas2rad(150.0), μas2rad(150.0), 256, 256)
skym = SkyModel(test_model, test_prior(), g)
post = VLBIPosterior(skym, lcamp, cphase)
a1 = Nested(dimension(ascube(post)), 1000)
chain = sample(post, a1; dlogz=0.01, progress=false)
echain = resample_equal(chain, 1000)
#cpost = ascube(post)
#xopt = chain[end]
#@test isapprox(xopt.f1/xopt.f2, 2.0, atol=1e-2)
#@test isapprox(xopt.σ1*2*sqrt(2*log(2)), μas2rad(40.0), rtol=1e-3)
#@test isapprox(xopt.σ1*xopt.τ1*2*sqrt(2*log(2)), μas2rad(20.0), rtol=1e-3)
#@test isapprox(-xopt.ξ1, π/3, atol=1e-2)
#@test isapprox(xopt.σ2*2*sqrt(2*log(2)), μas2rad(20.0), atol=1e-2)
#@test isapprox(xopt.σ2*xopt.τ2*2*sqrt(2*log(2)), μas2rad(10.0), rtol=1e-2)
#@test isapprox(-xopt.ξ2, π/6, atol=1e-2)
#@test isapprox(xopt.x, μas2rad(30.0), rtol=1e-2)
#@test isapprox(xopt.y, μas2rad(30.0), rtol=1e-2)
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 288 | module ComradeOptimization
using Comrade: VLBIPosterior, asflat, ascube, transform
using Reexport
using Distributions
using ForwardDiff
using LinearAlgebra
import SciMLBase
function __init__()
@warn "ComradeOptimization is deprecated. Optimization.jl is now an extension."
end
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 1221 | export fishermatrix
"""
$(SIGNATURES)
Compute the Fisher information matrix of a `model` transformed by `t` using the array configuration
`ac`. You can also optionally pass the `ad_type` as the last argument which is which
backend to `AbstractDifferentiation` you want to use to compute derivatives.
`model` is assumed to be a function that takes the `NamedTuple`, `θ` and returns
a `<:Comrade.AbstractModel` that coincides with the visibility model you want to consider.
This returns a `Tuple` where the first entry is Fisher information metric and the second
is distribution assuming that the mean is the transformed `θ` and the covariance matrix
is the inverse of the Fisher information.
"""
function fishermatrix(model, t, θ::NamedTuple, ac::ArrayConfiguration)
v = Base.Fix2(visibilitymap, ac)
tr = Base.Fix1(transform, t)
# split into real and imaginary since ForwardDiff struggles with complex functions
fr = real∘v∘model∘tr
fi = imag∘v∘model∘tr
x0 = inverse(t, θ)
vr = first(AD.jacobian(ad_type, fr, x0))
vi = first(AD.jacobian(ad_type, fi, x0))
v1 = complex.(vr, vi)
M = Symmetric(real.(v1'*v1) .+ eps())
h = M*x0
return M, Dists.MvNormalCanon(h, M)
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 3140 | using Pkg;Pkg.activate(@__DIR__)
using Comrade
using Plots
using ComradeAHMC
using ComradeOptimization
using OptimizationBBO
using Distributions
using DistributionsAD
# To download the data visit https://doi.org/10.25739/g85n-f134
obs = ehtim.obsdata.load_uvfits(joinpath(@__DIR__, "SR1_M87_2017_096_hi_hops_netcal_StokesI.uvfits"))
obs.add_scans()
obsavg = obs.avg_coherent(0.0, scan_avg=true)
# Lets make a gaussian image
img = ehtim.image.make_empty(512, μas2rad(250.0), obs.ra, obs.dec, obs.rf, obs.source)
img = img.add_gauss(1.0, [μas2rad(40.0), μas2rad(30.0), π/3, 0.0, 0.0])
# Set the gain priors
gainoff = 0.0
gainp = Dict("AA"=> 0.01,
"AP" => 0.1,
"AZ" => 0.1,
"JC" => 0.1,
"LM" => 0.2,
"PV" => 0.1,
"SM" => 0.1,
"SP" => 0.1)
obsim = img.observe_same(obsavg, ttype="fast", gainp=gainp, gain_offset=gainoff, ampcal=false, phasecal=false, stabilize_scan_phase=true, stabilize_scan_amp=true)
# now get cal table
ctable = ehtim.calibrating.self_cal.self_cal(obsim, img, caltable=true)
#ehtim.caltable.save_caltable(ctable, obsim, datadir=joinpath(@__DIR__ ,"CaltableTest"))
dcphase = extract_cphase(obsim)
damp = extract_amp(obsim)
st = timetable(damp)
gcache = Comrade.GainCache(st)
# Now create the Comrade Gain model
struct Model{G}
gcache::G
end
function Model(st::Comrade.TimeTable)
gcache = Comrade.GainCache(st)
return Model{typeof(gcache)}(gcache)
end
function (mod::Model)(θ)
(;f, σ, τ, ξ, gamp) = θ
g = exp.(gamp)
m = f*rotated(stretched(Gaussian(), σ*τ, σ), ξ)
return GainModel(mod.gcache, g, m)
end
# define the priors
distamp = (AA = Normal(0.0, 0.01),
AP = Normal(0.0, 0.1),
LM = Normal(0.0, 0.2),
AZ = Normal(0.0, 0.1),
JC = Normal(0.0, 0.1),
PV = Normal(0.0, 0.1),
SM = Normal(0.0, 0.1)
)
prior = (
f = Uniform(0.9, 1.1),
σ = Uniform(μas2rad(10.0), μas2rad(30.0)),
τ = Uniform(0.1, 1.0),
ξ = Uniform(-π/2, π/2),
gamp = Comrade.GainPrior(distamp, st),
)
# Now form the posterior
mms = Model(st)
lklhd = RadioLikelihood(mms, damp, dcphase)
post = Posterior(lklhd, prior)
tpost = asflat(post)
# We will use HMC to sample the posterior.
# First to reduce burn in we use pathfinder
ndim = dimension(tpost)
f = OptimizationFunction(tpost, Optimization.AutoForwardDiff())
x0 = Comrade.HypercubeTransform.inverse(tpost, rand(post.prior))
using OptimizationOptimJL
prob = OptimizationProblem(f, rand(ndim) .- 0.5, nothing)
sol = solve(prob, LBFGS(); g_tol=1e-5, maxiters=2_000)
@info sol.minimum
xopt = Comrade.transform(tpost, sol)
residual(mms(xopt), damp)
plot(caltable(mms(xopt)), layout=(3,3), size=(600,500))
# Compare the results for LMT
ctab = caltable(mms(xopt))
scatter(ctab[:time], inv.(ctab[:LM]),
label="Comrade", size=(400,300),
xlabel="Time (hr)",
ylabel="LMT Gain Amp.",
)
scatter!(pyconvert(Vector, ctable.data["LM"]["time"]), abs.(pyconvert(Vector, ctable.data["LM"]["rscale"])), label="eht-imaging")
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 3763 | # # Self-calibrating data with Comrade
# Here we will self-cal the data with Comrade. This means we take the results of a
# Comrade run, and the use eht-imaging to self-calibrate the fitted data and save the
# new observation object.
# This script assumes that you have the eht-imaging Obsdata object, the
# Comrade MCMC chain, and the model you fit to the data.
using Pkg;Pkg.activate(@__DIR__)
using Comrade
using Tables
using DataFrames
using CSV
using PyCall
using Printf
using Serialization
@pyimport numpy as np
"""
selfcal(obs, model::GainModel)
Takes in a `eht-imaging` observation object that you fit the data to, and
a `Comrade` gain model and returns the `self-calibrated` data and the calibration table
object from eht-imaging.
"""
function selfcal(obs::PyCall.PyObject, model::GainModel)
obscpy = obs.copy()
ctable = caltable(model)
# Now make the caltable for eht-imaging
sites = sites(ctable)
time = ctable.time
ctabcol = map(sites) do s
mask = Base.:!.(ismissing.(getproperty(ctable, s)))
tmask = time[mask]
gmask = ctable[:,s][mask]
# make the ndarray that eht-imaging expects
arr = np.array(PyObject(tmask), dtype = ehtim.DTCAL)
set!(arr, "time", tmask)
set!(arr, "rscale", inv.(gmask))
set!(arr, "lscale", inv.(gmask))
return Pair(s, arr)
end
datatable = PyDict(Dict(ctabcol))
ctab_eh = ehtim.caltable.Caltable(
obs.ra, obs.dec,
obs.rf, obs.bw,
datatable,
obs.tarr,
source=obs.source, mjd=obs.mjd)
o2 = ctab_eh.applycal(obscpy)
return o2, ctab_eh
end
"""
selfcal_submission(results, obsfile, outdir, nsamples, nburn)
Creates a directory with the selfcalibrated data sets and their corresponding images.
# Arguments
- `results::String`: The .jls serialized file from a run
- `obs`: The eht-imaging obsdata object for the data you fit
- `outdir::String`: The directory you wish to save the images and uvfits files to
- `nsamples::Int`: The number of samples from the posterior you want to create self-cal data sets for
- `nburn::Int`: The number of adaptation steps used in the sample. This is required because you need to remove these
# Warning
We have assumed a number of things about how the data was processed, i.e. we cut zero baselines. If this
is not the case then this function will need to be modified.
"""
function selfcal_submission(results::String, obs, outdir::String, nsamples::Int, nburn::Int)
res = deserialize(results)
# obs = ehtim.obsdata.load_uvfits(obsfile)
# obs.add_scans()
# # make scan-average data #.flag_uvdist(uv_min=0.1e9)
# obs = scan_average(obs.flag_uvdist(uv_min=0.1e9).add_fractional_noise(0.01))
# extract amplitudes and closure phases
damp = extract_amp(obs)
mms = GModel(damp, res[:fovx], res[:fovy], res[:npixx], res[:npixy])
mkpath(outdir)
fov = max(res[:fovx], res[:fovy])*1.1
chain = sample(res[:chain][nburn:end], nsamples)
for i in 1:nsamples
model = mms(chain[i])
img = intensitymap(model, fov, fov, 256, 256)
obscal, _ = selfcal(obs, model)
outim = @sprintf "image_%04d.fits" i
save_fits(joinpath(outdir, outim), img, damp)
outcal = @sprintf "selfcal_data_comrade_%04d.uvfits" i
obscal.save_uvfits(joinpath(outdir, outcal))
end
return nothing
end
function selfcal_2018(results, obsfile, outdir, nsamples, nburn)
obs = ehtim.obsdata.load_uvfits(obsfile)
obs.add_scans()
# make scan-average data #.flag_uvdist(uv_min=0.1e9)
obs = scan_average(obs.flag_uvdist(uv_min=0.1e9).add_fractional_noise(0.01))
return selfcal_submission(results, obs, outdir, nsamples, nburn)
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 2428 | """
Comrade
Composable Modeling of Radio Emission
"""
module Comrade
using AbstractMCMC
using Accessors: @set
using ArgCheck: @argcheck
using DensityInterface
import Distributions as Dists
using DocStringExtensions
using ChainRulesCore
using EnzymeCore
using EnzymeCore: EnzymeRules
using FillArrays: Fill
using ForwardDiff
using IntervalSets
using LogDensityProblems
using LinearAlgebra
import HypercubeTransform: ascube, asflat, NamedDist, NamedDist, transform, inverse
using HypercubeTransform
#using MappedArrays: mappedarray
using NamedTupleTools
using Printf
using Random
using RecipesBase
using Reexport
using SparseArrays
using StaticArraysCore
using StructArrays: StructVector, StructArray, append!!
import StructArrays
using Tables
import TransformVariables as TV
using ComradeBase: AbstractDomain, AbstractSingleDomain, AbstractRectiGrid
using VLBISkyModels: FourierTransform, FourierDualDomain
# Reexport the core libraries for Comrade
@reexport using VLBISkyModels
@reexport using ComradeBase
@reexport using PolarizedTypes
@reexport using VLBIImagePriors
export linearpol, mbreve, evpa
using ComradeBase: AbstractRectiGrid, AbstractDomain, UnstructuredDomain,
AbstractModel, AbstractPolarizedModel, AbstractHeader
export rad2μas, μas2rad, logdensity_def, logdensityof
import ComradeBase: flux, radialextent, intensitymap, intensitymap!,
intensitymap_analytic, intensitymap_analytic!,
intensitymap_numeric, intensitymap_numeric!,
visibilitymap, visibilitymap!,
_visibilitymap, _visibilitymap!,
visibilitymap_analytic, visibilitymap_analytic!,
visibilitymap_numeric, visibilitymap_numeric!,
visanalytic, imanalytic, ispolarized,
NotAnalytic, IsAnalytic, NotPolarized, IsPolarized,
visibility_point, intensity_point,
closure_phase, closure_phasemap,
logclosure_amplitude, logclosure_amplitudemap,
visibility, amplitude,
amplitudemap
include("observations/observations.jl")
include("instrument/instrument.jl")
include("skymodels/models.jl")
include("posterior/abstract.jl")
include("inference/inference.jl")
include("visualizations/visualizations.jl")
include("dirty_image.jl")
include("mrf_image.jl")
include("rules.jl")
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
|
[
"MIT"
] | 0.11.0 | b35d823d152a6a3f401ed956314df4a0a5540b92 | code | 2251 | export dirty_image, dirty_beam
function reflect_vis(obs::EHTObservationTable{<:EHTVisibilityDatum})
ac = arrayconfig(obs)
con = datatable(arrayconfig(obs))
conn = copy(con)
conn.U .= -con.U
conn.V .= -con.V
con2 = vcat(con, conn)
meas = measurement(obs)
noise = Comrade.noise(obs)
measn = conj.(copy(meas))
meas2 = vcat(meas, measn)
noise2= vcat(noise, noise)
conf2 = EHTArrayConfiguration(
ac.bandwidth, ac.tarr, ac.scans,
ac.mjd, ac.ra, ac.dec, ac.source,
ac.timetype, con2)
return EHTObservationTable{datumtype(obs)}(meas2, noise2, conf2)
end
"""
dirty_image(fov::Real, npix::Int, obs::EHTObservation{<:EHTVisibilityDatum}) where T
Computes the dirty image of the complex visibilities assuming a field of view of `fov`
and number of pixels `npix` using the complex visibilities found in the observation `obs`.
The `dirty image` is the inverse Fourier transform of the measured visibilties assuming every
other visibility is zero.
"""
function dirty_image(fov::Real, npix::Int, obs::EHTObservationTable{D}) where {D<:EHTVisibilityDatum}
# First we double the baselines, i.e. we reflect them and conjugate the measurements
# This ensures a real NFFT
img = IntensityMap(zeros(npix, npix), imagepixels(fov, fov, npix, npix))
vis2 = reflect_vis(obs)
# Get the number of pixels
gfour = FourierDualDomain(axisdims(img), arrayconfig(vis2), NFFTAlg())
plr = VLBISkyModels.reverse_plan(gfour)
m = plr.plan*(conj.(vis2[:measurement]).*plr.phases)
return IntensityMap(real.(m)./npix^2, axisdims(img))
end
"""
dirty_beam(fov::Real, npix::Int, obs::EHTObservation{<:EHTVisibilityDatum})
Computes the dirty beam of the complex visibilities assuming a field of view of `fov`
and number of pixels `npix` using baseline coverage found in `obs`.
The `dirty beam` is the inverse Fourier transform of the (u,v) coverage assuming every
visibility is unity and everywhere else is zero.
"""
function dirty_beam(fov, npix, obs::EHTObservationTable{D}) where {D<:EHTVisibilityDatum}
vis2 = reflect_vis(obs)
vis2.measurement .= complex(oneunit(fov), zero(fov))
return dirty_image(fov, npix, vis2)
end
| Comrade | https://github.com/ptiede/Comrade.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.