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"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 4133 | mutable struct Energy_density_measurement{Dim,TG} <: AbstractMeasurement
filename::String
_temporary_gaugefields::Vector{TG}
temp_UμνTA::Matrix{TG}
Dim::Int8
#factor::Float64
verbose_print::Union{Verbose_print,Nothing}
printvalues::Bool
function Energy_density_measurement(
U::Vector{T};
filename = nothing,
verbose_level = 2,
printvalues = true,
) where {T}
myrank = get_myrank(U)
if printvalues
verbose_print = Verbose_print(verbose_level, myid = myrank, filename = filename)
else
verbose_print = nothing
end
Dim = length(U)
temp_UμνTA = Array{T,2}(undef, Dim, Dim)
for μ = 1:Dim
for ν = 1:Dim
temp_UμνTA[ν, μ] = similar(U[1])
end
end
numg = 3
_temporary_gaugefields = Vector{T}(undef, numg)
_temporary_gaugefields[1] = similar(U[1])
for i = 2:numg
_temporary_gaugefields[i] = similar(U[1])
end
return new{Dim,T}(
filename,
_temporary_gaugefields,
temp_UμνTA,
Dim,
verbose_print,
printvalues,
)
end
end
function Energy_density_measurement(U, params, filename) where {T}
return Energy_density_measurement(
U;
filename = filename,
verbose_level = params.verbose_level,
printvalues = params.printvalues,
)
end
function measure(
m::M,
itrj,
U::Array{<:AbstractGaugefields{NC,Dim},1};
additional_string = "",
) where {M<:Energy_density_measurement,NC,Dim}
temps = get_temporary_gaugefields(m)
value = calculate_energy_density(U, m.temp_UμνTA, temps)
measurestring = ""
if m.printvalues
st = "-----------------"
measurestring *= st * "\n"
println_verbose_level2(U[1], st)
st = "$itrj $additional_string $value # energydensity"
measurestring *= st * "\n"
println_verbose_level2(m.verbose_print, st)
st = "-----------------"
measurestring *= st * "\n"
println_verbose_level2(U[1], st)
end
return values, measurestring
end
# = = = calc energy density = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function calculate_energy_density(U::Array{T,1}, Wmat, temps) where {T<:AbstractGaugefields}
# Making a ( Ls × Lt) Wilson loop operator for potential calculations
WL = 0.0 + 0.0im
NV = U[1].NV
NC = U[1].NC
#Wmat = Array{T,2}(undef,4,4)
#
make_energy_density!(Wmat, U, temps) # make wilon loop operator and evaluate as a field, not traced.
WL = make_energy_density_core(Wmat, U, NV) # tracing over color and average over spacetime and x,y,z.
NDir = 4.0 * 3.0 / 2 # choice of 2 axis from 4.
return real(WL) / NV / NDir / NC / 8
end
function make_energy_density!(
Wmat,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
W_operator, numofloops = calc_loopset_μν_name("clover", Dim)#make_Wilson_loop(Lt,Ls)
calc_large_wilson_loop!(Wmat, W_operator, U, temps)
return
end
function make_energy_density_core(
Wmat::Array{<:AbstractGaugefields{NC,Dim},2},
U::Array{T,1},
NV,
) where {T<:AbstractGaugefields,NC,Dim}
@assert Dim == 4
W = 0.0 + 0.0im
for μ = 1:Dim # all directions
for ν = 1:Dim
if μ == ν
continue
end
W += tr(Wmat[μ, ν], Wmat[μ, ν]) / 4
end
end
return W
end
function calc_large_wilson_loop!(
temp_Wmat::Array{<:AbstractGaugefields{NC,Dim},2},
W_operator,
U::Array{T,1},
temps,
) where {T<:AbstractGaugefields,NC,Dim}
W = temp_Wmat
for μ = 1:Dim
for ν = 1:Dim
if μ == ν
continue
end
#println(typeof(μ)," ",typeof(ν))
#exit()
#loopset = Loops(U,W_operator[μ,ν])
evaluate_gaugelinks!(W[μ, ν], W_operator[μ, ν], U, temps)
#W[μ,ν] = evaluate_loops(loopset,U)
end
end
return
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2332 | mutable struct Plaquette_measurement{Dim,TG} <: AbstractMeasurement
filename::Union{Nothing,String}
_temporary_gaugefields::Vector{TG}
Dim::Int8
factor::Float64
verbose_print::Union{Verbose_print,Nothing}
printvalues::Bool
function Plaquette_measurement(
U::Vector{T};
filename = nothing,
verbose_level = 2,
printvalues = true,
) where {T}
myrank = get_myrank(U)
#=
if U[1].mpi == false
myrank = 0
else
myrank = U[1].myrank
end
=#
if printvalues
verbose_print = Verbose_print(verbose_level, myid = myrank, filename = filename)
#println(verbose_print)
#error("v")
else
verbose_print = nothing
end
Dim = length(U)
if Dim == 4
comb = 6
elseif Dim == 2
comb = 1
else
error("Dim = $Dim is not supported in Plaquette_measurement")
end
factor = 1 / (comb * U[1].NV * U[1].NC)
numg = 2
_temporary_gaugefields = Vector{T}(undef, numg)
_temporary_gaugefields[1] = similar(U[1])
for i = 2:numg
_temporary_gaugefields[i] = similar(U[1])
end
return new{Dim,T}(
filename,
_temporary_gaugefields,
Dim,
factor,
verbose_print,
printvalues,
)
end
end
function Plaquette_measurement(U::Vector{T}, params::Plaq_parameters, filename) where {T}
return Plaquette_measurement(
U,
filename = filename,
verbose_level = params.verbose_level,
printvalues = params.printvalues,
)
end
function measure(m::M, itrj, U; additional_string = "") where {M<:Plaquette_measurement}
temps = get_temporary_gaugefields(m)
plaq = real(calculate_Plaquette(U, temps[1], temps[2]) * m.factor)
measurestring = ""
if m.printvalues
#println("m.verbose_print ",m.verbose_print)
#println_verbose_level2(U[1],"-----------------")
measurestring = "$itrj $additional_string $plaq # plaq"
println_verbose_level2(m.verbose_print, measurestring)
#println_verbose_level2(U[1],"-----------------")
end
return plaq, measurestring
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 1896 | mutable struct Polyakov_measurement{Dim,TG} <: AbstractMeasurement
filename::Union{Nothing,String}
_temporary_gaugefields::Vector{TG}
Dim::Int8
#factor::Float64
verbose_print::Union{Verbose_print,Nothing}
printvalues::Bool
function Polyakov_measurement(
U::Vector{T};
filename = nothing,
verbose_level = 2,
printvalues = true,
) where {T}
myrank = get_myrank(U)
#=
if U[1].mpi == false
myrank = 0
else
myrank = U[1].myrank
end
=#
if printvalues
verbose_print = Verbose_print(verbose_level, myid = myrank, filename = filename)
else
verbose_print = nothing
end
Dim = length(U)
numg = 2
_temporary_gaugefields = Vector{T}(undef, numg)
_temporary_gaugefields[1] = similar(U[1])
for i = 2:numg
_temporary_gaugefields[i] = similar(U[1])
end
return new{Dim,T}(filename, _temporary_gaugefields, Dim, verbose_print, printvalues)
end
end
function Polyakov_measurement(U::Vector{T}, params::Poly_parameters, filename) where {T}
return Polyakov_measurement(
U,
filename = filename,
verbose_level = params.verbose_level,
printvalues = params.printvalues,
)
end
function measure(m::M, itrj, U; additional_string = "") where {M<:Polyakov_measurement}
temps = get_temporary_gaugefields(m)
poly = calculate_Polyakov_loop(U, temps[1], temps[2])
measurestring = ""
if m.printvalues
#println_verbose_level2(U[1],"-----------------")
measurestring = "$itrj $additional_string $(real(poly)) $(imag(poly)) # poly"
println_verbose_level2(m.verbose_print, measurestring)
#println_verbose_level2(U[1],"-----------------")
end
return poly, measurestring
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 9877 | mutable struct Topological_charge_measurement{Dim,TG} <: AbstractMeasurement
filename::String
_temporary_gaugefields::Vector{TG}
temp_UμνTA::Matrix{TG}
Dim::Int8
#factor::Float64
verbose_print::Union{Verbose_print,Nothing}
printvalues::Bool
TC_methods::Vector{String}
function Topological_charge_measurement(
U::Vector{T};
filename = nothing,
verbose_level = 2,
printvalues = true,
TC_methods = ["plaquette"],
) where {T}
myrank = get_myrank(U)
if printvalues
verbose_print = Verbose_print(verbose_level, myid = myrank, filename = filename)
else
verbose_print = nothing
end
Dim = length(U)
temp_UμνTA = Array{T,2}(undef, Dim, Dim)
for μ = 1:Dim
for ν = 1:Dim
temp_UμνTA[ν, μ] = similar(U[1])
end
end
numg = 3
_temporary_gaugefields = Vector{T}(undef, numg)
_temporary_gaugefields[1] = similar(U[1])
for i = 2:numg
_temporary_gaugefields[i] = similar(U[1])
end
return new{Dim,T}(
filename,
_temporary_gaugefields,
temp_UμνTA,
Dim,
verbose_print,
printvalues,
TC_methods,
)
end
end
function Topological_charge_measurement(
U::Vector{T},
params::TopologicalCharge_parameters,
filename,
) where {T}
return Topological_charge_measurement(
U,
filename = filename,
verbose_level = params.verbose_level,
printvalues = params.printvalues,
TC_methods = params.kinds_of_topological_charge, #["plaquette"]
)
end
function measure(
m::M,
itrj,
U::Array{<:AbstractGaugefields{NC,Dim},1};
additional_string = "",
) where {M<:Topological_charge_measurement,NC,Dim}
temps = get_temporary_gaugefields(m)
temp1 = temps[1]
temp2 = temps[2]
measurestring = ""
nummethod = length(m.TC_methods)
values = Float64[]
printstring = "$itrj " * additional_string
for i = 1:nummethod
methodname = m.TC_methods[i]
if methodname == "plaquette"
Qplaq = calculate_topological_charge_plaq(U, m.temp_UμνTA, temps)
push!(values, real(Qplaq))
elseif methodname == "clover"
Qclover = calculate_topological_charge_clover(U, m.temp_UμνTA, temps)
push!(values, real(Qclover))
Qimproved =
calculate_topological_charge_improved(U, m.temp_UμνTA, Qclover, temps)
push!(values, real(Qimproved))
else
error("method $methodname is not supported in topological charge measurement")
end
#printstring *= "$(values[i]) "
end
for value in values
printstring *= "$(value) "
end
printstring *= "# itrj "
for i = 1:nummethod
methodname = m.TC_methods[i]
if methodname == "plaquette"
printstring *= "Qplaq "
elseif methodname == "clover"
printstring *= "Qclover Qimproved "
else
error("method $methodname is not supported in topological charge measurement")
end
end
if m.printvalues
#println_verbose_level2(U[1],"-----------------")
measurestring = printstring
println_verbose_level2(m.verbose_print, printstring)
#println_verbose_level2(U[1],"-----------------")
end
return values, measurestring
end
function calculate_topological_charge_plaq(U::Array{T,1}, temp_UμνTA, temps) where {T}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "plaq", U, temps)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calculate_topological_charge_clover(U::Array{T,1}, temp_UμνTA, temps) where {T}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "clover", U, temps)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calculate_topological_charge_improved(
U::Array{T,1},
temp_UμνTA,
Qclover,
temps,
) where {T}
UμνTA = temp_UμνTA
#numofloops = calc_UμνTA!(UμνTA,"clover",U)
#Qclover = calc_Q(UμνTA,numofloops,U)
numofloops = calc_UμνTA!(UμνTA, "rect", U, temps)
Qrect = 2 * calc_Q(UμνTA, numofloops, U)
c1 = -1 / 12
c0 = 5 / 3
Q = c0 * Qclover + c1 * Qrect
return Q
end
function calc_UμνTA!(
temp_UμνTA,
name::String,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
loops_μν, numofloops = calc_loopset_μν_name(name, Dim)
calc_UμνTA!(temp_UμνTA, loops_μν, U, temps)
return numofloops
end
function calc_UμνTA!(
temp_UμνTA,
loops_μν,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
UμνTA = temp_UμνTA
for μ = 1:Dim
for ν = 1:Dim
if ν == μ
continue
end
evaluate_gaugelinks!(temps[1], loops_μν[μ, ν], U, temps[2:3])
Traceless_antihermitian!(UμνTA[μ, ν], temps[1])
#loopset = Loops(U,loops_μν[μ,ν])
#UμνTA[μ,ν] = evaluate_loops(loopset,U)
#UμνTA[μ,ν] = Traceless_antihermitian(UμνTA[μ,ν])
end
end
return
end
#=
implementation of topological charge is based on
https://arxiv.org/abs/1509.04259
=#
function calc_Q(UμνTA, numofloops, U::Array{<:AbstractGaugefields{NC,Dim},1}) where {NC,Dim}
Q = 0.0
if Dim == 4
ε(μ, ν, ρ, σ) = epsilon_tensor(μ, ν, ρ, σ)
else
error("Dimension $Dim is not supported")
end
for μ = 1:Dim
for ν = 1:Dim
if ν == μ
continue
end
Uμν = UμνTA[μ, ν]
for ρ = 1:Dim
for σ = 1:Dim
if ρ == σ
continue
end
Uρσ = UμνTA[ρ, σ]
s = tr(Uμν, Uρσ)
Q += ε(μ, ν, ρ, σ) * s / numofloops^2
end
end
end
end
return -Q / (32 * (π^2))
end
#topological charge
function epsilon_tensor(mu::Int, nu::Int, rho::Int, sigma::Int)
sign = 1 # (3) 1710.09474 extended epsilon tensor
if mu < 0
sign *= -1
mu = -mu
end
if nu < 0
sign *= -1
nu = -nu
end
if rho < 0
sign *= -1
rh = -rho
end
if sigma < 0
sign *= -1
sigma = -sigma
end
epsilon = zeros(Int, 4, 4, 4, 4)
epsilon[1, 2, 3, 4] = 1
epsilon[1, 2, 4, 3] = -1
epsilon[1, 3, 2, 4] = -1
epsilon[1, 3, 4, 2] = 1
epsilon[1, 4, 2, 3] = 1
epsilon[1, 4, 3, 2] = -1
epsilon[2, 1, 3, 4] = -1
epsilon[2, 1, 4, 3] = 1
epsilon[2, 3, 1, 4] = 1
epsilon[2, 3, 4, 1] = -1
epsilon[2, 4, 1, 3] = -1
epsilon[2, 4, 3, 1] = 1
epsilon[3, 1, 2, 4] = 1
epsilon[3, 1, 4, 2] = -1
epsilon[3, 2, 1, 4] = -1
epsilon[3, 2, 4, 1] = 1
epsilon[3, 4, 1, 2] = 1
epsilon[3, 4, 2, 1] = -1
epsilon[4, 1, 2, 3] = -1
epsilon[4, 1, 3, 2] = 1
epsilon[4, 2, 1, 3] = 1
epsilon[4, 2, 3, 1] = -1
epsilon[4, 3, 1, 2] = -1
epsilon[4, 3, 2, 1] = 1
return epsilon[mu, nu, rho, sigma] * sign
end
function calc_loopset_μν_name(name, Dim)
loops_μν = Array{Vector{Wilsonline{Dim}},2}(undef, Dim, Dim)
if name == "plaq"
numofloops = 1
for μ = 1:Dim
for ν = 1:Dim
loops_μν[μ, ν] = Wilsonline{Dim}[]
if ν == μ
continue
end
plaq = make_plaq(μ, ν, Dim = Dim)
push!(loops_μν[μ, ν], plaq)
end
end
elseif name == "clover"
numofloops = 4
for μ = 1:Dim
for ν = 1:Dim
loops_μν[μ, ν] = Wilsonline{Dim}[]
if ν == μ
continue
end
loops_μν[μ, ν] = make_cloverloops_topo(μ, ν, Dim = Dim)
end
end
elseif name == "rect"
numofloops = 8
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loops = Wilsonline{Dim}[]
loop_righttop = Wilsonline([(μ, 2), (ν, 1), (μ, -2), (ν, -1)])
loop_lefttop = Wilsonline([(ν, 1), (μ, -2), (ν, -1), (μ, 2)])
loop_rightbottom = Wilsonline([(ν, -1), (μ, 2), (ν, 1), (μ, -2)])
loop_leftbottom = Wilsonline([(μ, -2), (ν, -1), (μ, 2), (ν, 1)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loop_righttop = Wilsonline([(μ, 1), (ν, 2), (μ, -1), (ν, -2)])
loop_lefttop = Wilsonline([(ν, 2), (μ, -1), (ν, -2), (μ, 1)])
loop_rightbottom = Wilsonline([(ν, -2), (μ, 1), (ν, 2), (μ, -1)])
loop_leftbottom = Wilsonline([(μ, -1), (ν, -2), (μ, 1), (ν, 2)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loops_μν[μ, ν] = loops
end
end
else
error("$name is not supported")
end
return loops_μν, numofloops
end
function make_cloverloops_topo(μ, ν; Dim = 4)
loops = Wilsonline{Dim}[]
loop_righttop = Wilsonline([(μ, 1), (ν, 1), (μ, -1), (ν, -1)])
loop_lefttop = Wilsonline([(ν, 1), (μ, -1), (ν, -1), (μ, 1)])
loop_rightbottom = Wilsonline([(ν, -1), (μ, 1), (ν, 1), (μ, -1)])
loop_leftbottom = Wilsonline([(μ, -1), (ν, -1), (μ, 1), (ν, 1)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
return loops
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 13018 | mutable struct Topological_charge_measurement{Dim,TG,S} <: AbstractMeasurement
filename::String
_temporary_gaugefields::Vector{TG}
temp_UμνTA::Matrix{TG}
Dim::Int8
#factor::Float64
verbose_print::Union{Verbose_print,Nothing}
printvalues::Bool
Usmr::Array{TG,1}
smearing::S
smearing_type::String
numflow::Int64
function Topological_charge_measurement(
U::Vector{T};
Nflowsteps = 1,
eps_flow = 0.01,
smearing_type = "gradient_flow",
numflow = 10,
filename = nothing,
verbose_level = 2,
printvalues = true,
) where {T}
myrank = get_myrank(U)
Usmr = deepcopy(U)
if printvalues
verbose_print = Verbose_print(verbose_level, myid = myrank, filename = filename)
else
verbose_print = nothing
end
Dim = length(U)
temp_UμνTA = Array{T,2}(undef, Dim, Dim)
for μ = 1:Dim
for ν = 1:Dim
temp_UμνTA[ν, μ] = similar(U[1])
end
end
if smearing_type == "gradient_flow"
smearing = Gradientflow(U, Nflow = Nflowsteps, eps = eps_flow)
#smearing = Gradientflow(U,Nflow = Nflowsteps,eps = eps_flow)
S = typeof(smearing)
else
error("smearing_type = $smearing_type is not supported")
end
numg = 3
_temporary_gaugefields = Vector{T}(undef, numg)
_temporary_gaugefields[1] = similar(U[1])
for i = 2:numg
_temporary_gaugefields[i] = similar(U[1])
end
return new{Dim,T,S}(
filename,
_temporary_gaugefields,
temp_UμνTA,
Dim,
verbose_print,
printvalues,
Usmr,
smearing,
smearing_type,
numflow,
)
end
end
function measure(
m::M,
itrj,
U::Array{<:AbstractGaugefields{NC,Dim},1},
) where {M<:Topological_charge_measurement,NC,Dim}
temps = get_temporary_gaugefields(m)
temp1 = temps[1]
temp2 = temps[2]
eps_flow = m.smearing.eps
#Nflowsteps = m.smearing.Nflow
if m.printvalues
println_verbose_level2(U[1], "-----------------")
println_verbose_level2(U[1], "# epsilon for the Wilson flow is $(eps_flow)")
end
substitute_U!(m.Usmr, U)
τ = 0.0
if Dim == 4
comb = 6 #4*3/2
elseif Dim == 3
comb = 3
elseif Dim == 2
comb = 1
else
error("dimension $Dim is not supported")
end
factor = 1 / (comb * U[1].NV * NC)
plaq = calculate_Plaquette(U, temp1, temp2) * factor
Qplaq = calculate_topological_charge_plaq(m.Usmr, m.temp_UμνTA, temps)
#println("Qplaq = ",Qplaq)
Qclover = calculate_topological_charge_clover(m.Usmr, m.temp_UμνTA, temps)
Qimproved = calculate_topological_charge_improved(m.Usmr, m.temp_UμνTA, Qclover, temps)
#println("Qimproved = ",Qimproved)
clov = calculate_energy_density(m.Usmr, m.temp_UμνTA, temps)
if m.printvalues
println_verbose_level2(
U[1],
"$itrj $τ $plaq $clov $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #flow itrj flowtime plaq E Qplaq Qclov Qimproved",
)
#println(m.fp,"$itrj $τ $plaq $clov $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #flow itrj flowtime plaq E Qplaq Qclov Qimproved")
flush(stdout)
end
if m.smearing_type == "gradient_flow"
for iflow = 1:m.numflow#5000 # eps=0.01: t_flow = 50
flow!(m.Usmr, m.smearing)
plaq = calculate_Plaquette(m.Usmr, temp1, temp2) * factor
Qplaq = calculate_topological_charge_plaq(m.Usmr, m.temp_UμνTA, temps)
Qclover = calculate_topological_charge_clover(m.Usmr, m.temp_UμνTA, temps)
Qimproved =
calculate_topological_charge_improved(m.Usmr, m.temp_UμνTA, Qclover, temps)
clov = calculate_energy_density(m.Usmr, m.temp_UμνTA, temps)
#@time Q = calc_topological_charge(Usmr)
τ = iflow * eps_flow * m.smearing.Nflow
if m.printvalues
println_verbose_level2(
m.verbose_print,
"$itrj $(round(τ, digits=3)) $plaq $clov $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #flow itrj flowtime plaq E Qplaq Qclov Qimproved",
)
#println(m.fp,"$itrj $(round(τ, digits=3)) $plaq $clov $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #flow itrj flowtime plaq E Qplaq Qclov Qimproved")
#if iflow%10 == 0
flush(stdout)
end
end
else
error("$(m.smearig_type) is not suppoorted")
end
return Qclover
end
function calculate_topological_charge_plaq(U::Array{T,1}, temp_UμνTA, temps) where {T}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "plaq", U, temps)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calculate_topological_charge_clover(U::Array{T,1}, temp_UμνTA, temps) where {T}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "clover", U, temps)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calculate_topological_charge_improved(
U::Array{T,1},
temp_UμνTA,
Qclover,
temps,
) where {T}
UμνTA = temp_UμνTA
#numofloops = calc_UμνTA!(UμνTA,"clover",U)
#Qclover = calc_Q(UμνTA,numofloops,U)
numofloops = calc_UμνTA!(UμνTA, "rect", U, temps)
Qrect = 2 * calc_Q(UμνTA, numofloops, U)
c1 = -1 / 12
c0 = 5 / 3
Q = c0 * Qclover + c1 * Qrect
return Q
end
function calc_UμνTA!(
temp_UμνTA,
name::String,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
loops_μν, numofloops = calc_loopset_μν_name(name, Dim)
calc_UμνTA!(temp_UμνTA, loops_μν, U, temps)
return numofloops
end
function calc_UμνTA!(
temp_UμνTA,
loops_μν,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
UμνTA = temp_UμνTA
for μ = 1:Dim
for ν = 1:Dim
if ν == μ
continue
end
evaluate_gaugelinks!(temps[1], loops_μν[μ, ν], U, temps[2:3])
Traceless_antihermitian!(UμνTA[μ, ν], temps[1])
#loopset = Loops(U,loops_μν[μ,ν])
#UμνTA[μ,ν] = evaluate_loops(loopset,U)
#UμνTA[μ,ν] = Traceless_antihermitian(UμνTA[μ,ν])
end
end
return
end
#=
implementation of topological charge is based on
https://arxiv.org/abs/1509.04259
=#
function calc_Q(UμνTA, numofloops, U::Array{<:AbstractGaugefields{NC,Dim},1}) where {NC,Dim}
Q = 0.0
if Dim == 4
ε(μ, ν, ρ, σ) = epsilon_tensor(μ, ν, ρ, σ)
else
error("Dimension $Dim is not supported")
end
for μ = 1:Dim
for ν = 1:Dim
if ν == μ
continue
end
Uμν = UμνTA[μ, ν]
for ρ = 1:Dim
for σ = 1:Dim
if ρ == σ
continue
end
Uρσ = UμνTA[ρ, σ]
s = tr(Uμν, Uρσ)
Q += ε(μ, ν, ρ, σ) * s / numofloops^2
end
end
end
end
return -Q / (32 * (π^2))
end
#topological charge
function epsilon_tensor(mu::Int, nu::Int, rho::Int, sigma::Int)
sign = 1 # (3) 1710.09474 extended epsilon tensor
if mu < 0
sign *= -1
mu = -mu
end
if nu < 0
sign *= -1
nu = -nu
end
if rho < 0
sign *= -1
rh = -rho
end
if sigma < 0
sign *= -1
sigma = -sigma
end
epsilon = zeros(Int, 4, 4, 4, 4)
epsilon[1, 2, 3, 4] = 1
epsilon[1, 2, 4, 3] = -1
epsilon[1, 3, 2, 4] = -1
epsilon[1, 3, 4, 2] = 1
epsilon[1, 4, 2, 3] = 1
epsilon[1, 4, 3, 2] = -1
epsilon[2, 1, 3, 4] = -1
epsilon[2, 1, 4, 3] = 1
epsilon[2, 3, 1, 4] = 1
epsilon[2, 3, 4, 1] = -1
epsilon[2, 4, 1, 3] = -1
epsilon[2, 4, 3, 1] = 1
epsilon[3, 1, 2, 4] = 1
epsilon[3, 1, 4, 2] = -1
epsilon[3, 2, 1, 4] = -1
epsilon[3, 2, 4, 1] = 1
epsilon[3, 4, 1, 2] = 1
epsilon[3, 4, 2, 1] = -1
epsilon[4, 1, 2, 3] = -1
epsilon[4, 1, 3, 2] = 1
epsilon[4, 2, 1, 3] = 1
epsilon[4, 2, 3, 1] = -1
epsilon[4, 3, 1, 2] = -1
epsilon[4, 3, 2, 1] = 1
return epsilon[mu, nu, rho, sigma] * sign
end
# = = = calc energy density = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function calculate_energy_density(U::Array{T,1}, Wmat, temps) where {T<:AbstractGaugefields}
# Making a ( Ls × Lt) Wilson loop operator for potential calculations
WL = 0.0 + 0.0im
NV = U[1].NV
NC = U[1].NC
#Wmat = Array{T,2}(undef,4,4)
#
make_energy_density!(Wmat, U, temps) # make wilon loop operator and evaluate as a field, not traced.
WL = make_energy_density_core(Wmat, U, NV) # tracing over color and average over spacetime and x,y,z.
NDir = 4.0 * 3.0 / 2 # choice of 2 axis from 4.
return real(WL) / NV / NDir / NC / 8
end
function make_energy_density!(
Wmat,
U::Array{<:AbstractGaugefields{NC,Dim},1},
temps,
) where {NC,Dim}
W_operator, numofloops = calc_loopset_μν_name("clover", Dim)#make_Wilson_loop(Lt,Ls)
calc_large_wilson_loop!(Wmat, W_operator, U, temps)
return
end
function make_energy_density_core(
Wmat::Array{<:AbstractGaugefields{NC,Dim},2},
U::Array{T,1},
NV,
) where {T<:AbstractGaugefields,NC,Dim}
@assert Dim == 4
W = 0.0 + 0.0im
for μ = 1:Dim # all directions
for ν = 1:Dim
if μ == ν
continue
end
W += tr(Wmat[μ, ν], Wmat[μ, ν]) / 4
end
end
return W
end
function calc_loopset_μν_name(name, Dim)
loops_μν = Array{Vector{Wilsonline{Dim}},2}(undef, Dim, Dim)
if name == "plaq"
numofloops = 1
for μ = 1:Dim
for ν = 1:Dim
loops_μν[μ, ν] = Wilsonline{Dim}[]
if ν == μ
continue
end
plaq = make_plaq(μ, ν, Dim = Dim)
push!(loops_μν[μ, ν], plaq)
end
end
elseif name == "clover"
numofloops = 4
for μ = 1:Dim
for ν = 1:Dim
loops_μν[μ, ν] = Wilsonline{Dim}[]
if ν == μ
continue
end
loops_μν[μ, ν] = make_cloverloops(μ, ν, Dim = Dim)
end
end
elseif name == "rect"
numofloops = 8
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loops = Wilsonline{Dim}[]
loop_righttop = Wilsonline([(μ, 2), (ν, 1), (μ, -2), (ν, -1)])
loop_lefttop = Wilsonline([(ν, 1), (μ, -2), (ν, -1), (μ, 2)])
loop_rightbottom = Wilsonline([(ν, -1), (μ, 2), (ν, 1), (μ, -2)])
loop_leftbottom = Wilsonline([(μ, -2), (ν, -1), (μ, 2), (ν, 1)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loop_righttop = Wilsonline([(μ, 1), (ν, 2), (μ, -1), (ν, -2)])
loop_lefttop = Wilsonline([(ν, 2), (μ, -1), (ν, -2), (μ, 1)])
loop_rightbottom = Wilsonline([(ν, -2), (μ, 1), (ν, 2), (μ, -1)])
loop_leftbottom = Wilsonline([(μ, -1), (ν, -2), (μ, 1), (ν, 2)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loops_μν[μ, ν] = loops
end
end
else
error("$name is not supported")
end
return loops_μν, numofloops
end
function make_cloverloops(μ, ν; Dim = 4)
loops = Wilsonline{Dim}[]
loop_righttop = Wilsonline([(μ, 1), (ν, 1), (μ, -1), (ν, -1)])
loop_lefttop = Wilsonline([(ν, 1), (μ, -1), (ν, -1), (μ, 1)])
loop_rightbottom = Wilsonline([(ν, -1), (μ, 1), (ν, 1), (μ, -1)])
loop_leftbottom = Wilsonline([(μ, -1), (ν, -1), (μ, 1), (ν, 1)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
return loops
end
function calc_large_wilson_loop!(
temp_Wmat::Array{<:AbstractGaugefields{NC,Dim},2},
W_operator,
U::Array{T,1},
temps,
) where {T<:AbstractGaugefields,NC,Dim}
W = temp_Wmat
for μ = 1:Dim
for ν = 1:Dim
if μ == ν
continue
end
#println(typeof(μ)," ",typeof(ν))
#exit()
#loopset = Loops(U,W_operator[μ,ν])
evaluate_gaugelinks!(W[μ, ν], W_operator[μ, ν], U, temps)
#W[μ,ν] = evaluate_loops(loopset,U)
end
end
return
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 597 | module MPImodules
using MPI
import ..Simpleprint: println_rank0
MPI.Init()
const comm = MPI.COMM_WORLD
const myrank = MPI.Comm_rank(comm)
const nprocs = MPI.Comm_size(comm)
struct MPI_lattice
PEs::Vector{Int64}
end
const mpi_lattice = MPI_lattice([1, 1, 1, 1])
function get_myrank()
return myrank
end
function get_nprocs()
return nprocs
end
function println_rank0(jj...)
if myrank == 0
println(jj...)
end
end
function set_PEs(PEs)
for i = 1:length(PEs)
mpi_lattice.PEs[i] = PEs[i]
end
end
function get_PEs()
return mpi_lattice.PEs
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 77 | module Simpleprint
function println_rank0(jj...)
println(jj...)
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 382 | L = (4, 4, 4, 4)
β = 6
NTRACE = 3
#gparam = Setup_Gauge_action(β)
gparam = GaugeActionParam_standard(β, NTRACE)
BoundaryCondition = [1, 1, 1, -1]
Nwing = 1
initial = "cold"
NC = 3
hop = 0.141139#Hopping parameter
r = 1#Wilson term
eps = 1e-19
Dirac_operator = "Wilson"
MaxCGstep = 3000
fparam = FermiActionParam_Wilson(hop, r, eps, Dirac_operator, MaxCGstep)
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 6546 | module LQCD
import ..Universe_module: Univ
import ..Transform_oldinputfile: transform_to_toml
import ..Parameters_TOML: construct_Params_from_TOML
import ..AbstractUpdate_module: Updatemethod, update!
import Gaugefields:
Gradientflow,
println_verbose_level1,
get_myrank,
flow!,
save_binarydata,
save_textdata,
saveU
using QCDMeasurements
#import ..AbstractMeasurement_module:Measurement_methods,
#calc_measurement_values,measure,Plaquette_measurement,get_temporary_gaugefields
import QCDMeasurements: measure, Plaquette_measurement#, get_temporary_gaugefields
import ..LatticeQCD: Measurement_methods, calc_measurement_values
using Gaugefields
using InteractiveUtils
using Dates
using Random
import ..Simpleprint: println_rank0
function run_LQCD(filenamein::String; MPIparallel=false)
plaq = run_LQCD_file(filenamein, MPIparallel=MPIparallel)
return plaq
end
function run_LQCD_file(filenamein::String; MPIparallel=false)
if MPIparallel == true
println_rank0("test")
end
filename_head = splitext(filenamein)[1]
ext = splitext(filenamein)[end]
filename = filename_head * ".toml"
if ext == ".jl"
transform_to_toml(filenamein)
println_rank0("input file $filenamein is transformed to $filename")
elseif ext == ".toml"
else
@error "$filenamein is not supported. use a TOML format."
end
parameters = construct_Params_from_TOML(filename)
Random.seed!(parameters.randomseed)
univ = Univ(parameters)
println_verbose_level1(univ, "# ", pwd())
println_verbose_level1(univ, "# ", Dates.now())
io = IOBuffer()
InteractiveUtils.versioninfo(io)
versioninfo = String(take!(io))
println_verbose_level1(univ, versioninfo)
updatemethod = Updatemethod(parameters, univ)
eps_flow = parameters.eps_flow
numflow = parameters.numflow
Nflow = parameters.Nflow
dτ = Nflow * eps_flow
gradientflow = Gradientflow(univ.U, Nflow=1, eps=eps_flow)
measurements =
Measurement_methods(univ.U, parameters.measuredir, parameters.measurement_methods)
plaq_m = Plaquette_measurement(univ.U, printvalues=false)
i_plaq = 0
for i = 1:measurements.num_measurements
if isa(measurements.measurements[i], Plaquette_measurement)
i_plaq = i
plaq_m = measurements.measurements[i]
end
end
#if i_plaq == 0
# plaq_m = Plaquette_measurement(univ.U, printvalues=false)
#end
measurements_for_flow =
Measurement_methods(univ.U, parameters.measuredir, parameters.measurements_for_flow)
calc_measurement_values(measurements, 0, univ.U)
savedata = Savedata(
parameters.saveU_format,
parameters.saveU_dir,
parameters.saveU_every,
parameters.update_method,
univ.U,
)
value, runtime_all = @timed begin
numaccepts = 0
for itrj = parameters.initialtrj:parameters.Nsteps
println_verbose_level1(univ, "# itrj = $itrj")
accepted, runtime = @timed update!(updatemethod, univ.U)
println_verbose_level1(univ, "Update: Elapsed time $runtime [s]")
if accepted
numaccepts += 1
end
save_gaugefield(savedata, univ.U, itrj)
measurestrings = calc_measurement_values(measurements, itrj, univ.U)
#println(measurestrings)
#println("$(univ.verbose_print.fp)")
for st in measurestrings
println(univ.verbose_print.fp, st)
end
Usmr = deepcopy(univ.U)
for istep = 1:numflow
τ = istep * dτ
flow!(Usmr, gradientflow)
additional_string = "$itrj $istep $τ "
for i = 1:measurements_for_flow.num_measurements
interval = measurements_for_flow.intervals[i]
if istep % interval == 0
measure(
measurements_for_flow.measurements[i],
Usmr,
additional_string=additional_string,
)
end
end
end
println_verbose_level1(
univ,
"Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %",
)
flush(univ.verbose_print.fp)
end
#println(stdout,univ.verbose_print.fp)
#println("close file")
close(univ.verbose_print.fp)
for meas in measurements.measurements
close(meas.verbose_print.fp)
end
#println(stdout,univ.verbose_print.fp)
end
println_verbose_level1(univ, "Total Elapsed time $(runtime_all) [s]")
temps = QCDMeasurements.get_temporary_gaugefields(plaq_m)
plaq = real(calculate_Plaquette(univ.U, temps[1], temps[2]) * plaq_m.factor)
return plaq
end
mutable struct Savedata
issaved::Bool
saveU_format::Union{Nothing,String}
saveU_dir::String
saveU_every::Int64
itrjsavecount::Int64
function Savedata(saveU_format, saveU_dir, saveU_every, update_method, U)
itrjsavecount = 0
if saveU_format != nothing && update_method != "Fileloading"
itrj = 0
itrjstring = lpad(itrj, 8, "0")
println_verbose_level1(
U[1],
"save gaugefields U every $(saveU_every) trajectory",
)
#println("save gaugefields U every $(parameters.saveU_every) trajectory")
issaved = true
else
issaved = false
end
return new(issaved, saveU_format, saveU_dir, saveU_every, itrjsavecount)
end
end
function save_gaugefield(savedata::Savedata, U, itrj)
if savedata.issaved == false
return
end
if itrj % savedata.saveU_every == 0
savedata.itrjsavecount += 1
itrjstring = lpad(itrj, 8, "0")
if savedata.saveU_format == "JLD"
filename = savedata.saveU_dir * "/conf_$(itrjstring).jld2"
saveU(filename, U)
elseif savedata.saveU_format == "ILDG"
filename = savedata.saveU_dir * "/conf_$(itrjstring).ildg"
save_binarydata(U, filename)
elseif savedata.saveU_format == "BridgeText"
filename = savedata.saveU_dir * "/conf_$(itrjstring).txt"
save_textdata(U, filename)
else
error("$(savedata.saveU_format) is not supported")
end
end
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 21929 | module Mainrun
using Dates
using InteractiveUtils
import Gaugefields: Gradientflow, println_verbose_level1, get_myrank
import ..Universe_module: Univ, get_gauge_action, is_quenched
import ..AbstractMD_module: MD, runMD!
import ..AbstractUpdate_module: Updatemethod, update!
import ..AbstractMeasurement_module:
Plaquette_measurement,
measure,
Polyakov_measurement,
Topological_charge_measurement,
Energy_density_measurement,
Measurements_set,
measure_withflow
import ..LTK_universe:
Universe,
show_parameters,
make_WdagWmatrix,
calc_Action,
set_β!,
set_βs!,
get_β,
Wilsonloops_actions,
calc_looptrvalues,
calc_trainingdata,
calc_looptrvalues_site
import ..Actions: Setup_Gauge_action, Setup_Fermi_action, GaugeActionParam_autogenerator
import ..Measurements:
calc_plaquette,
measure_correlator,
Measurement,
calc_polyakovloop,
measure_chiral_cond,
calc_topological_charge,
measurements,
Measurement_set
import ..MD:
md_initialize!, MD_parameters_standard, md!, metropolis_update!, construct_MD_parameters
import ..System_parameters: Params
import ..Print_config: write_config
import ..Smearing: gradientflow!, calc_fatlink_APE, calc_stout
import ..ILDG_format: ILDG, load_gaugefield, load_gaugefield!, save_binarydata
import ..Bridge_format: load_BridgeText!, save_textdata
import ..Heatbath: heatbath!, overrelaxation!
import ..Wilsonloops:
make_plaq, make_loopforactions, make_plaqloops, make_rectloops, make_polyakovloops
import ..IOmodule: saveU, loadU, loadU!
import ..SLMC: SLMC_data, show_effbeta, update_slmcdata!
import ..Gaugefields: calc_GaugeAction
import ..Actions:
GaugeActionParam_standard, GaugeActionParam, GaugeActionParam_autogenerator
import ..Verbose_print: println_verbose1, println_verbose2, Verbose_1
import ..System_parameters: system, actions, md, cg, wilson, staggered, measurement
import ..Transform_oldinputfile: transform_to_toml
import ..Parameters_TOML: construct_Params_from_TOML
import ..LQCD: run_LQCD_file
function run_LQCD(filenamein::String)
plaq = run_LQCD_file(filenamein)
return plaq
end
#=
function run_LQCD()
parameters = parameterloading()
load_gaugefield()
univ = Universe(parameters)
run_LQCD!(univ,parameters)
return
end
=#
function run_LQCD(parameters::Params)
univ = Universe(parameters)
plaq = run_LQCD!(univ, parameters)
return plaq
end
function run_LQCD_new!(univ::Univ, parameters::Params)
println_verbose_level1(univ.U[1], "# " * pwd())
println_verbose_level1(univ.U[1], "# " * string(Dates.now()))
if get_myrank(univ.U) == 0
InteractiveUtils.versioninfo()
end
#md = MD(parameters,univ)
#update_Uold!(univ)
#substitute_U!(univ.Uold,univ.U)
gauge_action = get_gauge_action(univ)
quench = is_quenched(univ)
updatemethod = Updatemethod(
univ.U,
gauge_action,
parameters.update_method,
quench,
parameters.Δτ,
parameters.MDsteps,
fermi_action = univ.fermi_action,
SextonWeingargten = parameters.SextonWeingargten,
loadU_dir = parameters.loadU_dir,
loadU_format = parameters.loadU_format,
isevenodd = parameters.isevenodd,
β = parameters.β,
ITERATION_MAX = parameters.ITERATION_MAX,
numOR = parameters.numOR,
useOR = parameters.useOR,
)
#runMD!(univ.U,md)
eps_flow = 0.01
numflow = 500
Nflow = 1
meas = Measurements_set(univ.U, parameters.measuredir, parameters.measurement_methods)
gradientflow = Gradientflow(univ.U, Nflow = 1, eps = eps_flow)
#=
plaq_m = Plaquette_measurement(univ.U,filename="plaq.txt")
poly_m = Polyakov_measurement(univ.U,filename="poly.txt")
topo_m = Topological_charge_measurement(univ.U, filename="topo.txt",
TC_methods = ["plaquette","clover"])
energy_m = Energy_density_measurement(univ.U, filename="energydensity.txt")
=#
#=
plaq = measure(plaq_m,0,univ.U)
poly = measure(poly_m,0,univ.U)
topo = measure(topo_m,0,univ.U)
energy = measure(energy_m,0,univ.U)
=#
dτ = Nflow * eps_flow
measure(meas, 0, univ.U)
measure_withflow(meas, 0, univ.U, gradientflow, numflow, dτ)
for itrj = parameters.initialtrj:parameters.Nsteps
println_verbose_level1(univ.U[1], "# itrj = $itrj")
@time update!(updatemethod, univ.U)
measure(meas, itrj, univ.U)
measure_withflow(meas, itrj, univ.U, gradientflow, numflow, dτ)
#=
plaq = measure(plaq_m,itrj,univ.U)
poly = measure(poly_m,itrj,univ.U)
topo = measure(topo_m,itrj,univ.U)
energy = measure(energy_m,itrj,univ.U)
=#
end
error("error in run_LQCD_new!")
end
function run_LQCD!(univ::Universe, parameters::Params)
verbose = univ.kind_of_verboselevel
#println("# ",pwd())
#println("# ",Dates.now())
println_verbose1(verbose, "# ", pwd())
println_verbose1(verbose, "# ", Dates.now())
if univ.U[1].myrank == 0
InteractiveUtils.versioninfo()
end
#show_parameters(univ)
mdparams = construct_MD_parameters(parameters)
measset = Measurement_set(
univ,
parameters.measuredir,
measurement_methods = parameters.measurement_methods,
)
#if isdemo
#run_demo!(parameters,univ,measset)
#else
plaq = run_core!(parameters, univ, mdparams, measset)
#end
end
function checkfile(filename, list)
for name in list
end
end
function run_init_Fileloading!(parameters, univ, mdparams, meas, verbose)
ildg = nothing
println_verbose1(verbose, "load U from ", parameters.loadU_dir)
if parameters.loadU_format == "JLD"
datatype = "JLD"
filename_load =
filter(f -> contains(f, ".jld2"), readdir("./$(parameters.loadU_dir)"))
#filename_load = filter(f -> contains(f,".jld"),readdir("./$(parameters.loadU_dir)"))
elseif parameters.loadU_format == "ILDG"
datatype = "ILDG"
filename_load =
filter(f -> contains(f, "ildg"), readdir("./$(parameters.loadU_dir)"))
elseif parameters.loadU_format == "BridgeText"
datatype = "BridgeText"
filename_load =
filter(f -> contains(f, "txt"), readdir("./$(parameters.loadU_dir)"))
else
error("loadU_format should be JLD or ILDG")
end
if parameters.loadU_fromfile
data = readlines("./$(parameters.loadU_dir)/$(parameters.loadU_filename)")
datafromlist = String[]
for (i, datai) in enumerate(data)
havesharp = findfirst('#', datai)
#println("havesharp: $havesharp")
if havesharp == 1
datau = ""
elseif havesharp != nothing
datau = datai[begin:havesharp-1]
else
datau = datai
end
datau = strip(datau)
if datatype == "JLD"
doescontains = contains(datau, ".jld2")
#doescontains = contains(datau,".jld")
elseif datatype == "ILDG"
doescontains = contains(datau, ".ildg")
elseif datatype == "BridgeText"
doescontains = contains(datau, ".txt")
end
#println(doescontains)
if doescontains
if isfile("./$(parameters.loadU_dir)/$(datau)")
push!(datafromlist, datau)
else
println(
"Warning! $(datau) does not exist in $(parameters.loadU_dir)! We ignore this.",
)
end
#println(datau)
end
end
filename_load = datafromlist
#println(datafromlist)
end
#exit()
#filename = filter(f -> isfile(f), readdir("./$(parameters.loadU_dir)"))
#println(filename)
numfiles = length(filename_load)
println_verbose1(verbose, "Num of files = $numfiles")
for file in filename_load
println_verbose1(verbose, "$file")
end
#println("Num of files = $numfiles")
Nsteps = numfiles - 1
filename_i = filename_load[1]
if parameters.loadU_format == "JLD"
loadU!(parameters.loadU_dir * "/" * filename_i, univ.U)
elseif parameters.loadU_format == "ILDG"
ildg = ILDG(parameters.loadU_dir * "/" * filename_i)
i = 1
load_gaugefield!(univ.U, i, ildg, parameters.L, parameters.NC)
elseif parameters.loadU_format == "BridgeText"
load_BridgeText!(
parameters.loadU_dir * "/" * filename_i,
univ.U,
parameters.L,
parameters.NC,
)
end
return Nsteps, numfiles, filename_load, ildg
end
function print_trainingdata(trs, Sg, Sf)
for i = 1:length(trs)
print(real(trs[i]), "\t", imag(trs[i]), "\t")
end
println(Sg, "\t", Sf, "\t #trainingdata")
end
function print_trainingdata(fp, trs, Sg, Sf)
for i = 1:length(trs)
print(fp, real(trs[i]), "\t", imag(trs[i]), "\t")
end
println(fp, Sg, "\t", Sf, "\t #trainingdata")
end
function print_trainingdata_site(fp, trs, Sg, Sf)
return
numloops, NX, NY, NZ, NT = size(trs)
println(fp, Sg, "\t", Sf, " $numloops $NX $NY $NZ $NT")
for it = 1:NT
for iz = 1:NZ
for iy = 1:NY
for ix = 1:NX
print(fp, "$ix $iy $iz $it ")
for i = 1:numloops
print(
fp,
real(trs[i, ix, iy, iz, it]),
"\t",
imag(trs[i, ix, iy, iz, it]),
"\t",
)
end
println(fp, "\t")
end
end
end
end
#println(fp,Sg,"\t",Sf,"\t #trainingdata_site")
end
function run_core!(parameters, univ, mdparams, meas)
# If an algorithm uses fermion integration (trlog(D+m)),
# it is flagged
if parameters.update_method == "IntegratedHMC" ||
parameters.update_method == "SLHMC" ||
parameters.update_method == "IntegratedHB" ||
parameters.update_method == "SLMC"
isIntegratedFermion = true
else
isIntegratedFermion = false
end
verbose = univ.kind_of_verboselevel
if parameters.integratedFermionAction
loopactions = Wilsonloops_actions(univ)
trainingfp = open(parameters.training_data_name, "w")
trainingfp2 = open("trainset.txt", "w")
couplinglist = loopactions.couplinglist
print(trainingfp, "# ")
for i = 1:loopactions.numloops
print(
trainingfp,
"Re($(loopactions.couplinglist[i])) Im($(loopactions.couplinglist[i])) ",
)
end
println(trainingfp, "Sg Sf")
#println(trainingfp,"#Re(plaq) Im(plaq) Re(rect) Im(rect) Re(polyx) Im(polyy) Re(polyz) Im(polyz) Re(polyt) Im(polyt) Sg Sf")
end
Nsteps = parameters.Nsteps
if parameters.update_method == "Fileloading"
Nsteps, numfiles, filename_load, ildg =
run_init_Fileloading!(parameters, univ, mdparams, meas, verbose)
elseif parameters.update_method == "SLHMC" || parameters.update_method == "SLMC"
#slmc_data = SLMC_data(1,univ.NC)
if typeof(univ.gparam) == GaugeActionParam_autogenerator
slmc_data = SLMC_data(length(univ.gparam.couplinglist), univ.NC)
else
slmc_data = SLMC_data(1, univ.NC)
end
end
numaccepts = 0
if (parameters.Nthermalization ≤ 0 && parameters.initialtrj == 1) ||
parameters.update_method == "Fileloading"
plaq, poly =
measurements(0, univ.U, univ, meas; verbose = univ.kind_of_verboselevel) # check consistency of preparation.
end
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
if parameters.saveU_format != nothing && parameters.update_method != "Fileloading"
itrj = 0
itrjstring = lpad(itrj, 8, "0")
itrjsavecount = 0
println_verbose1(
verbose,
"save gaugefields U every $(parameters.saveU_every) trajectory",
)
#println("save gaugefields U every $(parameters.saveU_every) trajectory")
end
if isIntegratedFermion
Sfold = nothing
end
for itrj = parameters.initialtrj:Nsteps
println("# itrj = $itrj")
# Update for different updaters
# HMC: Hybrid Monte-Carlo
if parameters.update_method == "HMC"
Hold = md_initialize!(univ)
@time Hnew = md!(univ, mdparams)
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
accept = metropolis_update!(univ, Hold, Hnew)
numaccepts += ifelse(accept, 1, 0)
#println("Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %")
println_verbose1(
verbose,
"Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %",
)
# Heatbath
elseif parameters.update_method == "Heatbath"
@time heatbath!(univ)
if parameters.useOR
for ior = 1:parameters.numOR
@time overrelaxation!(univ)
end
end
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
# Integrated HMC
# HMC with S = -tr(log(D+m)), instead of the pseudo-fermins
elseif parameters.update_method == "IntegratedHMC"
Sgold = md_initialize!(univ)
@time Sgnew, Sfnew, Sgold, Sfold = md!(univ, Sfold, Sgold, mdparams)
Sold = Sgold + Sfold
Snew = Sgnew + Sfnew
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
accept = metropolis_update!(univ, Sold, Snew)
numaccepts += ifelse(accept, 1, 0)
#println("Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %")
println_verbose1(
verbose,
"Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %",
)
Sfold = ifelse(accept, Sfnew, Sfold)
# File loading
# This actually loads files, and performs measurements
elseif parameters.update_method == "Fileloading"
filename_i = filename_load[itrj+1]
if parameters.loadU_format == "JLD"
loadU!(parameters.loadU_dir * "/" * filename_i, univ.U)
elseif parameters.loadU_format == "ILDG"
ildg = ILDG(parameters.loadU_dir * "/" * filename_i)
i = 1
load_gaugefield!(univ.U, i, ildg, parameters.L, parameters.NC)
elseif parameters.loadU_format == "BridgeText"
load_BridgeText!(
parameters.loadU_dir * "/" * filename_i,
univ.U,
parameters.L,
parameters.NC,
)
end
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
#loadU!(parameters.loadU_dir*"/"*filename_i,univ.U)
# SLHMC: Self-learing Hybrid Monte-Carlo
# This uses gluonic effective action for MD
elseif parameters.update_method == "SLHMC"
Sgold = md_initialize!(univ)
@time Sgnew, Sfnew, Sgold, Sfold, plaq = md!(univ, Sfold, Sgold, mdparams)
Sold = Sgold + Sfold
Snew = Sgnew + Sfnew
elseif parameters.update_method == "SLMC"
Sgold = md_initialize!(univ)
@time Sgnew, Sfnew, Sgeffnew, Sgold, Sfold, Sgeffold =
md!(univ, Sfold, Sgold, mdparams)
Sold = Sgold + Sfold - Sgeffold
Snew = Sgnew + Sfnew - Sgeffnew
elseif parameters.update_method == "IntegratedHB"
Sgold = md_initialize!(univ)
@time Sgnew, Sfnew, Sgeffnew, Sgold, Sfold, Sgeffold =
md!(univ, Sfold, Sgold, mdparams)
Sold = Sgold + Sfold - Sgeffold
Snew = Sgnew + Sfnew - Sgeffnew
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
accept = metropolis_update!(univ, Sold, Snew)
numaccepts += ifelse(accept, 1, 0)
#println("Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %")
println_verbose1(
verbose,
"Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %",
)
Sfold = ifelse(accept, Sfnew, Sfold)
end
if parameters.update_method == "SLHMC" || parameters.update_method == "SLMC"
S2, plaqetc = calc_GaugeAction(univ)
plaq = plaqetc
#S2,plaq = calc_Action(univ)
if typeof(plaqetc) == Float64
plaqetc = [plaq]
end
#println(plaq)
#exit()
Sf = Sfnew
outputdata = univ.gparam.β * plaqetc[1] * slmc_data.factor + Sf
update_slmcdata!(slmc_data, plaqetc, outputdata)
βeffs, Econst, IsSucs = show_effbeta(slmc_data, univ.gparam)
println("βeffs = ", βeffs)
println_verbose1(verbose, "#S = ", outputdata)
println_verbose1(
verbose,
"#Estimated Seff = ",
Econst + sum(βeffs[:] .* plaqetc[:]) * slmc_data.factor,
)
if IsSucs && itrj ≥ parameters.firstlearn
mdparams.βeff = βeffs[:]
end
if parameters.integratedFermionAction
trs, Sg, Sf = calc_trainingdata(loopactions, univ)
print_trainingdata(trs, Sg, Sf)
print_trainingdata(trainingfp, trs, Sg, Sf)
trs_site = calc_looptrvalues_site(loopactions, univ)
print_trainingdata_site(trainingfp2, trs_site, Sg, Sf)
end
accept = metropolis_update!(univ, Sold, Snew)
numaccepts += ifelse(accept, 1, 0)
println_verbose1(
verbose,
"Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %",
)
#println("Acceptance $numaccepts/$itrj : $(round(numaccepts*100/itrj)) %")
Sfold = ifelse(accept, Sfnew, Sfold)
end# update end
if (itrj ≥ parameters.Nthermalization) || parameters.update_method == "Fileloading"
plaq, poly =
measurements(itrj, univ.U, univ, meas; verbose = univ.kind_of_verboselevel)
end
if itrj % parameters.saveU_every == 0 &&
parameters.saveU_format != nothing &&
parameters.update_method != "Fileloading"
itrjsavecount += 1
itrjstring = lpad(itrj, 8, "0")
#itrjstring = lpad(itrjsavecount,8,"0")
if parameters.saveU_format == "JLD"
#filename = parameters.saveU_dir*"/conf_$(itrjstring).jld"
filename = parameters.saveU_dir * "/conf_$(itrjstring).jld2"
saveU(filename, univ.U)
elseif parameters.saveU_format == "ILDG"
filename = parameters.saveU_dir * "/conf_$(itrjstring).ildg"
save_binarydata(univ.U, filename)
elseif parameters.saveU_format == "BridgeText"
filename = parameters.saveU_dir * "/conf_$(itrjstring).txt"
save_textdata(univ.U, filename)
else
error("$(parameters.saveU_format) is not supported")
end
end
println_verbose1(verbose, "-------------------------------------")
#println("-------------------------------------")
flush(stdout)
flush(verbose)
if parameters.integratedFermionAction
flush(trainingfp)
flush(trainingfp2)
end
end
if parameters.integratedFermionAction
close(trainingfp)
end
return plaq
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 32726 | module Parameter_structs
using REPL.TerminalMenus
import ..Simpleprint: println_rank0
@enum SmearingMethod Nosmearing = 1 STOUT = 2
import QCDMeasurements:
Fermion_parameters,
Quench_parameters,
Wilson_parameters,
Staggered_parameters,
Domainwall_parameters,
initialize_fermion_parameters,
Measurement_parameters,
Plaq_parameters,
Poly_parameters,
Wilson_loop_parameters,
Pion_parameters,
ChiralCondensate_parameters,
Energy_density_parameters,
TopologicalCharge_parameters,
initialize_measurement_parameters,
prepare_measurement_from_dict,
construct_Measurement_parameters_from_dict
#=
Base.@kwdef mutable struct System
BoundaryCondition::Vector{Int64} = [1, 1, 1, -1]
Nwing::Int64 = 1
verboselevel::Int64 = 1
randomseed::Int64 = 111
L::Vector{Int64} = [4, 4, 4, 4]
NC::Int64 = 3
β::Float64 = 5.7
initialtrj::Int64 = 1
loadU_format::String = "nothing"
update_method::String = "HMC"
loadU_dir::String = ""
loadU_fromfile::Bool = false
loadU_filename::String = ""
initial::String = "cold"
Dirac_operator::String = "nothing"
quench::Bool = true
smearing_for_fermion::String = "nothing"
stout_numlayers::Union{Nothing,Int64} = nothing
stout_ρ::Union{Nothing,Array{Float64,1}} = nothing
stout_loops::Union{Nothing,Array{String,1}} = nothing
useOR::Bool = false #Over relaxation method for heatbath updates
numOR::Int64 = 0 #number of Over relaxation method
βeff::Float64 = 5.7 #effective beta for SLHMC
firstlearn::Int64 = 1
Nthermalization::Int64 = 0 #number of updates without measuring
#smearing::Smearing_parameters = NoSmearing_parameters()
log_dir::String = ""
logfile::String = ""
saveU_format::String = "nothing"
saveU_dir::String = ""
saveU_every::Int64 = 1
isevenodd = true
end
=#
const important_parameters = [
"L",
"β",
"update_method",
"MDsteps",
"Δτ",
"Dirac_operator",
"fermion_parameters",
"methodname",
"measurement_basedir",
"hasgradientflow",
"measurement_dir",
"kinds_of_topological_charge",
"measurements_for_flow",
"gradientflow_measurements",
]
function check_important_parameters(key)
findornot = findfirst(x -> x == key, important_parameters)
if findornot == nothing
return false
else
return true
end
end
struct2dict(x::T) where {T} =
Dict{String,Any}(string(fn) => getfield(x, fn) for fn ∈ fieldnames(T))
function generate_printlist(x::Type)
pnames = fieldnames(x)
plist = String[]
for i = 1:length(pnames)
push!(plist, String(pnames[i]))
end
return plist
end
# Physical setting
Base.@kwdef mutable struct Print_Physical_parameters
L::Vector{Int64} = [4, 4, 4, 4]
β::Float64 = 5.7
NC::Int64 = 3
Nthermalization::Int64 = 0
Nsteps::Int64 = 100
initial::String = "cold"
initialtrj::Int64 = 1
update_method::String = "HMC"
useOR::Bool = false
numOR::Int64 = 0
Nwing::Int64 = 0
end
# Physical setting(fermions)
Base.@kwdef mutable struct Print_Fermions_parameters
quench::Bool = true
Dirac_operator::Union{Nothing,String} = nothing
Clover_coefficient::Float64 = 1.5612
r::Float64 = 1
hop::Float64 = 0.141139
Nf::Int64 = 4
mass::Float64 = 0.5
Domainwall_M::Union{Nothing,Float64} = nothing
Domainwall_m::Union{Nothing,Float64} = nothing
Domainwall_L5::Union{Nothing,Int64} = nothing
BoundaryCondition::Array{Int64,1} = [1, 1, 1, -1]
smearing_for_fermion::String = "nothing"
stout_numlayers::Union{Nothing,Int64} = nothing
stout_ρ::Union{Nothing,Array{Float64,1}} = nothing
stout_loops::Union{Nothing,Array{String,1}} = nothing
# These three params should be revised.
M::Union{Nothing,Float64} = nothing
m::Union{Nothing,Float64} = nothing
N5::Union{Nothing,Int64} = nothing
end
# System Control
Base.@kwdef mutable struct Print_System_control_parameters
log_dir::String = ""
logfile::String = ""
loadU_format::Union{Nothing,String} = nothing
loadU_dir::String = ""
loadU_fromfile::Bool = false
loadU_filename::String = ""
saveU_dir::String = ""
saveU_format::Union{String,Nothing} = nothing
saveU_every::Int64 = 1
verboselevel::Int64 = 1
randomseed::Int64 = 111
measurement_basedir::String = ""
measurement_dir::String = ""
julian_random_number::Bool = false
isevenodd = true
hasgradientflow::Bool = false
eps_flow::Float64 = 0.01
numflow::Int64 = 100
Nflow::Int64 = 1
end
# HMC related
Base.@kwdef mutable struct Print_HMCrelated_parameters
Δτ::Float64 = 0.05
SextonWeingargten::Bool = false
N_SextonWeingargten::Int64 = 2
MDsteps::Int64 = 20
eps::Float64 = 1e-19
MaxCGstep::Int64 = 3000
end
# Gradient Flow
Base.@kwdef mutable struct Print_Gradientflow_parameters
hasgradientflow::Bool = false
eps_flow::Float64 = 0.01
numflow::Int64 = 100
Nflow::Int64 = 1
#gradientflow_measurements::Vector{Dict} = []
end
# Action parameter for SLMC
struct Print_SLMC_parameters
βeff::Union{Float64,Array{Float64,1}}
firstlearn::Int64
use_autogeneratedstaples::Bool
couplingcoeff::Array{Float64,1}
couplinglist::Array{String,1}
coupling_loops::Union{Nothing,Array{Array{Array{Tuple{Int,Int},1},1},1}}
end
# Measurement set
Base.@kwdef mutable struct Print_Measurement_parameters
measurement_methods::Array{Dict,1} = Dict[]
end
const printlist_physical = generate_printlist(Print_Physical_parameters)
const printlist_fermions = generate_printlist(Print_Fermions_parameters)
const printlist_systemcontrol = generate_printlist(Print_System_control_parameters)
const printlist_HMCrelated = generate_printlist(Print_HMCrelated_parameters)
const printlist_parameters_SLMC = generate_printlist(Print_SLMC_parameters)
const printlist_measurement = generate_printlist(Print_Measurement_parameters)
Base.@kwdef mutable struct Action
use_autogeneratedstaples::Bool = false
couplinglist::Vector{String} = []
couplingcoeff::Vector{ComplexF64} = []
end
Base.@kwdef mutable struct MD
MDsteps::Int64 = 20
Δτ::Float64 = 1 / 20
SextonWeingargten::Bool = false
N_SextonWeingargten::Int64 = 2
end
abstract type Smearing_parameters end
Base.@kwdef mutable struct NoSmearing_parameters <: Smearing_parameters end
const kindsof_loops = [
"plaquette",
"rectangular",
"chair",
"polyakov_x",
"polyakov_y",
"polyakov_z",
"polyakov_t",
]
Base.@kwdef mutable struct Stout_parameters <: Smearing_parameters
numlayers::Int64 = 1
ρ::Vector{Float64} = []
stout_loops::Union{Nothing,Array{String,1}} = nothing
end
#=
abstract type Fermion_parameters end
Base.@kwdef mutable struct Quench_parameters <: Fermion_parameters
Dirac_operator::String = "nothing"
end
Base.@kwdef mutable struct Wilson_parameters <: Fermion_parameters
Dirac_operator::String = "Wilson"
hop::Float64 = 0.141139
r::Float64 = 1
hasclover::Bool = false
Clover_coefficient::Float64 = 1.5612
end
Base.@kwdef mutable struct Staggered_parameters <: Fermion_parameters
Dirac_operator::String = "Staggered"
mass::Float64 = 0.5 #mass
Nf::Int64 = 2 #flavor
end
Base.@kwdef mutable struct Domainwall_parameters <: Fermion_parameters
Dirac_operator::String = "Domainwall"
Domainwall_L5::Int64 = 4
Domainwall_M::Float64 = -1 #mass for Wilson operator which should be negative
Domainwall_m::Float64 = 0.1 #physical mass
end
function initialize_fermion_parameters(fermion_type)
if fermion_type == "nothing"
fermion_parameter = Quench_parameters()
elseif fermion_type == "Wilson" || fermion_type == "WilsonClover"
fermion_parameter = Wilson_parameters()
elseif fermion_type == "Staggered"
fermion_parameter = Staggered_parameters()
elseif fermion_type == "Domainwall"
fermion_parameter = Domainwall_parameters()
else
@error "$fermion_type is not implemented in parameter_structs.jl"
end
return fermion_parameter
end
=#
Base.@kwdef mutable struct ConjugateGradient
eps::Float64 = 1e-19
MaxCGstep::Int64 = 3000
end
#=
abstract type Measurement_parameters end
Base.@kwdef mutable struct Plaq_parameters <: Measurement_parameters
#common::Measurement_common_parameters = Measurement_common_parameters()
methodname::String = "Plaquette"
measure_every::Int64 = 10
fermiontype::String = "nothing"
verbose_level::Int64 = 2
printvalues::Bool = true
end
Base.@kwdef mutable struct Poly_parameters <: Measurement_parameters
methodname::String = "Polyakov_loop"
measure_every::Int64 = 10
fermiontype::String = "nothing"
verbose_level::Int64 = 2
printvalues::Bool = true
#common::Measurement_common_parameters = Measurement_common_parameters()
end
Base.@kwdef mutable struct Energy_density_parameters <: Measurement_parameters
methodname::String = "Energy_density"
measure_every::Int64 = 10
fermiontype::String = "nothing"
verbose_level::Int64 = 2
printvalues::Bool = true
#common::Measurement_common_parameters = Measurement_common_parameters()
end
Base.@kwdef mutable struct TopologicalCharge_parameters <: Measurement_parameters
methodname::String = "Topological_charge"
measure_every::Int64 = 10
fermiontype::String = "nothing"
#common::Measurement_common_parameters = Measurement_common_parameters()
#numflow::Int64 = 1 #number of flows
#Nflowsteps::Int64 = 1
#eps_flow::Float64 = 0.01
verbose_level::Int64 = 2
printvalues::Bool = true
kinds_of_topological_charge::Vector{String} = ["plaquette","clover"]
end
Base.@kwdef mutable struct ChiralCondensate_parameters <: Measurement_parameters
#common::Measurement_common_parameters = Measurement_common_parameters()
methodname::String = "Chiral_condensate"
measure_every::Int64 = 10
fermiontype::String = "Staggered"
Nf::Int64 = 4
eps::Float64 = 1e-19
mass::Float64 = 0.5
MaxCGstep::Int64 = 3000
smearing_for_fermion::String = "nothing"
stout_numlayers::Union{Nothing,Int64} = nothing
stout_ρ::Union{Nothing,Array{Float64,1}} = nothing
stout_loops::Union{Nothing,Array{String,1}} = nothing
verbose_level::Int64 = 2
printvalues::Bool = true
Nr = 10
#smearing::Smearing_parameters = Stout_parameters()
end
Base.@kwdef mutable struct Pion_parameters <: Measurement_parameters
#common::Measurement_common_parameters = Measurement_common_parameters()
methodname::String = "Pion_correlator"
measure_every::Int64 = 10
fermiontype::String = "Wilson"
eps::Float64 = 1e-19
MaxCGstep::Int64 = 3000
smearing_for_fermion::String = "nothing"
stout_numlayers::Union{Nothing,Int64} = nothing
stout_ρ::Union{Nothing,Array{Float64,1}} = nothing
stout_loops::Union{Nothing,Array{String,1}} = nothing
#smearing::Smearing_parameters = NoSmearing_parameters()
fermion_parameters::Fermion_parameters = Wilson_parameters()
verbose_level::Int64 = 2
printvalues::Bool = true
end
Base.@kwdef mutable struct Wilson_loop_parameters <: Measurement_parameters
#common::Measurement_common_parameters = Measurement_common_parameters()
methodname::String = "Wilson_loop"
measure_every::Int64 = 10
fermiontype::String = "nothing"
verbose_level::Int64 = 2
printvalues::Bool = true
Tmax::Int64 = 4
Rmax::Int64 = 4
end
=#
#=
function initialize_measurement_parameters(methodname)
if methodname == "Plaquette"
method = Plaq_parameters()
elseif methodname == "Polyakov_loop"
method = Poly_parameters()
elseif methodname == "Topological_charge"
method = TopologicalCharge_parameters()
elseif methodname == "Chiral_condensate"
method = ChiralCondensate_parameters()
elseif methodname == "Pion_correlator"
method = Pion_parameters()
elseif methodname == "Energy_density"
method = Energy_density_parameters()
elseif methodname == "Wilson_loop"
method = Wilson_loop_parameters()
else
@error "$methodname is not implemented in parameter_structs.jl"
end
return method
end
=#
Base.@kwdef mutable struct Measurement_parameterset
measurement_methods::Vector{Measurement_parameters} = []
#measurement_basedir::String = ""
#measurement_dir::String = ""
end
function transform_measurement_dictvec(value)
#println(value)
flow_dict = Dict()
nummeasure = length(value)
value_out = Vector{Measurement_parameters}(undef, nummeasure)
hasgradientflow = false
for i = 1:nummeasure
if haskey(value[i], "methodname")
if value[i]["methodname"] == "Topological_charge"
hasgradientflow = true
value_out[i] =
transform_topological_charge_measurement!(flow_dict, value[i])
else
value_out[i] = construct_Measurement_parameters_from_dict(value[i])
end
else
@error("method name in measurement should be set")
end
end
return value_out, flow_dict, hasgradientflow
end
#=
function construct_Measurement_parameters_from_dict(value_i::Dict)
#println(value)
@assert haskey(value_i, "methodname") "methodname should be set in measurement."
methodname = value_i["methodname"]
method = initialize_measurement_parameters(methodname)
method_dict = struct2dict(method)
#println("value_i ",value_i)
if haskey(value_i, "Dirac_operator")
fermiontype = value_i["Dirac_operator"]
else
if haskey(value_i, "fermiontype")
if value_i["fermiontype"] == nothing
fermiontype = "nothing"
else
fermiontype = value_i["fermiontype"]
end
else
fermiontype = "nothing"
end
end
#println("fermiontype $fermiontype")
fermion_parameters = initialize_fermion_parameters(fermiontype)
fermion_parameters_dict = struct2dict(fermion_parameters)
#println("femriontype ",fermiontype)
for (key_ii, value_ii) in value_i
#println("$key_ii $value_ii")
if haskey(method_dict, key_ii)
if typeof(value_ii) != Nothing
keytype = typeof(getfield(method, Symbol(key_ii)))
setfield!(method, Symbol(key_ii), keytype(value_ii))
end
else
if haskey(fermion_parameters_dict, key_ii)
#println("fermion $key_ii $value_ii")
keytype = typeof(getfield(fermion_parameters, Symbol(key_ii)))
setfield!(fermion_parameters, Symbol(key_ii), keytype(value_ii))
else
@warn "$key_ii is not found! in $(typeof(method))"
end
end
end
if haskey(method_dict, "fermion_parameters")
setfield!(method, Symbol("fermion_parameters"), fermion_parameters)
end
value_out = deepcopy(method)
return value_out
end
=#
function transform_topological_charge_measurement!(flow_dict, measurement)
@assert haskey(measurement, "methodname") "method name in measurement should be set $(measurement)"
@assert measurement["methodname"] == "Topological_charge" "this function is for topological charge measurement"
measurement_revised = Dict()
for (key, value) in measurement
#println((key,value))
if key == "Nflowsteps"
flow_dict["Nflow"] = value
elseif key == "numflow"
flow_dict["numflow"] = value
elseif key == "eps_flow"
flow_dict["eps_flow"] = value
else
measurement_revised[key] = value
end
end
measurement_revised["fermiontype"] = "nothing"
#println(measurement_revised)
valuem = construct_Measurement_parameters_from_dict(measurement_revised)
flow_dict["measurements_for_flow"] = Dict()
flow_dict["measurements_for_flow"]["Topological_charge"] = measurement_revised
return valuem
end
function Plaq_parameters_interactive()
method = Plaq_parameters()
println_rank0("You measure Plaquette loops")
method.methodname = "Plaquette"
method.measure_every =
parse(Int64, Base.prompt("How often measure Plaquette loops?", default = "1"))
return method
end
function Poly_parameters_interactive()
method = Poly_parameters()
println_rank0("You measure Polyakov loops")
method.methodname = "Polyakov_loop"
method.measure_every =
parse(Int64, Base.prompt("How often measure Polyakov loops?", default = "1"))
return method
end
function Wilson_loop_parameters_interactive(L)
method = Wilson_loop_parameters()
println_rank0("You measure RxT Wilson loops")
method.methodname = "Wilson_loop"
Rmax0 = min(L[1], L[2], L[3]) ÷ 2
Tmax0 = L[4] ÷ 2
method.measure_every =
parse(Int64, Base.prompt("How often measure Wilson loops?", default = "1"))
method.Rmax =
parse(Int64, Base.prompt("maximum R for RxT Wilson loop?", default = "$Rmax0"))
method.Tmax =
parse(Int64, Base.prompt("maximum T for RxT Wilson loop??", default = "$Tmax0"))
return method
end
function Energy_density_parameters_interactive()
method = Energy_density_parameters()
println_rank0("You measure Energy density")
method.methodname = "Energy_density"
method.measure_every =
parse(Int64, Base.prompt("How often measure Plaquette loops?", default = "1"))
return method
end
function TopologicalCharge_parameters_interactive()
method = TopologicalCharge_parameters()
println_rank0("You measure a topological charge")
method.methodname = "Topological_charge"
method.measure_every =
parse(Int64, Base.prompt("How often measure a topological charge?", default = "1"))
#=
method.numflow = parse(
Int64,
Base.prompt(
"How many times do you want to flow gauge fields to measure the topological charge?",
default = "10",
),
)
=#
#=
Nflowsteps = 1#L[1]
eps_flow = 0.01
method.Nflowsteps = parse(Int64, Base.prompt("Nflowsteps?", default = "$Nflowsteps"))
method.eps_flow = parse(Float64, Base.prompt("eps_flow?", default = "$eps_flow"))
=#
return method
end
function MD_interactive(; Dirac_operator = nothing)
md = MD()
println_rank0("Choose parameters for MD")
MDsteps = parse(Int64, Base.prompt("Input MD steps", default = "20"))
Δτ = parse(Float64, Base.prompt("Input Δτ", default = "$(1/MDsteps)"))
md.MDsteps = MDsteps
md.Δτ = Δτ
if Dirac_operator != nothing
SW = request(
"Use SextonWeingargten method? multi-time scale",
RadioMenu(["false", "true"]),
)
SextonWeingargten = ifelse(SW == 1, false, true)
if SextonWeingargten
N_SextonWeingargten = parse(
Int64,
Base.prompt("Input number of SextonWeingargten steps", default = "2"),
)
else
N_SextonWeingargten = 2
end
md.SextonWeingargten = SextonWeingargten
md.N_SextonWeingargten = N_SextonWeingargten
end
return md
end
function Stout_parameters_interactive()
stout = Stout_parameters()
stout_menu = MultiSelectMenu(kindsof_loops)
choices =
request("Select the kinds of loops you want to add in stout smearing:", stout_menu)
count = 0
ρs = Float64[]
loops = String[]
for i in choices
count += 1
ρ = parse(
Float64,
Base.prompt("coefficient ρ for $(kindsof_loops[i]) loop?", default = "0.1"),
)
push!(ρs, ρ)
push!(loops, kindsof_loops[i])
end
stout.ρ = ρs
stout.stout_loops = loops
return stout
end
function CG_params_interactive()
cg = ConjugateGradient()
eps = parse(Float64, Base.prompt("relative error in CG loops", default = "1e-19"))
MaxCGstep =
parse(Int64, Base.prompt("Maximum iteration steps in CG loops", default = "3000"))
if eps <= 0
error("Invalid value for eps=$eps. This has to be strictly positive.")
end
if MaxCGstep <= 0
error("Invalid value for MaxCGstep=$MaxCGstep. This has to be strictly positive.")
end
cg.eps = eps
cg.MaxCGstep = MaxCGstep
return cg
end
function ChiralCondensate_parameters_interactive(; mass = 0.5)
method = ChiralCondensate_parameters()
println_rank0("You measure chiral condensates with the statteggred fermion")
method.methodname = "Chiral_condensate"
method.measure_every =
parse(Int64, Base.prompt("How often measure chiral condensates?", default = "1"))
method.mass = parse(
Float64,
Base.prompt(
"Input mass for the measurement of chiral condensates",
default = "$mass",
),
)
method.Nf = 4
println_rank0(
"Number of flavors (tastes) for the measurement of chiral condensates is $(method.Nf)",
)
eps = parse(Float64, Base.prompt("relative error in CG loops", default = "1e-19"))
MaxCGstep =
parse(Int64, Base.prompt("Maximum iteration steps in CG loops", default = "3000"))
if eps <= 0
error("Invalid value for eps=$eps. This has to be strictly positive.")
end
if MaxCGstep <= 0
error("Invalid value for MaxCGstep=$MaxCGstep. This has to be strictly positive.")
end
method.eps = eps
method.MaxCGstep = MaxCGstep
smearingmethod =
request(
"Choose a configuration format for loading",
RadioMenu(["No smearing", "stout smearing"]),
) |> SmearingMethod
if smearingmethod == Nosmearing
method.smearing_for_fermion = "nothing"
smearing = NoSmearing_parameters()
elseif smearingmethod == STOUT
method.smearing_for_fermion = "stout"
smearing = Stout_parameters_interactive()
method.stout_ρ = smearing.ρ
method.stout_loops = smearing.stout_loops
method.stout_numlayers = smearing.numlayers
end
return method
end
function Pion_parameters_interactive()
method = Pion_parameters()
println_rank0("You measure Pion_correlator")
method.methodname = "Pion_correlator"
method.measure_every =
parse(Int64, Base.prompt("How often measure Pion_correlator?", default = "1"))
wtype = request(
"Choose fermion type for the measurement of Pion_correlator",
RadioMenu([
"Standard Wilson fermion action",
"Staggered fermion action",
#"Wilson+Clover fermion action",
]),
)
if wtype == 1
println_rank0("Standard Wilson fermion action will be used for the measurement")
method.fermiontype = "Wilson"
fermion_parameters, cg = wilson_wizard()
elseif wtype == 3
println_rank0("Wilson+Clover fermion action will be used for the measurement")
method.fermiontype = "WilsonClover"
fermion_parameters, cg = wilson_wizard()
elseif wtype == 2
println_rank0("Staggered fermion action will be used for the measurement")
method.fermiontype = "Staggered"
fermion_parameters, cg = staggered_wizard()
end
method.eps = cg.eps
method.MaxCGstep = cg.MaxCGstep
smearingmethod =
request(
"Choose a configuration format for loading",
RadioMenu(["No smearing", "stout smearing"]),
) |> SmearingMethod
if smearingmethod == Nosmearing
method.smearing_for_fermion = "nothing"
smearing = NoSmearing_parameters()
elseif smearingmethod == STOUT
method.smearing_for_fermion = "stout"
smearing = Stout_parameters_interactive()
method.stout_ρ = smearing.ρ
method.stout_loops = smearing.stout_loops
method.stout_numlayers = smearing.numlayers
end
return method
end
function wilson_wizard()
fermion_parameters = Wilson_parameters()
hop = parse(Float64, Base.prompt("Input the hopping parameter κ", default = "0.141139"))
#hop = parse(Float64,readline(stdin))
if hop <= 0
error("Invalid value for κ=$hop. This has to be strictly positive.")
end
println_rank0("κ = $hop")
fermion_parameters.hop = hop
cg = CG_params_interactive()
return fermion_parameters, cg
end
function staggered_wizard()
staggered = Staggered_parameters()
mass = parse(Float64, Base.prompt("Input mass", default = "0.5"))
if mass <= 0
error("Invalid value for mass=$mass. This has to be strictly positive.")
end
staggered.mass = mass
Nftype = request(
"Choose the number of flavors(tastes)",
RadioMenu([
"2 (RHMC will be used)",
"3 (RHMC will be used)",
"4 (HMC will be used)",
"8 (HMC will be used)",
"1 (RHMC will be used)",
]),
)
if Nftype == 1
Nf = 2
elseif Nftype == 2
Nf = 3
elseif Nftype == 3
Nf = 4
elseif Nftype == 4
Nf = 8
elseif Nftype == 5
Nf = 1
end
staggered.Nf = Nf
cg = CG_params_interactive()
return staggered, cg
end
function Domainwall_wizard()
fermion_parameters = Domainwall_parameters()
N5 =
parse(Int64, Base.prompt("Input the size of the extra dimension L5", default = "4"))
#fermion_parameters.Domainwall_L5 = N5
fermion_parameters.N5 = N5
println_rank0("Standard Domainwall fermion action is used")
M = parse(Float64, Base.prompt("Input M", default = "-1"))
while M >= 0
println_rank0("M should be M < 0. ")
M = parse(Float64, Base.prompt("Input M", default = "-1"))
end
#fermion_parameters.Domainwall_M = M
fermion_parameters.M = M
m = parse(Float64, Base.prompt("Input mass", default = "0.25"))
#fermion_parameters.Domainwall_m = m
fermion_parameters.m = m
cg = CG_params_interactive()
return fermion_parameters, cg
end
#=
function generate_printable_parameters(p::System)
pnames = fieldnames(System)
physical = Print_Physical_parameters()
names_physical = fieldnames(typeof(physical))
fermions = Print_Fermions_parameters()
names_fermions = fieldnames(typeof(fermions))
control = Print_System_control_parameters()
names_control = fieldnames(typeof(control))
hmc = Print_HMCrelated_parameters()
names_hmc = fieldnames(typeof(hmc))
#measure = Print_Measurement_parameters()
#names_measure = fieldnames(typeof(measure))
for pname_i in pnames
value = getfield(p, pname_i)
#println_rank0(value)
hasvalue = false
physical_index = findfirst(x -> x == pname_i, names_physical)
if physical_index != nothing
setfield!(physical, pname_i, value)
#println_rank0(value, "\t", pname_i)
hasvalue = true
end
fermions_index = findfirst(x -> x == pname_i, names_fermions)
if fermions_index != nothing
setfield!(fermions, pname_i, value)
#println_rank0(value, "\t", pname_i)
hasvalue = true
end
control_index = findfirst(x -> x == pname_i, names_control)
if control_index != nothing
setfield!(control, pname_i, value)
#println_rank0(value, "\t", pname_i)
hasvalue = true
end
hmc_index = findfirst(x -> x == pname_i, names_hmc)
if hmc_index != nothing
setfield!(hmc, pname_i, value)
#println_rank0(value, "\t", pname_i)
hasvalue = true
end
#=
measure_index = findfirst(x -> x == pname_i, names_measure)
if measure_index != nothing
setfield!(measure, pname_i, value)
#println_rank0(value, "\t", pname_i)
hasvalue = true
end
=#
#=
if hasvalue == false
@warn "$(pname_i) is not set!"
end
=#
#@assert hasvalue "$(pname_i) is not set!"
end
return physical, fermions, control, hmc#, measure
end
=#
function construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
if key == "L"
value = collect(value)
elseif key == "r"
value = Float64(value)
end
#println_rank0("$key $value")
hasvalue = false
pname_i = Symbol(key)
physical_index = findfirst(x -> x == key, printlist_physical)
if physical_index != nothing
setfield!(physical, pname_i, value)
hasvalue = true
end
fermions_index = findfirst(x -> x == key, printlist_fermions)
if fermions_index != nothing
setfield!(fermions, pname_i, value)
hasvalue = true
end
control_index = findfirst(x -> x == key, printlist_systemcontrol)
if control_index != nothing
setfield!(control, pname_i, value)
hasvalue = true
end
hmc_index = findfirst(x -> x == key, printlist_HMCrelated)
if hmc_index != nothing
setfield!(hmc, pname_i, value)
hasvalue = true
end
#if hasvalue == false
# @warn "$(pname_i) is not set!"
#end
if hasvalue == false
@warn "$(key) is not used!"
end
return hasvalue
end
function construct_printable_parameters_fromdict!(x::Dict, physical, fermions, control, hmc)
for (key, value) in x
hasvalue = false
pname_i = Symbol(key)
physical_index = findfirst(x -> x == pname_i, names_physical)
if physical_index != nothing
setfield!(physical, pname_i, value)
hasvalue = true
end
fermions_index = findfirst(x -> x == pname_i, names_fermions)
if fermions_index != nothing
setfield!(fermions, pname_i, value)
hasvalue = true
end
control_index = findfirst(x -> x == pname_i, names_control)
if control_index != nothing
setfield!(control, pname_i, value)
hasvalue = true
end
hmc_index = findfirst(x -> x == pname_i, names_hmc)
if hmc_index != nothing
setfield!(hmc, pname_i, value)
hasvalue = true
end
if hasvalue == false
@warn "$(pname_i) is not set!"
end
end
end
function remove_default_values!(x::Dict, defaultsystem)
for (key, value) in x
if hasfield(typeof(defaultsystem), Symbol(key))
default_value = getfield(defaultsystem, Symbol(key))
#println_rank0(key, "\t", value, "\t", default_value)
if value == default_value || string(value) == string(default_value)
if check_important_parameters(key) == false
delete!(x, key)
end
else
if value == nothing
x[key] = "nothing"
end
end
else
if value == nothing
x[key] = "nothing"
end
end
if typeof(value) == Vector{Measurement_parameters}
construct_dict_from_measurement!(x, value)
end
if typeof(value) <: Fermion_parameters
construct_dict_from_fermion!(x, value)
end
end
end
function construct_dict_from_fermion!(x, value)
fermiondic = struct2dict(value)
#println_rank0("fermiondic",fermiondic)
fermiondic_default = typeof(value)()
remove_default_values!(fermiondic, fermiondic_default)
x["fermion_parameters"] = fermiondic
end
function construct_dict_from_measurement!(x, value)
measuredic = Dict()
#println_rank0(value)
for measure in value
methoddic = struct2dict(measure)
measure_struct_default = typeof(measure)()
remove_default_values!(methoddic, measure_struct_default)
measuredic[methoddic["methodname"]] = methoddic
end
#println_rank0("x",x)
#println_rank0(measuredic)
x["measurement_methods"] = measuredic
end
function remove_default_values!(x::Dict)
physical = Print_Physical_parameters()
fermions = Print_Fermions_parameters()
control = Print_System_control_parameters()
hmc = Print_HMCrelated_parameters()
#measure = Print_Measurement_parameters()
#defaultsystem = System()
for (params, paramsname) in x
remove_default_values!(x[params], physical)
remove_default_values!(x[params], fermions)
remove_default_values!(x[params], control)
remove_default_values!(x[params], hmc)
#remove_default_values!(x[params], measure)
end
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 10100 | module Parameters_TOML
using TOML
import ..System_parameters: Params
import ..Parameter_structs:
Print_Physical_parameters,
Print_Fermions_parameters,
Print_System_control_parameters,
Print_HMCrelated_parameters,
struct2dict,
initialize_fermion_parameters,
Print_Gradientflow_parameters
function demo_TOML()
println("demo for TOML format")
p = construct_Params_from_TOML("parametertest.toml")
end
function set_params_value!(value_Params, values)
d = struct2dict(values)
pnames = fieldnames(Params)
for (i, pname_i) in enumerate(pnames)
if haskey(d, String(pname_i))
if d[String(pname_i)] == "nothing" && String(pname_i) != "smearing_for_fermion"
value_Params[i] = nothing
else
value_Params[i] = d[String(pname_i)]
end
end
end
end
const unused_bool_values = ["use_autogeneratedstaples", "integratedFermionAction"]
const unused_array_values = ["couplinglist", "couplingcoeff"]
const unused_int_values = ["firstlearn"]
const unused_float_values = ["βeff"]
const unused_nothing_values = ["coupling_loops"]
const unused_string_values = ["training_data_name"]
function set_unused_parameters!(value_Params)
pnames = fieldnames(Params)
for (i, pname_i) in enumerate(pnames)
valuename = String(pname_i)
if findfirst(x -> x == valuename, unused_bool_values) != nothing
value_Params[i] = false
elseif findfirst(x -> x == valuename, unused_array_values) != nothing
value_Params[i] = []
elseif findfirst(x -> x == valuename, unused_int_values) != nothing
value_Params[i] = 0
elseif findfirst(x -> x == valuename, unused_float_values) != nothing
value_Params[i] = 0.0
elseif findfirst(x -> x == valuename, unused_nothing_values) != nothing
value_Params[i] = nothing
elseif findfirst(x -> x == valuename, unused_string_values) != nothing
value_Params[i] = ""
end
end
end
function show_parameters(parameters)
#println(parameters)
for (key, value) in parameters
println("[$(key)]")
if key == "Measurement set"
for (key_i, value_i) in value
println("[$(key_i)]")
display(value_i)
println("\t")
end
else
display(value)
println("\t")
end
end
end
function construct_Params_from_TOML(filename::String)
parameters = TOML.parsefile(filename)
println("inputfile: ", pwd() * "/" * filename)
construct_Params_from_TOML(parameters)
end
function construct_Params_from_TOML(parameters)
show_parameters(parameters)
pnames = fieldnames(Params)
numparams = length(pnames)
value_Params = Vector{Any}(undef, numparams)
physical = Print_Physical_parameters()
set_params_value!(value_Params, physical)
fermions = Print_Fermions_parameters()
set_params_value!(value_Params, fermions)
control = Print_System_control_parameters()
set_params_value!(value_Params, control)
hmc = Print_HMCrelated_parameters()
set_params_value!(value_Params, hmc)
gradientflow = Print_Gradientflow_parameters()
set_params_value!(value_Params, gradientflow)
set_unused_parameters!(value_Params)
#println(pnames)
pos = findfirst(x -> String(x) == "ITERATION_MAX", pnames)
value_Params[pos] = 10^5
pos = findfirst(x -> String(x) == "isevenodd", pnames)
value_Params[pos] = true
pos = findfirst(x -> String(x) == "load_fp", pnames)
logfilename = parameters["System Control"]["logfile"]
log_dir = parameters["System Control"]["log_dir"]
if isdir(log_dir) == false
mkdir(log_dir)
end
logfile = pwd() * "/" * log_dir * "/" * logfilename
load_fp = open(logfile, "w")
value_Params[pos] = load_fp
if haskey(parameters["Physical setting(fermions)"],"Dirac_operator")
if parameters["Physical setting(fermions)"]["Dirac_operator"] == "Domainwall"
pairs = [("M","Domainwall_M"),("m","Domainwall_m"),("N5","Domainwall_L5")]
param = parameters["Physical setting(fermions)"]
for pair in pairs
if haskey(param,pair[1])
if haskey(param,pair[2]) == false
param[pair[2]] = param[pair[1]]
end
if param[pair[1]] == nothing
param[pair[2]] = param[pair[1]]
end
end
if haskey(param,pair[2])
if haskey(param,pair[1]) == false
param[pair[1]] = param[pair[2]]
end
if param[pair[2]] == nothing
param[pair[1]] = param[pair[2]]
end
end
end
end
end
if haskey(parameters["Measurement set"], "measurement_basedir") &&
haskey(parameters["System Control"], "measurement_basedir") == false
measurement_basedir = parameters["Measurement set"]["measurement_basedir"]
measurement_dir = parameters["Measurement set"]["measurement_dir"]
elseif haskey(parameters["Measurement set"], "measurement_basedir") == false &&
haskey(parameters["System Control"], "measurement_basedir")
measurement_basedir = parameters["System Control"]["measurement_basedir"]
measurement_dir = parameters["System Control"]["measurement_dir"]
elseif haskey(parameters["Measurement set"], "measurement_basedir") &&
haskey(parameters["System Control"], "measurement_basedir")
@error "both \"Measurement set\" and \"System Control\" have \"measurement_basedir\". remove one."
else
measurement_basedir = parameters["Measurement set"]["measurement_basedir"]
measurement_dir = parameters["Measurement set"]["measurement_dir"]
end
if isdir(measurement_basedir) == false
mkdir(measurement_basedir)
end
if isdir(pwd() * "/" * measurement_basedir * "/" * measurement_dir) == false
mkdir(pwd() * "/" * measurement_basedir * "/" * measurement_dir)
end
pos = findfirst(x -> String(x) == "measuredir", pnames)
measuredir = pwd() * "/" * measurement_basedir * "/" * measurement_dir
value_Params[pos] = measuredir
for (i, pname_i) in enumerate(pnames)
#println("before $(value_Params[i])")
for (key, value) in parameters
if haskey(value, String(pname_i))
#println("$pname_i $key ",value[String(pname_i)])
if String(pname_i) == "measurement_methods"
#println("$pname_i $key ",value[String(pname_i)])
valuedir = construct_measurement_dir(value[String(pname_i)])
value_Params[i] = valuedir
elseif String(pname_i) == "measurements_for_flow"
valuedir = construct_measurement_dir(value[String(pname_i)])
value_Params[i] = valuedir
elseif String(pname_i) == "L"
value_Params[i] = Tuple(value[String(pname_i)])
else
if value[String(pname_i)] == "nothing" &&
String(pname_i) != "smearing_for_fermion"
value_Params[i] = nothing
else
value_Params[i] = value[String(pname_i)]
end
end
end
end
if isassigned(value_Params, i) == false
@error "$(pname_i) is not defined!"
end
#println(pname_i,"::$(typeof(value_Params[i])) $(value_Params[i])")
end
parameters = Params(value_Params...)
parameter_check(parameters)
return parameters
end
function parameter_check(p::Params)
if p.Dirac_operator != nothing
println("$(p.Dirac_operator) fermion is used")
if p.smearing_for_fermion == "stout"
println("stout smearing is used for fermions")
end
end
if p.saveU_format ≠ nothing
if isdir(p.saveU_dir) == false
mkdir(p.saveU_dir)
end
println("$(p.saveU_dir) is used for saving configurations")
end
if p.update_method == "HMC"
println("HMC will be used")
elseif p.update_method == "Heatbath"
println("Heatbath will be used")
elseif p.update_method == "Fileloading"
println("No update will be used (read-measure mode)")
p.quench = true
elseif p.update_method == "SLHMC"
println("SLHMC will be used")
if p.quench == false
println("quench = true is set")
p.quench = true
#error("system[\"quench\"] = false. The SLHMC needs the quench update. Put the other system[\"update_method\"] != \"SLHMC\" or system[\"quench\"] = true")
end
else
error("""
update_method in [\"Physical setting\"] = $(p.update_method) is not supported.
Supported methods are
HMC
Heatbath
Fileloading
""")
end
log_dir = p.log_dir
if isdir(log_dir) == false
mkdir(log_dir)
end
end
function construct_measurement_dir(x)
#println(x)
valuedic = Dict[]
for (method, methoddic) in x
dic_i = Dict()
for (key, value) in methoddic
if key == "fermion_parameters"
fermion_type = value["Dirac_operator"]
fermion_dict = struct2dict(initialize_fermion_parameters(fermion_type))
for (key_i, value_i) in fermion_dict
if haskey(value, key_i)
dic_i[key_i] = value[key_i]
else
dic_i[key_i] = value_i
end
end
else
dic_i[key] = value
end
end
#println("dic_i $dic_i")
push!(valuedic, dic_i)
end
#display(valuedic)
return valuedic
end
#demo_TOML()
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 3648 | module System_parameters
using Random
export Params
import ..Transform_oldinputfile:
default_system,
default_md,
default_defaultmeasures,
default_actions,
default_cg,
default_wilson,
default_staggered,
default_measurement
import ..Parameter_structs:
printlist_physical,
printlist_fermions,
printlist_systemcontrol,
printlist_HMCrelated,
printlist_parameters_SLMC,
printlist_measurement
const printlists = [
printlist_physical,
printlist_fermions,
printlist_systemcontrol,
printlist_HMCrelated,
printlist_parameters_SLMC,
printlist_measurement,
]
system = default_system()
md = default_md()
defaultmeasures = default_defaultmeasures()
actions = default_actions()
cg = default_cg()
wilson = default_wilson()
staggered = default_staggered()
measurement = default_measurement()
struct Params
L::Tuple # = (2,2,2,2) # Mandatory
β::Float64 # = 6 # Mandatory
NC::Int64 # = 3
Dirac_operator::Union{Nothing,String} # = "Wilson"
quench::Bool # = false
initial::String # = "cold"
BoundaryCondition::Array{Int64,1} # =[1,1,1,-1]
Nwing::Int64 # = 1
randomseed::Int64 # = 111
#For actions
use_autogeneratedstaples::Bool # = false
couplinglist::Array{String,1} # = []
couplingcoeff::Array{Float64,1} # = []
coupling_loops::Union{Nothing,Array{Array{Array{Tuple{Int,Int},1},1},1}}
#For MD
Δτ::Float64 # = 0.05
MDsteps::Int64 # = 20
SextonWeingargten::Bool # = false
Nsteps::Int64 # = 100
Nthermalization::Int64 # = 10
#For Sexton-Weingargten
N_SextonWeingargten::Int64 # = 10 # Mandatory
#For IntegratedHMC
#IntegratedHMC::Bool # = false
#For Heatbath
#Heatbath::Bool # = false
#For CG
eps::Float64 # = 1e-19
MaxCGstep::Int64 # = 3000
#For Wilson
hop::Float64 # = 0.141139#Hopping parameter # Mandatory
r::Float64 # = 1 #Wilson term
#For WilsonClover
Clover_coefficient::Float64 # = 1.5612
#For Staggered
mass::Float64 # = 0.5 # Mandatory
Nf::Int64 # = 4
#verbose
verboselevel::Int64 # = 2
#For measurement
measurement_methods::Vector{Dict} # = defaultmeasures
saveU_format::Union{String,Nothing}
saveU_every::Int64
saveU_dir::String
loadU_format::Union{String,Nothing}
loadU_dir::String
update_method::String
βeff::Union{Float64,Array{Float64,1}}
firstlearn::Int64
log_dir::String
logfile::String
load_fp::IOStream
measuredir::String
integratedFermionAction::Bool
training_data_name::String
useOR::Bool
numOR::Int64
initialtrj::Int64
loadU_fromfile::Bool
loadU_filename::String
smearing_for_fermion::String
stout_numlayers::Union{Nothing,Int64}
stout_ρ::Union{Nothing,Array{Float64,1}}
stout_loops::Union{Nothing,Array{String,1}}
Domainwall_M::Union{Nothing,Float64}
Domainwall_m::Union{Nothing,Float64}
Domainwall_L5::Union{Nothing,Int64}
#Domainwall_b::Union{Nothing,Float64}
##Domainwall_c::Union{Nothing,Float64}
#Domainwall_ωs::Union{Nothing,Array{Float64,1}}
#Domainwall_r::Union{Nothing,Float64}
julian_random_number::Bool
ITERATION_MAX::Int64
isevenodd::Bool
hasgradientflow::Bool
eps_flow::Float64
numflow::Int64
Nflow::Int64
measurements_for_flow::Vector{Dict} #measurement in gradientflow
end
end
#using .System_parameters
#System_parameters.parameterloading(ARGS[1])
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 6138 | module Transform_oldinputfile
import ..Parameter_structs:
Print_Physical_parameters,
Print_Fermions_parameters,
Print_System_control_parameters,
Print_HMCrelated_parameters,
construct_printable_parameters_fromdict!,
remove_default_values!,
struct2dict,
initialize_fermion_parameters,
Measurement_parameters,
initialize_measurement_parameters,
generate_printlist,
transform_measurement_dictvec,
transform_topological_charge_measurement!,
Print_Gradientflow_parameters
using TOML
function default_system()
system = Dict()
system["Dirac_operator"] = "Wilson"
system["quench"] = false
system["initial"] = "cold"
system["BoundaryCondition"] = [1, 1, 1, -1]
system["Nwing"] = 1
system["randomseed"] = 111
system["verboselevel"] = 2
system["saveU_format"] = "JLD"
system["saveU_every"] = 1
system["saveU_dir"] = "./confs"
system["initialtrj"] = 1
system["update_method"] = "HMC"
system["isevenodd"] = true
system["Nsteps"] = 100
system["Nthermalization"] = 0
system["julian_random_number"] = false
return system
end
function default_md()
md = Dict()
md["Δτ"] = 0.05
md["MDsteps"] = 20
md["SextonWeingargten"] = false
return md
end
function default_defaultmeasures()
defaultmeasures = Array{Dict,1}(undef, 2)
for i = 1:length(defaultmeasures)
defaultmeasures[i] = Dict()
end
defaultmeasures[1]["methodname"] = "Plaquette"
defaultmeasures[1]["measure_every"] = 1
defaultmeasures[1]["fermiontype"] = nothing
defaultmeasures[2]["methodname"] = "Polyakov_loop"
defaultmeasures[2]["measure_every"] = 1
defaultmeasures[2]["fermiontype"] = nothing
return defaultmeasures
end
function default_actions()
actions = Dict()
actions["use_autogeneratedstaples"] = false
#actions["couplinglist"] = []
actions["couplingcoeff"] = []
actions["coupling_loops"] = nothing
return actions
end
function default_cg()
cg = Dict()
cg["eps"] = 1e-19
cg["MaxCGstep"] = 3000
return cg
end
function default_wilson()
wilson = Dict()
wilson["r"] = 1
wilson["Clover_coefficient"] = 1.5612
return wilson
end
function default_staggered()
staggered = Dict()
staggered["Nf"] = 4
return staggered
end
function default_measurement()
measurement = Dict()
measurement["measurement_methods"] = defaultmeasures
return measurement
end
system = default_system()
md = default_md()
defaultmeasures = default_defaultmeasures()
actions = default_actions()
cg = default_cg()
wilson = default_wilson()
staggered = default_staggered()
measurement = default_measurement()
function transform_to_toml(filename)
include(abspath(filename))
physical = Print_Physical_parameters()
fermions = Print_Fermions_parameters()
control = Print_System_control_parameters()
hmc = Print_HMCrelated_parameters()
for (key, value) in system
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
for (key, value) in md
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
for (key, value) in cg
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
for (key, value) in wilson
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
for (key, value) in staggered
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
measurement_dict = Dict()
flow_dict = Dict()
hasgradientflow = false
for (key, value) in measurement
if key == "measurement_methods"
valuem, flow_dict, hasgradientflow = transform_measurement_dictvec(value)
measurement_dict[key] = valuem
else
hasvalue = construct_printable_parameters_fromdict!(
key,
value,
physical,
fermions,
control,
hmc,
)
end
end
#println(control)
#=
display(physical)
println("\t")
display(fermions)
println("\t")
display(control)
println("\t")
display(hmc)
println("\t")
=#
system_parameters_dict = Dict()
system_parameters_dict["Physical setting"] = struct2dict(physical)
system_parameters_dict["Physical setting(fermions)"] = struct2dict(fermions)
system_parameters_dict["System Control"] = struct2dict(control)
system_parameters_dict["HMC related"] = struct2dict(hmc)
system_parameters_dict["Measurement set"] = measurement_dict
if hasgradientflow
system_parameters_dict["System Control"]["hasgradientflow"] = true
else
flow_dict["measurements_for_flow"] = Dict()
end
system_parameters_dict["gradientflow_measurements"] = flow_dict
#system_parameters_dict["Measurement set"] = struct2dict(measurement)
#=
display(system_parameters_dict)
println("\t")
=#
#println(system_parameters_dict["System Control"])
#println(system_parameters_dict)
remove_default_values!(system_parameters_dict)
#println(system_parameters_dict)
#println(system_parameters_dict["System Control"])
filename_toml = splitext(filename)[1] * ".toml"
#display(system_parameters_dict)
open(filename_toml, "w") do io
TOML.print(io, system_parameters_dict)
end
end
function demo_transform()
filename = "demo.jl"
transform_to_toml(filename)
end
#demo_transform()
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 5014 | module Universe_module
import ..System_parameters: Params
using Gaugefields
using LatticeDiracOperators
import Gaugefields
struct Univ{Dim,TG,T_FA}
L::NTuple{Dim,Int64}
NC::Int64
Nwing::Int8
gauge_action::GaugeAction{Dim,TG}
U::Vector{TG}
quench::Bool
fermi_action::T_FA
cov_neural_net::Union{Nothing,CovNeuralnet{Dim}}
#Uold::Vector{TG}
verbose_print::Verbose_print
end
function get_gauge_action(univ::Univ)
return univ.gauge_action
end
function is_quenched(univ::Univ)
return univ.quench
end
function Univ(p::Params; MPIparallel = false, PEs = nothing)
Dim = length(p.L)
L = Tuple(p.L)
NC = p.NC
Nwing = p.Nwing
if p.initial == "cold" || p.initial == "hot" || p.initial == "one instanton"
if Dim == 2
U = Initialize_Gaugefields(NC, Nwing, L..., condition = p.initial)
else
U = Initialize_Gaugefields(NC, Nwing, L..., condition = p.initial)
end
else
if Dim == 2
U = Initialize_Gaugefields(NC, Nwing, L..., condition = "cold")
else
U = Initialize_Gaugefields(NC, Nwing, L..., condition = "cold")
end
end
close(p.load_fp)
logfilename = pwd() * "/" * p.log_dir * "/" * p.logfile
verbose_print =
Verbose_print(p.verboselevel, myid = get_myrank(U[1]), filename = logfilename)
if p.initial == "cold" || p.initial == "hot" || p.initial == "one instanton"
else
println_verbose_level2(verbose_print, "..... File start")
println_verbose_level1(verbose_print, "File name is $(p.initial)")
if p.loadU_format == "ILDG"
ildg = ILDG(p.initial)
i = 1
load_gaugefield!(U, i, ildg, L, NC)
elseif p.loadU_format == "BridgeText"
filename = p.initial
load_BridgeText!(filename, U, L, NC)
else
error("loadU_format should be ILDG or BridgeText. Now $(p.loadU_format)")
end
end
#println_verbose_level1(verbose_print, "..... test mode")
#Uold = similar(U)
gauge_action = GaugeAction(U)
if p.use_autogeneratedstaples
error("p.use_autogeneratedstaples = true is not supported yet!")
else
plaqloop = make_loops_fromname("plaquette", Dim = Dim)
append!(plaqloop, plaqloop')
βinp = p.β / 2
push!(gauge_action, βinp, plaqloop)
end
TG = eltype(U)
#println(TG)
#show(gauge_action)
if p.Dirac_operator == nothing
fermi_action = nothing
else
params = Dict()
parameters_action = Dict()
if p.Dirac_operator == "Staggered"
x = Initialize_pseudofermion_fields(U[1], "staggered")
params["Dirac_operator"] = "staggered"
params["mass"] = p.mass
parameters_action["Nf"] = p.Nf
elseif p.Dirac_operator == "Wilson"
x = Initialize_pseudofermion_fields(U[1], "Wilson", nowing = true)
params["Dirac_operator"] = "Wilson"
params["κ"] = p.hop
params["r"] = p.r
params["faster version"] = true
elseif p.Dirac_operator == "Domainwall"
L5 = p.Domainwall_L5
#println(L5)
#error("L5")
M = p.Domainwall_M
mass = p.Domainwall_m
params["Dirac_operator"] = "Domainwall"
params["mass"] = mass
params["L5"] = L5
params["M"] = M
x = Initialize_pseudofermion_fields(U[1], "Domainwall", L5 = L5, nowing = true)
else
error("not supported")
end
params["eps_CG"] = p.eps
params["verbose_level"] = p.verboselevel #2
params["MaxCGstep"] = p.MaxCGstep
params["boundarycondition"] = p.BoundaryCondition
D = Dirac_operator(U, x, params)
fermi_action = FermiAction(D, parameters_action)
end
T_FA = typeof(fermi_action)
if p.smearing_for_fermion == "nothing"
cov_neural_net = nothing
elseif p.smearing_for_fermion == "stout"
cov_neural_net = CovNeuralnet()
@assert p.stout_numlayers == 1 "stout_numlayers should be one. But now $(p.stout_numlayers)"
st = STOUT_Layer(p.stout_loops, p.stout_ρ, L)
push!(cov_neural_net, st)
else
error("p.smearing_for_fermion = $(p.smearing_for_fermion) is not supported")
end
return Univ{Dim,TG,T_FA}(
L,
NC,
Nwing,
gauge_action,
U,
p.quench,
fermi_action,
cov_neural_net,
verbose_print,
)
end
function Gaugefields.println_verbose_level1(univ::T, val...) where {T<:Univ}
println_verbose_level1(univ.verbose_print, val...)
end
function Gaugefields.println_verbose_level2(univ::T, val...) where {T<:Univ}
println_verbose_level2(univ.verbose_print, val...)
end
function Gaugefields.println_verbose_level3(univ::T, val...) where {T<:Univ}
println_verbose_level3(univ.verbose_print, val...)
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 28216 | module Wizard
using REPL.TerminalMenus
using TOML
import ..System_parameters: Params
import ..Parameter_structs:
#System,
Action,
CG_params_interactive,
Quench_parameters,
Fermion_parameters,
Wilson_parameters,
Staggered_parameters,
Stout_parameters,
kindsof_loops,
Stout_parameters_interactive,
ConjugateGradient,
NoSmearing_parameters,
Domainwall_parameters,
MD,
MD_interactive,
Measurement_parameters,
Plaq_parameters_interactive,
Poly_parameters_interactive,
ChiralCondensate_parameters_interactive,
TopologicalCharge_parameters_interactive,
staggered_wizard,
wilson_wizard,
Domainwall_wizard,
Pion_parameters_interactive,
Measurement_parameterset,
#generate_printable_parameters,
remove_default_values!,
struct2dict,
Print_Gradientflow_parameters,
Print_Physical_parameters,
Print_Fermions_parameters,
Print_System_control_parameters,
Print_HMCrelated_parameters,
Wilson_loop_parameters_interactive,
Energy_density_parameters_interactive
import ..Parameters_TOML: demo_TOML, construct_Params_from_TOML
@enum Wizardmode simple = 1 expert = 2
@enum Initialconf coldstart = 1 hotstart = 2 filestart = 3 instantonstart = 4
@enum Fileformat JLD = 1 ILDG = 2 BridgeText = 3 Nosave = 0
@enum SmearingMethod Nosmearing = 1 STOUT = 2
@enum Fermiontype Nofermion = 1 Wilsonfermion = 2 Staggeredfermion = 3 Domainwallfermion = 4
@enum Options Plaquette = 1 Polyakov_loop = 2 Topological_charge = 3 Chiral_condensate = 4 Pion_correlator =
5 Wilson_loop = 6 Energy_density = 7
function get_filename_extension(loadtype::Fileformat)
if loadtype == JLD
ext = ".jld"
elseif loadtype == ILDG
ext = ".ildg"
elseif v == BridgeText
ext = ".txt"
else
error("error!")
end
return ext
end
function print_wizard_logo(outs)
blue = "\033[34m"
red = "\033[31m"
green = "\033[32m"
magenta = "\033[35m"
normal = "\033[0m\033[0m"
logo = raw"""
--------------------------------------------------------------------------------
run_wizard
格 格
色 格
色色色 格
子子色色色色色子子子子子格子子子子
色色色 格
色 格
格 格
力 学 LatticeQCD.jl
力力力 学学学
子子力力力力力子子子学学学学学子子
力力力 学学学
力 学
格 格
"""
logo = replace(logo, "Q" => "$(red)Q$(normal)")
logo = replace(logo, "C" => "$(blue)C$(normal)")
logo = replace(logo, "D" => "$(green)D$(normal)")
logo = replace(logo, "色" => "$(red)色$(normal)")
logo = replace(logo, "力" => "$(blue)力$(normal)")
logo = replace(logo, "学" => "$(green)学$(normal)")
println(outs, logo)
println(
outs,
"Welcome to a wizard for Lattice QCD.\n",
"We'll get you set up simulation parameters in no time.",
)
println(
"--------------------------------------------------------------------------------",
)
println("If you leave the prompt empty, a default value will be used.")
println("To exit, press Ctrl + c.")
end
function run_wizard()
print_wizard_logo(stdout)
physicalparams = Print_Physical_parameters()
controlparams = Print_System_control_parameters()
fermionparams = Print_Fermions_parameters()
hmcparams = Print_HMCrelated_parameters()
#system = System()
#action = Action()
#println(system)
#println(action)
mode =
request(
"Choose wizard mode",
Wizardmode |> instances |> collect .|> string |> RadioMenu,
) |> Wizardmode
isexpert::Bool = (mode == expert)
filename = String(
Base.prompt(
"put the name of the parameter file you make",
default = "my_parameters.toml",
),
)
physicalparams.L = set_Lattice_size(isexpert)
#system.L = set_Lattice_size(isexpert)
physicalparams.NC = set_gaugegroup(isexpert)
#system.NC = set_gaugegroup(isexpert)
physicalparams.β = set_β(physicalparams.NC)
#system.β = set_β(system.NC)
if isexpert
controlparams.randomseed =
parse(Int64, Base.prompt("Input random seed.", default = "111"))
controlparams.verboselevel = set_verboselevel()
#system.randomseed = parse(Int64, Base.prompt("Input random seed.", default = "111"))
#system.verboselevel = set_verboselevel()
end
if check_isfileloading()
controlparams.loadU_format, _ = set_loadU_format()
physicalparams.update_method = "Fileloading"
controlparams.loadU_dir =
String(Base.prompt("Loading directory", default = "./confs"))
filelist = request(
"Which configurations do you use?",
RadioMenu([
"All configurations in the directory",
"Configurations written in a list",
]),
)
if filelist == 1
controlparams.loadU_fromfile = false
else
controlparams.loadU_fromfile = true
controlparams.loadU_filename = String(
Base.prompt(
"name of the list in $(controlparams.loadU_dir)",
default = "filelist.txt",
),
)
end
else
if physicalparams.NC == 2
initialconf =
request(
"Choose initial configurations",
RadioMenu([
"cold start",
"hot start",
"start from a file",
"start from one instanton (Radius is half of Nx)",
]),
) |> Initialconf
else
initialconf =
request(
"Choose initial configurations",
RadioMenu(["cold start", "hot start", "start from a file"]),
) |> Initialconf
end
if initialconf == coldstart
physicalparams.initial = "cold"
elseif initialconf == hotstart
physicalparams.initial = "hot"
elseif initialconf == filestart
println("Initial configuration is loaded from a file")
controlparams.loadU_format, filetype = set_loadU_format()
extstring = get_filename_extension(filetype)
physicalparams.initial = String(
Base.prompt(
"Input the file name that you want to use",
default = "./confs/conf_00000001.$(extstring)",
),
)
physicalparams.initialtrj =
parse(Int64, Base.prompt("Start trj number?", default = "1"))
elseif initialconf == instantonstart
physicalparams.initial = "one instanton"
end
if isexpert
ftype =
request(
"Choose a dynamical fermion",
RadioMenu([
"Nothing (quenched approximation)",
"Wilson Fermion (2-flavor)",
"Staggered Fermion",
"Domain-wall Fermion (Experimental)",
]),
) |> Fermiontype
if ftype == Nofermion
cg = ConjugateGradient()
fermion_parameters = Quench_parameters()
fermionparams.Dirac_operator = "nothing"
fermionparams.quench = true
elseif ftype == Wilsonfermion
fermionparams.quench = false
println("Standard Wilson fermion action will be used")
fermionparams.Dirac_operator = "Wilson"
#=
wtype = request(
"Choose Wilson fermion type",
RadioMenu([
"Standard Wilson fermion action",
"Wilson+Clover fermion action",
]),
)
if wtype == 1
println("Standard Wilson fermion action will be used")
fermionparams.Dirac_operator = "Wilson"
else
println("Wilson+Clover fermion action will be used")
fermionparams.Dirac_operator = "WilsonClover"
end
=#
fermion_parameters, cg = wilson_wizard()
elseif ftype == Staggeredfermion
fermionparams.quench = false
fermionparams.Dirac_operator = "Staggered"
fermion_parameters, cg = staggered_wizard()
elseif ftype == Domainwallfermion
fermionparams.quench = false
fermionparams.Dirac_operator = "Domainwall"
fermion_parameters, cg = Domainwall_wizard()
end
else
fermionparams.Dirac_operator = "Wilson"
fermionparams.quench = false
fermion_parameters, cg = wilson_wizard_simple()
end
if fermionparams.quench == false
smearingmethod =
request(
"Choose a configuration format for loading",
RadioMenu(["No smearing", "stout smearing"]),
) |> SmearingMethod
if smearingmethod == Nosmearing
fermionparams.smearing_for_fermion = "nothing"
smearing = NoSmearing_parameters()
elseif smearingmethod == STOUT
fermionparams.smearing_for_fermion = "stout"
smearing = Stout_parameters_interactive()
fermionparams.stout_ρ = smearing.ρ
fermionparams.stout_loops = smearing.stout_loops
fermionparams.stout_numlayers = smearing.numlayers
end
else
smearing = NoSmearing_parameters()
end
if isexpert
if fermionparams.quench
methodtype = request(
"Choose an update method",
RadioMenu(["Heatbath", "Hybrid Monte Carlo"]),
)
if methodtype == 1
physicalparams.update_method = "Heatbath"
or = request("Use overrelazation method?", RadioMenu(["true", "false"]))
physicalparams.useOR = ifelse(or == 1, true, false)
if physicalparams.useOR
physicalparams.numOR = parse(
Int64,
Base.prompt(
"How many times do you want to do the OR?",
default = "3",
),
)
end
else
methodtype == 2
physicalparams.update_method = "HMC"
end
else
methodtype = request(
"Choose an update method",
RadioMenu([
"Hybrid Monte Carlo",
"Self-learning Hybrid Monte Carlo (SLHMC)",
]),
)
if methodtype == 1
physicalparams.update_method = "HMC"
else
methodtype == 2
physicalparams.update_method = "SLHMC"
@warn "SLHMC is not well developed"
#=
system.βeff = parse(
Float64,
Base.prompt("Input initial effective β", default = "$β"),
)
system.firstlearn = parse(
Int64,
Base.prompt(
"When do you want to start updating the effective action?",
default = "10",
),
)
=#
end
end
else
physicalparams.update_method = "HMC"
end
if isexpert
Nthermalization = parse(
Int64,
Base.prompt(
"Input the number of thermalization steps (no mearurement)",
default = "0",
),
)
if Nthermalization < 0
error(
"Invalid value for Nthermalization=$Nthermalization. This has to be positive/zero.",
)
end
physicalparams.Nthermalization = Nthermalization
end
Nsteps = parse(
Int64,
Base.prompt(
"Input the number of total trajectories after the thermalization",
default = "$(100+physicalparams.initialtrj)",
),
)
if Nsteps <= 0
error("Invalid value for Nsteps=$Nsteps. This has to be strictly positive.")
end
physicalparams.Nsteps = Nsteps
if isexpert && physicalparams.update_method != "Heatbath"
md = MD_interactive(Dirac_operator = fermionparams.Dirac_operator)
else
md = MD()
end
hmcparams.MDsteps = md.MDsteps
hmcparams.Δτ = md.Δτ
hmcparams.SextonWeingargten = md.SextonWeingargten
hmcparams.N_SextonWeingargten = md.N_SextonWeingargten
hmcparams.eps = cg.eps
hmcparams.MaxCGstep = cg.MaxCGstep
end
measurement = Measurement_parameterset()
measurementmenu = MultiSelectMenu(Options |> instances |> collect .|> string)
if isexpert
choices =
request("Select the measurement methods you want to do:", measurementmenu) |>
collect .|>
Options
else
choices = [1, 2, 5] .|> Options
end
nummeasurements = length(choices)
measurement.measurement_methods = Vector{Measurement_parameters}(undef, nummeasurements)
#@enum Options Plaquette=1 Polyakov_loop=2 Topological_charge=3 Chiral_condensate=4 Pion_correlator=5
count = 0
for method in choices
count += 1
if method == Plaquette
measurement.measurement_methods[count] = Plaq_parameters_interactive() #plaq_wizard()
elseif method == Polyakov_loop
measurement.measurement_methods[count] = Poly_parameters_interactive()
elseif method == Topological_charge
measurement.measurement_methods[count] =
TopologicalCharge_parameters_interactive()
elseif method == Chiral_condensate
measurement.measurement_methods[count] =
ChiralCondensate_parameters_interactive()
elseif method == Pion_correlator
measurement.measurement_methods[count] = Pion_parameters_interactive()
elseif method == Wilson_loop
measurement.measurement_methods[count] =
Wilson_loop_parameters_interactive(physicalparams.L)
elseif method == Energy_density
measurement.measurement_methods[count] = Energy_density_parameters_interactive()
end
end
headername = make_headername(physicalparams, fermionparams, fermion_parameters)
if nummeasurements != 0
controlparams.measurement_basedir = String(
Base.prompt("base directory for measurements", default = "./measurements"),
)
controlparams.measurement_dir = String(
Base.prompt(
"directory for measurements in $(controlparams.measurement_basedir)/",
default = headername,
),
)
end
gradient_params = Print_Gradientflow_parameters()
measurement_gradientflow = Measurement_parameterset()
if isexpert
methodtype = request(
"Perform measurements with the gradient flow?",
RadioMenu(["No", "Yes"]),
)
if methodtype == 2 #Yes
gradient_params.hasgradientflow = true
else
gradient_params.hasgradientflow = false
end
if gradient_params.hasgradientflow
println("---------------------------------------------")
println("---set measurements in gradient flow----------")
gradient_params.eps_flow = parse(
Float64,
Base.prompt(
"time step for gradient flow?",
default = "$(gradient_params.eps_flow)",
),
)
gradient_params.numflow = parse(
Int64,
Base.prompt(
"How many times do you want to flow gauge fields?",
default = "$(gradient_params.numflow)",
),
)
#gradient_params.numflow = parse(Int64, Base.prompt("number of steps for gradient flow?", default = "$(gradient_params.numflow)"))
#measurement_gradientflow = Measurement_parameterset()
measurementmenu = MultiSelectMenu(Options |> instances |> collect .|> string)
choices =
request(
"Select the measurement methods you want to do:",
measurementmenu,
) |>
collect .|>
Options
nummeasurements = length(choices)
measurement_gradientflow.measurement_methods =
Vector{Measurement_parameters}(undef, nummeasurements)
count = 0
for method in choices
count += 1
if method == Plaquette
measurement_gradientflow.measurement_methods[count] =
Plaq_parameters_interactive() #plaq_wizard()
elseif method == Polyakov_loop
measurement_gradientflow.measurement_methods[count] =
Poly_parameters_interactive()
elseif method == Topological_charge
measurement_gradientflow.measurement_methods[count] =
TopologicalCharge_parameters_interactive()
elseif method == Chiral_condensate
measurement_gradientflow.measurement_methods[count] =
ChiralCondensate_parameters_interactive()
elseif method == Pion_correlator
measurement_gradientflow.measurement_methods[count] =
Pion_parameters_interactive()
elseif method == Energy_density
measurement_gradientflow.measurement_methods[count] = Energy_density_parameters_interactive()
end
end
println("---done for gradient flow----------")
println("---------------------------------------------")
end
end
controlparams.log_dir = String(Base.prompt("log directory", default = "./logs"))
controlparams.logfile =
String(Base.prompt("logfile name", default = headername * ".txt"))
if isexpert
savetype =
request(
"Choose a configuration format for saving",
RadioMenu(["no save", "JLD", "ILDG", "Text format (BridgeText)"]),
) |> x -> x - 1 |> Fileformat
if savetype == Nosave
controlparams.saveU_format = "nothing"
elseif savetype == JLD
controlparams.saveU_format = "JLD"
elseif savetype == ILDG
controlparams.saveU_format = "ILDG"
elseif savetype == BridgeText
controlparams.saveU_format = "BridgeText"
end
if controlparams.saveU_format .≠ "nothing"
controlparams.saveU_every = parse(
Int64,
Base.prompt(
"How often do you save a configuration in file (Save every)?",
default = "10",
),
)
#system["saveU_basedir"] = String(Base.prompt("base directory for saving configuration", default="./confs"))
controlparams.saveU_dir =
String(Base.prompt("Saving directory", default = "./confs_$(headername)"))
#system["saveU_dir"] = system["saveU_basedir"]*"/"*system["saveU_dir"]
end
end
#physical, fermions, control, hmc = generate_printable_parameters(system)
system_parameters_dict = Dict()
system_parameters_dict["Physical setting"] = struct2dict(physicalparams)
system_parameters_dict["Physical setting(fermions)"] =
merge(struct2dict(fermionparams), struct2dict(fermion_parameters))
system_parameters_dict["System Control"] = struct2dict(controlparams)
system_parameters_dict["HMC related"] = struct2dict(hmcparams)
system_parameters_dict["Measurement set"] = struct2dict(measurement)
system_parameters_dict["gradientflow_measurements"] =
merge(struct2dict(gradient_params), struct2dict(measurement_gradientflow))
remove_default_values!(system_parameters_dict)
system_parameters_dict["gradientflow_measurements"]["measurements_for_flow"] =
deepcopy(system_parameters_dict["gradientflow_measurements"]["measurement_methods"])
delete!(system_parameters_dict["gradientflow_measurements"], "measurement_methods")
open(filename, "w") do io
TOML.print(io, system_parameters_dict)
end
#system_parameters_dict["Measurement set"]
params_set = construct_Params_from_TOML(filename)
#p = Params(params_set)
println("""
--------------------------------------------------------------------------------
run_wizard is done.
The returned value in this run_wizard() is params_set.
If you want to run a simulation in REPL or other Julia codes, just do
run_LQCD(params_set)
or
run_LQCD("$filename")
The output parameter file is $filename.
If you want to run a simulation, just do
julia run.jl $filename
--------------------------------------------------------------------------------
""")
return params_set
end
function wilson_wizard_simple()
wtype = 1
println("Standard Wilson fermion action will be used")
hop = parse(Float64, Base.prompt("Input the hopping parameter κ", default = "0.141139"))
if hop <= 0
error("Invalid value for κ=$hop. This has to be strictly positive.")
end
fermion_parameters = Wilson_parameters()
fermion_parameters.hop = hop
cg = ConjugateGradient()
return fermion_parameters, cg
end
function set_verboselevel!(system)
verboselevel = parse(Int64, Base.prompt("verbose level ?", default = "2"))
if 1 ≤ verboselevel ≤ 3
println("verbose level = ", verboselevel)
else
error("verbose level should be 1 ≤ verboselevel ≤ 3")
end
system.verboselevel = verboselevel
#system["verboselevel"] = verboselevel
end
function set_verboselevel()
verboselevel = parse(Int64, Base.prompt("verbose level ?", default = "2"))
if 1 ≤ verboselevel ≤ 3
println("verbose level = ", verboselevel)
else
error("verbose level should be 1 ≤ verboselevel ≤ 3")
end
return verboselevel
#system["verboselevel"] = verboselevel
end
function set_Lattice_size(isexpert)
if isexpert
println("Input Lattice size, L=(Nx,Ny,Nz,Nt)")
NX = parse(Int64, Base.prompt("Nx ?", default = "4"))
NY = parse(Int64, Base.prompt("Ny ?", default = "4"))
NZ = parse(Int64, Base.prompt("Nz ?", default = "4"))
NT = parse(Int64, Base.prompt("Nt ?", default = "4"))
#NT = parse(Int64,readline(stdin))
L = [NX, NY, NZ, NT]
#L = (NX, NY, NZ, NT)
#system["L"] = L
if (NX <= 0) | (NY <= 0) | (NZ <= 0) | (NT <= 0)
error("Invalid parameter L=$L, elements must be positive integers")
end
else
NX = parse(Int64, Base.prompt("Input spatial lattice size ", default = "4"))
NT = parse(Int64, Base.prompt("Input temporal lattice size ", default = "4"))
#L = (NX, NX, NX, NT)
L = [NX, NX, NX, NT]
#system["L"] = L
if (NX <= 0) | (NT <= 0)
error("Invalid parameter L=$L, elements must be positive integers")
end
end
println("Lattice is $L")
return L
end
function set_gaugegroup(isexpert)
if isexpert
SNC = request("Choose a gauge group", RadioMenu(["SU(3)", "SU(2)"]))
NC = ifelse(SNC == 1, 3, 2)
else
NC = 3
end
println("SU($NC) will be used")
return NC
end
function set_β(NC)
if NC == 3
β = parse(Float64, Base.prompt("β ?", default = "5.7"))
elseif NC == 2
β = parse(Float64, Base.prompt("β ?", default = "2.7"))
end
@assert β > 0 "Invalid value for β=$β. This has to be positive or zero"
return β
end
function check_isfileloading()
fileloading = request(
"Do you perform only measurements on configurations in a directory? (no update)",
RadioMenu(["No", "Yes"]),
)
if fileloading == 2
isfileloading = true
else
isfileloading = false
end
return isfileloading
end
function set_loadU_format()
loadtype =
request(
"Choose a configuration format for loading",
RadioMenu(["JLD", "ILDG", "Text format(BridgeText)"]),
) |> Fileformat
if loadtype == JLD
loadU_format = "JLD"
elseif loadtype == ILDG
loadU_format = "ILDG"
elseif v == BridgeText
loadU_format = "BridgeText"
end
return loadU_format, loadtype
end
function make_headername(physicalparams, fermionparams, fermion_parameters)
L = physicalparams.L
update_method = physicalparams.update_method
β = physicalparams.β
quench = fermionparams.quench
Dirac_operator = fermionparams.Dirac_operator
#L = system.L
headername =
update_method *
"_L" *
string(L[1], pad = 2) *
string(L[2], pad = 2) *
string(L[3], pad = 2) *
string(L[4], pad = 2) *
"_beta" *
string(β)
if update_method == "HMC"
if quench == true
headername *= "_quenched"
else
headername *= "_" * Dirac_operator
if Dirac_operator == "Staggered"
headername *=
"_mass" *
string(fermion_parameters.mass) *
"_Nf" *
string(fermion_parameters.Nf)
elseif Dirac_operator == "Wilson" || Dirac_operator == "WilsonClover"
headername *= "_kappa" * string(fermion_parameters.hop)
end
end
elseif update_method == "Heatbath"
headername *= "_quenched"
else
if Dirac_operator != nothing
headername *= "_" * Dirac_operator
if Dirac_operator == "Staggered"
headername *=
"_mass" *
string(fermion_parameters.mass) *
"_Nf" *
string(fermion_parameters.Nf)
elseif Dirac_operator == "Wilson" || Dirac_operator == "WilsonClover"
headername *= "_kappa" * string(fermion_parameters.hop)
end
else
end
end
return headername
end
end
#using .Wizard
#Wizard.run_wizard()
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 31466 | module MD
using LinearAlgebra
using Base.Threads
using Random, Distributions
import ..Verbose_print: Verbose_level, Verbose_3, Verbose_2, Verbose_1, println_verbose3
import ..Actions:
GaugeActionParam_standard,
FermiActionParam_WilsonClover,
FermiActionParam_Wilson,
GaugeActionParam_autogenerator,
SmearingParam_single,
SmearingParam_multi,
Nosmearing
import ..LTK_universe:
Universe,
calc_Action,
gauss_distribution,
make_WdagWmatrix,
set_β!,
calc_IntegratedFermionAction,
construct_fermion_gauss_distribution!,
construct_fermionfield_φ!,
construct_fermionfield_η!
import ..Gaugefields:
GaugeFields,
substitute!,
SU3GaugeFields,
set_wing!,
projlink!,
make_staple_double!,
GaugeFields_1d,
SU3GaugeFields_1d,
SU2GaugeFields_1d,
calc_Plaq_notrace_1d,
calc_GaugeAction,
apply_smearing,
calc_smearingU
import ..Gaugefields
import ..LieAlgebrafields:
gauss_distribution_lie!,
LieAlgebraFields,
SU3AlgebraFields,
SU2AlgebraFields,
Gauge2Lie!,
add!,
add_gaugeforce!,
expA!,
stoutfource
import ..Fermionfields:
gauss_distribution_fermi!,
set_wing_fermi!,
Wdagx!,
vvmat!,
FermionFields,
fermion_shift!,
WilsonFermion,
fermion_shiftB!,
StaggeredFermion,
Wx!,
clear!,
WdagWx!,
substitute_fermion!
using ..Fermionfields
import ..Heatbath: heatbath!
#import ..CGfermion:cg0!,cg0_WdagW!,shiftedcg0_WdagW!
import ..Clover: Make_CloverFμν!, dSclover!
import ..System_parameters: Params
import ..Diracoperators:
Wilson_operator,
Adjoint_Wilson_operator,
WilsonClover_operator,
Dirac_operator,
DdagD_operator
import ..CGmethods: bicg, cg, shiftedcg
import ..RationalApprox: calc_exactvalue, calc_Anϕ
import ..Rhmc: get_order, get_β, get_α, get_α0, get_β_inverse, get_α_inverse, get_α0_inverse
abstract type MD_parameters end
struct MD_parameters_SextonWeingargten <: MD_parameters
Δτ::Float64
MDsteps::Int64
N_SextonWeingargten::Int64
QPQ::Bool
function MD_parameters_SextonWeingargten(Δτ, MDsteps, N_SextonWeingargten; QPQ = true)
return new(Δτ, MDsteps, N_SextonWeingargten, QPQ)
end
end
struct MD_parameters_standard <: MD_parameters
Δτ::Float64
MDsteps::Int64
QPQ::Bool
function MD_parameters_standard(Δτ, MDsteps; QPQ = true)
return new(Δτ, MDsteps, QPQ)
end
end
struct MD_parameters_IntegratedHMC <: MD_parameters
Δτ::Float64
MDsteps::Int64
end
struct MD_parameters_IntegratedHB <: MD_parameters end
mutable struct MD_parameters_SLMC <: MD_parameters
βeff::Union{Float64,Array{Float64,1}}
debug::Bool
function MD_parameters_SLMC(βeff)
debug = false
#debug = true
return new(βeff, debug)
end
end
mutable struct MD_parameters_SLHMC <: MD_parameters
Δτ::Float64
MDsteps::Int64
βeff::Union{Float64,Array{Float64,1}}
end
function calc_factor(univ::Universe, mdparams::MD_parameters)
return -univ.gparam.β * mdparams.Δτ / (2 * univ.NC)
end
function construct_MD_parameters(p::Params)
#fac = - p.Δτ * p.β / (2*p.NC)
if p.SextonWeingargten
if p.quench == true
error(
"The quench update does not need the SextonWeingargten method. Put SextonWeingargten = false",
)
end
#return MD_parameters_SextonWeingargten(p.Δτ,p.MDsteps,fac,p.β,p.N_SextonWeingargten)
return MD_parameters_SextonWeingargten(p.Δτ, p.MDsteps, p.N_SextonWeingargten)
elseif p.SextonWeingargten == false && p.update_method == "IntegratedHMC"
if p.quench == false
error(
"quench = false. The IntegratedHMC needs the quench update. Put update_method != IntegratedHMC or quench = true",
)
end
#return MD_parameters_IntegratedHMC(p.Δτ,p.MDsteps,fac,p.β)
return MD_parameters_IntegratedHMC(p.Δτ, p.MDsteps)
elseif p.SextonWeingargten == false && p.update_method == "SLHMC"
if p.quench == false
error(
"quench = false. The SLHMC needs the quench update. Put update_method != SLHMC or quench = true",
)
end
#return MD_parameters_IntegratedHMC(p.Δτ,p.MDsteps,fac,p.β)
return MD_parameters_SLHMC(p.Δτ, p.MDsteps, p.βeff)
elseif p.SextonWeingargten == false && p.update_method == "IntegratedHB"
if p.quench == false
error(
"quench = false. The IntegratedHB needs the quench update. Put update_method != IntegratedHB or quench = true",
)
end
#return MD_parameters_IntegratedHMC(p.Δτ,p.MDsteps,fac,p.β)
return MD_parameters_IntegratedHB()
elseif p.SextonWeingargten == false && p.update_method == "SLMC"
if p.quench == false
error(
"quench = false. The SLMC needs the quench update. Put update_method != SLMC or quench = true",
)
end
#return MD_parameters_IntegratedHMC(p.Δτ,p.MDsteps,fac,p.β)
return MD_parameters_SLMC(p.βeff)
else
#return MD_parameters_standard(p.Δτ,p.MDsteps,fac,p.β)
return MD_parameters_standard(p.Δτ, p.MDsteps)
end
end
function MD_parameters_standard(gparam::GaugeActionParam_standard)
#βMD = gparam.β
MDsteps = 10
Δτ = 0.1
#fac = - Δτ * βMD / (2*gparam.NTRACE)
return MD_parameters_standard(gparam, Δτ, MDsteps)#,βMD)
end
function MD_parameters_standard(gparam::GaugeActionParam_standard, Δτ, MDsteps, βMD)
#fac = - Δτ * βMD / (2*gparam.NTRACE)
return MD_parameters_standard(Δτ, MDsteps)#,fac,βMD)
end
function md!(univ::Universe, mdparams::MD_parameters_standard)
#Sold = md_initialize!(univ::Universe)
QPQ = mdparams.QPQ #true
if QPQ
for istep = 1:mdparams.MDsteps
#println("istep = $istep")
updateU!(univ, mdparams, 0.5)
updateP!(univ, mdparams, 1.0)
if univ.quench == false
#if univ.fparam != nothing
updateP_fermi!(univ, mdparams, 1.0)
end
updateU!(univ, mdparams, 0.5)
#Sold,Sg = calc_Action(univ)
#println("$istep Sold,plaq = ",Sold,"\t",Sg)
#exit()
end
else
for istep = 1:mdparams.MDsteps
#println("istep = $istep")
updateP!(univ, mdparams, 0.5)
if univ.quench == false
#if univ.fparam != nothing
updateP_fermi!(univ, mdparams, 0.5)
end
updateU!(univ, mdparams, 1.0)
updateP!(univ, mdparams, 0.5)
if univ.quench == false
#if univ.fparam != nothing
updateP_fermi!(univ, mdparams, 0.5)
end
end
end
if univ.quench == false
construct_fermionfield_η!(univ)
end
Snew, plaq = calc_Action(univ)
return Snew
end
function md!(univ::Universe, mdparams::MD_parameters_SextonWeingargten)
#Sold = md_initialize!(univ::Universe)
QPQ = mdparams.QPQ
if QPQ != true
for istep = 1:mdparams.MDsteps
if univ.quench == false
updateP_fermi!(univ, mdparams, 0.5)
end
for istep_SW = 1:mdparams.N_SextonWeingargten
#println("istep_SW = $(istep_SW)")
updateP!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
updateU!(univ, mdparams, 1 / mdparams.N_SextonWeingargten)
updateP!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
end
if univ.quench == false
updateP_fermi!(univ, mdparams, 0.5)
end
end
elseif QPQ
@assert mdparams.N_SextonWeingargten % 2 == 0 "mdparams.N_SextonWeingargten % 2 should be 0!"
for istep = 1:mdparams.MDsteps
for istep_SW = 1:div(mdparams.N_SextonWeingargten, 2)
updateU!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
updateP!(univ, mdparams, 1 / mdparams.N_SextonWeingargten)
updateU!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
end
if univ.quench == false
updateP_fermi!(univ, mdparams, 1.0)
end
for istep_SW = 1:div(mdparams.N_SextonWeingargten, 2)
updateU!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
updateP!(univ, mdparams, 1 / mdparams.N_SextonWeingargten)
updateU!(univ, mdparams, 0.5 / mdparams.N_SextonWeingargten)
end
end
end
if univ.quench == false
construct_fermionfield_η!(univ)
end
Snew, plaq = calc_Action(univ)
return Snew
end
function md!(univ::Universe, Sfold, Sgold, mdparams::MD_parameters_IntegratedHMC)
@assert univ.quench == true "quench should be true!"
if Sfold == nothing
WdagW = make_WdagWmatrix(univ)
#e,_ = eigen(WdagW)
#println(e)
Sfold = -real(logdet(WdagW))
#Uold = deepcopy(univ.U)
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfold /= 2
end
end
end
for istep = 1:mdparams.MDsteps
updateU!(univ, mdparams, 0.5)
updateP!(univ, mdparams, 1.0)
updateU!(univ, mdparams, 0.5)
end
Sgnew, plaq = calc_Action(univ)
println("Making W^+W matrix...")
@time WdagW = make_WdagWmatrix(univ)
println("Calculating logdet")
@time Sfnew = -real(logdet(WdagW))
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfnew /= 2
end
end
#
#println("Snew,plaq = ",Snew,"\t",plaq)
println("Sgnew,Sfnew,Sgold,Sfold: ", Sgnew, "\t", Sfnew, "\t", Sgold, "\t", Sfold)
return Sgnew, Sfnew, Sgold, Sfold
end
function md!(univ::Universe, Sfold, Sgold, mdparams::MD_parameters_IntegratedHB)
@assert univ.quench == true "quench should be true!"
@assert univ.NC == 2 "Only SU(2) is supported now."
if Sfold == nothing
@time Sfold = calc_IntegratedFermionAction(univ)
#=
WdagW = make_WdagWmatrix(univ)
#e,_ = eigen(WdagW)
#println(e)
Sfold = -real(logdet(WdagW))
#Uold = deepcopy(univ.U)
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfold /= 2
end
end
=#
end
Sgold, plaq = calc_GaugeAction(univ)
Sgeffold = Sgold
heatbath!(univ)
Sgnew, plaq = calc_GaugeAction(univ)
Sgeffnew = Sgnew
#=
println("Making W^+W matrix...")
@time WdagW = make_WdagWmatrix(univ)
println("Calculating logdet")
@time Sfnew = -real(logdet(WdagW))
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfnew /= 2
end
end
=#
@time Sfnew = calc_IntegratedFermionAction(univ)
#
#println("Snew,plaq = ",Snew,"\t",plaq)
println("Sgnew,Sfnew,Sgold,Sfold: ", Sgnew, "\t", Sfnew, "\t", Sgold, "\t", Sfold)
return Sgnew, Sfnew, Sgeffnew, Sgold, Sfold, Sgeffold
end
function md!(univ::Universe, Sfold, Sgold, mdparams::MD_parameters_SLMC)
@assert univ.quench == true "quench should be true!"
#@assert univ.NC == 2 "Only SU(2) is supported now."
if Sfold == nothing
@time Sfold = calc_IntegratedFermionAction(univ, debug = mdparams.debug)
#=
WdagW = make_WdagWmatrix(univ)
#e,_ = eigen(WdagW)
#println(e)
Sfold = -real(logdet(WdagW))
#Uold = deepcopy(univ.U)
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfold /= 2
end
end
=#
end
β = univ.gparam.β
Sgold, plaq = calc_GaugeAction(univ)
set_β!(univ, mdparams.βeff)
Sgeffold, plaq = calc_GaugeAction(univ)
heatbath!(univ)
#heatbath!(univ)
Sgeffnew, plaq = calc_GaugeAction(univ)
set_β!(univ, β)
Sgnew, plaq = calc_GaugeAction(univ)
@time Sfnew = calc_IntegratedFermionAction(univ, debug = mdparams.debug)
#println("Sfnew comparison: $Sfnew,$Sfnew2")
#
#println("Snew,plaq = ",Snew,"\t",plaq)
println(
"Sgnew,Sfnew,Sgeffnew,Sgold,Sfold,Sgeffold: ",
Sgnew,
"\t",
Sfnew,
"\t",
Sgeffnew,
"\t",
Sgold,
"\t",
Sfold,
"\t",
Sgeffold,
)
return Sgnew, Sfnew, Sgeffnew, Sgold, Sfold, Sgeffold
end
function md!(univ::Universe, Sfold, Sgold, mdparams::MD_parameters_SLHMC)
@assert univ.quench == true "quench should be true!"
if Sfold == nothing
WdagW = make_WdagWmatrix(univ)
#e,_ = eigen(WdagW)
Sfold = -real(logdet(WdagW))
#Uold = deepcopy(univ.U)
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfold /= 2
end
end
end
β = univ.gparam.β
set_β!(univ, mdparams.βeff)
for istep = 1:mdparams.MDsteps
updateU!(univ, mdparams, 0.5)
updateP!(univ, mdparams, 1.0)
updateU!(univ, mdparams, 0.5)
end
set_β!(univ, β)
Sgnew, plaq = calc_Action(univ)
println("Making W^+W matrix...")
@time WdagW = make_WdagWmatrix(univ)
println("Calculating logdet")
@time Sfnew = -real(logdet(WdagW))
if univ.Dirac_operator == "Staggered"
if univ.fparam.Nf == 4
Sfnew /= 2
end
end
#
#println("Snew,plaq = ",Snew,"\t",plaq)
println("Sgnew,Sfnew,Sgold,Sfold: ", Sgnew, "\t", Sfnew, "\t", Sgold, "\t", Sfold)
return Sgnew, Sfnew, Sgold, Sfold, plaq
end
function md_initialize!(univ::Universe)
substitute!(univ.Uold, univ.U)
NV = univ.NV
NDFALG = univ.NDFALG
for μ = 1:4
pwork = gauss_distribution(univ, NV * NDFALG)
substitute!(univ.p[μ], pwork)
#display(univ.p[μ])
end
#gauss_distribution_lie!(univ.p)
if univ.quench == false
#if univ.fparam != nothing
construct_fermion_gauss_distribution!(univ) #generate η
#println(univ.η*univ.η)
construct_fermionfield_φ!(univ) #generate φ
end
Sold, Sg = calc_Action(univ)
#println("-----------------------------------------------")
#println("Sold,plaq in init = ",Sold,"\t",Sg)
#println("-----------------------------------------------")
#exit()
return Sold
end
function metropolis_update!(univ::Universe, Sold, Snew)
accept = exp(Sold - Snew) >= univ.ranf()
println("Snew,Sold $Snew $Sold")
println("Sold,Snew,Diff,accept: $Sold $Snew $(Sold-Snew) $accept")
if accept
else
substitute!(univ.U, univ.Uold)
end
return accept
end
function updateP_fermi!(univ::Universe, mdparams::MD_parameters, τ)
updateP_fermi!(
univ.η,
univ.φ,
univ.ξ,
univ.fparam,
univ.p,
mdparams,
τ,
univ.U,
univ._temporal_gauge,
univ._temporal_algebra,
univ._temporal_fermi,
kind_of_verboselevel = univ.kind_of_verboselevel,
)
return
end
function updateP_fermi_fromX!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
U::Array{T,1},
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
) where {F<:WilsonFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
W = Dirac_operator(U, φ, fparam)
mul!(Y, W, X)
set_wing_fermi!(Y)
for μ = 1:4
#! Construct U(x,mu)*P1
# U_{k,μ} X_{k+μ}
fermion_shift!(temp0_f, U, μ, X)
# (r-γ_μ) U_{k,μ} X_{k+μ}
mul!(temp0_f, view(X.rminusγ, :, :, μ), temp0_f)
# κ (r-γ_μ) U_{k,μ} X_{k+μ}
mul!(temp1_f, X.hopp[μ], temp0_f)
# κ ((r-γ_μ) U_{k,μ} X_{k+μ}) ⊗ Y_k
vvmat!(temp2_g, temp1_f, Y, 1)
#..... Projection onto Lie Algebra .....
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
#... p(new) = p(old) + fac * c .....
add!(p[μ], τ * mdparams.Δτ, c)
#! Construct P2*U_adj(x,mu)
# Y_{k+μ}^dag U_{k,μ}^dag
fermion_shiftB!(temp0_f, U, -μ, Y)
# Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
mul!(temp0_f, temp0_f, view(X.rplusγ, :, :, μ))
# κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
mul!(temp1_f, X.hopm[μ], temp0_f)
# X_k ⊗ κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
vvmat!(temp2_g, X, temp1_f, 2)
#..... Projection onto Lie Algebra .....
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
add!(p[μ], -τ * mdparams.Δτ, c)
if typeof(fparam) == FermiActionParam_WilsonClover
dSclover!(c, μ, X, Y, U, fparam, temps)
add!(p[μ], -τ * mdparams.Δτ, c)
end
end
end
function updateP_fermi_fromX_smearing!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
U::Array{T,1},
Uout_multi,
dSdU,
Uin,
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
) where {F<:WilsonFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
W = Dirac_operator(U, φ, fparam)
mul!(Y, W, X)
set_wing_fermi!(Y)
for μ = 1:4
#! Construct U(x,mu)*P1
# U_{k,μ} X_{k+μ}
fermion_shift!(temp0_f, U, μ, X)
# (r-γ_μ) U_{k,μ} X_{k+μ}
mul!(temp0_f, view(X.rminusγ, :, :, μ), temp0_f)
# κ (r-γ_μ) U_{k,μ} X_{k+μ}
mul!(temp1_f, X.hopp[μ], temp0_f)
# κ ((r-γ_μ) U_{k,μ} X_{k+μ}) ⊗ Y_k
vvmat!(temp2_g, temp1_f, Y, 1)
mul!(dSdU[μ], U[μ]', temp2_g) #additional term
#! Construct P2*U_adj(x,mu)
# Y_{k+μ}^dag U_{k,μ}^dag
fermion_shiftB!(temp0_f, U, -μ, Y)
# Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
mul!(temp0_f, temp0_f, view(X.rplusγ, :, :, μ))
# κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
mul!(temp1_f, X.hopm[μ], temp0_f)
# X_k ⊗ κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
vvmat!(temp2_g, X, temp1_f, 2)
mul!(temp3_g, U[μ]', temp2_g)
#Gaugefields.add!(dSdU[μ],temp3_g)
Gaugefields.muladd!(dSdU[μ], -1, temp3_g)
if typeof(fparam) == FermiActionParam_WilsonClover
dSclover!(c, μ, X, Y, U, fparam, temps)
Gaugefields.muladd!(dSdU[μ], -1, c)
#add!(p[μ],-τ*mdparams.Δτ,c)
end
end
if typeof(fparam.smearing) <: SmearingParam_single
dSdUnew, _ = stoutfource(dSdU, Uin, fparam.smearing)
elseif typeof(fparam.smearing) <: SmearingParam_multi
dSdUnew, _ = stoutfource(dSdU, Uout_multi, Uin, fparam.smearing)
elseif typeof(fparam.smearing) <: Nosmearing
dSdUnew = dSdU
else
error("$(typeof(fparam.smearing)) is not supported")
end
for μ = 1:4
mul!(temp2_g, Uin[μ], dSdUnew[μ])
#..... Projection onto Lie Algebra .....
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
#... p(new) = p(old) + fac * c .....
add!(p[μ], τ * mdparams.Δτ, c)
end
end
function updateP_fermi_fromX!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
U::Array{T,1},
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
coeff = 1,
) where {F<:StaggeredFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
W = Dirac_operator(U, φ, fparam)
mul!(Y, W, X)
for μ = 1:4
#! Construct U(x,mu)*P1
# U_{k,μ} X_{k+μ}
fermion_shift!(temp0_f, U, μ, X)
# κ ((r-γ_μ) U_{k,μ} X_{k+μ}) ⊗ Y_k
vvmat!(temp2_g, temp0_f, Y, 1)
#..... Projection onto Lie Algebra .....
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
#... p(new) = p(old) + fac * c .....
add!(p[μ], -0.5 * τ * mdparams.Δτ * coeff, c)
#! Construct P2*U_adj(x,mu)
# Y_{k+μ}^dag U_{k,μ}^dag
fermion_shiftB!(temp0_f, U, -μ, Y)
# Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
# X_k ⊗ κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
vvmat!(temp2_g, X, temp0_f, 2)
#..... Projection onto Lie Algebra .....
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
add!(p[μ], -0.5 * τ * mdparams.Δτ * coeff, c)
end
return
end
function updateP_fermi_fromX_smearing!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
U::Array{T,1},
Uout_multi,
dSdU,
Uin,
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
coeff = 1,
) where {F<:StaggeredFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
W = Dirac_operator(U, φ, fparam)
mul!(Y, W, X)
for μ = 1:4
#! Construct U(x,mu)*P1
# U_{k,μ} X_{k+μ}
fermion_shift!(temp0_f, U, μ, X)
# κ ((r-γ_μ) U_{k,μ} X_{k+μ}) ⊗ Y_k
vvmat!(temp2_g, temp0_f, Y, 1)
mul!(dSdU[μ], U[μ]', temp2_g) #additional term
#! Construct P2*U_adj(x,mu)
# Y_{k+μ}^dag U_{k,μ}^dag
fermion_shiftB!(temp0_f, U, -μ, Y)
# X_k ⊗ κ Y_{k+μ}^dag U_{k,μ}^dag*(r+γ_μ)
#vvmat!(UdSdU2[μ],X,temp0_f,2)
#if fparam.smearing != nothing
vvmat!(temp2_g, X, temp0_f, 2)
mul!(temp3_g, U[μ]', temp2_g)
Gaugefields.add!(dSdU[μ], temp3_g)
end
if typeof(fparam.smearing) <: SmearingParam_single
dSdUnew, _ = stoutfource(dSdU, Uin, fparam.smearing)
elseif typeof(fparam.smearing) <: SmearingParam_multi
dSdUnew, _ = stoutfource(dSdU, Uout_multi, Uin, fparam.smearing)
else
error("$(typeof(fparam.smearing)) is not supported")
end
for μ = 1:4
mul!(temp2_g, Uin[μ], dSdUnew[μ])
projlink!(temp3_g, temp2_g)
Gauge2Lie!(c, temp3_g)
add!(p[μ], -0.5 * τ * mdparams.Δτ * coeff, c)
end
return
end
function updateP_fermi!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
Uin::Array{T,1},
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
) where {F<:WilsonFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
U, Uout_multi, dSdU =
calc_smearingU(Uin, fparam.smearing, calcdSdU = true, temps = temps)
WdagW = DdagD_operator(U, φ, fparam)
cg(
X,
WdagW,
φ,
eps = fparam.eps,
maxsteps = fparam.MaxCGstep,
verbose = kind_of_verboselevel,
)
set_wing_fermi!(X)
if fparam.smearing != nothing && typeof(fparam.smearing) != Nosmearing
updateP_fermi_fromX_smearing!(
Y,
φ,
X,
fparam,
p,
mdparams,
τ,
U,
Uout_multi,
dSdU,
Uin,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
)
else
updateP_fermi_fromX!(
Y,
φ,
X,
fparam,
p,
mdparams,
τ,
U,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
)
end
return
end
function updateP_fermi!(
Y::F,
φ::F,
X::F,
fparam,
p::Array{N,1},
mdparams::MD_parameters,
τ,
Uin::Array{T,1},
temps::Array{T_1d,1},
temp_a::Array{N,1},
temps_fermi;
kind_of_verboselevel = Verbose_2(),
) where {F<:StaggeredFermion,T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp0_f = temps_fermi[1] #F_field
temp1_f = temps_fermi[2] #F_field
temp2_g = temps[1] #G_field1
temp3_g = temps[2] #G_field1
c = temp_a[1]
NV = temp2_g.NV
U, Uout_multi, dSdU =
calc_smearingU(Uin, fparam.smearing, calcdSdU = true, temps = temps)
WdagW = DdagD_operator(U, φ, fparam)
if fparam.Nf == 4 || fparam.Nf == 8
#X = (D^dag D)^(-1) ϕ
#
cg(
X,
WdagW,
φ,
eps = fparam.eps,
maxsteps = fparam.MaxCGstep,
verbose = kind_of_verboselevel,
)
set_wing_fermi!(X)
if fparam.smearing != nothing && typeof(fparam.smearing) != Nosmearing
updateP_fermi_fromX_smearing!(
Y,
φ,
X,
fparam,
p,
mdparams,
τ,
U,
Uout_multi,
dSdU,
Uin,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
)
else
updateP_fermi_fromX!(
Y,
φ,
X,
fparam,
p,
mdparams,
τ,
U,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
)
end
else
N_MD = get_order(fparam.rhmc_MD)
#numtemps_fermi = length(temps_fermi)
x = temps_fermi[end-N_MD]
vec_x = temps_fermi[end-N_MD+1:end]
for j = 1:N_MD
Fermionfields.clear!(vec_x[j])
end
vec_β = get_β_inverse(fparam.rhmc_MD)
vec_α = get_α_inverse(fparam.rhmc_MD)
α0 = get_α0_inverse(fparam.rhmc_MD)
shiftedcg(vec_x, vec_β, x, WdagW, φ, eps = fparam.eps, maxsteps = fparam.MaxCGstep)
for j = 1:N_MD
set_wing_fermi!(vec_x[j])
if fparam.smearing != nothing && typeof(fparam.smearing) != Nosmearing
updateP_fermi_fromX_smearing!(
Y,
φ,
vec_x[j],
fparam,
p,
mdparams,
τ,
U,
Uout_multi,
dSdU,
Uin,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
coeff = vec_α[j],
)
else
updateP_fermi_fromX!(
Y,
φ,
vec_x[j],
fparam,
p,
mdparams,
τ,
U,
temps,
temp_a,
temps_fermi,
kind_of_verboselevel = kind_of_verboselevel,
coeff = vec_α[j],
)
end
end
end
#exit()
return
end
function updateP!(univ::Universe, mdparams::MD_parameters, τ)
factor = calc_factor(univ, mdparams)
updateP!(
univ.p,
factor,
τ,
univ.U,
univ._temporal_gauge,
univ._temporal_algebra[1],
univ.gparam,
)
return
end
function updateP!(
p::Array{N,1},
factor,
τ,
U::Array{T,1},
temps::Array{T_1d,1},
temp_a::N,
gparam::GaugeActionParam_autogenerator,
) where {T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
add_gaugeforce!(p, U, temps, temp_a, gparam, fac = τ * factor)
return
end
function updateP!(
p::Array{N,1},
factor,
τ,
U::Array{T,1},
temps::Array{T_1d,1},
temp_a::N,
gparam::GaugeActionParam_standard,
) where {T<:GaugeFields,N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
add_gaugeforce!(p, U, temps, temp_a, fac = τ * factor)
return
end
function updateU!(univ::Universe, mdparams::MD_parameters, τ)
updateU!(univ.U, mdparams, τ, univ.p, univ._temporal_gauge, univ._temporal_algebra[1])
return
end
function updateU!(
U,
mdparams::MD_parameters,
τ,
p::Array{N,1},
temps,
temp_a::N,
) where {N<:LieAlgebraFields}
temp1 = temps[1]
temp2 = temps[2]
temp3 = temps[3]
temp4 = temps[4]
c = temp_a
for μ = 1:4
substitute!(temp1, U[μ])
mul!(c, τ * mdparams.Δτ, p[μ])
expA!(temp2, c, temp3, temp4)
#mul!(temp3,temp1,U[μ])
mul!(temp3, temp2, temp1)
substitute!(U[μ], temp3)
set_wing!(U[μ])
end
end
function updateU!(
U,
mdparams::MD_parameters,
τ,
p::Array{N,1},
temps::Array{T_1d,1},
temp_a::N,
) where {N<:LieAlgebraFields,T_1d<:GaugeFields_1d}
temp1 = temps[1]
temp2 = temps[2]
temp3 = temps[3]
temp4 = temps[4]
c = temp_a
for μ = 1:4
substitute!(temp1, U[μ])
mul!(c, τ * mdparams.Δτ, p[μ])
expA!(temp2, c, temp3, temp4)
#mul!(temp3,temp1,U[μ])
mul!(temp3, temp2, temp1)
substitute!(U[μ], temp3)
set_wing!(U[μ])
end
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 53320 | module Measurements
using LinearAlgebra
using SparseArrays
using KrylovKit
import ..LTK_universe: Universe, make_WdagWmatrix, calc_IntegratedFermionAction
import ..Gaugefields:
GaugeFields,
set_wing!,
substitute!,
make_staple!,
calc_Plaq!,
SU3GaugeFields,
SU2GaugeFields,
SU3GaugeFields_1d,
SU2GaugeFields_1d,
GaugeFields_1d,
calc_Polyakov,
calc_Plaq,
calc_Plaq_notrace_1d,
SUn,
SU2,
SU3,
TA,
add!,
SUNGaugeFields,
SUNGaugeFields_1d,
Loops,
evaluate_loops!,
evaluate_loops,
U1GaugeFields,
U1GaugeFields_1d,
calc_smearingU
import ..Fermionfields: clear!, FermionFields, WilsonFermion
import ..Fermionfields: Z4_distribution_fermi!, gauss_distribution_fermi!, set_wing_fermi!
import ..CGmethods: bicg
#import ..CGfermion:cg0!
import ..System_parameters: Params
import ..Actions:
FermiActionParam_Wilson, FermiActionParam_Staggered, FermiActionParam_WilsonClover
import ..Diracoperators: Dirac_operator, γ5D_operator
import ..Verbose_print:
Verbose_level,
Verbose_3,
Verbose_2,
Verbose_1,
println_verbose3,
println_verbose2,
println_verbose1,
print_verbose1,
print_verbose2,
print_verbose3
import ..Smearing:
gradientflow!,
calc_stout!,
calc_fatlink_APE!,
calc_stout,
calc_fatlink_APE,
calc_multihit!
import ..Wilsonloops: Wilson_loop, Wilson_loop_set
#import ..System_parameters: set_params
#=
abstract type MeasureMethod end
Base.@kwdef mutable struct Pion_correlator <: MeasureMethod
measure_every::Int64 = 10
Dirac_operator::String = "Wilson"
end
=#
struct Measurement{Fermi,GaugeP,FermiP,Gauge_temp}
gparam::GaugeP
fparam::Union{Nothing,FermiP}
_temporal_gauge::Array{Gauge_temp,1}
_temporal_fermi1::Union{Nothing,Array{Fermi,1}}
_temporal_fermi2::Union{Nothing,Array{Fermi,1}}
function Measurement(p::Params, univ::Universe)
if p.Dirac_operator == p.Dirac_operator_measurement
return Measurement(univ, Dirac_operator = univ.Dirac_operator)
else
if p.Dirac_operator_measurement == nothing
fparam = nothing
else
if p.Dirac_operator_measurement == "Wilson"
fparam = FermiActionParam_Wilson(
p.hop_measurement,
p.r_measurement,
p.eps_measurement,
p.Dirac_operator_measurement,
p.MaxCGstep_measurement,
p.quench,
)
elseif p.Dirac_operator_measurement == "Staggered"
fparam = FermiActionParam_Staggered(
p.mass_measurement,
p.eps_measurement,
p.Dirac_operator_measurement,
p.MaxCGstep_measurement,
p.quench,
p.Nf,
)
end
end
return Measurement(univ, fparam; Dirac_operator = p.Dirac_operator_measurement)
end
end
function Measurement(univ::Universe, gparam, fparam; Dirac_operator = nothing)
NX = univ.NX
NY = univ.NY
NZ = univ.NZ
NT = univ.NT
NC = univ.NC
if NC == 3
U = Array{SU3GaugeFields,1}(undef, 4)
_temporal_gauge = Array{SU3GaugeFields_1d,1}(undef, 4)
elseif NC == 2
U = Array{SU2GaugeFields,1}(undef, 4)
_temporal_gauge = Array{SU2GaugeFields_1d,1}(undef, 4)
elseif NC ≥ 4
U = Array{SUNGaugeFields,1}(undef, 4)
_temporal_gauge = Array{SUNGaugeFields_1d,1}(undef, 4)
elseif NC == 1
U = Array{U1GaugeFields,1}(undef, 4)
_temporal_gauge = Array{U1GaugeFields_1d,1}(undef, 4)
end
for i = 1:length(_temporal_gauge)
_temporal_gauge[i] = GaugeFields_1d(NC, NX, NY, NZ, NT) #similar(U[1])
end
if Dirac_operator == nothing
_temporal_fermi1 = nothing
_temporal_fermi2 = nothing
φ = nothing
else
φ = FermionFields(NC, NX, NY, NZ, NT, fparam, univ.BoundaryCondition)
_temporal_fermi1 = Array{FermionFields,1}(undef, 4)
_temporal_fermi2 = Array{FermionFields,1}(undef, 4)
for i = 1:length(_temporal_fermi1)
_temporal_fermi1[i] = similar(φ)
end
for i = 1:length(_temporal_fermi2)
_temporal_fermi2[i] = similar(φ)
end
end
Fermi = typeof(φ)
GaugeP = typeof(gparam)
FermiP = typeof(fparam)
Gauge_temp = eltype(_temporal_gauge)
return new{Fermi,GaugeP,FermiP,Gauge_temp}(
gparam,
fparam,
_temporal_gauge,
_temporal_fermi1,
_temporal_fermi2,
)
end
function Measurement(univ::Universe; Dirac_operator = nothing)
return Measurement(
univ::Universe,
univ.gparam,
univ.fparam,
Dirac_operator = Dirac_operator,
)
end
function Measurement(univ::Universe, fparam; Dirac_operator = nothing)
return Measurement(
univ::Universe,
univ.gparam,
fparam,
Dirac_operator = Dirac_operator,
)
end
end
defaultmeasures = Array{Dict,1}(undef, 2)
for i = 1:length(defaultmeasures)
defaultmeasures[i] = Dict()
end
defaultmeasures[1]["methodname"] = "Plaquette"
defaultmeasures[1]["measure_every"] = 1
defaultmeasures[1]["fermiontype"] = nothing
defaultmeasures[2]["methodname"] = "Polyakov_loop"
defaultmeasures[2]["measure_every"] = 1
defaultmeasures[2]["fermiontype"] = nothing
#=
defaultmeasures[3]["methodname"] = "Chiral_cond"
defaultmeasures[3]["measure_every"] = 10
defaultmeasures[3]["fermiontype"] = "Staggered"
defaultmeasures[4]["methodname"] = "Pion_correlator"
defaultmeasures[4]["measure_every"] = 20
defaultmeasures[4]["fermiontype"] = "Wilson"
defaultmeasures[5]["methodname"] = "Topologicalcharge"
defaultmeasures[5]["measure_every"] = 5
defaultmeasures[5]["fermiontype"] = nothing
defaultmeasures[5]["numflow"] = 10
=#
struct Measurement_set
nummeasurement::Int64
fermions::Array{Measurement,1}
measurement_methods::Array{Dict,1}
measurementfps::Array{IOStream,1}
function Measurement_set(
univ::Universe,
measurement_dir;
measurement_methods = defaultmeasures,
)
nummeasurement = length(measurement_methods)
fermions = Array{Measurement,1}(undef, nummeasurement)
measurementfps = Array{IOStream,1}(undef, nummeasurement)
for i = 1:nummeasurement
method = measurement_methods[i]
if haskey(method, "fermiontype")
fermiontype = method["fermiontype"]
else
fermiontype = nothing
end
measure_overwrite = "w"
if method["methodname"] == "Plaquette"
measurementfps[i] =
open(measurement_dir * "/Plaquette.txt", measure_overwrite)
elseif method["methodname"] == "Polyakov_loop"
measurementfps[i] =
open(measurement_dir * "/Polyakov_loop.txt", measure_overwrite)
elseif method["methodname"] == "Topological_charge"
measurementfps[i] =
open(measurement_dir * "/Topological_charge.txt", measure_overwrite)
elseif method["methodname"] == "Chiral_condensate"
measurementfps[i] =
open(measurement_dir * "/Chiral_condensate.txt", measure_overwrite)
@assert fermiontype != nothing "fermiontype should be set in Chiral_condensate measurement"
elseif method["methodname"] == "Pion_correlator"
measurementfps[i] =
open(measurement_dir * "/Pion_correlator.txt", measure_overwrite)
@assert fermiontype != nothing "fermiontype should be set in Pion_correlator measurement"
elseif method["methodname"] == "Polyakov_loop_correlator"
measurementfps[i] = open(
measurement_dir * "/Polyakov_loop_correlator.txt",
measure_overwrite,
)
elseif method["methodname"] == "Wilson_loop"
measurementfps[i] =
open(measurement_dir * "/Wilson_loop.txt", measure_overwrite)
elseif method["methodname"] == "smeared_Wilson_loop"
measurementfps[i] =
open(measurement_dir * "/smeared_Wilson_loop.txt", measure_overwrite)
elseif method["methodname"] == "integrated_fermion_action"
measurementfps[i] = open(measurement_dir * "/Fermion_actions.txt", "w")
elseif method["methodname"] == "eigenvalues"
measurementfps[i] = open(measurement_dir * "/eigenvalues.txt", "w")
else
error("$(method["methodname"]) is not supported in measurement functions")
end
if haskey(method, "eps")
eps = method["eps"]
else
eps = 1e-16
end
if haskey(method, "MaxCGstep")
MaxCGstep = method["MaxCGstep"]
else
MaxCGstep = 5000
end
if fermiontype == "Wilson"
if haskey(method, "hop")
hop = method["hop"]
else
hop = 0.141139
println(
"Warning. hop = $hop, Default value is used in measurement $(method["methodname"])",
)
end
if haskey(method, "r")
r = method["r"]
else
r = 1
end
quench = false
smearing_for_fermion = set_params(method, "smearing_for_fermion", "nothing")
stout_numlayers = set_params(method, "stout_numlayers", nothing)
stout_ρ = set_params(method, "stout_ρ", nothing)
stout_loops = set_params(method, "stout_loops", nothing)
#fparam = FermiActionParam_Wilson(hop,r,eps,fermiontype,MaxCGstep,quench)
if smearing_for_fermion == "nothing"
fparam =
FermiActionParam_Wilson(hop, r, eps, fermiontype, MaxCGstep, quench)
else
L = (univ.NX, univ.NY, univ.NZ, univ.NT)
fparam = FermiActionParam_Wilson(
hop,
r,
eps,
fermiontype,
MaxCGstep,
quench,
smearingparameters = "stout",
loops_list = stout_loops,
coefficients = stout_ρ,
numlayers = stout_numlayers,
L = L,
)
end
elseif fermiontype == "WilsonClover"
if haskey(method, "hop")
hop = method["hop"]
else
hop = 0.141139
println(
"Warning. hop = $hop, Default value is used in measurement $(method["methodname"])",
)
end
if haskey(method, "r")
r = method["r"]
else
r = 1
end
if haskey(method, "Clover_coefficient")
Clover_coefficient = method["Clover_coefficient"]
else
Clover_coefficient = 1.5612
end
NV = univ.NV
inn_table = zeros(Int64, NV, 4, 2)
internal_flags = zeros(Bool, 2)
_ftmp_vectors = Array{Array{ComplexF64,3},1}(undef, 6)
for i = 1:6
_ftmp_vectors[i] = zeros(ComplexF64, univ.NC, NV, 4)
end
_is1 = zeros(Int64, NV)
_is2 = zeros(Int64, NV)
quench = false
fparam = FermiActionParam_WilsonClover(
hop,
r,
eps,
fermiontype,
MaxCGstep,
Clover_coefficient,
internal_flags,
inn_table,
_ftmp_vectors,
_is1,
_is2,
quench,
)
smearing_for_fermion = set_params(method, "smearing_for_fermion", "nothing")
stout_numlayers = set_params(method, "stout_numlayers", nothing)
stout_ρ = set_params(method, "stout_ρ", nothing)
stout_loops = set_params(method, "stout_loops", nothing)
if smearing_for_fermion == "nothing"
FermiActionParam_WilsonClover(
hop,
r,
eps,
fermiontype,
MaxCGstep,
Clover_coefficient,
internal_flags,
inn_table,
_ftmp_vectors,
_is1,
_is2,
quench,
)
else
error("stout for WilsonClover is not supported yet!")
L = (univ.NX, univ.NY, univ.NZ, univ.NT)
FermiActionParam_WilsonClover(
hop,
r,
eps,
fermiontype,
MaxCGstep,
Clover_coefficient,
internal_flags,
inn_table,
_ftmp_vectors,
_is1,
_is2,
quench,
smearingparameters = "stout",
loops_list = stout_loops,
coefficients = stout_ρ,
numlayers = stout_numlayers,
L = L,
)
end
elseif fermiontype == "Staggered"
if haskey(method, "mass")
mass = method["mass"]
else
mass = 0.5
println(
"Warning. mass = $mass, Default value is used in measurement $(method["methodname"])",
)
end
if haskey(method, "Nf")
Nf = method["Nf"]
else
error(
"Nf should be set if you want to use the staggered fermion in measurements",
)
#println("Warning. mass = $hop, Default value is used")
end
quench = false
smearing_for_fermion = set_params(method, "smearing_for_fermion", "nothing")
stout_numlayers = set_params(method, "stout_numlayers", nothing)
stout_ρ = set_params(method, "stout_ρ", nothing)
stout_loops = set_params(method, "stout_loops", nothing)
if smearing_for_fermion == "nothing"
fparam = FermiActionParam_Staggered(
mass,
eps,
fermiontype,
MaxCGstep,
quench,
Nf,
)
else
L = (univ.NX, univ.NY, univ.NZ, univ.NT)
fparam = FermiActionParam_Staggered(
mass,
eps,
fermiontype,
MaxCGstep,
quench,
Nf,
smearingparameters = "stout",
loops_list = stout_loops,
coefficients = stout_ρ,
numlayers = stout_numlayers,
L = L,
)
end
#println("Measurement_set::mass_measurement = $(p.mass_measurement)")
#fparam = FermiActionParam_Staggered(mass,eps,fermiontype,MaxCGstep,quench,Nf)
elseif fermiontype == nothing
fparam = nothing
else
error("$fermiontype is not supported. use Wilson or Staggered")
end
fermions[i] = Measurement(univ, fparam; Dirac_operator = fermiontype)
end
return new(nummeasurement, fermions, measurement_methods, measurementfps)
end
end
function measurements(itrj, U, univ, measset::Measurement_set; verbose = Verbose_2())
plaq = 0.0
poly = 0.0 + 0.0im
for i = 1:measset.nummeasurement
method = measset.measurement_methods[i]
measfp = measset.measurementfps[i]
#println(method)
#println(method["measure_every"])
if itrj % method["measure_every"] == 0
println_verbose1(verbose, "-----------------")
if method["methodname"] == "Plaquette"
plaq = calc_plaquette(U)
println_verbose1(verbose, "$itrj $plaq # plaq")
println(measfp, "$itrj $plaq # plaq")
elseif method["methodname"] == "integrated_fermion_action"
Sfexact, Sfapprox = calc_fermionaction(univ, measset.fermions[i], method)
println_verbose1(
verbose,
"$itrj $(real(Sfexact)) $(real(Sfapprox)) # fermion action",
)
println(measfp, "$itrj $(real(Sfexact)) $(real(Sfapprox)) # fermion action")
elseif method["methodname"] == "Wilson_loop"
for T = 1:method["Tmax"]
for R = 1:method["Rmax"]
WL = calc_Wilson_loop(U, T, R) # calculate RxT Wilson loop
println_verbose1(verbose, "$itrj $T $R $WL # WL # itrj T R W(T,R)")
println(measfp, "$itrj $T $R $WL # WL # itrj T R W(T,R)")
end
end
elseif method["methodname"] == "smeared_Wilson_loop"
Usmr = deepcopy(U)
# arXiv:hep-lat/0107006
α = 0.5
for iflow = 1:5 #method["numflow"]
calc_fatlink_APE!(
Usmr,
α,
α,
normalize_method = "special unitary",
temporal_dir_smear = false,
)
end
for T = 1:method["Tmax"]
for R = 1:method["Rmax"]
WL = calc_Wilson_loop(Usmr, T, R) # calculate RxT Wilson loop
println_verbose1(verbose, "$itrj $T $R $WL # sWL # itrj T R W(T,R)")
println(measfp, "$itrj $T $R $WL # sWL # itrj T R W(T,R)")
end
end
elseif method["methodname"] == "Polyakov_loop"
poly = calc_Polyakov(U)
println_verbose1(verbose, "$itrj $(real(poly)) $(imag(poly)) # poly")
println(measfp, "$itrj $(real(poly)) $(imag(poly)) # poly")
elseif method["methodname"] == "Polyakov_loop_correlator"
Usmr = deepcopy(U)
β = univ.gparam.β
calc_multihit!(Usmr, U, β)
#α = 0.5
#calc_fatlink_APE!(Usmr,α,α,normalize_method="special unitary", temporal_dir_smear=false)
for R = 1:method["Rmax"]
PP = calc_Polyakov_loop_correlator(Usmr, R)
println_verbose1(verbose, "$itrj $R $PP # PP # itrj R PP(R)")
println(measfp, "$itrj $R $PP # PP # itrj R PP(R)")
end
elseif method["methodname"] == "Topological_charge"
Nflowsteps = method["Nflowsteps"]#50
eps_flow = method["eps_flow"] #0.01
println_verbose2(verbose, "# epsilon for the Wilson flow is $eps_flow")
Usmr = deepcopy(U)
W1 = deepcopy(univ.U)
W2 = deepcopy(univ.U)
temp_UμνTA = Array{GaugeFields_1d,2}(undef, 4, 4)
τ = 0.0
plaq = calc_plaquette(Usmr)
Eclov = calc_energy_density(Usmr)
Qplaq = calc_topological_charge_plaq(Usmr, temp_UμνTA)
Qclov = calc_topological_charge_clover(Usmr)
Qimpr = calc_topological_charge_improved(Usmr, temp_UμνTA, Qclov)
#Q = calc_topological_charge(Usmr)
# sign of topological charge defined to be positive for one-instanton.
#println("Qplaq = ",Qplaq)
#println("Qclover = ",Qclover)
#println_verbose1(verbose,"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) #flow itrj flowtime plaq Qplaq Qclov")
#println(measfp,"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) #flow itrj flowtime plaq Qplaq Qclov")
println_verbose1(
verbose,
"$itrj $τ $plaq $Eclov $(real(Qplaq)) $(real(Qclov)) $(real(Qimpr)) #flow itrj flowtime plaq Eclov Qplaq Qclov Qimproved",
)
println(
measfp,
"$itrj $τ $plaq $Eclov $(real(Qplaq)) $(real(Qclov)) $(real(Qimpr)) #flow itrj flowtime plaq Eclov Qplaq Qclov Qimproved",
)
flush(stdout)
smearing_type = "gradient_flow" # now, gradient flow is the only scheme for toplogical charge.
#smearing_type = "APE"
#smearing_type = "stout"
if smearing_type == "gradient_flow"
for iflow = 1:method["numflow"]#5000 # eps=0.01: t_flow = 50
gradientflow!(Usmr, univ, W1, W2, Nflowsteps, eps_flow)
τ = iflow * eps_flow * Nflowsteps
plaq = calc_plaquette(Usmr)
Eclov = calc_energy_density(Usmr)
Qplaq = calc_topological_charge_plaq(Usmr, temp_UμνTA)
Qclov = calc_topological_charge_clover(Usmr, temp_UμνTA)
Qimpr = calc_topological_charge_improved(Usmr, temp_UμνTA, Qclov)
#@time Q = calc_topological_charge(Usmr)
println_verbose1(
verbose,
"$itrj $(round(τ, digits=3)) $plaq $Eclov $(real(Qplaq)) $(real(Qclov)) $(real(Qimpr)) #flow itrj flowtime plaq Eclov Qplaq Qclov Qimproved",
)
println(
measfp,
"$itrj $(round(τ, digits=3)) $plaq $Eclov $(real(Qplaq)) $(real(Qclov)) $(real(Qimpr)) #flow itrj flowtime plaq Eclov Qplaq Qclov Qimproved",
)
#if iflow%10 == 0
flush(stdout)
#end
end
elseif smearing_type == "APE" # TODO this should be commonized to gradient flow
Usmr = deepcopy(U)
α = 1 / (7 / 6 + 1) # magic number from hep-lat/9907019 for reproduction. This should be an input parameter
for iflow = 1:method["numflow"]
Usmr = calc_fatlink_APE(
Usmr,
α,
α,
normalize_method = "special unitary",
)
#calc_fatlink_APE!(Usmr,α,α,normalize_method="special unitary")
plaq = calc_plaquette(Usmr)
Qplaq = calc_topological_charge_plaq(Usmr, temp_UμνTA)
Qclover = calc_topological_charge_clover(Usmr, temp_UμνTA)
Qimproved =
calc_topological_charge_improved(Usmr, temp_UμνTA, Qclover)
τ = iflow
println_verbose1(
verbose,
"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #ape itrj flowtime plaq Qplaq Qclov Qimproved",
)
println(
measfp,
"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #ape itrj flowtime plaq Qplaq Qclov Qimproved",
)
#if iflow%10 == 0
flush(stdout)
#end
end
elseif smearing_type == "stout" # TODO this should be commonized to gradient flow
Usmr = deepcopy(U)
ρ = 1 / (7 / 6 + 1) / 6
for iflow = 1:method["numflow"]
Usmr = calc_stout(Usmr, ρ)
#calc_stout!(Usmr,Usmr,ρ)
plaq = calc_plaquette(Usmr)
Qplaq = calc_topological_charge_plaq(Usmr, temp_UμνTA)
Qclover = calc_topological_charge_clover(Usmr, temp_UμνTA)
Qimproved =
calc_topological_charge_improved(Usmr, temp_UμνTA, Qclover)
τ = iflow
println_verbose1(
verbose,
"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #stout itrj flowtime plaq Qplaq Qclov Qimproved",
)
println(
measfp,
"$itrj $τ $plaq $(real(Qplaq)) $(real(Qclover)) $(real(Qimproved)) #stout itrj flowtime plaq Qplaq Qclov Qimproved",
)
#if iflow%10 == 0
flush(stdout)
#end
end
else
error("Invalid smearing_type = $smearing_type")
end
elseif method["methodname"] == "Chiral_condensate"
#fermiontype = method["fermiontype"]
measure_chiral_cond(univ, measset.fermions[i], itrj, measfp, verbose)
elseif method["methodname"] == "Pion_correlator"
#fermiontype = method["fermiontype"]
#calc_pion_correlator(univ,measset.fermions[i])
measure_correlator(univ, measset.fermions[i], itrj, measfp, verbose)
elseif method["methodname"] == "eigenvalues"
measure_eigenvalues(univ, measset.fermions[i], itrj, measfp, verbose)
else
error("$(method["methodname"]) is not supported")
end
println_verbose1(verbose, "-----------------")
flush(measfp)
end
end
return plaq, poly
end
function calc_polyakovloop(univ::Universe)
poly = calc_Polyakov(univ.U)
return poly
end
function calc_factor_plaq(U)
factor = 2 / (U[1].NV * 4 * 3 * U[1].NC)
end
# - - - Polyakov loop correlator
function calc_Polyakov_loop_correlator(U::Array{T,1}, R) where {T<:GaugeFields}
WL = 0.0 + 0.0im
NV = U[1].NV
NC = U[1].NC
Wmat = Array{GaugeFields_1d,2}(undef, 4, 4)
#
construct_Polyakov_correlator!(Wmat, U) # make wilon loop operator and evaluate as a field, not traced.
WL = calc_Polyakov_loop_correlator_core(Wmat, U, R) # tracing over color and average over spacetime and x,y,z.
NDir = 3.0 # in 4 diemension, 3 associated staples. t-x plane, t-y plane, t-z plane
return real(WL) / NV / NDir / NC
end
function construct_Polyakov_correlator!(Wmat, U)
NT = U[1].NT
W_operator = make_2Polyakov_loop(NT)
calc_2Polyakov_loop!(Wmat, W_operator, U)
return
end
function calc_Polyakov_loop_correlator_core(
Wmat,
U::Array{GaugeFields{S},1},
R,
) where {S<:SUn}
if S == SU3
NC = 3
elseif S == SU2
NC = 2
else
NC = U[1].NC
#error("NC != 2,3 is not supported")
end
W = 0.0 + 0.0im
NX = U[1].NX
NY = U[1].NY
NZ = U[1].NZ
it = 1
for ix = 1:NX
for iy = 1:NY
for iz = 1:NZ
i = (((it - 1)NZ + iz - 1)NY + iy - 1) * NX + ix
#
μ = 1
ix2 = (ix + R - 1) % NX + 1
i2 = (((it - 1)NZ + iz - 1)NY + iy - 1) * NX + ix2
W += tr(Wmat[μ][:, :, i]') * tr(Wmat[μ][:, :, i2])
#
μ = 2
iy2 = (iy + R - 1) % NY + 1
i2 = (((it - 1)NZ + iz - 1)NY + iy2 - 1) * NX + ix
W += tr(Wmat[μ][:, :, i]') * tr(Wmat[μ][:, :, i2])
#
μ = 3
iz2 = (iz + R - 1) % NZ + 1
i2 = (((it - 1)NZ + iz2 - 1)NY + iy - 1) * NX + ix
W += tr(Wmat[μ][:, :, i]') * tr(Wmat[μ][:, :, i2])
end
end
end
return W
end
function make_2Polyakov_loop(NT)
#= Making a Wilson loop operator for potential calculations
Ls × Lt
ν=4
↑
+
|
|
|
+ → μ=1,2,3 (averaged)
=#
Wmatset = Array{Wilson_loop_set,1}(undef, 3)
for μ = 1:3 #
t = 4
loops = Wilson_loop_set()
loop = Wilson_loop([(t, NT)]) #plakov loop # This part is under construction.
push!(loops, loop)
Wmatset[μ] = loops
end
return Wmatset
end
function calc_2Polyakov_loop!(temp_Wmat, loops_μν, U)
W = temp_Wmat
for μ = 1:3 # spatial directions
loopset = Loops(U, loops_μν[μ])
W[μ] = evaluate_loops(loopset, U)
end
return
end
# - - - end Polyakov loop correlator
function calc_Wilson_loop(U::Array{T,1}, Lt, Ls) where {T<:GaugeFields}
# Making a ( Ls × Lt) Wilson loop operator for potential calculations
WL = 0.0 + 0.0im
NV = U[1].NV
NC = U[1].NC
Wmat = Array{GaugeFields_1d,2}(undef, 4, 4)
#
calc_large_wiloson_loop!(Wmat, Lt, Ls, U) # make wilon loop operator and evaluate as a field, not traced.
WL = calc_Wilson_loop_core(Wmat, U, NV) # tracing over color and average over spacetime and x,y,z.
NDir = 3.0 # in 4 diemension, 3 associated staples. t-x plane, t-y plane, t-z plane
return real(WL) / NV / NDir / NC
end
function calc_Wilson_loop_core(Wmat, U::Array{GaugeFields{S},1}, NV) where {S<:SUn}
if S == SU3
NC = 3
elseif S == SU2
NC = 2
else
NC = U[1].NC
#error("NC != 2,3 is not supported")
end
W = 0.0 + 0.0im
for n = 1:NV
for μ = 1:3 # spatial directions
ν = 4 # T-direction is not summed over
W += tr(Wmat[μ, ν][:, :, n])
end
end
return W
end
function calc_large_wiloson_loop!(Wmat, Lt, Ls, U)
W_operator = make_Wilson_loop(Lt, Ls)
calc_large_wiloson_loop!(Wmat, W_operator, U)
return
end
function make_Wilson_loop(Lt, Ls)
#= Making a Wilson loop operator for potential calculations
Ls × Lt
ν=4
↑
+--+
| |
| |
| |
+--+ → μ=1,2,3 (averaged)
=#
Wmatset = Array{Wilson_loop_set,2}(undef, 4, 4)
for μ = 1:3 # spatial directions
ν = 4 # T-direction is not summed over
loops = Wilson_loop_set()
loop = Wilson_loop([(μ, Ls), (ν, Lt), (μ, -Ls), (ν, -Lt)])
push!(loops, loop)
Wmatset[μ, ν] = loops
end
return Wmatset
end
function calc_large_wiloson_loop!(temp_Wmat, loops_μν, U)
W = temp_Wmat
for μ = 1:3 # spatial directions
ν = 4 # T-direction is not summed over
loopset = Loops(U, loops_μν[μ, ν])
W[μ, ν] = evaluate_loops(loopset, U)
end
return
end
# = = = calc energy density = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function calc_energy_density(U::Array{T,1}) where {T<:GaugeFields}
# definition in https://arxiv.org/abs/1508.05552 (published version. There is a mistake in the arXiv version)
# WL = 0.0+0.0im
NV = U[1].NV
#NC = U[1].NC
Gμν = Array{GaugeFields_1d,2}(undef, 4, 4)
#
make_clover_leaf!(Gμν, U) # make a clover Wilson loop operator, which is same as Gμν
E = calc_energy_density_core(Gμν, U, NV) #
#NDir = 4.0*3.0/2 # choice of 2 axis from 4.
return E / NV #/NDir/NC/8
end
function calc_energy_density_core(G, U::Array{GaugeFields{S},1}, NV) where {S<:SUn}
#if S == SU3
# NC = 3
#elseif S == SU2
# NC = 2
#else
# NC = U[1].NC
# #error("NC != 2,3 is not supported")
#end
E = 0.0 + 0.0im
for n = 1:NV
for μ = 1:4 # all directions
for ν = 1:4
if μ == ν
continue
end
E += -tr(G[μ, ν][:, :, n] * G[μ, ν][:, :, n]) / 2
end
end
end
return real(E) / 4^2 # this is a factor in the Gmunu but including here
end
function make_clover_leaf!(G, U)
W_operator, numofloops = calc_loopset_μν("clover")# abstract clover loop
instantiate_clover_leaf!(G, W_operator, U) # instantiate
return
end
function instantiate_clover_leaf!(G, W_operator, U)
#G = temp_Wmat
for μ = 1:4
for ν = 1:4
if μ == ν
continue
end
loopset = Loops(U, W_operator[μ, ν])
G[μ, ν] = TA(evaluate_loops(loopset, U)) # factor 1/4 is included above
end
end
return
end
# = = = end of energy density = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function calc_plaquette(U::Array{T,1}) where {T<:GaugeFields}
plaq = 0
factor = calc_factor_plaq(U)
plaq = calc_Plaq(U) * factor
return real(plaq)
end
function calc_plaquette(univ::Universe, U::Array{T,1}) where {T<:GaugeFields}
plaq = 0
temps = univ._temporal_gauge
factor = calc_factor_plaq(U)
plaq = calc_Plaq!(U, temps) * factor
return real(plaq)
end
function calc_topological_charge(U::Array{GaugeFields{S},1}) where {S<:SUn}
return calc_topological_charge_plaq(U)
end
function calc_topological_charge_clover(U::Array{GaugeFields{S},1}) where {S<:SUn}
UμνTA = Array{GaugeFields_1d,2}(undef, 4, 4)
Q = calc_topological_charge_clover(U, UμνTA)
return Q
end
function calc_topological_charge_clover(
U::Array{GaugeFields{S},1},
temp_UμνTA,
) where {S<:SUn}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "clover", U)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calc_topological_charge_improved(
U::Array{GaugeFields{S},1},
temp_UμνTA,
) where {S<:SUn}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "clover", U)
Qclover = calc_Q(UμνTA, numofloops, U)
Q = calc_topological_charge_improved(U, UμνTA, Qclover)
return Q
end
function calc_topological_charge_improved(
U::Array{GaugeFields{S},1},
temp_UμνTA,
Qclover,
) where {S<:SUn}
UμνTA = temp_UμνTA
#numofloops = calc_UμνTA!(UμνTA,"clover",U)
#Qclover = calc_Q(UμνTA,numofloops,U)
numofloops = calc_UμνTA!(UμνTA, "rect", U)
Qrect = 2 * calc_Q(UμνTA, numofloops, U)
c1 = -1 / 12
c0 = 5 / 3
Q = c0 * Qclover + c1 * Qrect
return Q
end
function calc_topological_charge_plaq(U::Array{GaugeFields{S},1}, temp_UμνTA) where {S<:SUn}
UμνTA = temp_UμνTA
numofloops = calc_UμνTA!(UμνTA, "plaq", U)
Q = calc_Q(UμνTA, numofloops, U)
return Q
end
function calc_topological_charge_plaq(U::Array{GaugeFields{S},1}) where {S<:SUn}
UμνTA = Array{GaugeFields_1d,2}(undef, 4, 4)
return calc_topological_charge_plaq(U, UμνTA)
end
function calc_loopset_μν(name)
loops_μν = Array{Wilson_loop_set,2}(undef, 4, 4)
if name == "plaq"
numofloops = 1
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loops = Wilson_loop_set()
loop = Wilson_loop([(μ, 1), (ν, 1), (μ, -1), (ν, -1)])
push!(loops, loop)
loops_μν[μ, ν] = loops
end
end
elseif name == "clover"
numofloops = 4
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loops = Wilson_loop_set()
# notation in 1508.05552
loop_righttop = Wilson_loop([(μ, 1), (ν, 1), (μ, -1), (ν, -1)]) # Pmunu
loop_rightbottom = Wilson_loop([(ν, -1), (μ, 1), (ν, 1), (μ, -1)]) # Qmunu
loop_leftbottom = Wilson_loop([(μ, -1), (ν, -1), (μ, 1), (ν, 1)]) # Rmunu
loop_lefttop = Wilson_loop([(ν, 1), (μ, -1), (ν, -1), (μ, 1)]) # Smunu
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loops_μν[μ, ν] = loops
end
end
elseif name == "rect"
numofloops = 8
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loops = Wilson_loop_set()
loop_righttop = Wilson_loop([(μ, 2), (ν, 1), (μ, -2), (ν, -1)])
loop_lefttop = Wilson_loop([(ν, 1), (μ, -2), (ν, -1), (μ, 2)])
loop_rightbottom = Wilson_loop([(ν, -1), (μ, 2), (ν, 1), (μ, -2)])
loop_leftbottom = Wilson_loop([(μ, -2), (ν, -1), (μ, 2), (ν, 1)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loop_righttop = Wilson_loop([(μ, 1), (ν, 2), (μ, -1), (ν, -2)])
loop_lefttop = Wilson_loop([(ν, 2), (μ, -1), (ν, -2), (μ, 1)])
loop_rightbottom = Wilson_loop([(ν, -2), (μ, 1), (ν, 2), (μ, -1)])
loop_leftbottom = Wilson_loop([(μ, -1), (ν, -2), (μ, 1), (ν, 2)])
push!(loops, loop_righttop)
push!(loops, loop_lefttop)
push!(loops, loop_rightbottom)
push!(loops, loop_leftbottom)
loops_μν[μ, ν] = loops
end
end
else
error("$name is not supported")
end
return loops_μν, numofloops
end
function calc_UμνTA!(temp_UμνTA, loops_μν, U)
UμνTA = temp_UμνTA
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
loopset = Loops(U, loops_μν[μ, ν])
UμνTA[μ, ν] = evaluate_loops(loopset, U)
UμνTA[μ, ν] = TA(UμνTA[μ, ν])
end
end
return
end
function calc_UμνTA!(temp_UμνTA, name::String, U)
loops_μν, numofloops = calc_loopset_μν(name)
calc_UμνTA!(temp_UμνTA, loops_μν, U)
return numofloops
end
#=
implementation of topological charge is based on
https://arxiv.org/abs/1509.04259
=#
function calc_Q(UμνTA, numofloops, U::Array{GaugeFields{S},1}) where {S<:SUn}
if S == SU3
NC = 3
elseif S == SU2
NC = 2
else
NC = U[1].NC
#error("NC != 2,3 is not supported")
end
Q = 0.0
ε(μ, ν, ρ, σ) = epsilon_tensor(μ, ν, ρ, σ)
NV = UμνTA[1, 2].NV
for n = 1:NV
for μ = 1:4
for ν = 1:4
if ν == μ
continue
end
for ρ = 1:4
for σ = 1:4
if ρ == σ
continue
end
s = 0im
for i = 1:NC
for j = 1:NC
s += UμνTA[μ, ν][i, j, n] * UμνTA[ρ, σ][j, i, n]
end
end
Q += ε(μ, ν, ρ, σ) * s / numofloops^2 #*tr(tmp1*tmp2)
end
end
end
end
end
return -Q / (32 * (π^2))
end
function TAm(M)
NC = size(M)[1]
AM = (M - M') / 2
t = tr(AM) / NC
for i = 1:NC
AM[i, i] -= t
end
return AM
end
function calc_plaquette(univ::Universe)
return calc_plaquette(univ, univ.U)
end
function spincolor(ic, is, univ::Universe)
return ic - 1 + (is - 1) * univ.NC + 1
end
function calc_chiral_cond(
univ::Universe,
meas,
measfp,
itrj,
Nr = 10,
verbose = Verbose_2(),
)
# pbp = (1/Nr) Σ_i p_i
# p_i = r_i^\dag xi_i
# xi_i = D^{-1} r_i # D xi = r : r is a random veccor
#
Nfbase = ifelse(meas.fparam.Dirac_operator == "Staggered", 4, 1)
Nf = meas.fparam.Nf
factor = Nf / Nfbase
#
println_verbose2(
verbose,
"Chiral condensate for Nf = $(Nf), Dirac_operator = $(meas.fparam.Dirac_operator), factor=$factor is multiplied.",
)
#
pbp = 0.0
# setup a massive Dirac operator
U, _... = calc_smearingU(univ.U, meas.fparam.smearing)
M = Dirac_operator(U, meas._temporal_fermi2[1], meas.fparam)
#M = Dirac_operator(univ.U,meas._temporal_fermi2[1],meas.fparam)
for ir = 1:Nr
r = similar(meas._temporal_fermi2[1])
p = similar(r)
clear!(p)
#gauss_distribution_fermi!(r,univ.ranf)
Z4_distribution_fermi!(r)
#set_wing_fermi!(r)
bicg(
p,
M,
r,
eps = meas.fparam.eps,
maxsteps = meas.fparam.MaxCGstep,
verbose = verbose,
) # solve Mp=b, we get p=M^{-1}b
tmp = r * p # hemitian inner product
println_verbose2(
verbose,
"# $itrj $ir $(real(tmp)/univ.NV) # itrj irand chiralcond",
)
println(measfp, "# $itrj $ir $(real(tmp)/univ.NV) # itrj irand chiralcond")
pbp += tmp
end
return real(pbp / Nr) / univ.NV * factor
end
function measure_chiral_cond(
univ::Universe,
meas::Measurement,
itrj,
measfp,
verbose = Verbose_2(),
)
Nr = 10
pbp = calc_chiral_cond(univ, meas, measfp, itrj, Nr, verbose)
println_verbose1(verbose, "$itrj $pbp # pbp Nr=$Nr")
println(measfp, "$itrj $pbp # pbp Nr=$Nr")
flush(stdout)
end
function calc_fermionaction(univ::Universe, meas::Measurement, method)
println("Making W^+W matrix...")
@time WdagW = make_WdagWmatrix(
univ.U,
meas._temporal_fermi2[1],
meas._temporal_fermi2[2],
meas.fparam,
)
if haskey(method, "nc")
nc = method["nc"]
else
nc = 20
end
if haskey(method, "M")
M = method["M"]
else
M = 128
end
if haskey(method, "nonc")
nonc = method["nonc"]
else
nonc = false
end
if haskey(method, "m")
m = method["m"]
else
m = 100
end
Sfexact = calc_IntegratedFermionAction(univ, WdagW; debug = false)
Sfapprox = calc_IntegratedFermionAction(
univ,
WdagW;
debug = true,
M = M,
m = m,
nc = nc,
nonc = nonc,
)
return Sfexact, Sfapprox
end
function calc_quark_propagators_point_source_each(M, meas, i, NC, verbose)
# calculate D^{-1} for a given source at the origin.
# Nc*Ns (Ns: dim of spinor, Wilson=4, ks=1) elements has to be gathered.
# staggered Pion correlator relies on https://itp.uni-frankfurt.de/~philipsen/theses/breitenfelder_ba.pdf (3.33)
b = similar(meas._temporal_fermi2[1]) # source is allocated
p = similar(b) # sink is allocated (propagator to sink position)
#k = meas._temporal_fermi2[2]
clear!(b)
Nspinor = ifelse(meas.fparam.Dirac_operator == "Staggered", 1, 4)
is = ((i - 1) % Nspinor) + 1 # spin index
ic = ((i - is) ÷ Nspinor) + 1 # color index
println_verbose1(verbose, "$ic $is")
#println("$ic $is")
b[ic, 1, 1, 1, 1, is] = 1 # source at the origin
@time bicg(
p,
M,
b,
eps = meas.fparam.eps,
maxsteps = meas.fparam.MaxCGstep,
verbose = verbose,
) # solve Mp=b, we get p=M^{-1}b
#@time cg0!(k,b,1, univ.U, meas._temporal_gauge, meas._temporal_fermi1, meas.fparam) # k[x] = M^{-1}b[0]
println_verbose1(verbose, "Hadron spectrum: Inversion $(i)/$(NC*Nspinor) is done")
#println("Hadron spectrum: Inversion $(i)/$(NC*4) is done")
flush(stdout)
return p
end
function calc_quark_propagators_point_source(D, meas, NC, verbose)
# D^{-1} for each spin x color element
Nspinor = ifelse(meas.fparam.Dirac_operator == "Staggered", 1, 4)
propagators = map(
i -> calc_quark_propagators_point_source_each(D, meas, i, NC, verbose),
1:NC*Nspinor,
)
return propagators
end
function calc_pion_correlator(univ::Universe, meas::Measurement, verbose)
println_verbose2(verbose, "Hadron spectrum started")
#println("Hadron spectrum started")
#U = univ._temporal_gauge
#if univ.NC != 3
# error("not implemented yet for calc_pion_correlator")
#end
#b = meas._temporal_fermi2[1] # source allocate
#k = meas._temporal_fermi2[2] # sink allocate
# setup a massive Dirac operator
U, _... = calc_smearingU(univ.U, meas.fparam.smearing)
M = Dirac_operator(U, meas._temporal_fermi2[1], meas.fparam)
#M = Dirac_operator(univ.U,meas._temporal_fermi2[1],meas.fparam)
# Allocate the Wilson matrix = S
Nspinor = ifelse(meas.fparam.Dirac_operator == "Staggered", 1, 4)
S = zeros(
ComplexF64,
(univ.NX, univ.NY, univ.NZ, univ.NT, Nspinor * univ.NC, Nspinor * univ.NC),
)
# calculate quark propagators from a point source at he origin
propagators = calc_quark_propagators_point_source(M, meas, univ.NC, verbose)
#ctr = 0 # a counter
for ic = 1:univ.NC
for is = 1:Nspinor
icum = (ic - 1) * Nspinor + is
#=
clear!(b)
b[ic,1,1,1,1,is]=1 # source at the origin
@time cg0!(k,b,1, univ.U, meas._temporal_gauge, meas._temporal_fermi1, meas.fparam) # k[x] = M^{-1}b[0]
=#
propagator = propagators[icum]
α0 = spincolor(ic, is, univ) # source(color-spinor) index
#
# reconstruction
for t = 1:univ.NT
for z = 1:univ.NZ
for y = 1:univ.NY
for x = 1:univ.NX
for ic2 = 1:univ.NC
for is2 = 1:Nspinor # Nspinor is the number of spinor index in 4d.
β = spincolor(ic2, is2, univ)
S[x, y, z, t, α0, β] += propagator[ic, x, y, z, t, is]
end
end
end
end
end
end
# end for the substitution
#ctr+=1
end
end
# contruction end.
println_verbose2(verbose, "Hadron spectrum: Reconstruction")
#println("Hadron spectrum: Reconstruction")
Cpi = zeros(univ.NT)
# Construct Pion propagator
for t = 1:univ.NT
tmp = 0.0 + 0.0im
for z = 1:univ.NZ
for y = 1:univ.NY
for x = 1:univ.NX
for ic = 1:univ.NC
for is = 1:Nspinor # Nspinor is the number of spinor index in 4d.
α = spincolor(ic, is, univ)
for ic2 = 1:univ.NC
for is2 = 1:Nspinor # Nspinor is the number of spinor index in 4d.
β = spincolor(ic2, is2, univ)
tmp += S[x, y, z, t, α, β] * S[x, y, z, t, α, β]'#inner product.
# complex conjugate = g5 S g5.
end
end
# complex conjugate = g5 S g5.
end
end
end
end
end
# staggered Pion correlator relies on https://itp.uni-frankfurt.de/~philipsen/theses/breitenfelder_ba.pdf (3.33)
# we adopt ignoreing the staggering factor. See detail above reference.
ksfact = 1.0 #ifelse( meas.fparam.Dirac_operator == "Staggered" , (-1)^(t-1) * 64, 1)
Cpi[t] = real(tmp) * ksfact
end
#println(typeof(verbose),"\t",verbose)
println_verbose2(verbose, "Hadron spectrum end")
#println("Hadron spectrum end")
return Cpi
end
function measure_correlator(univ::Universe, meas::Measurement, itrj, measfp, verbose)
C = calc_pion_correlator(univ, meas, verbose)
print_verbose1(verbose, "$itrj ")
print(measfp, "$itrj ")
for it = 1:length(C)
cc = C[it]
print_verbose1(verbose, "$cc ")
print(measfp, "$cc ")
end
println_verbose1(verbose, "#pioncorrelator")
println(measfp, "#pioncorrelator")
end
function measure_eigenvalues(univ::Universe, meas::Measurement, itrj, measfp, verbose)
ene = calc_eigenvalues(univ, meas, verbose)
print_verbose1(verbose, "$itrj ")
print(measfp, "$itrj ")
for it = 1:length(ene)
e = ene[it]
print_verbose1(verbose, "$e ")
print(measfp, "$e ")
end
println_verbose1(verbose, "#eigenvalues")
println(measfp, "#eigenvalues")
end
function calc_eigenvalues(univ, meas, verbose)
println_verbose2(verbose, "Dirac spectrum started")
U, _... = calc_smearingU(univ.U, meas.fparam.smearing)
γ5D = γ5D_operator(U, meas._temporal_fermi2[1], meas.fparam)
function γ5Dx(x)
y = similar(x)
mul!(y, γ5D, x)
return y
end
x = similar(meas._temporal_fermi2[1])
x.f[1] = 1
for i = 1:length(x.f)
x.f[i] = rand()
end
#decomp, history = partialschur(γ5D, nev=10, tol=1e-6, which=SR());
result = eigsolve(γ5Dx, x, 10, EigSorter(abs; rev = false), Lanczos())
println(result)
end
#topological charge
function epsilon_tensor(mu::Int, nu::Int, rho::Int, sigma::Int)
sign = 1 # (3) 1710.09474 extended epsilon tensor
if mu < 0
sign *= -1
mu = -mu
end
if nu < 0
sign *= -1
nu = -nu
end
if rho < 0
sign *= -1
rho = -rho
end
if sigma < 0
sign *= -1
sigma = -sigma
end
epsilon = zeros(Int, 4, 4, 4, 4)
epsilon[1, 2, 3, 4] = 1
epsilon[1, 2, 4, 3] = -1
epsilon[1, 3, 2, 4] = -1
epsilon[1, 3, 4, 2] = 1
epsilon[1, 4, 2, 3] = 1
epsilon[1, 4, 3, 2] = -1
epsilon[2, 1, 3, 4] = -1
epsilon[2, 1, 4, 3] = 1
epsilon[2, 3, 1, 4] = 1
epsilon[2, 3, 4, 1] = -1
epsilon[2, 4, 1, 3] = -1
epsilon[2, 4, 3, 1] = 1
epsilon[3, 1, 2, 4] = 1
epsilon[3, 1, 4, 2] = -1
epsilon[3, 2, 1, 4] = -1
epsilon[3, 2, 4, 1] = 1
epsilon[3, 4, 1, 2] = 1
epsilon[3, 4, 2, 1] = -1
epsilon[4, 1, 2, 3] = -1
epsilon[4, 1, 3, 2] = 1
epsilon[4, 2, 1, 3] = 1
epsilon[4, 2, 3, 1] = -1
epsilon[4, 3, 1, 2] = -1
epsilon[4, 3, 2, 1] = 1
return epsilon[mu, nu, rho, sigma] * sign
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 35529 | module LTK_universe
using LinearAlgebra
using SparseArrays
using Random
#export Universe
import ..Gaugefields:
GaugeFields,
GaugeFields_1d,
IdentityGauges,
RandomGauges,
set_wing!,
substitute!,
calc_GaugeAction,
SU3GaugeFields,
SU3GaugeFields_1d,
SU2GaugeFields,
SU2GaugeFields_1d,
SUNGaugeFields,
SUNGaugeFields_1d,
Oneinstanton,
evaluate_wilson_loops!,
U1GaugeFields,
U1GaugeFields_1d,
apply_smearing,
calc_smearingU
import ..Gaugefields
import ..Fermionfields:
FermionFields,
WilsonFermion,
StaggeredFermion,
substitute_fermion!,
gauss_distribution_fermi!,
set_wing_fermi!
import ..Fermionfields
import ..Actions:
GaugeActionParam,
FermiActionParam,
Setup_Gauge_action,
Setup_Fermi_action,
GaugeActionParam_standard,
FermiActionParam_Wilson,
show_parameters_action,
FermiActionParam_WilsonClover,
FermiActionParam_Staggered,
GaugeActionParam_autogenerator,
SmearingParam_multi,
SmearingParam_single,
Nosmearing,
FermiActionParam_Domainwall
import ..LieAlgebrafields: LieAlgebraFields, clear!, add_gaugeforce!
import ..LieAlgebrafields
import ..Rand: Random_LCGs
import ..System_parameters: Params
import ..Diracoperators:
DdagD_operator, Domainwall_operator, make_densematrix, D5DW_Domainwall_operator
import ..Diracoperators
import ..Wilsonloops:
make_loopforactions, Wilson_loop_set, make_originalactions_fromloops, make_cloverloops
import ..Verbose_print: Verbose_level, Verbose_3, Verbose_2, Verbose_1
import ..IOmodule: loadU
import ..SUN_generator: Generator
import ..RationalApprox: calc_exactvalue, calc_Anϕ
import ..ILDG_format: ILDG, load_gaugefield, load_gaugefield!, save_binarydata
import ..Bridge_format: load_BridgeText!
import ..Othermethods: tdlogdet
import ..CGmethods: bicg, cg, shiftedcg
import ..Rhmc: get_order, get_β, get_α, get_α0, get_β_inverse, get_α_inverse, get_α0_inverse
#import ..Smearing:apply_smearing
"""
Your universe is described in this type.
"""
struct Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp}
NX::Int64
NY::Int64
NZ::Int64
NT::Int64
NV::Int64
NC::Int64
Nwing::Int64
Dirac_operator::Union{Nothing,String}
U::Array{Gauge,1}
Uold::Array{Gauge,1}
p::Array{Lie,1}
φ::Union{Nothing,Fermi}
ξ::Union{Nothing,Fermi}
η::Union{Nothing,Fermi}
gparam::GaugeP
fparam::Union{Nothing,FermiP}
BoundaryCondition::Array{Int8,1}
initial::String
quench::Bool
NDFALG::Int64
_temporal_gauge::Array{Gauge_temp,1}
_temporal_fermi::Union{Nothing,Array{Fermi,1}}
_temporal_algebra::Array{Lie,1}
ranf::Random_LCGs
verboselevel::Int8
kind_of_verboselevel::Verbose_level
#rng::MersenneTwister
end
function set_β!(univ::Universe, β)
if typeof(univ.gparam) == GaugeActionParam_standard
univ.gparam.β = β
#univ.gparam = GaugeActionParam_standard(β,univ.gparam.NTRACE)
elseif typeof(univ.gparam) == GaugeActionParam_autogenerator
#univ.gparam =GaugeActionParam_autogenerator(univ.gparam.βs * (univ.gparam.β/β),β,univ.gparam.numactions,univ.gparam.NTRACE,univ.gparam.loops,univ.gparam.staples)
univ.gparam.β = β
univ.gparam.βs .= 0#univ.gparam.βs * (univ.gparam.β/β)
univ.gparam.βs[1] = β
else
error("$(typeof(univ.gparam)) is not supported!")
end
end
function set_β!(univ::Universe, βs::Array{T,1}) where {T<:Number}
if typeof(univ.gparam) == GaugeActionParam_standard
univ.gparam.β = βs[1]
#univ.gparam = GaugeActionParam_standard(β,univ.gparam.NTRACE)
elseif typeof(univ.gparam) == GaugeActionParam_autogenerator
@assert length(univ.gparam.βs) == length(βs) "univ.gparam.βs = $(univ.gparam.βs) and βs = $βs"
#univ.gparam =GaugeActionParam_autogenerator(univ.gparam.βs * (univ.gparam.β/β),β,univ.gparam.numactions,univ.gparam.NTRACE,univ.gparam.loops,univ.gparam.staples)
univ.gparam.β = βs[1]
univ.gparam.βs .= βs
#univ.gparam.βs = univ.gparam.βs * (univ.gparam.β/β)
else
error("$(typeof(univ.gparam)) is not supported!")
end
end
function get_β(univ::Universe)
if typeof(univ.gparam) == GaugeActionParam_standard
return univ.gparam.β
elseif typeof(univ.gparam) == GaugeActionParam_autogenerator
return univ.gparam.β
else
error("$(typeof(univ.gparam)) is not supported!")
end
end
function set_βs!(univ::Universe, βs)
if typeof(univ.gparam) == GaugeActionParam_standard
univ.gparam.β = βs[1]
elseif typeof(univ.gparam) == GaugeActionParam_autogenerator
univ.gparam.β = βs[1]
univ.gparam.βs = βs[:]
else
error("$(typeof(univ.gparam)) is not supported!")
end
end
include("default.jl")
function Universe()
file = "default.jl"
return Universe(file)
end
function Universe(p::Params)
L = p.L
β = p.β
NTRACE = p.NC
#rng = MersenneTwister(p.randomseed, (0, 1002, 0, 1))
if p.use_autogeneratedstaples
#loops = make_loopforactions(p.couplinglist,L)
#println(loops)
loops = make_originalactions_fromloops(p.coupling_loops)
gparam =
GaugeActionParam_autogenerator(p.couplingcoeff, loops, p.NC, p.couplinglist)
else
gparam = GaugeActionParam_standard(β, NTRACE)
end
if p.Dirac_operator == nothing
fparam = nothing
else
if p.Dirac_operator == "Wilson"
if p.smearing_for_fermion == "nothing"
fparam = FermiActionParam_Wilson(
p.hop,
p.r,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
)
else
fparam = FermiActionParam_Wilson(
p.hop,
p.r,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
smearingparameters = "stout",
loops_list = p.stout_loops,
coefficients = p.stout_ρ,
numlayers = p.stout_numlayers,
L = p.L,
)
end
elseif p.Dirac_operator == "WilsonClover"
#if p.NC == 2
# error("You use NC = 2. But WilsonClover Fermion is not supported in SU2 gauge theory yet. Use NC = 3.")
#end
NV = prod(p.L)
#CloverFμν = zeros(ComplexF64,p.NC,p.NC,NV,6)
inn_table = zeros(Int64, NV, 4, 2)
internal_flags = zeros(Bool, 2)
_ftmp_vectors = Array{Array{ComplexF64,3},1}(undef, 6)
for i = 1:6
_ftmp_vectors[i] = zeros(ComplexF64, p.NC, NV, 4)
end
_is1 = zeros(Int64, NV)
_is2 = zeros(Int64, NV)
if p.NC ≥ 4
SUNgenerator = Generator(p.NC)
else
SUNgenerator = nothing
end
_cloverloops = Array{Wilson_loop_set,2}(undef, 3, 4)
for μ = 1:3
for ν = μ+1:4
_cloverloops[μ, ν] = make_cloverloops(μ, ν)
end
end
#fparam = FermiActionParam_WilsonClover(p.hop,p.r,p.eps,p.Dirac_operator,p.MaxCGstep,p.Clover_coefficient,CloverFμν,
# internal_flags,inn_table,_ftmp_vectors,_is1,_is2,
# p.quench)
if p.smearing_for_fermion == "nothing"
fparam = FermiActionParam_WilsonClover(
p.hop,
p.r,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.Clover_coefficient,
internal_flags,
inn_table,
_ftmp_vectors,
_is1,
_is2,
p.quench,
SUNgenerator,
_cloverloops,
)
else
error("stout for Wilson with clover is not supported yet!")
fparam = FermiActionParam_WilsonClover(
p.hop,
p.r,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.Clover_coefficient,
internal_flags,
inn_table,
_ftmp_vectors,
_is1,
_is2,
p.quench,
SUNgenerator,
_cloverloops,
smearingparameters = "stout",
loops_list = p.stout_loops,
coefficients = p.stout_ρ,
numlayers = p.stout_numlayers,
L = p.L,
)
end
elseif p.Dirac_operator == "Staggered"
if p.smearing_for_fermion == "nothing"
fparam = FermiActionParam_Staggered(
p.mass,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
p.Nf,
)
else
fparam = FermiActionParam_Staggered(
p.mass,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
p.Nf,
smearingparameters = "stout",
loops_list = p.stout_loops,
coefficients = p.stout_ρ,
numlayers = p.stout_numlayers,
L = p.L,
)
end
elseif p.Dirac_operator == "Domainwall"
if p.smearing_for_fermion == "nothing"
fparam = FermiActionParam_Domainwall(
p.Domainwall_N5,
p.r,
p.Domainwall_M,
p.Domainwall_m,
p.Domainwall_ωs,
p.Domainwall_b,
p.Domainwall_c,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
)
else
fparam = FermiActionParam_Domainwall(
p.Domainwall_N5,
p.r,
p.Domainwall_M,
p.Domainwall_m,
p.Domainwall_ωs,
p.Domainwall_b,
p.Domainwall_c,
p.eps,
p.Dirac_operator,
p.MaxCGstep,
p.quench,
smearingparameters = "stout",
loops_list = p.stout_loops,
coefficients = p.stout_ρ,
numlayers = p.stout_numlayers,
L = p.L,
)
end
#error("Not implemented! here is in LTK_universe.jl")
else
error(p.Dirac_operator, " is not supported!")
end
end
univ = Universe(
L,
gparam,
p.Nwing,
fparam,
p.BoundaryCondition,
p.initial,
p.NC,
p.verboselevel,
p.load_fp,
p.loadU_format,
p.julian_random_number,
)
end
"""
```Universe(file)```
- file: file name of the input file.
Make your universe. The input file is loaded.
Undefined parameters in your input file are defined with the default values.
The default values are as follows.
```julia
L = (4,4,4,4)
β = 6
NTRACE = 3
#gparam = Setup_Gauge_action(β)
gparam = GaugeActionParam_standard(β,NTRACE)
BoundaryCondition=[1,1,1,-1]
Nwing = 1
initial="cold"
NC =3
hop= 0.141139 #Hopping parameter
r= 1 #Wilson term
eps= 1e-19
Dirac_operator= "Wilson"
MaxCGstep= 3000
fparam = FermiActionParam_Wilson(hop,r,eps,Dirac_operator,MaxCGstep)
```
"""
function Universe(file)
if file != "default.jl"
include(pwd() * "/" * file)
end
univ = Universe(L, gparam, Nwing, fparam, BoundaryCondition, initial, NC)
end
function show_parameters(univ::Universe)
println("""
L = $((univ.NX,univ.NY,univ.NZ,univ.NT))
""")
show_parameters_action(univ.gparam)
println("""
BoundaryCondition= $(univ.BoundaryCondition)
Nwing = $(univ.Nwing)
initial= $(univ.initial)
NC =$(univ.NC)
""")
if univ.fparam != nothing
show_parameters_action(univ.fparam)
end
end
"""
```Universe(L::Tuple,gparam::GaugeActionParam,initial="cold",fparam=nothing)```
- L: system size (NX,NY,NZ,NT)
- gparam: parameters for gauge actions
- [initial]: initial Gauge configuration
- [fparam]: parameters for fermion actions
"""
function Universe(L::Tuple, gparam::GaugeActionParam, initial = "cold", fparam = nothing)
Nwing = 1
BoundaryCondition = [1, 1, 1, -1]
NC = 3
Universe(L, gparam, Nwing, fparam, BoundaryCondition, initial, NC)
end
function Universe(
L,
gparam,
Nwing,
fparam,
BoundaryCondition,
initial,
NC,
verboselevel,
load_fp,
loadU_format,
julian_random_number,
)
#(L::Tuple,gparam::GaugeActionParam;
# Nwing = 1,fparam=nothing,
# BoundaryCondition=[1,1,1,-1],initial="cold",NC =3)
if verboselevel == 1
kind_of_verboselevel = Verbose_1(load_fp)
elseif verboselevel == 2
kind_of_verboselevel = Verbose_2(load_fp)
elseif verboselevel == 3
kind_of_verboselevel = Verbose_3(load_fp)
end
ranf = Random_LCGs(1, julian_random_number = julian_random_number)
NX = L[1]
NY = L[2]
NZ = L[3]
NT = L[4]
NV = NX * NY * NZ * NT
NDFALG = ifelse(NC == 1, 1, NC^2 - 1)
num_tempfield_g = 5
num_tempfield_f = 4
if fparam != nothing && fparam.Dirac_operator == "WilsonClover"
numbasis = NC^2 - 1
num_tempfield_g += 4 + 4 + 2numbasis
elseif fparam != nothing # && fparam.Dirac_operator == "Staggered"
num_tempfield_f += 4
end
if fparam != nothing && fparam.Dirac_operator == "Staggered"
if fparam.Nf != 4 && fparam.Nf != 8
N_action = get_order(fparam.rhmc_action)
N_MD = get_order(fparam.rhmc_MD)
num_tempfield_f += maximum((N_action, N_MD)) + 1
end
end
if fparam != nothing && fparam.smearing != nothing
num_tempfield_g += 4
end
if typeof(gparam) == GaugeActionParam_autogenerator
num_tempfield_g += 1
end
if NC == 3
U = Array{SU3GaugeFields,1}(undef, 4)
_temporal_gauge = Array{SU3GaugeFields_1d,1}(undef, num_tempfield_g)
elseif NC == 2
U = Array{SU2GaugeFields,1}(undef, 4)
_temporal_gauge = Array{SU2GaugeFields_1d,1}(undef, num_tempfield_g)
elseif NC ≥ 4
U = Array{SUNGaugeFields{NC},1}(undef, 4)
_temporal_gauge = Array{SUNGaugeFields_1d{NC},1}(undef, num_tempfield_g)
elseif NC == 1
U = Array{U1GaugeFields,1}(undef, 4)
_temporal_gauge = Array{U1GaugeFields_1d,1}(undef, num_tempfield_g)
end
# Uold = Array{GaugeFields,1}(undef,4)
p = Array{LieAlgebraFields,1}(undef, 4)
for μ = 1:4
p[μ] = LieAlgebraFields(NC, NX, NY, NZ, NT)
end
if initial == "cold"
println("..... Cold start")
for μ = 1:4
U[μ] = IdentityGauges(NC, NX, NY, NZ, NT, Nwing)
end
elseif initial == "hot"
println("..... Hot start")
for μ = 1:4
U[μ] = RandomGauges(NC, NX, NY, NZ, NT, Nwing)
end
elseif initial == "one instanton"
@assert NC == 2 "From one instanton start, NC should be 2!"
U = Oneinstanton(NC, NX, NY, NZ, NT, Nwing)
else #if initial == "file"
println("..... File start")
println("File name is $initial")
if loadU_format == "JLD"
U = loadU(initial, NX, NY, NZ, NT, NC)
elseif loadU_format == "ILDG"
ildg = ILDG(initial)
i = 1
for μ = 1:4
U[μ] = IdentityGauges(NC, NX, NY, NZ, NT, Nwing)
end
load_gaugefield!(U, i, ildg, L, NC)
elseif loadU_format == "BridgeText"
for μ = 1:4
U[μ] = IdentityGauges(NC, NX, NY, NZ, NT, Nwing)
end
load_BridgeText!(initial, U, L, NC)
else
error("loadU_format should be JLD or ILDG")
end
#error("not supported yet.")
end
set_wing!(U)
Uold = similar(U)
substitute!(Uold, U)
#=
for μ=1:4
set_wing!(U[μ])
Uold[μ] = similar(U[μ])
substitute!(Uold[μ],U[μ])
end
=#
#_temporal_gauge = Array{GaugeFields,1}(undef,4)
for i = 1:length(_temporal_gauge)
_temporal_gauge[i] = GaugeFields_1d(NC, NX, NY, NZ, NT) #similar(U[1])
#_temporal_gauge[i] = similar(U[1])
end
_temporal_algebra = Array{LieAlgebraFields,1}(undef, 1)
for i = 1:length(_temporal_algebra)
_temporal_algebra[i] = similar(p[1])
end
if fparam == nothing
Dirac_operator = nothing
φ = nothing
η = nothing
ξ = nothing
_temporal_fermi = nothing
quench = true
else
Dirac_operator = fparam.Dirac_operator
φ = FermionFields(NC, NX, NY, NZ, NT, fparam, BoundaryCondition)
η = similar(φ)
ξ = similar(φ)
_temporal_fermi = Array{FermionFields,1}(undef, num_tempfield_f)
for i = 1:length(_temporal_fermi)
_temporal_fermi[i] = similar(φ)
end
quench = fparam.quench
if Dirac_operator == "Domainwall"
gauss_distribution_fermi!(ξ)
#A = D5DW_Domainwall_operator(U,ξ,fparam)
A = Domainwall_operator(U, ξ, fparam)
A_dense_PV = make_densematrix(A.D5DW_PV)
A_dense = make_densematrix(A.D5DW)
M = A_dense * inv(A_dense_PV)
#e,v = eigen(A_dense)
e, v = eigen(M)
fp = open("eigenvalues_M.txt", "w")
for ene in e
println(fp, real(ene), "\t", imag(ene))
end
close(fp)
#println(e)
error("stop!")
bicg(η, A, ξ)
error("stop!")
end
end
Gauge = eltype(U)
Fermi = typeof(φ)
Lie = eltype(p)
GaugeP = typeof(gparam)
FermiP = typeof(fparam)
Gauge_temp = eltype(_temporal_gauge)
return Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp}(
NX,
NY,
NZ,
NT,
NV,
NC,
Nwing,
Dirac_operator,
U,
Uold,
p,
φ,
ξ,
η,
gparam,
fparam,
BoundaryCondition,
initial,
quench,
NDFALG,
_temporal_gauge,
_temporal_fermi,
_temporal_algebra,
ranf,
verboselevel,
kind_of_verboselevel,
)
end
function gauss_distribution(univ::Universe, nv)
variance = 1
nvh = div(nv, 2)
granf = zeros(Float64, nv)
for i = 1:nvh
rho = sqrt(-2 * log(univ.ranf()) * variance)
theta = 2pi * univ.ranf()
granf[i] = rho * cos(theta)
granf[i+nvh] = rho * sin(theta)
end
if 2 * nvh == nv
return granf
end
granf[nv] = sqrt(-2 * log(univ.ranf()) * variance) * cos(2pi * univ.ranf())
return granf
end
function expF_U!(
U::Array{T,1},
F::Array{N,1},
Δτ,
univ::Universe,
) where {T<:GaugeFields,N<:LieAlgebraFields}
LieAlgebrafields.expF_U!(U, F, Δτ, univ._temporal_gauge, univ._temporal_algebra[1])
end
function calc_gaugeforce!(F::Array{N,1}, univ::Universe) where {N<:LieAlgebraFields}
clear!(F)
calc_gaugeforce!(F, univ.U, univ)
#add_gaugeforce!(F,univ.U,univ._temporal_gauge,univ._temporal_algebra[1])
return
end
function calc_gaugeforce!(
F::Array{N,1},
U::Array{T,1},
univ::Universe,
) where {N<:LieAlgebraFields,T<:GaugeFields}
clear!(F)
calc_gaugeforce!(F, U, univ, univ.gparam)
#add_gaugeforce!(F,U,univ._temporal_gauge,univ._temporal_algebra[1],univ.gparam)
return
end
function calc_gaugeforce!(
F::Array{N,1},
U::Array{T,1},
univ::Universe,
gparam::GP,
) where {N<:LieAlgebraFields,T<:GaugeFields,GP<:GaugeActionParam_autogenerator}
clear!(F)
add_gaugeforce!(F, U, univ._temporal_gauge, univ._temporal_algebra[1], gparam)
return
end
function calc_gaugeforce!(
F::Array{N,1},
U::Array{T,1},
univ::Universe,
gparam::GP,
) where {N<:LieAlgebraFields,T<:GaugeFields,GP}
clear!(F)
add_gaugeforce!(F, U, univ._temporal_gauge, univ._temporal_algebra[1])
return
end
function Gaugefields.calc_GaugeAction(univ::Universe)
Sg, plaq = calc_GaugeAction(univ.U, univ.gparam, univ._temporal_gauge)
return real(Sg), real(plaq)
end
function calc_Action(univ::Universe)
Sg, plaq = calc_GaugeAction(univ.U, univ.gparam, univ._temporal_gauge)
SP = univ.p * univ.p / 2
#println("ek = $SP")
S = Sg + SP
#println("eym = $plaq")
#println("e = $S")
if univ.quench == false
#if univ.fparam != nothing
Sf = univ.η * univ.η
S += Sf
end
return real(S), real(plaq)
end
function calc_IntegratedFermionAction(
univ::Universe;
debug = false,
M = 16,
m = 100,
nc = 20,
nonc = false,
)
println("Making W^+W matrix...")
NX = univ.U[1].NX
NY = univ.U[1].NY
NZ = univ.U[1].NZ
NT = univ.U[1].NT
NC = univ.U[1].NC
T = eltype(univ._temporal_fermi)
if T == StaggeredFermion
NG = 1
else
NG = 4
end
Nsize = NX * NY * NZ * NT * NC * NG
WdagW = zeros(ComplexF64, Nsize, Nsize)
@time make_WdagWmatrix!(WdagW, univ)
#@time WdagW = make_WdagWmatrix(univ)
Sfnew = calc_IntegratedFermionAction(
univ,
WdagW,
debug = debug,
M = M,
m = m,
nc = nc,
nonc = nonc,
)
return Sfnew
end
function calc_IntegratedFermionAction(
univ::Universe,
WdagW;
debug = false,
M = 16,
m = 100,
nc = 20,
nonc = false,
)
if debug
#WdagW = DdagD_operator(univ.U,univ.η,univ.fparam)
#println("Calculating approximated logdet")
#@time Sfnew = -tdlogdet(WdagW,M,m,nc=nc,nonc=nonc)
#exit()
WdagWsp = sparse(WdagW)
N, _ = size(WdagW)
tempvecs = Array{Array{ComplexF64,1}}(undef, 3)
for i = 1:3
tempvecs[i] = zeros(ComplexF64, N)
end
println("Calculating approximated logdet")
#@time Sfnew = -tdlogdet(WdagWsp,M2,m2,tempvecs,nc=nc2,nonc=nonc)
#M2 = 100
#m2 = 100
#nc2 = 100
@time Sfnew = -tdlogdet(WdagWsp, M, m, tempvecs, nc = nc, nonc = nonc)
#exit()
#=
M = 8*2
#M = 4#8*2
m = 100
NX = univ.U[1].NX
#m = 20
N,_ = size(WdagW)
tempvecs = Array{Array{ComplexF64,1}}(undef,3)
for i=1:3
tempvecs[i] = zeros(ComplexF64,N)
end
nc = 20
nonc = false
@time ldet = logdet(WdagW)
if nonc
fp = open("deltavalue_m$(m)_nonc_NX$(NX)_6.dat","w")
else
fp = open("deltavalue_m$(m)_nc$(nc)_NX$(NX)_6.dat","w")
end
for M in [4,8,16,32,64,128]
if nonc
filename="delta_$(NX)$(NX)$(NX)$(NX)_$(M)_m$(m)_nonc_6.dat"
else
filename="delta_$(NX)$(NX)$(NX)$(NX)_$(M)_m$(m)_nc$(nc)_6.dat"
end
a = tdlogdet(WdagWsp,M,m,tempvecs,filename=filename,nc=nc,nonc=nonc)
println("$M $a $ldet")
println(fp,"$M $a $ldet")
end
close(fp)
exit()
@time Sfnew = -tdlogdet(WdagWsp,M,m,tempvecs)
=#
else
println("Calculating logdet")
@time Sfnew = -real(logdet(WdagW))
end
if univ.Dirac_operator == "Staggered"
#if univ.fparam.Nf == 4
# Sfnew /= 2
#end
Sfnew /= (8 / univ.fparam.Nf)
end
return Sfnew
end
struct Wilsonloops_actions{Gauge_temp}
loops::Array{Wilson_loop_set,1}
loopaction::Gauge_temp
temps::Array{Gauge_temp,1}
numloops::Int64
β::Float64
NC::Float64
couplinglist::Array{String,1}
function Wilsonloops_actions(univ)
couplinglist = ["plaq", "rect", "polyx", "polyy", "polyz", "polyt"]
L = (univ.U[1].NX, univ.U[1].NY, univ.U[1].NZ, univ.U[1].NT)
loops = make_loopforactions(couplinglist, L)
loopaction = similar(univ._temporal_gauge[1])
sutype = typeof(loopaction)
temps = Array{sutype,1}(undef, 3)
for i = 1:3
temps[i] = similar(loopaction)
end
numloops = length(couplinglist)
β = univ.gparam.β
NC = univ.NC
return new{sutype}(loops, loopaction, temps, numloops, β, NC, couplinglist)
end
end
function calc_looptrvalues(w::Wilsonloops_actions, univ)
numloops = w.numloops
trs = zeros(ComplexF64, numloops)
for i = 1:numloops
evaluate_wilson_loops!(w.loopaction, w.loops[i], univ.U, w.temps[1:3])
trs[i] = tr(w.loopaction)
end
return trs
end
function calc_looptrvalues_site(w::Wilsonloops_actions, univ)
return
numloops = w.numloops
NX = univ.U[1].NX
NY = univ.U[1].NY
NZ = univ.U[1].NZ
NT = univ.U[1].NT
NC = univ.NC
V = zeros(ComplexF64, NC, NC)
trs = zeros(ComplexF64, numloops, NX, NY, NZ, NT)
for it = 1:NT
for iz = 1:NZ
for iy = 1:NY
for ix = 1:NX
for i = 1:numloops
evaluate_wilson_loops!(V, w.loops[i], univ.U, ix, iy, iz, it)
trs[i, ix, iy, iz, it] = tr(V)
end
end
end
end
end
return trs
end
function get_looptrvalues(w::Wilsonloops_actions)
return w.trs
end
function calc_IntegratedSf(w::Wilsonloops_actions, univ)
Sf = calc_IntegratedFermionAction(univ)
return Sf
end
function calc_gaugeSg(w::Wilsonloops_actions, univ)
trs = calc_looptrvalues(w, univ)
Sg = (-w.β / w.NC) * trs[1]
return real(Sg), trs
end
function calc_trainingdata(w::Wilsonloops_actions, univ)
Sf = calc_IntegratedSf(w, univ)
Sg, trs = calc_gaugeSg(w, univ)
return trs, Sg, Sf
end
function make_WdagWmatrix(univ::Universe)
return make_WdagWmatrix(univ.U, univ._temporal_fermi, univ.fparam)
end
function make_WdagWmatrix!(WdagW, univ::Universe)
make_WdagWmatrix!(WdagW, univ.U, univ._temporal_fermi, univ.fparam)
return
end
function make_WdagWmatrix(univ::Universe, U::Array{T,1}) where {T<:GaugeFields}
return make_WdagWmatrix(U, univ._temporal_fermi, univ.fparam)
end
function make_WdagWmatrix(
U::Array{G,1},
temps::Array{T,1},
fparam,
) where {G<:GaugeFields,T<:FermionFields}
x0 = temps[7]
xi = temps[8]
return make_WdagWmatrix(U, x0, xi, fparam)
end
function make_WdagWmatrix!(
WdagW,
U::Array{G,1},
temps::Array{T,1},
fparam,
) where {G<:GaugeFields,T<:FermionFields}
x0 = temps[7]
xi = temps[8]
make_WdagWmatrix!(WdagW, U, x0, xi, fparam)
return
end
function make_WdagWmatrix(
U::Array{G,1},
x0::T,
xi::T,
fparam,
) where {G<:GaugeFields,T<:FermionFields}
NX = x0.NX
NY = x0.NY
NZ = x0.NZ
NT = x0.NT
NC = x0.NC
if T == StaggeredFermion
NG = 1
else
NG = 4
end
Nsize = NX * NY * NZ * NT * NC * NG
WdagW = zeros(ComplexF64, Nsize, Nsize)
make_WdagWmatrix!(WdagW, U, x0, xi, fparam)
return WdagW
end
function make_WdagWmatrix!(
WdagW,
U::Array{G,1},
x0::T,
xi::T,
fparam,
) where {G<:GaugeFields,T<:FermionFields}
Fermionfields.clear!(x0)
NX = x0.NX
NY = x0.NY
NZ = x0.NZ
NT = x0.NT
NC = x0.NC
if T == StaggeredFermion
NG = 1
else
NG = 4
end
Nsize = NX * NY * NZ * NT * NC * NG
#WdagW = zeros(ComplexF64,Nsize,Nsize)
WdagWoperator = DdagD_operator(U, x0, fparam)
j = 0
for α = 1:NG
for it = 1:NT
for iz = 1:NZ
for iy = 1:NY
for ix = 1:NX
for ic = 1:NC
Fermionfields.clear!(x0)
j += 1
x0[ic, ix, iy, iz, it, α] = 1
#set_wing_fermi!(x0)
#WdagWx!(xi,U,x0,temps,fparam)
#println(xi*xi)
#Wx!(xi,U,x0,temps,fparam)
#println(xi*xi)
#Wx!(xi,U,x0,temps,fparam,(ix,iy,iz,it,α))
#println(xi*xi)
mul!(xi, WdagWoperator, x0, (ix, iy, iz, it, α))
#WdagWx!(xi,U,x0,temps,fparam,(ix,iy,iz,it,α))
#println("fast ",xi*xi)
#exit()
#display(xi)
#exit()
substitute_fermion!(WdagW, j, xi)
end
end
end
end
end
end
#return WdagW
end
function construct_fermion_gauss_distribution!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp}
gauss_distribution_fermi!(univ.η, univ.ranf)
end
function construct_fermion_gauss_distribution!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi<:StaggeredFermion,GaugeP,FermiP,Gauge_temp}
gauss_distribution_fermi!(univ.η, univ.ranf)
if univ.fparam.Nf == 4
U, _... = calc_smearingU(univ.U, univ.fparam.smearing)
evensite = false
W = Diracoperators.Dirac_operator(U, univ.η, univ.fparam)
mul!(univ.φ, W', univ.η)
#Wdagx!(univ.φ,univ.U,univ.η,univ._temporal_fermi,univ.fparam)
Fermionfields.clear!(univ.φ, evensite)
bicg(univ.η, W', univ.φ, eps = univ.fparam.eps, maxsteps = univ.fparam.MaxCGstep)
end
end
function construct_fermionfield_φ!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp}
U, _... = calc_smearingU(univ.U, univ.fparam.smearing)
W = Diracoperators.Dirac_operator(U, univ.η, univ.fparam)
mul!(univ.φ, W', univ.η)
set_wing_fermi!(univ.φ)
end
function construct_fermionfield_φ!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi<:StaggeredFermion,GaugeP,FermiP,Gauge_temp}
U, _... = calc_smearingU(univ.U, univ.fparam.smearing)
if univ.fparam.Nf == 4 || univ.fparam.Nf == 8
W = Diracoperators.Dirac_operator(U, univ.η, univ.fparam)
mul!(univ.φ, W', univ.η)
else
WdagW = Diracoperators.DdagD_operator(U, univ.η, univ.fparam)
N = get_order(univ.fparam.rhmc_action)
x = univ.φ
vec_x = univ._temporal_fermi[end-N+1:end]
for j = 1:N
Fermionfields.clear!(vec_x[j])
end
# eta = (MdagM)^{-alpha/2} phi -> phi = (MdagM)^{alpha/2} eta
#(MdagM)^{alpha/2} eta ~ α0 eta + sum_k αk (MdagM + βk)^{-1} eta
vec_β = get_β(univ.fparam.rhmc_action)
vec_α = get_α(univ.fparam.rhmc_action)
α0 = get_α0(univ.fparam.rhmc_action)
shiftedcg(
vec_x,
vec_β,
x,
WdagW,
univ.η,
eps = univ.fparam.eps,
maxsteps = univ.fparam.MaxCGstep,
)
Fermionfields.clear!(univ.φ)
Fermionfields.add!(univ.φ, α0, univ.η)
for j = 1:N
αk = vec_α[j]
Fermionfields.add!(univ.φ, αk, vec_x[j])
end
end
set_wing_fermi!(univ.φ)
end
function construct_fermionfield_η!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp}
U, _... = calc_smearingU(univ.U, univ.fparam.smearing)
W = Diracoperators.Dirac_operator(U, univ.η, univ.fparam)
bicg(
univ.η,
W',
univ.φ,
eps = univ.fparam.eps,
maxsteps = univ.fparam.MaxCGstep,
verbose = univ.kind_of_verboselevel,
)
end
function construct_fermionfield_η!(
univ::Universe{Gauge,Lie,Fermi,GaugeP,FermiP,Gauge_temp},
) where {Gauge,Lie,Fermi<:StaggeredFermion,GaugeP,FermiP,Gauge_temp} # eta = Wdag^{-1} phi
U, _... = calc_smearingU(univ.U, univ.fparam.smearing)
if univ.fparam.Nf == 4 || univ.fparam.Nf == 8
W = Diracoperators.Dirac_operator(U, univ.η, univ.fparam)
bicg(
univ.η,
W',
univ.φ,
eps = univ.fparam.eps,
maxsteps = univ.fparam.MaxCGstep,
verbose = univ.kind_of_verboselevel,
)
else
WdagW = Diracoperators.DdagD_operator(U, univ.η, univ.fparam)
N = get_order(univ.fparam.rhmc_action)
x = univ.η
vec_x = univ._temporal_fermi[end-N+1:end]
for j = 1:N
Fermionfields.clear!(vec_x[j])
end
# eta = (MdagM)^{-alpha/2} phi -> phi = (MdagM)^{alpha/2} eta
#(MdagM)^{alpha/2} eta ~ α0 eta + sum_k αk (MdagM + βk)^{-1} eta
vec_β = get_β_inverse(univ.fparam.rhmc_action)
vec_α = get_α_inverse(univ.fparam.rhmc_action)
α0 = get_α0_inverse(univ.fparam.rhmc_action)
shiftedcg(
vec_x,
vec_β,
x,
WdagW,
univ.φ,
eps = univ.fparam.eps,
maxsteps = univ.fparam.MaxCGstep,
)
Fermionfields.clear!(univ.η)
Fermionfields.add!(univ.η, α0, univ.φ)
for j = 1:N
αk = vec_α[j]
Fermionfields.add!(univ.η, αk, vec_x[j])
end
end
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 4995 | module Rand
export Crand
mutable struct Crand
iw::Array{Int64,1}
jr::Int64
kr::Int64
end
mutable struct Random_LCGs{T}
crand_public::Crand
Random_LCGs(ndelay; julian_random_number = false) =
new{julian_random_number}(cint3(ndelay))
end
function (g::Random_LCGs{false})()
#return rand()
return ranf!(g.crand_public)
end
function (g::Random_LCGs{true})()
return rand()
#return ranf!(g.crand_public)
end
const IP = 521
const IQ = 32
const MACRM = 40
const MACRI = 1
const FNORM = Float32(0.465661e-9)
const intmax32 = Int32(2147483647)
function cint3(ndelay)
println("ndelay : $ndelay")
#ccall((:readseed,"./randfortran.so"),Nothing,(),)
crand_public = init3()
delay3!(crand_public, ndelay)
#display(crand_public.iw)
return crand_public
end
function make_value_Int32_again(ix)
while ix < -intmax32 - 1
ix += 2 * intmax32 + 1
end
while ix > intmax32
ix -= 2 * (intmax32 + 1)
end
return ix
end
function init3()
#println(2147483647+1-2*(intmax32+1))
ib = zeros(Int64, IP) #INTEGER ib(0:IP-1)
iw = zeros(Int64, IP) #INTEGER iw(0:IP-1)
ix = Int32(MACRI)
for i = 0:IP-1
ix = ix * 69069
ix = make_value_Int32_again(ix)
#while ix < -intmax32-1 || intmax32 < ix
# ix -= Int32(Int32(2)*(intmax32+Int32(1)))
#end
#println(Int32(ix) >>> -(-31))
ib[i+1] = Int32(ix) >>> -(-31)
#println("$i ",ix," ",typeof(ix))
#println(ix,"\t",ib[i+1])
#ib[i+1] = ishift(ix,-31)
end
jr = 0
kr = IP - IQ
for j = 0:IP-1
iwork = 0
for i = 0:31
iwork = iwork * 2 + ib[jr+1]
#while iwork < -intmax32-1 || intmax32 < iwork
# iwork -= Int32(Int32(2)*(intmax32+Int32(1)))
#end
iwork = make_value_Int32_again(iwork)
ib[jr+1] = Int32(ib[jr+1]) ⊻ Int32(ib[kr+1])
jr += 1
if jr == IP
jr = 0
end
kr += 1
if kr == IP
kr = 0
end
end
iw[j+1] = Int32(iwork) >>> -(-1)
#println(j,"\t",iw[j+1])
end
return Crand(iw, jr, kr)
# exit()
end
function delay3!(crand_public::Crand, lambda)
iwk = zeros(Int32, 2 * IP - 2 + 1)
c = zeros(Int32, 2 * IP - 1 + 1)
ib = zeros(Int32, IP + 31 + 1)
mu = MACRM
for i = 0:IP-1
iwk[i+1] = crand_public.iw[i+1]
end
for i = IP:2*IP-2
iwk[i+1] = Int32(iwk[i-IP+1]) ⊻ Int32(iwk[i-IQ+1])
end
for i = 0:mu-1
ib[i+1] = 0
end
m = lambda
nb = mu - 1
#count = 0
while m > IP - 1
nb += 1
ib[nb+1] = m % 2
m = div(m, 2)
#count += 1
#if count > 100000000
# error("something is wrong in rand.jl!")
#end
end
for i = 0:IP-1
c[i+1] = 0
end
c[m+1] = 1
for j = nb:-1:0
for i = IP-1:-1:0
c[2*i+ib[j+1]+1] = c[i+1]
c[2*i+1-ib[j+1]+1] = 0
end
for i = 2*IP-1:-1:IP
c[i-IP+1] = Int32(c[i-IP+1]) ⊻ Int32(c[i+1])
c[i-IQ+1] = Int32(c[i-IQ+1]) ⊻ Int32(c[i+1])
end
end
for j = 0:IP-1
iwork = 0
for i = 0:IP-1
#while iwork < -intmax32-1 || intmax32 < iwork
# iwork -= Int32(Int32(2)*(intmax32+Int32(1)))
#end
iwork = make_value_Int32_again(iwork)
iwork = Int32(iwork) ⊻ Int32(c[i+1] * iwk[j+i+1])
end
crand_public.iw[j+1] = iwork
end
end
function ranf!(crand_public)
#ranfs = zeros(Float64,1)
#ccall((:call_random,"./randfortran.so"),Nothing,(Ref{Float64},),ranfs)
#return ranfs[1]
ir = crand_public.iw
j = crand_public.jr
k = crand_public.kr
crand_public.iw[j+1] = Int32(crand_public.iw[j+1]) ⊻ Int32(crand_public.iw[k+1])
irnd = crand_public.iw[j+1]
#println("irnd = $irnd ", FNORM,"\t",irnd*FNORM)
#ranf = Float32(irnd*FNORM)
#granf = Float64(irnd)*FNORM
frnd = Float32(irnd * FNORM)
#println(frnd,"\t",irnd*FNORM,"\t",Float64(irnd),"\t",granf)
#exit()
ranf = Float32(frnd)
crand_public.jr = crand_public.jr + 1
if crand_public.jr >= IP
crand_public.jr = crand_public.jr - IP
end
crand_public.kr = crand_public.kr + 1
if crand_public.kr >= IP
crand_public.kr = crand_public.kr - IP
end
return ranf
end
function rgauss1!(crand_public, nup)
xr = zeros(Float64, nup)
nup2 = div(nup, 2)
if nup != 2 * nup2
error("""
!!!! Attention nup in rgauss should be even nup = $nup
""")
end
for i = 1:nup2
i2 = 2 * i
i1 = i2 - 1
v1 = sqrt(-log(ranf!(crand_public) + 1e-10) * 2)
v2 = 2pi * ranf!(crand_public)
xr[i1] = v1 * cos(v2)
xr[i2] = v1 * sin(v2)
end
return xr
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2811 | module AbstractUpdate_module
using Gaugefields
using LinearAlgebra
using LatticeDiracOperators
import ..Universe_module: Univ, get_gauge_action, is_quenched
import ..System_parameters: Params
import ..AbstractMD_module: StandardMD, MD, initialize_MD!, runMD!
abstract type AbstractUpdate end
include("./standardHMC.jl")
include("./givenconfigurations.jl")
include("./heatbath.jl")
#=
function Updatemethod(p::Params, univ::Univ)
gauge_action = get_gauge_action(univ)
quench = is_quenched(univ)
U = univ.U
updatemethod = Updatemethod(
U,
gauge_action,
update_method,
quench,
p.Δτ,
p.MDsteps,
SextonWeingargten = SextonWeingargten,
)
return updatemethod
end
=#
function Updatemethod(parameters::Params, univ::Univ)
gauge_action = get_gauge_action(univ)
quench = is_quenched(univ)
updatemethod = Updatemethod(
univ.U,
gauge_action,
parameters.update_method,
quench,
parameters.Δτ,
parameters.MDsteps,
fermi_action = univ.fermi_action,
cov_neural_net = univ.cov_neural_net,
SextonWeingargten = parameters.SextonWeingargten,
loadU_dir = parameters.loadU_dir,
loadU_format = parameters.loadU_format,
isevenodd = parameters.isevenodd,
β = parameters.β,
ITERATION_MAX = parameters.ITERATION_MAX,
numOR = parameters.numOR,
useOR = parameters.useOR,
)
return updatemethod
end
function Updatemethod(
U,
gauge_action,
update_method,
quench,
Δτ = nothing,
MDsteps = nothing;
fermi_action = nothing,
cov_neural_net = nothing,
SextonWeingargten = false,
loadU_dir = nothing,
loadU_format = nothing,
isevenodd = true,
β = 5.7,
ITERATION_MAX = 10^5,
numOR = 3,
useOR = false,
)
if update_method == "HMC"
updatemethod = StandardHMC(
U,
gauge_action,
quench,
Δτ,
MDsteps,
fermi_action,
cov_neural_net,
SextonWeingargten = SextonWeingargten,
)
elseif update_method == "Fileloading"
updatemethod = GivenConfigurations(U, loadU_dir, loadU_format)
elseif update_method == "Heatbath"
updatemethod = Heatbathupdate(
U,
gauge_action,
quench,
isevenodd = isevenodd,
β = β,
ITERATION_MAX = ITERATION_MAX,
numOR = numOR,
useOR = useOR,
)
else
error("update method $(update_method) is not supported!")
end
return updatemethod
end
function update!(updatemethod::T, U) where {T<:AbstractUpdate}
error("updatemethod type $(typeof(updatemethod)) is not supported!!")
end
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2274 | struct SLHMC{Tmd,Tmd_eff,TG} <: AbstractUpdate
md::Tmd
md_eff::Tmd_eff
Uold::Vector{TG}
end
function SLHMC(
U,
gauge_action,
quench,
Δτ,
MDsteps,
fermi_action,
gauge_eff_action,
fermi_eff_action;
SextonWeingargten = false,
)
md = MD(
U,
gauge_action,
quench,
Δτ,
MDsteps,
fermi_action;
SextonWeingargten = SextonWeingargten,
)
Tmd = typeof(md)
md_eff = MD(
U,
gauge_eff_action,
quench,
Δτ,
MDsteps,
fermi_eff_action;
SextonWeingargten = SextonWeingargten,
)
Tmd_eff = typeof(md_eff)
Uold = similar(U)
TG = eltype(Uold)
return SLHMC{Tmd,Tmd_eff,TG}(md, md_eff, Uold)
#error("in StandardHMC!!")
end
function update!(updatemethod::T, U) where {T<:SLHMC}
NC = U[1].NC
md = updatemethod.md
md_eff = updatemethod.md_eff
Uold = updatemethod.Uold
substitute_U!(Uold, U) #previous configuration
initialize_MD!(U, md)
Sp = md.p * md.p / 2
Sg = -evaluate_GaugeAction(md.gauge_action, U) / NC
println_verbose_level3(U[1], "Sp_old = $Sp, Sg_old = $Sg")
Sold = real(Sp + Sg)
if md.quench == false
Sfold = real(dot(md.ξ, md.ξ))
println_verbose_level3(U[1], "Sfold = $Sfold")
Sold += Sfold
md_eff.ξ = md.ξ
md_eff.η = md.η
end
md_eff.p = md.p
runMD!(U, md_eff)
md.p = md_eff.p
Sp = md.p * md.p / 2
Sg = -evaluate_GaugeAction(md.gauge_action, U) / NC
println_verbose_level3(U[1], "Sp_new = $Sp, Sg_new = $Sg")
Snew = real(Sp + Sg)
if md.quench == false
Sfnew = evaluate_FermiAction(md.fermi_action, U, md.η)
println_verbose_level3(U[1], "Sfnew = $Sfnew")
Snew += Sfnew
end
println_verbose_level2(U[1], "Sold = $Sold, Snew = $Snew")
println_verbose_level2(U[1], "Snew - Sold = $(Snew-Sold)")
accept = exp(Sold - Snew) >= rand()
if accept
println_verbose_level2(U[1], "Accepted")
else
substitute_U!(U, Uold) #back to previous configuration
println_verbose_level2(U[1], "Rejected")
end
return accept
#error("updatemethod type $(typeof(updatemethod)) is not supported!!")
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2209 | struct GivenConfigurations <: AbstractUpdate
loadU_dir::String
loadU_format::String
filename_load::Vector{String}
current_fileindex::Vector{Int64}
function GivenConfigurations(U, loadU_dir, loadU_format)
ildg = nothing
println_verbose_level1(U[1], "load U from ", loadU_dir)
if loadU_format == "JLD"
datatype = "JLD"
filename_load = filter(f -> contains(f, ".jld2"), readdir("./$(loadU_dir)"))
#filename_load = filter(f -> contains(f,".jld"),readdir("./$(parameters.loadU_dir)"))
elseif loadU_format == "ILDG"
datatype = "ILDG"
filename_load = filter(f -> contains(f, "ildg"), readdir("./$(loadU_dir)"))
elseif loadU_format == "BridgeText"
datatype = "BridgeText"
filename_load = filter(f -> contains(f, "txt"), readdir("./$(loadU_dir)"))
else
error("loadU_format should be JLD, ILDG or BridgeText. now $(loadU_format)")
end
numfiles = length(filename_load)
println_verbose_level1(U[1], "Num of files = $numfiles")
for file in filename_load
println_verbose_level1(U[1], "$file")
end
current_fileindex = Vector{Int64}(undef, 1)
current_fileindex[1] = 0
updatemethod = new(loadU_dir, loadU_format, filename_load, current_fileindex)
update!(updatemethod, U)
return updatemethod #new(loadU_dir,loadU_format,filename_load,current_fileindex)
end
end
function update!(updatemethod::T, U) where {T<:GivenConfigurations}
updatemethod.current_fileindex[1] += 1
itrj = updatemethod.current_fileindex[1]
fileformat = updatemethod.loadU_format
loadU_dir = updatemethod.loadU_dir
filename_i = updatemethod.filename_load[itrj]
_, _, L... = size(U[1])
NC = U[1].NC
if fileformat == "JLD"
error("not supported now")
elseif fileformat == "ILDG"
ildg = ILDG(loadU_dir * "/" * filename_i)
i = 1
load_gaugefield!(U, i, ildg, L, NC)
elseif fileformat == "BridgeText"
filename = loadU_dir * "/" * filename_i
load_BridgeText!(filename, U, L, NC)
end
return true
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 1184 | struct Heatbathupdate{Dim,T} <: AbstractUpdate
heatbath::Union{Heatbath_update{Dim,T},Heatbath{T}}
isevenodd::Bool
numOR::Int64
useOR::Bool
end
function Heatbathupdate(
U::Array{T,1},
gauge_action,
quench;
useOR = false,
numOR = 0,
isevenodd = false,
β = 2.3,
ITERATION_MAX = 10^5,
) where {T}
@assert quench "Heatbath update is only for quanch case!"
Dim = length(U)
if isevenodd
println_verbose_level1(
U[1],
"Heatbath update with even-odd method. Only plaquette action can be treated. Now β = $β",
)
hb = Heatbath(U, β, ITERATION_MAX = ITERATION_MAX)
else
hb = Heatbath_update(U, gauge_action, ITERATION_MAX = ITERATION_MAX)
end
return Heatbathupdate{Dim,T}(hb, isevenodd, numOR, useOR)
#error("in StandardHMC!!")
end
function update!(updatemethod::T, U) where {T<:Heatbathupdate}
heatbath!(U, updatemethod.heatbath)
if updatemethod.useOR
for i = 1:updatemethod.numOR
overrelaxation!(U, updatemethod.heatbath)
end
end
return true
#error("updatemethod type $(updatemethod) is not supported!!")
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2132 | struct StandardHMC{Tmd,TG} <: AbstractUpdate
md::Tmd
Uold::Vector{TG}
end
function StandardHMC(
U,
gauge_action,
quench,
Δτ,
MDsteps,
fermi_action,
cov_neural_net;
SextonWeingargten = false,
)
md = MD(
U,
gauge_action,
quench,
Δτ,
MDsteps,
fermi_action,
cov_neural_net;
SextonWeingargten = SextonWeingargten,
)
Tmd = typeof(md)
Uold = similar(U)
TG = eltype(Uold)
return StandardHMC{Tmd,TG}(md, Uold)
#error("in StandardHMC!!")
end
function update!(updatemethod::T, U) where {T<:StandardHMC}
NC = U[1].NC
md = updatemethod.md
Uold = updatemethod.Uold
substitute_U!(Uold, U) #previous configuration
initialize_MD!(U, md)
Sp = md.p * md.p / 2
Sg = -evaluate_GaugeAction(md.gauge_action, U) / NC
println_verbose_level3(U[1], "Sp_old = $Sp, Sg_old = $Sg")
Sold = real(Sp + Sg)
if md.quench == false
Sfold = real(dot(md.ξ, md.ξ))
println_verbose_level3(U[1], "Sfold = $Sfold")
Sold += Sfold
end
runMD!(U, md)
Sp = md.p * md.p / 2
Sg = -evaluate_GaugeAction(md.gauge_action, U) / NC
println_verbose_level3(U[1], "Sp_new = $Sp, Sg_new = $Sg")
Snew = real(Sp + Sg)
if md.quench == false
if md.cov_neural_net != Nothing
Uout, Uout_multi, _ = calc_smearedU(U, md.cov_neural_net)
Sfnew = evaluate_FermiAction(md.fermi_action, Uout, md.η)
else
Sfnew = evaluate_FermiAction(md.fermi_action, U, md.η)
end
println_verbose_level3(U[1], "Sfnew = $Sfnew")
Snew += Sfnew
end
println_verbose_level2(U[1], "Sold = $Sold, Snew = $Snew")
println_verbose_level2(U[1], "Snew - Sold = $(Snew-Sold)")
accept = exp(Sold - Snew) >= rand()
if accept
println_verbose_level2(U[1], "Accepted")
else
substitute_U!(U, Uold) #back to previous configuration
println_verbose_level2(U[1], "Rejected")
end
return accept
#error("updatemethod type $(typeof(updatemethod)) is not supported!!")
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 5621 | using LatticeQCD
using Test
function readplaqdata()
data = readlines("debugplaqdata.txt")
num = length(data)
plaqvalues = Float64[]
for i=1:num
push!(plaqvalues,parse(Float64,split(data[i])[1]))
end
return plaqvalues
end
@testset "LatticeQCD.jl" begin
eps = 1e-5
plaqvalues = readplaqdata()
#fout = open("Testvalues.txt","w");println(fout,"Test values")
#@time begin # time
@testset "quenched HMC" begin
@testset "SU(2)" begin
@time plaq = run_LQCD("test02.toml")
#plaq_comparison = 0.5575491312570713
plaq_comparison = plaqvalues[1] #0.4870451289565683#for 1.9 0.48785061558469406
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"qhmc SU(2), $plaq")
end
@testset "SU(3)" begin
@time plaq = run_LQCD("test01.toml")
#plaq_comparison = 0.6190393357419764
plaq_comparison = plaqvalues[2]
#plaq_comparison = 0.5753703885492326
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"qhmc SU(3), $plaq")
end
@testset "SU(4)" begin
@time plaq = run_LQCD("test03.toml")
#plaq_comparison = 0.4966683811089479
plaq_comparison = plaqvalues[3]
#plaq_comparison = 0.3915274700011152
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"qhmc SU(4), $plaq")
end
end
@testset "Heatbath" begin
@testset "SU(2)" begin
@time plaq = run_LQCD("test02-hb.toml")
#plaq_comparison = 0.5287735727118359
plaq_comparison = plaqvalues[4]
#plaq_comparison = 0.4855523668804699
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"hb SU(2), $plaq")
end
@testset "SU(3)" begin
@time plaq = run_LQCD("test01-hb.toml")
#plaq_comparison = 0.5821680570717788
plaq_comparison = plaqvalues[5]
#plaq_comparison = 0.5502269475635925
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"hb SU(3), $plaq")
end
@testset "SU(4)" begin
@time plaq = run_LQCD("test03-hb.toml")
#plaq_comparison = 0.5467724338528576
plaq_comparison = plaqvalues[6]
#plaq_comparison = 0.4425954597477664
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"hb SU(4), $plaq")
end
end
@testset "HMC" begin
@testset "Wilson SU(3) with SextonWeingargten" begin
@time plaq = run_LQCD("test_wilson.toml")
#plaq_comparison = 0.3449688128155864
#plaq_comparison = 0.4867607208994073
#plaq_comparison = 0.4976172009730353
#plaq_comparison = 0.49956695470173684
plaq_comparison = plaqvalues[7]
#println(plaq)
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"Wilson SU(3) with SextonWeingargten, $plaq")
end
@testset "Staggered SU(3) with 4 tastes" begin
@time plaq = run_LQCD("test_staggered.toml")
#plaq_comparison = 0.25455870400018477 #0.00624053999484795
#plaq_comparison = 0.4987738124715037
#plaq_comparison = 0.4713469212809392
#plaq_comparison = 0.49956695470173684
#plaq_comparison = 0.48966257272554553
plaq_comparison = plaqvalues[8]
#println(plaq)
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"Staggered SU(3) with 4 tastes, $plaq")
end
@testset "Staggered SU(3) with 2 tastes" begin
@time plaq = run_LQCD("test_Nf2.toml")
#plaq_comparison = 0.5630198767336069
#plaq_comparison = 0.5837848292310798
plaq_comparison = plaqvalues[9]
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"Staggered SU(3) with 2 tastes, $plaq")
end
@testset "Staggered SU(3) with 3 tastes" begin
@time plaq = run_LQCD("test_Nf3.toml")
#plaq_comparison = 0.565176584402352
#plaq_comparison = 0.5864438294310259
plaq_comparison = plaqvalues[10]
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"Staggered SU(3) with 3 tastes, $plaq")
end
@testset "Domain-wall SU(3)" begin
# cold start
@time plaq = run_LQCD("test_domainwallhmc.toml")
#plaq_comparison = 0.649479122018118
plaq_comparison = plaqvalues[11]
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
#println(fout,"Domain-wall SU(3), $plaq")
end
end
#end # time
#close(fout)
#=
@testset "SLMC" begin
@testset "Staggered SU(3)" begin
@time plaq = run_LQCD("test06_slmc_ks.jl")
plaq_comparison = 0.5279623287035208
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
end
end
@testset "WilsonClover SU(3) with SextonWeingargten" begin
@time plaq = run_LQCD("test_wilsonclover.jl")
plaq_comparison = 0.3449688128155864
#plaq_comparison = 0.00624053999484795
@test abs(plaq - plaq_comparison)/plaq_comparison < eps
end
=#
end
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2382 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "Heatbath_L04040404_beta5.7_quenched_su3.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "Heatbath"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 5,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "Heatbath_L04040404_beta5.7_quenched_su3"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 1700 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "HMC_L04040404_beta5.7_quenched_su3.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_quenched_su3"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2381 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "Heatbath_L04040404_beta5.7_quenched_su2.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "Heatbath"
system["randomseed"] = 111
system["NC"] = 2
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 1.9
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 5,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "Heatbath_L04040404_beta5.7_quenched_su2"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2366 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "HMC_L04040404_beta5.7_quenched_su2.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 2
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 1.9
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 5,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_quenched_su2"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2381 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "Heatbath_L04040404_beta5.7_quenched_su4.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "Heatbath"
system["randomseed"] = 111
system["NC"] = 4
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 9.0
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 5,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "Heatbath_L04040404_beta5.7_quenched_su4"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2366 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = true
system["logfile"] = "HMC_L04040404_beta5.7_quenched_su4.txt"
system["initial"] = "cold"
system["Dirac_operator"] = nothing
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 4
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 9.0
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.06666666666666667
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 15
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 5,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_quenched_su4"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2452 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 15
system["firstlearn"] = 10
system["quench"] = true
system["logfile"] = "SLMC_L04040404_beta5.7_Staggered_mass0.5.txt"
system["βeff"] = 5.7
system["initial"] = "hot"
system["Dirac_operator"] = "Staggered"
system["log_dir"] = "./logs"
system["Nthermalization"] = 10
system["update_method"] = "SLMC"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
staggered["Nf"] = 4
staggered["mass"] = 0.5
measurement["measurement_methods"] = Dict[]
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 50,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 50,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 50,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "SLMC_L04040404_beta5.7_Staggered_mass0.5"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 1381 | # - - parameters - - - - - - - - - - -
# Physical setting
system["L"] = (4, 4, 4, 4)
system["β"] = 5.7
system["NC"] = 3
system["Nthermalization"] = 0
system["Nsteps"] = 10
system["initial"] = "cold"
system["initialtrj"] = 1
system["update_method"] = "HMC"
system["Nwing"] = 1
# Physical setting(fermions)
system["quench"] = false
system["Dirac_operator"] = "Staggered"
staggered["Nf"] = 2
staggered["mass"] = 0.5
system["BoundaryCondition"] = [1, 1, 1, -1]
# System Control
system["log_dir"] = "./logs"
system["logfile"] = "HMC_L04040404_beta5.7_Staggered_mass0.5_Nf2.txt"
system["saveU_dir"] = ""
system["saveU_format"] = nothing
system["verboselevel"] = 2
system["randomseed"] = 111
measurement["measurement_basedir"] = "./measurements"
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_Staggered_mass0.5_Nf2"
# HMC related
md["Δτ"] = 0.05
md["SextonWeingargten"] = false
md["N_SextonWeingargten"] = 2
md["MDsteps"] = 20
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
# Action parameter for SLMC
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
# Measurement set
measurement["measurement_methods"] = Dict[
Dict{Any,Any}("methodname" => "Polyakov_loop",
"measure_every" => 1
),
Dict{Any,Any}("methodname" => "Plaquette",
"measure_every" => 1
)
]
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 1302 | # - - parameters - - - - - - - - - - -
# Physical setting
system["L"] = (4, 4, 4, 4)
system["β"] = 5.7
system["NC"] = 3
system["Nthermalization"] = 0
system["Nsteps"] = 10
system["initial"] = "cold"
system["initialtrj"] = 1
system["update_method"] = "HMC"
system["Nwing"] = 1
# Physical setting(fermions)
system["quench"] = false
system["Dirac_operator"] = "Staggered"
staggered["Nf"] = 3
staggered["mass"] = 0.5
system["BoundaryCondition"] = [1, 1, 1, -1]
# System Control
system["log_dir"] = "./logs"
system["logfile"] = "HMC_L04040404_beta5.7_Staggered_mass0.5_Nf3.txt"
system["saveU_dir"] = ""
system["saveU_format"] = nothing
system["verboselevel"] = 2
system["randomseed"] = 111
measurement["measurement_basedir"] = "./measurements"
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_Staggered_mass0.5_Nf3"
# HMC related
md["Δτ"] = 0.05
md["SextonWeingargten"] = false
md["N_SextonWeingargten"] = 2
md["MDsteps"] = 20
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
# Action parameter for SLMC
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
# Measurement set
measurement["measurement_methods"] = Dict[
Dict{Any,Any}("methodname" => "Plaquette",
"measure_every" => 1
)
]
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2456 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = false
system["logfile"] = "HMC_L04040404_beta5.7_Staggered_mass0.5.txt"
system["initial"] = "hot"
system["Dirac_operator"] = "Staggered"
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.025
md["N_SextonWeingargten"] = 2
md["SextonWeingargten"] = false
md["MDsteps"] = 40
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
staggered["Nf"] = 4
staggered["mass"] = 0.5
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 50,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 50,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 50,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_Staggered_mass0.5"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2499 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 10
system["quench"] = false
system["logfile"] = "HMC_L04040404_beta5.7_Wilson_kappa0.141139.txt"
system["initial"] = "hot"
system["Dirac_operator"] = "Wilson"
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.05
md["N_SextonWeingargten"] = 10
md["SextonWeingargten"] = true
md["MDsteps"] = 20
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
wilson["r"] = 1
wilson["hop"] = 0.141139
measurement["measurement_methods"] = Dict[]
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 50,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 50,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 50,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_Wilson_kappa0.141139"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | code | 2554 | # - - parameters - - - - - - - - - - -
system["saveU_dir"] = ""
system["verboselevel"] = 2
system["L"] = (4, 4, 4, 4)
system["Nwing"] = 1
system["Nsteps"] = 2
system["quench"] = false
system["logfile"] = "HMC_L04040404_beta5.7_WilsonClover_kappa0.141139.txt"
system["initial"] = "hot"
system["Dirac_operator"] = "WilsonClover"
system["log_dir"] = "./logs"
system["Nthermalization"] = 0
system["update_method"] = "HMC"
system["randomseed"] = 111
system["NC"] = 3
system["BoundaryCondition"] = [1, 1, 1, -1]
system["saveU_format"] = nothing
system["β"] = 5.7
actions["use_autogeneratedstaples"] = false
actions["couplingcoeff"] = Any[]
actions["couplinglist"] = Any[]
md["Δτ"] = 0.05
md["N_SextonWeingargten"] = 10
md["SextonWeingargten"] = true
md["MDsteps"] = 20
cg["eps"] = 1.0e-19
cg["MaxCGstep"] = 3000
wilson["Clover_coefficient"] = 1.5612
wilson["r"] = 1
wilson["hop"] = 0.141139
measurement["measurement_methods"] = Dict[]
measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 5,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"),
Dict{Any,Any}("eps_flow" => 0.01,"fermiontype" => nothing,"numflow" => 10,"measure_every" => 10,"methodname" => "Topological_charge","Nflowsteps" => 4),
Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 5,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
#measurement["measurement_methods"] = Dict[Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Staggered","Nf" => 4,"mass" => 0.5,"measure_every" => 50,"MaxCGstep" => 3000,"methodname" => "Chiral_condensate"), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Polyakov_loop"), Dict{Any,Any}("fermiontype" => nothing,"numflow" => 10,"measure_every" => 50,"methodname" => "Topological_charge"), Dict{Any,Any}("eps" => 1.0e-19,"fermiontype" => "Wilson","r" => 1,"measure_every" => 50,"hop" => 0.141139,"methodname" => "Pion_correlator","MaxCGstep" => 3000), Dict{Any,Any}("fermiontype" => nothing,"measure_every" => 1,"methodname" => "Plaquette")]
measurement["measurement_dir"] = "HMC_L04040404_beta5.7_WilsonClover_kappa0.141139"
measurement["measurement_basedir"] = "./measurements"
# - - - - - - - - - - - - - - - - - - -
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | docs | 8150 | # LatticeQCD.jl
[](https://github.com/akio-tomiya/LatticeQCD.jl/actions/workflows/CI.yml)
<img src="logo.png" width=400>
This code enabales you to perform lattice QCD calculations! A native Julia code for Lattice QCD.
- [What is lattice QCD? (PDG)](https://pdg.lbl.gov/2019/reviews/rpp2018-rev-lattice-qcd.pdf) : Lattice regulated quantum chromo-dynamics used in high energy physics.
- [What is Julia?](https://julialang.org/) : An easy and fast scientific programming launguage with the JIT compiler
<img src="demo.gif" width=500>
## Star History
[](https://star-history.com/#akio-tomiya/LatticeQCD.jl&Date)
## Tutorial
You can start it in [Google Colab](https://colab.research.google.com/drive/1dMD7Uo-Z5SjK_LLHq9HkunQajXTXCE-L?usp=sharing)
# Quick start
You can start lattice QCD in 5 steps!
1.Download a Julia binary from [Julialang.org](https://julialang.org/downloads/). Set a path to the binary of Julia.
Julia 1.6 (or higher) is supported.
Julia 1.9 (or higher) is supported in LatticeQCD.jl 1.0.4 (or higher).
2.In Julia REPL, push "]" key to enter the package mode and type
```
add LatticeQCD
```
and "return" key. Press "backspace" key ( "delete" key for mac) to exit the package mode.
You can get the latest version via ``add LatticeQCD#master``.
(All dependence will be solved automatically)
3.Include the package with
```
using LatticeQCD
```
4.Make a parameter file with wizard,
```
run_wizard()
```
Choose parameters as you want!
5.Start simulation with created your parameter file!
```
run_LQCD("my_parameters.toml")
```
You'll get results!
Of cource, you can write/modify a parameter file by yourself.
Enjoy life with lattice QCD.
To see our demonstration above, execute,
```julia
using Plots
using LatticeQCD
demo()
```
it takes time before showing up the window.
# What is supported?
We support lattice gauge theory in 4 dimensional euclidean spacetime.
- Wizard for parameter files
- Gauge fields
- Optimized SU(2), SU(3)
- General SU(N)
- General gauge action = plaquette + rect + etc action
- Fermions
- Wilson (2 flavor)
- Staggered fermion (1-8 tastes ~ flavor)
- Standard Domain-wall (2 flavor, experimental)
- Configuration generation algorithms
- Cold/Hot start for SU(N). One instanton configuration for SU(2)
- Heatbath for SU(N) & overelaxation for a general gauge action
- Even-odd heatbath for the plaquette action
- Quenched HMC with SU(N) for a general gauge action
- HMC (2 flavor Wilson) with SU(N) with a general gauge action
- HMC (4 taste staggered fermions) with SU(N) with a general gauge action
- RHMC (any flavor staggered) with SU(N) for a general gauge action*
- SU(N) stout smeared dynamical fermions (experimental)
- Self-learning HMC with the plaquette action
- Measurements
- Plaquette
- Polyakov loop
- Chiral condensates (Wilson, staggered)
- Momentum projected pion correlator (Wilson fermion, staggered)
- RxT Wilson loop
- Energy density
- Topological charge (plaquette, clover and O(a^2) improved definition)
- Load & measurement mode (load and measure all configurations in a directory)
- Smearing
- Stout
- Gradient flow for a generic action (experimental)
- I/O for gauge configurations
- ILDG format (Binary)
- JLD format (Default binary file for Julia, one of HDF5)
- Text file for Bridge++ (Bridgetext)
*If you specified other than Nf=4, 8 with the staggered fermion HMC, RHMC is automatically used. For a machine with the apple silicon, Nf=1-8 is avalable.
To use following functions, please use v 0.1.2
- Fermion integrated HMC with a general gauge action
- Self-learning Monte-Carlo with a general action (ref. [this paper](https://arxiv.org/abs/2010.11900) )
*Version below 1.0, it uses ``***.jl`` as a default parameter file, and now it uses ``***.toml``. Version 1.0 supports both parameter file formats.
*Parallelazation is supported by [LatticeDiracOperators.jl](https://github.com/akio-tomiya/LatticeDiracOperators.jl). See below.
# Related packages
<img src="LQCDjl_block.png" width=300>
LatticeQCD.jl is basically a wrapper of the following packages
- [Wilsonloop.jl](https://github.com/akio-tomiya/Wilsonloop.jl) :Wilsonloop.jl helps us to treat with the Wilson loops and generic Wilson lines in any Nc and dimensions. Wilson lines can be defined in symbolly.
- [Gaugefields.jl](https://github.com/akio-tomiya/Gaugefields.jl): Gaugefields.jl is a package for lattice lattice SU(N) gauge fileds. Treating gauge fields (links), gauge actions with MPI and autograd. This can generate quenched configurations.
- [LatticeDiracOperators.jl](https://github.com/akio-tomiya/LatticeDiracOperators.jl): LatticeDiracOperators.jl is a package for Dirac operators and fermions on the lattice. Treating pseudo-femrion fields with various lattice Dirac operators, fermion actions with MPI. This can generate configurations with dynamical fermions.
- [QCDMeasurements.jl](https://github.com/akio-tomiya/QCDMeasurements.jl): QCDMeasurements.jl is a package for measuring physical quantities. This has measurements for basic quantities like chiral condensates, plaquettes. Moreover, pion correlators and topological charge with several definitions. This also has the gradient flow with several actions.
This package is a code in a project [JuliaQCD](https://github.com/JuliaQCD/).
# USAGE/User interface
We support following two user interfaces
1. Julia REPL interface (For beginners, just after the lattice QCD textbook)
2. Genral interface (Experience with another code, for batch job, customised purpose)
Usage 1 was already explained.
For Usage 2, in Julia REPL, push "]" key to enter the package mode and type
```
add LatticeQCD
```
Then, LatticeQCD.jl is installed on your machine.
The "PARAMETER_FILE" can be created through the wizard. To use the wizard on the shell, you write the following code (& save as ``wizard.jl``):
```julia:wizard.jl
using LatticeQCD
run_wizard()
```
Then, you can run the wizard:
```
julia wizard.jl
```
You write the following code (& save as ``run.jl``):
```julia:run.jl
using LatticeQCD
run_LQCD(ARGS[1])
```
Then, you can execute like
```
julia run.jl PARAMETER_FILE
```
then, you get results though standard I/O.
# Purpose of the code
We develop this code to achive following things:
1. Good portability (If one has Julia, this code is runnable. All dependences are under control.)
2. Easy to start/ pedagogical (start in 10 minutes)
3. Suite (configuration generation with and without fermions, and measurements)
4. Easy to modify (Good for prototyping)
5. Compatitive speed with Fortran 90 codes
This is the first open source Julia code for lattice QCD. High performance is out of our scope.
# How has it been tested?
We compared results to following papers/codes
- Nf=4 SU(3) staggered HMC with https://inspirehep.net/literature/283285
- Quenched SU(2) improved thermodynamics https://inspirehep.net/literature/1614325
- RHMC https://doi.org/10.1051/epjconf/201817507041
- HMC for Wilson and Clover Wilson fermions "Lattice Tool Kit": https://nio-mon.riise.hiroshima-u.ac.jp/LTK/
- Pion correlator with the Wilson-Dirac operator https://inspirehep.net/literature/37901
- Pion correlator with the staggered Dirac operator https://inspirehep.net/literature/21821
# Reference
We refer "Lattice Tool Kit" https://nio-mon.riise.hiroshima-u.ac.jp/LTK/ written in Fortran 90.
# Acknowledgement
If you write a paper using this package, please refer this code.
E.g. This work is in part based on LatticeQCD.jl (https://github.com/akio-tomiya/LatticeQCD.jl).
BibTeX citation is following
```
@article{Nagai:2024yaf,
author = "Nagai, Yuki and Tomiya, Akio",
title = "{JuliaQCD: Portable lattice QCD package in Julia language}",
eprint = "2409.03030",
archivePrefix = "arXiv",
primaryClass = "hep-lat",
month = "9",
year = "2024"
}
```
and the paper is [arXiv:2409.03030](https://arxiv.org/abs/2409.03030).
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | docs | 4570 | # LatticeQCD.jl
This is the lattice QCD package purely written in Julia language.
Lattice QCD is a well-established non-perturbative approach to solving the quantum chromodynamics (QCD) theory of quarks and gluons.
We confirmed that it works in Julia 1.5 or later.
This code is inspired by the Lattice Tool Kit (LTK) written in [Fortran](https://nio-mon.riise.hiroshima-u.ac.jp/LTK/).
With the use of a modern programing language, it is easy to understand how the code works.
The part of the codes is translated from the LTK.
What LatticeQCD.jl can do is :
- Two flavor SU(3) Hybrid Monte Carlo with the Wilson Fermion (We want to add more functionalities.).
- The speed is the faster than the original LTK code written in fortran.
## How to do
### simple version
You can try this code with
```
julia ./src/run.jl
```
or
```
julia ./src/run.jl params.jl
```
Here, in params.jl, we can see
```julia
L = (4,4,4,4)
β = 6
#gparam = Setup_Gauge_action(β)
NTRACE = 3
gparam = GaugeActionParam_standard(β,NTRACE)
#gparam = Setup_Gauge_action(β)
hop= 0.141139#Hopping parameter
r= 1#Wilson term
eps= 1e-19
Dirac_operator= "Wilson"
MaxCGstep= 3000
#fparam = Setup_Fermi_action()
fparam = FermiActionParam_Wilson(hop,r,eps,Dirac_operator,MaxCGstep)
```
You can change the parameters.
If you set ```fparam=nothing``` in this file, you can do the quench HMC.
### more details
In the LatticeQCD.jl, the Universe type is an important type for simulations.
At first, you have to generate your "universe".
```julia
univ = Universe(file)
```
The file is like:
```julia
L = (4,4,4,4)
β = 6
NTRACE = 3
#gparam = Setup_Gauge_action(β)
gparam = GaugeActionParam_standard(β,NTRACE)
BoundaryCondition=[1,1,1,-1]
Nwing = 1
initial="cold"
NC =3
hop= 0.141139#Hopping parameter
r= 1#Wilson term
eps= 1e-19
Dirac_operator= "Wilson"
MaxCGstep= 3000
fparam = FermiActionParam_Wilson(hop,r,eps,Dirac_operator,MaxCGstep)
```
The parameters that you do not provide are set by the default values.
Then, you can calculate physical obserbables.
For example, if you want to calculate a plaquette, just do
```julia
plaq = calc_plaquette(univ)
println("plaq = ",plaq)
```
If you want to do the HMC simulation, set the MD parameters:
```julia
Δτ = 0.1
MDsteps = 10
βMD = β
mdparams =MD_parameters_standard(gparam,Δτ,MDsteps,βMD)
```
and do it like:
```julia
for i=1:20
Sold = md_initialize!(univ)
Snew = md!(univ,mdparams)
metropolis_update!(univ,Sold,Snew)
plaq = calc_plaquette(univ)
println("-------------------------------------")
println("$i-th plaq = ",plaq)
println("-------------------------------------")
end
```
## Benchmarks
The speed is important for the Lattice QCD simulation.
Remarkably, this Julia code is faster than s similar code in Fortran.
For example, with the following parameters:
```
6.0d0 6.0d0 beta, betamd
0.141139d0 1.d0 hop, r (Hopping parametger, Wilson term)
.false. Clover term
(0.0d0,0.0d0) cmu (Chemical potential)
1 istart (1:Cold, 2:Hot, 3:File)
001 020 ntraj0, ntraj1
1.d0 gamma_G
10 0.1d0 nstep, dtau
.true. fermions
0 flagMD
```
, where this is an input file of the LTK.
We set eps=1e-19 as a convergence criteria in a CG solver.
The elapsed time of the original LTK code on Mac mini (2018) with 3.2Ghz Intel Core i7 (6 cores) is
```
Eold,Enew,Diff,accept: 0.1613911E+04 0.1614279E+04 -0.3678492E+00 T
Plaq : 0.60513145439721250
Pol : (1.1156431755476819,-3.20744714128515240E-002)
./a.out < input 227.40s user 0.07s system 99% cpu 3:47.51 total
```
On the other hand, the elapsed time of this LatticeQCD.jl is
```
-------------------------------------
20-th plaq = 0.6051309989225465
-------------------------------------
julia --sysimage ~/sys_plots.so run.jl 180.41s user 0.25s system 100% cpu 3:00.62 total
```
The LatticeQCD.jl is faster than the Fortran-based code.
We note that the plaquette value is consistently in single precision floating point numbers,
since the random number generation is based on the original Fortran code and random numbers are in single precision floating point.
```@autodocs
Modules = [LatticeQCD.LTK_universe]
```
```@docs
Setup_Gauge_action
Setup_Fermi_action
``` | LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 1.1.0 | e495a1eaee52a513e02fe6ca2c995a7d0ed671a7 | docs | 572 | # Analysis code
Please ``samples.zip`` decompress.
``analysis_sample.jl`` is the analysis code.
```
using LatticeQCD
betas = ["1.40","1.65"]
println("# beta plaquette")
for beta in betas
dir = "samples/HMC_L08080808_su2nf8_beta$(beta)_Staggered_mass0.015"
p = get_plaquette_average(dir)
println("$beta $p #$dir")
end
println("# ")
println("# beta Polyakov loop")
for beta in betas
dir = "samples/HMC_L08080808_su2nf8_beta$(beta)_Staggered_mass0.015"
p = get_polyakov_average(dir)
println("$beta $p #$dir")
end
```
| LatticeQCD | https://github.com/akio-tomiya/LatticeQCD.jl.git |
|
[
"MIT"
] | 0.0.6 | 28462d28ee55ed3378aa682be12c6fe09da06254 | code | 74 | module NatureGas
include("heatvalue.jl")
include("aga8.jl")
end # module
| NatureGas | https://github.com/hzgzh/NatureGas.jl.git |
|
[
"MIT"
] | 0.0.6 | 28462d28ee55ed3378aa682be12c6fe09da06254 | code | 8328 | using Roots
export ng_zfactor
"""
ng_zfactor(p,T;CH4=0.965,N2=0.003,CO2=0.006,C2H6=0.018,C3H8=0.045,H2O=0.,H2S=0.,
H2=0.,CO=0.,O2=0.,iC4H10=0.001,nC4H10=0.001,iC5H12=0.0005,nC5H12=0.0003,nC6H14=0.0007,
nC7H16=0.,nC8H18=0.,nNonane=0.,nDecane=0.,He=0.,Ar=0.)
Calculate the compress factor of specific pressure and temperature nature gas
# Auguments
...
- "p::Float64" : thre pressure,unit MPa
- "T::Float64" : the temperature,unit K
...
# Example
```
julia>ng_z_factor(6,300;CO2=0.006,N2=0.003,CH4=0.965,C2H6=0.018,C3H8=0.0045,
iC4H10=0.001,nC4H10=0.001,iC5H12=0.0005,nC5H12=0.0003,nC6H14=0.0007))
0.8953514530758864
```
"""
function ng_zfactor(p,T;
CH4=0.965,
N2=0.003,
CO2=0.006,
C2H6=0.018,
C3H8=0.0045,
H2O=0.,
H2S=0.,
H2=0.,
CO=0.,
O2=0.,
iC4H10=0.001,
nC4H10=0.001,
iC5H12=0.0005,
nC5H12=0.0003,
nC6H14=0.0007,
nC7H16=0.,
nC8H18=0.,
nNonane=0.,
nDecane=0.,
HE=0.,
AR=0.)
#参数检查
#=
ul=[12,338,1,0.2,0.2,0.1,0.035,0.015,0.005,0.001,0.0005,0.0005,0.1,0.03,0.005,0.00015]
ll=[0;263;0.7;zeros(13)]
pars=["pressure"=>p,"Temperature"=>T,"CH4"=>CH4,"N2"=>N2,"CO2"=>CO2,"C2H6"=>C2H6,"C3H8"=>C3H8,
"C4H10"=>iC4H10+nC4H10,"C5H12"=>iC5H12+nC5H12,"C6"=>nC6H14,"C7"=>nC7H16,"C8+"=>nC8H18+nNonane+nDecane,
"H2"=>H2,"CO"=>CO,"HE"=>HE,"H2O"=>H2O]
for i=1:16
!(ll[i]<pars[i].second<ul[i]) && error("$(pars[i].first) should be in range of $(ll[i]) - $(ul[i])")
end
=#
x=[CH4,N2,CO2,C2H6,C3H8,H2O,H2S,H2,CO,O2,iC4H10,nC4H10,iC5H12,nC5H12,nC6H14,nC7H16,nC8H18,nNonane,nDecane,HE,AR]
x=x./sum(x)
#sum(x)!=100. && error("all componnet sum should be 100")
N=21
R=8.31451e-3
#状态参数值
a=[ 0.153832600, 1.341953000,-2.998583000, -0.048312280, 0.375796500, -1.589575000,-0.053588470, 0.886594630,
-0.710237040,-1.471722000, 1.321850350, -0.786659250, 0.2291290e-08,0.157672400,-0.436386400,-0.044081590,
-0.003433888, 0.032059050, 0.024873550, 0.073322790,-0.001600573, 0.642470600,-0.416260100,-0.066899570,
0.279179500,-0.696605100,-0.002860589, -0.008098836, 3.150547000, 0.007224479,-0.705752900, 0.534979200,
-0.079314910,-1.418465000,-0.5999050e-16,0.105840200, 0.034317290, -0.007022847, 0.024955870, 0.042968180,
0.746545300,-0.291961300, 7.294616000, -9.936757000,-0.005399808, -0.243256700, 0.049870160, 0.003733797,
1.874951000, 0.002168144,-0.658716400, 0.000205518, 0.009776195, -0.020487080, 0.015573220, 0.006862415,
-0.001226752, 0.002850908]
b=Float64[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,6,6,7,7,8,8,8,9,9]
k=Float64[0,0,0,0,0,0,0,0,0,0,0,0,3,2,2,2,4,4,0,0,2,2,2,4,4,4,4,0,1,1,2,2,3,3,4,4,4,0,0,2,2,2,4,4,0,2,2,4,4,0,2,0,2,1,2,2,2,2]
c=Float64[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1]
g=Float64[0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,0]
f=Float64[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
q=Float64[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,1]
s=Float64[0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
w=Float64[0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
u=Float64[0,0.5 ,1,3.5 ,-0.5 ,4.5 ,0.5 ,7.5 ,9.5 ,6,12,12.5 ,-6,2,3,2,2,11,-0.5 ,0.5 ,0,4,6,21,23,22,-1,-0.5 ,7,-1,6,
4,1,9,-13,21,8,-0.5 ,0,2,7,9,22,23,1,9,3,8,23,1.5 ,5,-0.5 ,4,7,3,0,1,0]
#特征参数值
M=[16.0430 , 28.0135 , 44.0100 , 30.0700 , 44.0970 , 18.0153 , 34.0820 , 2.0159 , 28.0100 , 31.9988 ,
58.1230 , 58.1230 , 72.1500 , 72.1500 , 86.1770 ,100.2040 ,114.2310 ,128.2580 ,142.2850 , 4.0026 ,
39.9480 ]
E=[151.318300 , 99.737780 , 241.960600 , 244.166700 , 298.118300 , 514.015600 , 296.355000 , 26.957940 ,
105.534800 , 122.766700 , 324.068900 , 337.638900 , 365.599900 , 370.682300 , 402.636293 , 427.722630 ,
450.325022 , 470.840891 , 489.558373 , 2.610111 , 119.629900 ]
K=[ 0.4619255 , 0.4479153 , 0.4557489 , 0.5279209 , 0.5837490 , 0.3825868 , 0.4618263 , 0.3514916 ,
0.4533894 , 0.4186954 , 0.6406937 , 0.6341423 , 0.6738577 , 0.6798307 , 0.7175118 , 0.7525189 ,
0.7849550 , 0.8152731 , 0.8437826 , 0.3589888 , 0.4216551 ]
G=[0, 0.027815 , 0.189065 , 0.079300 , 0.141239 , 0.332500 , 0.088500 , 0.034369 , 0.038953 , 0.021000 ,
0.256692 , 0.281835 , 0.332267 , 0.366911 , 0.289731 , 0.337542 , 0.383381 , 0.427354 , 0.469659 , 0, 0]
Q=[zeros(2);0.69; zeros(2); 1.06775; 0.633276; zeros(14)]
F=[zeros(7);1.0;zeros(13,1)]
S=[zeros(5); 1.5822; 0.390; zeros(14)]
W=[zeros(5); 1; zeros(15)]
#交互作用参数值
Ex=[1.0 0.971640 0.960644 1.0 0.994635 0.708218 0.931484 1.170520 0.990126 1.0 1.019530 0.989844 1.002350 0.999268 1.107274 0.880880 0.880973 0.881067 0.881161 1.0 1.0;
ones(1,2) 1.022740 0.970120 0.945939 0.746954 0.902271 1.086320 1.005710 1.021000 0.946914 0.973384 0.959340 0.945520 ones(1,7);
ones(1,3) 0.925053 0.960237 0.849408 0.955052 1.281790 1.5 1 0.906849 0.897362 0.726255 0.859764 0.855134 0.831229 0.808310 0.786323 0.765171 ones(1,2);
ones(1,4) 1.022560 0.693168 0.946871 1.164460 ones(1,3) 1.013060 1 1.00532 ones(1,7);
ones(1,7) 1.034787 ones(1,3) 1.0049 ones(1,9);
ones(1,21);
ones(1,14) 1.008692 1.010126 1.011501 1.012821 1.014089 ones(1,2);
ones(1,8) 1.1 1 1.3 1.3 ones(1,9);ones(13,21)]
Gx=ones(21,21);Gx[1,3]=0.807653;Gx[1,8]=1.957310;Gx[2,3]=0.982746; Gx[3,4]=0.370296; Gx[3,6]=1.673090
Ux=[1.0 0.886106 0.963827 1 0.990877 1.0 0.736833 1.156390 ones(1,3) 0.992291 1 1.003670 1.302576 1.191904 1.205769 1.219634 1.233498 ones(1,2);
ones(1,2) 0.835058 0.816431 0.915502 1.0 0.993476 0.408838 ones(1,3) 0.993556 ones(1,9);
ones(1,3) 0.969870 ones(1,2) 1.045290 1.0 0.9 ones(1,5) 1.066638 1.077634 1.088178 1.098291 1.108021 ones(1,2);
ones(1,4) 1.065173 1.0 0.971926 1.616660 ones(1,2) ones(1,4)*1.25 ones(1,7);
ones(2,21);
ones(1,14) 1.028973 1.033754 1.038338 1.042735 1.046966 ones(1,2);
ones(14,21)]
Kx=[ones(1,1) 1.003630 0.995933 1 1.007619 1 1.000080 1.023260 ones(1,3) 0.997596 1 1.002529 0.982962 0.983565 0.982707 0.981849 0.980991 ones(1,2);
ones(1,2) 0.982361 1.007960 1 1 0.9425960 1.032270 ones(1,13);
ones(1,3) 1.008510 ones(1,2) 1.00779 ones(1,7) 0.910183 0.895362 0.881152 0.867520 0.854406 ones(1,2);
ones(1,4) 0.986893 1 0.999969 1.020340 ones(1,13);
ones(2,21);
ones(1,16) 0.968130 0.962870 0.957828 0.952441 0.948338;
ones(14,21)]
Eij=[Ex[i,j]*sqrt(E[i]*E[j]) for i=1:N,j=1:N]
Gij=[Gx[i,j]*(G[i]+G[j])/2.0 for i=1:N,j=1:N]
Bnij=[(Gij[i,j]+1.0-g[n])^g[n]*
(Q[i]*Q[j]+1.0-q[n])^q[n]*
(sqrt(F[i]*F[j])+1.0-f[n])^f[n]*
(S[i]*S[j]+1.0-s[n])^s[n]*
(W[i]*W[j]+1.0-w[n])^w[n] for n=1:18,i=1:N,j=1:N]
B=sum(a[n]*T^(-u[n])*sum(x[i]*x[j]*Bnij[n,i,j]*Eij[i,j]^u[n]*(K[i]*K[j])^1.5 for i=1:N,j=1:N) for n=1:18)
U0=(sum(x.*(E.^2.5))^2.0+sum(x[i]*x[j]*(Ux[i,j]^5.0-1.0)*(E[i]*E[j])^2.5 for i=1:N-1 for j=i+1:N))^0.2
G0=sum(x.*G)+sum(x[i]*x[j]*(Gx[i,j]-1.0)*(G[i]+G[j]) for i=1:N-1 for j=i+1:N)
Q0=sum(x.*Q)
F0=sum(x.^2.0.*F)
K0=(sum(x.*K.^2.5)^2.0+2*sum(x[i]*x[j]*(Kx[i,j]^5.0-1.0)*(K[i]*K[j])^2.5 for i=1:N-1 for j=i+1:N))^0.2
Cn=[a[n]*(G0+1-g[n])^g[n]*(Q0^2+1.0-q[n])^q[n]*(F0+1.0-f[n])^f[n]*U0^u[n]*T^(-u[n]) for n=13:58]
Cn=[zeros(12);Cn]
function fun(ρm)
ρr=K0^3.0*ρm
z=1.0+B*ρm-ρr*sum(Cn[n] for n=13:18)+sum(Cn[n]*(b[n]-c[n]*k[n]*ρr^k[n])*ρr^b[n]*exp(-c[n]*ρr^k[n]) for n=13:58)
ρm*R*T*z-p
end
ρm=find_zero(fun,40,rtol=1e-6)
p/(ρm*R*T)
end
| NatureGas | https://github.com/hzgzh/NatureGas.jl.git |
|
[
"MIT"
] | 0.0.6 | 28462d28ee55ed3378aa682be12c6fe09da06254 | code | 9690 | R=8.31451;p=101325;T=293.15
molemass=[
16.0430,30.0700,44.0970,58.1230,58.1230,72.1500,72.1500,72.1500,
86.1770,86.1770,86.1770,86.1770,86.1770,100.204,114.231,128.258,
142.285,28.0540,42.0810,56.1080,56.0180,56.1080,56.1080,70.1340,
40.0650,54.0920,54.0920,26.0380,70.1340,84.1610,98.1880,84.1610,
98.1880,112.215,78.1140,92.1410,106.167,106.167,32.0420,48.1090,
2.01590,18.0153,34.0820,17.0306,27.0260,28.0100,60.0760,76.1430,
4.00260,20.1797,39.9480,28.0135,31.9988,44.0100,64.0650,44.0129,
83.8000,131.290]
mol_heat_high=[
891.090,1561.41,2220.13,2878.57,2869.38,3537.17,3530.24,3516.01,
4196.58,4188.95,4191.54,4179.15,4186.93,4855.29,5513.88,6173.46,
6832.31,1411.65,2058.72,2717.75,2711.00,2707.40,2701.10,3376.57,
1943.53,2594.45,2541.43,1301.21,3320.88,3970.93,4630.19,3954.47,
4602.35,5264.98,3302.15,3948.84,4608.32,4597.46,764.590,1239.83,
285.990,44.2240,562.190,383.160,671.600,282.950,548.190,1104.41]
mol_heat_low=[
802.650,1428.74,2043.23,2657.45,2648.26,3271.83,3264.89,3250.67,
3887.01,3879.38,3881.97,3869.59,3877.36,4501.49,5115.87,5731.22,
6345.85,1323.20,1926.05,2540.86,2534.10,2530.50,2524.20,3155.45,
1855.08,2461.78,2408.76,1256.98,3099.76,3705.59,4320.63,3689.13,
4292.78,4911.19,3169.48,3771.95,4387.20,4376.34,676.140,1151.39,
241.760,0.00000,517.970,316.820,649.500,282.950,548.190,1104.41]
z=[
0.9981,0.9920,0.9834,0.9682,0.9710,0.9450,0.953,0.959,
0.9190,0.9260,0.9280,0.9350,0.9340,0.8760,0.817,0.735,
0.6230,0.9940,0.9850,0.9720,0.9690,0.9690,0.972,0.952,
0.9840,0.9650,0.9730,0.9930,0.9500,0.9270,0.885,0.924,
0.8940,0.8380,0.9360,0.8920,0.8370,0.8210,0.892,0.978,
1.0006,0.9520,0.9900,0.9890,0.9200,0.9996,0.988,0.965,
1.0005,1.0005,0.9993,0.9997,0.9993,0.9944,0.980]
b=[0.0436,0.0894,0.1288,0.1783,0.1703,0.2345,0.2168,0.2025,
0.2846,0.2720,0.2683,0.2550,0.2569,0.3521,0.4278,0.5148,
0.6140,0.0775,0.1225,0.1673,0.1761,0.1761,0.1673,0.2191,
0.1265,0.1871,0.1643,0.0837,0.2236,0.2702,0.3391,0.2757,
0.3256,0.4025,0.2530,0.3286,0.4037,0.4231,0.3286,0.1483,
-0.0051,0.2191,0.1000,0.1049,0.2828,0.0200,0.1095,0.1871,
0.0000,0.0000,0.0265,0.0173,0.0265,0.0728,0.1414]
N=48;N1=55
hhv_mole(x)=sum(mol_heat_high[1:N].*x[1:N])
lhv_mole(x)=sum(mol_heat_low[1:N].*x[1:N])
mole_mass(x)=sum(molemass.*x)
hhv_mass(x)=hhv_mole(x)/mole_mass(x)
lhv_mass(x)=lhv_mole(x)/mole_mass(x)
vol2mol(x)=x[1:N1]./z/sum(x[1:N1]./z)
zmix(x)=1.0-sum(x[1:N1].*b)
lhv_vol(x)=lhv_mole(x)*p/R/T
hhv_vol(x)=hhv_mole(x)*p/R/T
lhv_real_vol(x)=lhv_vol(x)/zmix(x)
hhv_real_vol(x)=hhv_vol(x)/zmix(x)
rel_ρ(x)=sum(x*mole_mass(x)/28.9625)
abs_ρ(x)=sum(x*mole_mass(x))*p/R/T
real_rel_ρ(x)=rel_ρ(x)*0.99963/zmix(x)
real_abs_ρ(x)=abs_ρ(x)/zmix(x)
function calorific(x,out)
if out==:mol
return (lhv_mole(x),hhv_mole(x))
elseif out==:mass
return (lhv_mass(x),hhv_mass(x))
elseif out==:vol
return (lhv_real_vol(x),hhv_real_vol(x))
elseif out==:rho
return (real_rel_ρ(x),real_abs_ρ(x))
end
end
"""
ng_calorific(mode=:mol,outoption=:mol;CH4=100.0,C2H6=0,C3H8=0,C4H10=0,C4H10_1=0,C5H12=0,C5H12_1=0.,C5H12_2=0,C6H14=0,
C6H14_1=0.0,C6H14_2=0.0,C6H14_3=0,C6H14_4=0,C7H16=0,C8H18=0.0,C9H20=0.0,C10H22=0.0,C2H4=0.0,
C3H6=0.0,C4H8=0.0,C4H8_1=0.0,C4H8_2=0.0,C4H8_3=0.0,C5H10=0.0,C3H4=0.0,C4H6=0.0,C4H6_1=0.0,C2H2=0.0,
C5H10_1=0.0,C6H12=0.0,C7H12=0.0,C6H12_1=0.0,C7H14=0.0,C8H16=0.0,C6H6=0.0,C7H8=0.0,C8H10=0.0,C8H10_1=0.0,
CH4O=0.0,C2H6HgS2=0.0,H2=0.0,H2O=0.0,H2S=0.0,NH3=0.0,CHN=0.0,CO2=0.0,COS=0.0,CS2=0.0,He=0.0,Ne=0.0,Ar=0.0,
N2=0.0,O2=0.0,CO2=0.0,O2S=0.0,N2O=0.0,Kr=0.0,Xe=0.0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
`:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific(mode=:mol,outoption=:mol;CH4=1.0,C2H6=0,C3H8=0,nC4H10=0,iC4H10=0,nC5H12=0,iC5H12=0.,
C5H12_2=0,nC6H14=0,iC6H14=0.0,C6H14_2=0.0,C6H14_3=0,C6H14_4=0,nC7H16=0,nC8H18=0.0,nC9H20=0.0,nC10H22=0.0,
C2H4=0.0,C3H6=0.0,C4H8=0.0,C4H8_1=0.0,C4H8_2=0.0,C4H8_3=0.0,C5H10=0.0,C3H4=0.0,C4H6=0.0,C4H6_1=0.0,C2H2=0.0,
C5H10_1=0.0,C6H12=0.0,C7H12=0.0,C6H12_1=0.0,C7H14=0.0,C8H16=0.0,C6H6=0.0,C7H8=0.0,C8H10=0.0,C8H10_1=0.0,
CH4O=0.0,C2H6HgS2=0.0,H2=0.0,H2O=0.0,H2S=0.0,NH3=0.0,CHN=0.0,CO=0.0,COS=0.0,CS2=0.0,He=0.0,Ne=0.0,Ar=0.0,
N2=0.0,O2=0.0,CO2=0.0,O2S=0.0,N2O=0.0,Kr=0.0,Xe=0.0)
x=[CH4,C2H6,C3H8,nC4H10,iC4H10,nC5H12,iC5H12,C5H12_2,nC6H14,
iC6H14,C6H14_2,C6H14_3,C6H14_4,nC7H16,nC8H18,nC9H20,nC10H22,C2H4,
C3H6,C4H8,C4H8_1,C4H8_2,C4H8_3,C5H10,C3H4,C4H6,C4H6_1,C2H2,
C5H10_1,C6H12,C7H12,C6H12_1,C7H14,C8H16,C6H6,C7H8,C8H10,C8H10_1,
CH4O,C2H6HgS2,H2,H2O,H2S,NH3,CHN,CO,COS,CS2,He,Ne,Ar,
N2,O2,CO2,O2S,N2O,Kr,Xe]
if mode==:vol;x=vol2mol(x);end
calorific(x,outoption)
end
"""
ng_calorific_cn(mode=:mol,outoption=:mol;甲烷=100,乙烷=0,丙烷=0,丁烷=0,二甲基丙烷=0,戊烷=0,二甲基丁烷=0,
二二甲基丙烷=0,已烷=0,二甲基戊烷=0,三甲基戊烷=0,二二甲基丁烷=0,二三甲基丁烷=0,庚烷=0,辛烷=0,
壬烷=0,癸烷=0,乙烯=0,丙烯=0,一丁烯=0,顺二丁烯=0,反二丁烯=0,二甲基丙烯=0,一戊烯=0,丙二烯=0,一二丁二烯=0,
一三丁二烯=0,乙炔=0,环戊烷=0,甲基环戊烷=0,乙基环戊烷=0,环己烷=0,甲基环己烷=0,乙基环己烷=0,苯=0,
甲苯=0,乙苯=0,邻二甲苯=0,甲醇=0,甲硫醇=0,氢气=0,水=0,硫化氢=0,氨=0,氰化氢=0,一氧化碳=0,硫氧碳=0,
二硫化碳=0,氦气=0,氖气=0,氩气=0,氮气=0,氧气=0,二氧化碳=0,二氧化硫=0,一氧化二氮=0,氪气=0,氙气=0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
`:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific_cn(mode=:mol,outoption=:mol;甲烷=1,乙烷=0,丙烷=0,丁烷=0,二甲基丙烷=0,戊烷=0,二甲基丁烷=0,
二二甲基丙烷=0,已烷=0,二甲基戊烷=0,三甲基戊烷=0,二二甲基丁烷=0,二三甲基丁烷=0,庚烷=0,辛烷=0,
壬烷=0,癸烷=0,乙烯=0,丙烯=0,一丁烯=0,顺二丁烯=0,反二丁烯=0,二甲基丙烯=0,一戊烯=0,丙二烯=0,一二丁二烯=0,
一三丁二烯=0,乙炔=0,环戊烷=0,甲基环戊烷=0,乙基环戊烷=0,环己烷=0,甲基环己烷=0,乙基环己烷=0,苯=0,
甲苯=0,乙苯=0,邻二甲苯=0,甲醇=0,甲硫醇=0,氢气=0,水=0,硫化氢=0,氨=0,氰化氢=0,一氧化碳=0,硫氧碳=0,
二硫化碳=0,氦气=0,氖气=0,氩气=0,氮气=0,氧气=0,二氧化碳=0,二氧化硫=0,一氧化二氮=0,氪气=0,氙气=0)
x=[甲烷,乙烷,丙烷,丁烷,二甲基丙烷,戊烷,二甲基丁烷,
二二甲基丙烷,已烷,二甲基戊烷,三甲基戊烷,二二甲基丁烷,二三甲基丁烷,庚烷,辛烷,
壬烷,癸烷,乙烯,丙烯,一丁烯,顺二丁烯,反二丁烯,二甲基丙烯,一戊烯,丙二烯,一二丁二烯,
一三丁二烯,乙炔,环戊烷,甲基环戊烷,乙基环戊烷,环己烷,甲基环己烷,乙基环己烷,苯,
甲苯,乙苯,邻二甲苯,甲醇,甲硫醇,氢气,水,硫化氢,氨,氰化氢,一氧化碳,硫氧碳,
二硫化碳,氦气,氖气,氩气,氮气,氧气,二氧化碳,二氧化硫,一氧化二氮,氪气,氙气]
if mode==:vol;x=vol2mol(x);end
calorific(x,outoption)
end
"""
ng_calorific_en(mode=:mol,outoption=:mol;Methane=100.0,Ethane=0.0,Propane=0.0,nButane=0.0,Alkanes=0.0,nPentane=0.0,
Methylbutane_2=0.0,Dimethylpropane_2_2=0.0,nHexane=0.0,Methylpentane_2=0.0,Methoylpentane_3=0.0,
Dimethylbutane_2_2=0.0,Dimethylbutane_2_3=0.0,nHeptane=0.0,nOctane=0.0,nNonane=0.0,nDecane=0.0,
Ethylene=0.0,Propylene=0.0, Butene_1=0.0,cis_2_Butene=0.0,trans_2_Butene=0.0,Methylpropene_2=0.0,
Pentene_1=0.0, Propadiene=0.0,Butadiene_1_2=0.0,Butadiene_1_3=0.0,Acetylene=0.0,Cyclopentane=0.0,
Methylcyclopentane=0.0,Ethylcyclopentane=0.0,Cyclohexane=0.0,Methylcyclohexane=0.0,Ethylcyclohexane=0.0,
Benzene=0.0,Toluene=0.0,Ethylbenzene=0.0,o_Xylene=0.0,Methanol=0.0,Methanethiol=0.0,Hydrogen=0.0,
Water=0.0,Hydrogen_sulfide=0.0,Ammonia=0.0,Hydrogen_cyanide=0.0,Carbon_monoxide=0.0,Carbonyl_sulfide=0.0,
Carbon_disulfide=0.0,Helium=0.0,Neon=0.0,Argon=0.0,Nitrogen=0.0,Oxygen=0.0,Carbon_dioxide=0.0,Sulfur_Dioxide=0.0,
Dinitrogen_monoxide=0.0,Krypton=0.0,Xenon=0.0)
# Augument
- `mode`: `:mol` mol heat;`:mass` mass heat;`:vol heat` volume heat
- `outoption` : `:mol` (mole_low_heat,mole_high_heat) kJ/mo1;`:mass` (mass_low_heat,mass_high_heat) MJ/kg;`:vol`(vol_low_heat,vol_high_heat) u"MJ/m3";
`:rho` (real rel_density,real abs_density u"kg/m3")
"""
function ng_calorific_en(mode=:mol,outoption=:mol;Methane=1.0,Ethane=0.0,Propane=0.0,nButane=0.0,Alkanes=0.0,nPentane=0.0,
Methylbutane_2=0.0,Dimethylpropane_2_2=0.0,nHexane=0.0,Methylpentane_2=0.0,Methoylpentane_3=0.0,
Dimethylbutane_2_2=0.0,Dimethylbutane_2_3=0.0,nHeptane=0.0,nOctane=0.0,nNonane=0.0,nDecane=0.0,
Ethylene=0.0,Propylene=0.0, Butene_1=0.0,cis_2_Butene=0.0,trans_2_Butene=0.0,Methylpropene_2=0.0,
Pentene_1=0.0, Propadiene=0.0,Butadiene_1_2=0.0,Butadiene_1_3=0.0,Acetylene=0.0,Cyclopentane=0.0,
Methylcyclopentane=0.0,Ethylcyclopentane=0.0,Cyclohexane=0.0,Methylcyclohexane=0.0,Ethylcyclohexane=0.0,
Benzene=0.0,Toluene=0.0,Ethylbenzene=0.0,o_Xylene=0.0,Methanol=0.0,Methanethiol=0.0,Hydrogen=0.0,
Water=0.0,Hydrogen_sulfide=0.0,Ammonia=0.0,Hydrogen_cyanide=0.0,Carbon_monoxide=0.0,Carbonyl_sulfide=0.0,
Carbon_disulfide=0.0,Helium=0.0,Neon=0.0,Argon=0.0,Nitrogen=0.0,Oxygen=0.0,Carbon_dioxide=0.0,Sulfur_Dioxide=0.0,
Dinitrogen_monoxide=0.0,Krypton=0.0,Xenon=0.0)
x=[Methane,Ethane,Propane,nButane,Alkanes,nPentane,Methylbutane_2,Dimethylpropane_2_2,nHexane,Methylpentane_2,Methoylpentane_3,
Dimethylbutane_2_2,Dimethylbutane_2_3,nHeptane,nOctane,nNonane,nDecane,Ethylene,Propylene,Butene_1,cis_2_Butene,trans_2_Butene,
Methylpropene_2,Pentene_1,Propadiene,Butadiene_1_2,Butadiene_1_3,Acetylene,Cyclopentane,Methylcyclopentane,Ethylcyclopentane,
Cyclohexane,Methylcyclohexane,Ethylcyclohexane,Benzene,Toluene,Ethylbenzene,o_Xylene,Methanol,Methanethiol,Hydrogen,Water,
Hydrogen_sulfide,Ammonia,Hydrogen_cyanide,Carbon_monoxide,Carbonyl_sulfide,Carbon_disulfide,Helium,Neon,Argon,Nitrogen,Oxygen,
Carbon_dioxide,Sulfur_Dioxide,Dinitrogen_monoxide,Krypton,Xenon]
if mode==:vol;x=vol2mol(x);end
calorific(x,outoption)
end
export ng_calorific,ng_calorific_cn,ng_calorific_en | NatureGas | https://github.com/hzgzh/NatureGas.jl.git |
|
[
"MIT"
] | 0.0.6 | 28462d28ee55ed3378aa682be12c6fe09da06254 | code | 2995 | using NatureGas
using Test
#=
gas=[
"CO2" 0.006 0.005 0.015 0.016 0.076 0.011;
"N2" 0.003 0.031 0.010 0.100 0.057 0.117;
"H2" 0.00 0.00 0.00 0.095 0.00 0.00;
"CO" 0.00 0.00 0.00 0.010 0.00 0.00;
"CH4" 0.965 0.907 0.859 0.735 0.812 0.826;
"C2H6" 0.018 0.0450 0.085 0.033 0.043 0.035;
"C3H8" 0.0045 0.0084 0.023 0.0074 0.009 0.0075;
"iC4H10" 0.0010 0.0010 0.0035 0.0012 0.0015 0.0012;
"nC4H10" 0.0010 0.0015 0.0035 0.0012 0.0015 0.0012;
"iC5H12" 0.0005 0.0003 0.0005 0.0004 0.00 0.0004;
"nC5H12" 0.0003 0.0004 0.0005 0.0004 0.00 0.0004;
"nC6H14" 0.0007 0.0004 0.00 0.0002 0.00 0.0002;
"nC7H16" 0.00 0.00 0.00 0.0001 0.00 0.000 ;
"nC8H18" 0.00 0.00 0.00 0.0001 0.00 0.00]
=#
case=[
60 -3.15 0.84053 0.83348 0.79380 0.88550 0.82609 0.85380;
60 6.85 0.86199 0.85596 0.82206 0.90144 0.84969 0.87370;
60 16.85 0.88006 0.87484 0.84544 0.91501 0.86944 0.89052;
60 36.85 0.90867 0.90466 0.88183 0.93674 0.90052 0.91723;
60 56.85 0.93011 0.92696 0.90868 0.95318 0.92368 0.93730;
120 -3.15 0.72133 0.71044 0.64145 0.81024 0.69540 0.75074;
120 6.85 0.76025 0.75066 0.68971 0.83782 0.73780 0.78586;
120 16.85 0.79317 0.78475 0.73123 0.86137 0.77369 0.81569;
120 36.85 0.84515 0.83863 0.79697 0.89913 0.83022 0.86311;
120 56.85 0.88383 0.87870 0.84553 0.92766 0.87211 0.89862]
atol=0.005
@testset "Gas 1" begin
for i=1:10
@test isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.006,N2=0.003,CH4=0.965,C2H6=0.018,
C3H8=0.0045,iC4H10=0.001,nC4H10=0.001,iC5H12=0.0005,nC5H12=0.0003,nC6H14=0.0007),case[i,3];rtol=atol)
end
end
@testset "Gas 2" begin
for i=1:10
@test isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.005,N2=0.031,CH4=0.907,C2H6=0.045,
C3H8=0.0084,iC4H10=0.001,nC4H10=0.0015,iC5H12=0.0003,nC5H12=0.0004,nC6H14=0.0004),case[i,4];rtol=atol)
end
end
@testset "Gas 3" begin
for i=1:10
@test isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.015,N2=0.01,CH4=0.859,C2H6=0.085,
C3H8=0.023,iC4H10=0.0035,nC4H10=0.0035,iC5H12=0.0005,nC5H12=0.0005,nC6H14=0.0000),case[i,5];rtol=atol)
end
end
@testset "Gas 4" begin
for i=1:10
@test isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.016,N2=0.1,H2=0.095,CO=0.01,CH4=0.735,C2H6=0.033,
C3H8=0.0074,iC4H10=0.0012,nC4H10=0.0012,iC5H12=0.0004,nC5H12=0.0004,nC6H14=0.0002,nC7H16=0.0001,nC8H18=0.0001),case[i,6];rtol=atol)
end
end
@testset "Gas 5" begin
for i=1:10
@test_skip isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.076,N2=0.057,CH4=0.812,C2H6=0.043,
C3H8=0.009,iC4H10=0.0015,nC4H10=0.0015),case[i,7];rtol=atol)
end
end
@testset "Gas 6" begin
for i=1:10
@test isapprox(ng_zfactor(case[i,1]/10,case[i,2]+273.15,CO2=0.011,N2=0.117,CH4=0.826,C2H6=0.035,
C3H8=0.0075,iC4H10=0.0012,nC4H10=0.0012,iC5H12=0.0004,nC5H12=0.0004,nC6H14=0.0002,nC7H16=0.0001),case[i,8];rtol=atol)
end
end
| NatureGas | https://github.com/hzgzh/NatureGas.jl.git |
|
[
"MIT"
] | 0.0.6 | 28462d28ee55ed3378aa682be12c6fe09da06254 | docs | 422 | # NG[](https://travis-ci.org/hzgzh/Naturegas.jl)
# Nature Gas Compress Factor Calculation
## install
Pkg.add("https://github.com/hzgzh/NatureGas.git")
## usage
# Example
```
julia>ng_zfactor(6,300;CO2=0.006,N2=0.003,CH4=0.965,C2H6=0.018,C3H8=0.0045,
iC4H10=0.001,nC4H10=0.001,iC5H12=0.0005,nC5H12=0.0003,nC6H14=0.0007))
0.8953514530758864
```
| NatureGas | https://github.com/hzgzh/NatureGas.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 58 | using Julog
include("population.jl")
include("zebra.jl")
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 2523 | # Population density benchmark from https://github.com/SWI-Prolog/bench
# Author: David H. D. Warren
#
# query population and area database to find coun-
# tries of approximately equal population density
clauses = @julog [
query([C1,D1,C2,D2]) <<=
density(C1,D1) &
density(C2,D2) &
(D1 > D2) &
is(T1, 20*D1) &
is(T2, 21*D2) &
(T1 < T2),
density(C,D) <<=
pop(C,P) &
area(C,A) &
is(D, (P*100)/A),
# populations in 100000's
pop(china, 8250) <<= true,
pop(india, 5863) <<= true,
pop(ussr, 2521) <<= true,
pop(usa, 2119) <<= true,
pop(indonesia, 1276) <<= true,
pop(japan, 1097) <<= true,
pop(brazil, 1042) <<= true,
pop(bangladesh, 750) <<= true,
pop(pakistan, 682) <<= true,
pop(w_germany, 620) <<= true,
pop(nigeria, 613) <<= true,
pop(mexico, 581) <<= true,
pop(uk, 559) <<= true,
pop(italy, 554) <<= true,
pop(france, 525) <<= true,
pop(philippines, 415) <<= true,
pop(thailand, 410) <<= true,
pop(turkey, 383) <<= true,
pop(egypt, 364) <<= true,
pop(spain, 352) <<= true,
pop(poland, 337) <<= true,
pop(s_korea, 335) <<= true,
pop(iran, 320) <<= true,
pop(ethiopia, 272) <<= true,
pop(argentina, 251) <<= true,
# areas in 1000's of square miles
area(china, 3380) <<= true,
area(india, 1139) <<= true,
area(ussr, 8708) <<= true,
area(usa, 3609) <<= true,
area(indonesia, 570) <<= true,
area(japan, 148) <<= true,
area(brazil, 3288) <<= true,
area(bangladesh, 55) <<= true,
area(pakistan, 311) <<= true,
area(w_germany, 96) <<= true,
area(nigeria, 373) <<= true,
area(mexico, 764) <<= true,
area(uk, 86) <<= true,
area(italy, 116) <<= true,
area(france, 213) <<= true,
area(philippines, 90) <<= true,
area(thailand, 200) <<= true,
area(turkey, 296) <<= true,
area(egypt, 386) <<= true,
area(spain, 190) <<= true,
area(poland, 121) <<= true,
area(s_korea, 37) <<= true,
area(iran, 628) <<= true,
area(ethiopia, 350) <<= true,
area(argentina, 1080) <<= true,
]
goal = @julog(query([C1,D1,C2,D2]))
println("Population (single run):")
@time resolve(goal, clauses)
function benchmark(n)
for i = 1:n
resolve(@julog(query([C1,D1,C2,D2])), clauses)
end
end
println("Population (100 runs):")
@time benchmark(100)
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1601 | # Logic puzzle benchmark from https://github.com/SWI-Prolog/bench
# Where does the zebra live?
# Puzzle solution written by Claude Sammut.
clauses = @julog [
query(Houses) <<=
houses(Houses) &
member(house(red, english, _, _, _), Houses) &
member(house(_, spanish, dog, _, _), Houses) &
member(house(green, _, _, coffee, _), Houses) &
member(house(_, ukrainian, _, tea, _), Houses) &
right_of(house(green,_,_,_,_), house(ivory,_,_,_,_), Houses) &
member(house(_, _, snails, _, winstons), Houses) &
member(house(yellow, _, _, _, kools), Houses) &
unifies(Houses, [_, _, house(_, _, _, milk, _), _,_]) &
unifies(Houses, [house(_, norwegian, _, _, _)|_]) &
next_to(house(_,_,_,_,chesterfields), house(_,_,fox,_,_), Houses) &
next_to(house(_,_,_,_,kools), house(_,_,horse,_,_), Houses) &
member(house(_, _, _, orange_juice, lucky_strikes), Houses) &
member(house(_, japanese, _, _, parliaments), Houses) &
next_to(house(_,norwegian,_,_,_), house(blue,_,_,_,_), Houses) &
member(house(_, _, zebra, _, _), Houses) &
member(house(_, _, _, water, _), Houses),
houses([
house(_, _, _, _, _),
house(_, _, _, _, _),
house(_, _, _, _, _),
house(_, _, _, _, _),
house(_, _, _, _, _)
]) <<= true,
right_of(A, B, [B, A | _]) <<= true,
right_of(A, B, [_ | Y]) <<= right_of(A, B, Y),
next_to(A, B, [A, B | _]) <<= true,
next_to(A, B, [B, A | _]) <<= true,
next_to(A, B, [_ | Y]) <<= next_to(A, B, Y),
member(X, [X|_]) <<= true,
member(X, [_|Y]) <<= member(X, Y)
]
println("Zebra puzzle (single run):")
goal = @julog query(Houses)
@time resolve(goal, clauses)
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 635 | module Julog
include("structs.jl")
include("parse.jl")
include("utils.jl")
include("clausetable.jl")
include("main.jl")
export Const, Var, Compound, Term, Clause, Subst, ClauseTable
export get_args, is_ground, substitute, has_subterm, find_subterms
export to_nnf, to_cnf, to_dnf, flatten_conjs, flatten_disjs, deuniversalize
export eval_term, unify, resolve, derivations, derive, fwd_chain, bwd_chain
export regularize_clauses, index_clauses, deindex_clauses, retrieve_clauses
export insert_clauses!, insert_clauses, subtract_clauses!, subtract_clauses
export parse_prolog, write_prolog
export @julog, @prolog, @varsub
end # module
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 4279 |
"Nested dictionary to store indexed clauses."
const ClauseSubtable{T} = Dict{Symbol,Vector{T}} where T <: AbstractClause
const ClauseTable{T} = Dict{Symbol,ClauseSubtable{T}}
function insert_clause!(table::ClauseTable{T}, c::Clause) where {T <: AbstractClause}
subtable = get!(table, c.head.name, Dict{Symbol,Vector{T}}())
if isa(c.head, Compound) && length(c.head.args) >= 1
arg = c.head.args[1]
if isa(arg, Var)
push!(get!(subtable, :__var__, Vector{T}()), c)
else
push!(get!(subtable, Symbol(arg.name), Vector{T}()), c)
end
push!(get!(subtable, :__all__, Vector{T}()), c)
else
push!(get!(subtable, :__no_args__, Vector{T}()), c)
end
end
"Insert clauses into indexed table for efficient look-up."
function insert_clauses!(table::ClauseTable{T}, clauses::Vector{T}) where {T <: AbstractClause}
# Ensure no duplicates are added
clauses = unique(clauses)
if (length(table) > 0) setdiff!(clauses, deindex_clauses(table)) end
# Iterate over clauses and insert into table
for c in clauses
insert_clause!(table, c)
end
return table
end
"Insert clauses into indexed table and return a new table."
function insert_clauses(table::ClauseTable{T}, clauses::Vector{T}) where {T <: AbstractClause}
return insert_clauses!(deepcopy(table), clauses)
end
"Index clauses by functor name and first argument for efficient look-up."
function index_clauses(clauses::Vector{T}) where {T <: AbstractClause}
return insert_clauses!(ClauseTable{T}(), clauses)
end
"Convert indexed clause table to flat list of clauses."
function deindex_clauses(table::ClauseTable{T}) where {T <: AbstractClause}
clauses = Vector{T}()
for (functor, subtable) in table
if :__no_args__ in keys(subtable)
append!(clauses, subtable[:__no_args__])
else
append!(clauses, subtable[:__all__])
end
end
return clauses
end
"Retrieve matching clauses from indexed clause table."
function retrieve_clauses(table::ClauseTable{T}, term::Term, funcs::Dict=Dict()) where {T <: AbstractClause}
clauses = Vector{T}()
funcs = length(funcs) > 0 ? merge(default_funcs, funcs) : default_funcs
subtable = get(table, term.name, nothing)
if subtable === nothing
return clauses
end
if isa(term, Compound) && length(term.args) >= 1
arg = term.args[1]
if isa(arg, Var) || arg.name in keys(funcs)
clauses = get(subtable, :__all__, clauses)
else
clauses = [get(subtable, Symbol(arg.name), clauses);
get(subtable, :__var__, clauses)]
end
else
clauses = get(subtable, :__no_args__, clauses)
end
return clauses
end
"Subtract one clause table from another (in-place)."
function subtract_clauses!(table1::ClauseTable{T}, table2::ClauseTable{T}) where {T <: AbstractClause}
for (functor, subtable2) in table2
if !(functor in keys(table1)) continue end
subtable1 = table1[functor]
for arg in keys(subtable2)
if !(arg in keys(subtable1)) continue end
setdiff!(subtable1[arg], subtable2[arg])
end
end
return table1
end
"Subtract one clause table from another (returns new copy)."
function subtract_clauses(table1::ClauseTable{T}, table2::ClauseTable{T}) where {T <: AbstractClause}
return subtract_clauses!(deepcopy(table1), table2)
end
"Subtract clauses from a indexed clause table (in-place)."
function subtract_clauses!(table::ClauseTable{T}, clauses::Vector{T}) where {T <: AbstractClause}
return subtract_clauses!(table, index_clauses(clauses))
end
"Subtract clauses from a indexed clause table (returns new copy)."
function subtract_clauses(table::ClauseTable{T}, clauses::Vector{T}) where {T <: AbstractClause}
return subtract_clauses(table, index_clauses(clauses))
end
"Return number of clauses in indexed clause table."
function num_clauses(table::ClauseTable{T}) where {T <: AbstractClause}
n = 0
for (functor, subtable) in table
if :__no_args__ in keys(subtable)
n += length(subtable[:__no_args__])
else
n += length(subtable[:__all__])
end
end
return n
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 20757 | "Recursive structure for representing goals."
mutable struct GoalTree
term::Term # Term to be proven
parent::Union{GoalTree,Nothing} # Parent goal
children::Vector{Term} # List of subgoals
active::Int # Index of active subgoal
env::Subst # Dictionary of variable mappings for the current goal
vmap::Subst # Variables inherited from parent
end
GoalTree(g::GoalTree) =
GoalTree(g.term, g.parent, copy(g.children), g.active, copy(g.env), g.vmap)
"Built-in arithmetic operations."
const math_ops = Set([:+, :-, :*, :/, :mod])
"Built-in comparison operations."
const comp_ops = Set([:(==), :<=, :>=, :<, :>, :(!=)])
"Built-in operators."
const ops = union(math_ops, comp_ops)
"Built-in functions."
const default_funcs = Dict(op => eval(op) for op in ops)
"Built-in logical connectives."
const logicals = Set([true, false, :and, :or, :not, :!,
:exists, :forall, :imply, :(=>)])
"Built-in predicates with special handling during SLD resolution."
const builtins = union(
comp_ops, logicals,
[:is, :call, :unifies, :≐, :cut, :fail, :findall, :countall]
)
"""
eval_term(term, env[, funcs])
Given an environment, evaluate all variables in a Julog term to constants.
Returns a term that is as fully evaluated as possible.
# Arguments
- `term::Term`: A term to evaluate.
- `env::Dict{Var,Term}`: An environment mapping variables to terms.
- `funcs::Dict=Dict()`: Additional custom functions (e.g. custom math).
"""
eval_term(term::Term, env::Subst, funcs::Dict=Dict()) = error("Not implemented")
eval_term(term::Var, env::Subst, funcs::Dict=Dict()) =
term in keys(env) ? eval_term(env[term], env, funcs) : term
function eval_term(term::Const, env::Subst, funcs::Dict=Dict())
val = get(funcs, term.name, term)
if val === term
return val
elseif isa(val, Function)
return Const(val())
else
return Const(val)
end
end
function eval_term(term::Compound, env::Subst, funcs::Dict=Dict())
args = Term[eval_term(a, env, funcs) for a in term.args]
func = get(funcs, term.name) do
get(default_funcs, term.name, nothing)
end
if func !== nothing && all(isa(a, Const) for a in args)
if isa(func, Function)
# Evaluate function if all arguments are fully evulated
return Const(func((a.name for a in args)...))
elseif isa(func, Dict)
# Lookup value if custom function is a lookup table
key = Tuple(a.name for a in args)
if key in keys(func) return Const(func[key]) end
# Leave un-evaluated if lookup table has missing entries
return Compound(term.name, args)
else
error("$(term.name) is neither a custom function or lookup table.")
end
else
return Compound(term.name, args)
end
end
"""
unify(src, dst[, occurs_check, funcs])
Unifies src with dst and returns a dictionary of any substitutions needed.
# Arguments
- `src::Term`: A term to unify.
- `dst::Term`: A term to unify (src/dst order does not matter).
- `occurs_check::Bool=true`: Whether to perform the occurs check.
- `funcs::Dict=Dict()`: Custom functions to evaluate.
"""
function unify(src::Term, dst::Term,
occurs_check::Bool=true, funcs::Dict=Dict())
src_stack, dst_stack = Term[src], Term[dst]
src_defer, dst_defer = Term[], Term[]
subst = Subst()
success = true
while length(src_stack) > 0
src, dst = pop!(src_stack), pop!(dst_stack)
# Unify $src with $dst
if isa(src, Const) && isa(dst, Const)
success = _unify!(src::Const, dst, funcs)
if !success break end
elseif isa(src, Var)
success = _unify!(src::Var, dst, src_stack, dst_stack,
subst, occurs_check)
if !success break end
elseif isa(dst, Var)
success = _unify!(dst::Var, src, dst_stack, src_stack,
subst, occurs_check)
if !success break end
elseif isa(src, Compound) && isa(dst, Compound)
success = _unify!(src::Compound, dst, src_stack, dst_stack)
if !success break end
elseif isa(src, Const) && isempty(dst.args)
success = _unify!(src::Const, dst, funcs)
if !success break end
elseif isa(dst, Const) && isempty(src.args)
success = _unify!(dst::Const, src, funcs)
if !success break end
else # Reaches here if one term is compound and the other is constant
push!(src_defer, src)
push!(dst_defer, dst)
end
end
# Try evaluating deferred Const vs Compound comparisons
for (src, dst) in zip(src_defer, dst_defer)
src, dst = eval_term(src, subst, funcs), eval_term(dst, subst, funcs)
if src != dst # "No: cannot unify $src and $dst after evaluation"
success = false; break
end
end
return success ? subst : nothing
end
function _unify!(src::Const, dst::Term, funcs::Dict=Dict())
if src.name != dst.name
src_val = get(funcs, src.name, src.name)
dst_val = get(funcs, dst.name, dst.name)
return src_val == dst_val
end
return true
end
function _unify!(src::Var, dst::Term, src_stack, dst_stack,
subst, occurs_check::Bool=true)
if isa(dst, Var) && src.name == dst.name # "Yes: same variable"
return true
elseif occurs_check && occurs_in(src, dst) # "No: src occurs in dst"
return false
end
# Replace src with dst in stack
for i in 1:length(src_stack)
s, d = src_stack[i], dst_stack[i]
ss = substitute(s, src, dst)
if s !== ss src_stack[i] = ss end
dd = substitute(d, src, dst)
if d !== dd dst_stack[i] = dd end
end
# Replace src with dst in substitution values
map!(v -> substitute(v, src, dst), values(subst))
# Add substitution of src to dst
subst[src] = dst
return true
end
function _unify!(src::Compound, dst::Term, src_stack, dst_stack)
if src.name != dst.name # "No: diff functors"
return false
elseif length(src.args) != length(dst.args) # "No: diff arity"
return false
end
# "Yes: pushing args onto stack"
append!(src_stack, src.args)
append!(dst_stack, dst.args)
return true
end
"Handle built-in predicates"
function handle_builtins!(queue, clauses, goal, term; options...)
funcs = get(options, :funcs, Dict())
occurs_check = get(options, :occurs_check, false)
vcount = get(options, :vcount, Ref(UInt(0)))
if term.name == true
return true
elseif term.name == false
return false
elseif term.name == :call
# Handle meta-call predicate
pred, args = term.args[1], term.args[2:end]
if isa(pred, Var) pred = get(goal.env, pred, nothing) end
if isnothing(pred) error("$term not sufficiently instantiated.") end
term = Compound(pred.name, [pred.args; args]) # Rewrite term
goal.children[goal.active] = term # Replace term
goal.active -= 1
return true
elseif term.name == :is
# Handle is/2 predicate
qn, ans = term.args[1], eval_term(term.args[2], goal.env, funcs)
# Failure if RHS is insufficiently instantiated
if !isa(ans, Const) return false end
# LHS can either be a variable or evaluate to a constant
if isa(qn, Var) && !(qn in keys(goal.env))
# If LHS is a free variable, bind to RHS
for (k, v) in goal.env
goal.env[k] = substitute(v, qn, ans)
end
goal.env[qn] = ans
return true
else
# If LHS evaluates to a constant, check if it is equal to RHS
qn = eval_term(qn, goal.env, funcs)
return isa(qn, Const) ? qn == ans : false
end
return false
elseif term.name in [:unifies, :≐]
# Check if LHS and RHS unify
term = substitute(term, goal.env)
lhs, rhs = term.args[1], term.args[2]
unifier = unify(lhs, rhs, occurs_check, funcs)
if isnothing(unifier) return false end
compose!(goal.env, unifier) # Update variable bindings if satisfied
return true
elseif term.name == :and
# Remove self and add all arguments as children to the goal, succeed
splice!(goal.children, goal.active, term.args)
goal.active -= 1
return true
elseif term.name == :or
# Create new goals for each term in disjunct, add to queue
for arg in term.args
g = GoalTree(goal)
g.children[g.active] = arg # Replace disjunct with term
push!(queue, g)
end
# No longer work on this goal
return false
elseif term.name in [:not, :!]
# Try to resolve negated predicate, return true upon failure
neg_goal = term.args[1]
sat, _ = resolve(Term[neg_goal], clauses; options...,
vcount=vcount, env=copy(goal.env), mode=:any)
return !sat # Success if no proof is found
elseif term.name == :exists
# exists(Cond, Body) holds if Body holds for at least 1 binding of Cond
cond, body = term.args
sat, subst = resolve(Term[cond, body], clauses; options...,
vcount=vcount, env=copy(goal.env), mode=:any)
# Update variable bindings if satisfied
goal.env = sat ? compose!(goal.env, subst[1]) : goal.env
return sat
elseif term.name == :forall
# forall(Cond, Body) holds if Body holds for all bindings of Cond
cond, body = term.args
term = @julog(not(and(:cond, not(:body)))) # Rewrite term
goal.children[goal.active] = term # Replace term
goal.active -= 1
return true
elseif term.name in [:imply, :(=>)]
# imply(Cond, Body) holds if or(not(Cond), Body) holds
cond, body = term.args
sat, _ = resolve(Term[cond], clauses; options...,
vcount=vcount, env=copy(goal.env), mode=:any)
# Return true if Cond does not hold
if !sat return true end
# Otherwise replace original term with [Cond, Body], return true
splice!(goal.children, goal.active, [cond, body])
goal.active -= 1
return true
elseif term.name == :cut
# Remove all other goals and succeed
empty!(queue)
return true
elseif term.name == :fail
# Fail and skip goal
return false
elseif term.name == :findall
# Find list of all cond matches, substituted into template
template, cond, list = term.args
_, subst = resolve(Term[cond], clauses; options...,
vcount=vcount, env=copy(goal.env), mode=:all)
matches = to_term_list([substitute(template, s) for s in subst])
unifier = unify(list, matches, occurs_check, funcs)
if isnothing(unifier) return false end
compose!(goal.env, unifier) # Update variable bindings if satisfied
return true
elseif term.name == :countall
# Count number of ways to prove the condition
cond, count = term.args
_, subst = resolve(Term[cond], clauses; options...,
vcount=vcount, env=copy(goal.env), mode=:all)
unifier = unify(count, Const(length(subst)), occurs_check, funcs)
if isnothing(unifier) return false end
compose!(goal.env, unifier) # Update variable bindings if satisfied
return true
elseif term.name in comp_ops || term.name in keys(funcs)
defer_eval = get(options, :defer_eval, false)
result = eval_term(term, goal.env, funcs)
if isa(result, Const)
# Return true if term evaluates to true
return result.name == true
elseif defer_eval && goal.active < length(goal.children)
# Defer evaluation
goal.children[goal.active] = goal.children[goal.active + 1]
goal.children[goal.active + 1] = term
goal.active -= 1
return true
end
end
return false
end
"""
resolve(goals, clauses; <keyword arguments>)
bwd_chain(goals, clauses; <keyword arguments>)
SLD-resolution of goals with additional Prolog-like control flow.
# Arguments
- `goals::Vector{<:Term}`: A list of Julog terms to be prove or query.
- `clauses::Vector{Clause}`: A list of Julog clauses.
- `env::Subst=Subst()`: An initial environment mapping variables to terms.
- `funcs::Dict=Dict()`: Custom functions for evaluating terms.
A function `f` should be stored as `funcs[:f] = f`
- `mode::Symbol=:all`: How results should be returned.
`:all` returns all possible substitutions. `:any` returns the first
satisfying substitution found. `:interactive` prompts for continuation
after each satisfying substitution is found.
- `search::Symbol=:bfs`: search either breadth (`:bfs`) or depth-first (`:dfs`)
- `occurs_check::Bool=false`: Flag for occurs check during unification
- `defer_eval::Bool=false`: Flag to defer evaluation of (custom) operators.
"""
function resolve(goals::Vector{<:Term}, clauses::Vector{<:AbstractClause}; options...)
return resolve(goals, index_clauses(clauses); options...)
end
function resolve(goals::Vector{<:Term}, clauses::ClauseTable; options...)
# Unpack options
env = get(options, :env, Subst())::Subst
funcs = get(options, :funcs, Dict())::Dict
mode = get(options, :mode, :all)::Symbol
search = get(options, :search, :bfs)::Symbol
occurs_check = get(options, :occurs_check, false)::Bool
vcount = get(options, :vcount, Ref(UInt(0)))::Ref{UInt}
# Construct top level goal and put it on the queue
queue = [GoalTree(Const(false), nothing, Vector{Term}(goals), 1, env, Subst())]
subst = Subst[]
# Iterate across queue of goals
while length(queue) > 0
goal = (search == :dfs) ? pop!(queue) : popfirst!(queue)
@debug string("Goal: ", Clause(goal.term, goal.children), " ",
"Env: ", goal.env)
if goal.active > length(goal.children)
# All subgoals are done
if isnothing(goal.parent)
# If goal has no parent, we are successful
@debug string("Success: ", goal.env)
if !(goal.env in subst)
push!(subst, goal.env)
end
if (mode == :all) continue
elseif (mode == :any || length(queue) == 0) break
elseif mode == :interactive
# Interactively prompt for continuation
println(goal.env)
print("Continue? [y/n]: ")
s = readline()
if s in ["y", "Y", ""] continue
else break
end
end
end
@debug string("Done, returning to parent.")
# Copy construct parent to create fresh copy of environment
parent = GoalTree(goal.parent)
# Remap variables from child to parent
vmap = Subst()
for (pvar, cvar) in goal.vmap
if !(cvar in keys(goal.env)) continue end
if pvar == goal.env[cvar] continue end
vmap[pvar] = goal.env[cvar]
end
parent.env = compose!(parent.env, vmap)
# Advance parent to next subgoal and put it back on the queue
parent.active += 1
push!(queue, parent)
continue
end
# Examine current subgoal
term = goal.children[goal.active]
@debug string("Subgoal: ", term)
# Handle built-in special terms
if term.name in builtins || term.name in keys(funcs)
success = handle_builtins!(queue, clauses, goal, term;
vcount=vcount, options...)
# If successful, go to next subgoal, otherwise skip to next goal
if success
@debug string("Done, returning to parent.")
goal.active += 1
push!(queue, goal)
end
continue
end
# Substitute and freshen variables in term
vmap = Subst()
term = freshen!(substitute(term, goal.env), vmap, vcount)
# Iterate across clause set with matching heads
matched_clauses = retrieve_clauses(clauses, term, funcs)
matched = false
for c in matched_clauses
# Freshen variables in clause
c = freshen!(c, Subst(), vcount)
# If term unifies with head of a clause, add it as a subgoal
unifier = unify(term, c.head, occurs_check, funcs)
if isnothing(unifier) continue end
child = GoalTree(c.head, goal, copy(c.body), 1, unifier, vmap)
push!(queue, child)
matched = true
end
if !matched @debug string("Failed, no matching clauses.") end
end
# Goals were satisfied if we found valid substitutions
return (length(subst) > 0), subst
end
resolve(goal::Term, clauses::Vector{<:AbstractClause}; options...) =
resolve(Term[goal], clauses; options...)
resolve(goals::Vector{Clause}, clauses::Vector{<:AbstractClause}; options...) =
resolve([convert(Term, g) for g in goals], clauses; options...)
const bwd_chain = resolve
"Return all facts derivable in `n` steps from the initial set of clauses."
function derivations(clauses::Vector{<:AbstractClause}, n::Real=1; options...)
rules = filter(c -> length(c.body) > 0, clauses)
facts = filter(c -> length(c.body) == 0, clauses)
return derivations(rules, facts, n; options...)
end
function derivations(rules::Vector{T}, facts::Vector{T}, n::Real=1;
options...) where {T <: AbstractClause}
return derivations(rules, index_clauses(facts), n; options...)
end
function derivations(rules::Vector{T}, facts::ClauseTable{T}, n::Real=1;
as_indexed::Bool=false, options...) where {T <: AbstractClause}
step = 0
n_facts = num_clauses(facts)
while step < n
# Iteratively add facts derivable from each rule
derived = derive_step(rules, facts; options...)
insert_clauses!(facts, derived)
# Terminate early if we reach a fixed point
n_facts_new = num_clauses(facts)
if (n_facts < n_facts_new) n_facts = n_facts_new else break end
step += 1
end
return as_indexed ? facts : deindex_clauses(facts)
end
"Iteratively add facts derivable from each rule."
function derive_step(rules::Vector{T}, facts::ClauseTable{T};
options...) where {T <: AbstractClause}
# Iteratively add facts derivable from each rule
derived = Term[]
for r in rules
# Find all valid substitutions of each rule's body
_, subst = resolve(r.body, facts; options...)
append!(derived, Term[substitute(r.head, s) for s in subst])
end
return [Clause(d, []) for d in derived]
end
"""
derive(goals, clauses; <keyword arguments>)
fwd_chain(goals, clauses; <keyword arguments>)
Derive goals via forward-chaining from the initial set of clauses.
# Arguments
- `goals::Vector{<:Term}`: A list of Julog terms to be prove or query.
- `clauses::Vector{Clause}`: A list of Julog clauses.
- `max-steps::Real=100`: Maximum steps before terminating with failure.
See `resolve` for other supported arguments.
"""
function derive(goals::Vector{<:Term}, clauses::Vector{T};
max_steps::Real=100, options...) where {T <: AbstractClause}
grounded = all(is_ground.(goals))
rules = filter(c -> length(c.body) > 0, clauses)
facts = index_clauses(filter(c -> length(c.body) == 0, clauses))
n_facts = num_clauses(facts)
step = 0
while step < max_steps
# Return all goals are grounded and satisfied
if grounded
sat, subst = resolve(goals, facts; options...)
if sat return sat, subst end
end
# Iteratively add facts derivable from each rule
derived = derive_step(rules, facts; options...)
insert_clauses!(facts, derived)
# Terminate early if we reach a fixed point
n_facts_new = num_clauses(facts)
if (n_facts < n_facts_new) n_facts = n_facts_new else break end
step += 1
end
return resolve(goals, facts; options...)
end
derive(goal::Term, clauses::Vector{<:AbstractClause}; options...) =
derive(Term[goal], clauses; options...)
derive(goals::Vector{Clause}, clauses::Vector{<:AbstractClause}; options...) =
derive([convert(Term, g) for g in goals], clauses; options...)
const fwd_chain = derive
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 8082 | "Parse Julog terms using Prolog-like syntax."
function parse_term(expr, esc=esc)
if isa(expr, Union{String,Number,Enum,Bool})
# Strings, numbers, enums and bools are automatically constants
return :(Const($expr))
elseif isa(expr, Symbol)
if expr == :_
# Underscores are wildcards, parsed to variables with new names
return Expr(:call, Var, Meta.quot(gensym(expr)))
elseif isuppercase(string(expr)[1]) || string(expr)[1] == "_"
# Initial uppercase / underscored symbols are parsed to variables
return Expr(:call, Var, Meta.quot(expr))
else
# Everything else is parsed to a constant
return Expr(:call, Const, Meta.quot(expr))
end
elseif isa(expr, Expr) && expr.head == :tuple
# Fully evaluated tuples are valid constants
return :(Const($(esc(expr))))
elseif isa(expr, Expr) && expr.head == :vect
# Parse vector as Prolog style list
return parse_list(expr.args, esc)
elseif isa(expr, Expr) && expr.head == :$
# Evaluate interpolated expression as Const within scope of caller
val = expr.args[1]
return :(Const($(esc(val))))
elseif isa(expr, Expr) && expr.head == :call
# A compound term comprises its name (functor) and arguments
name = esc(Meta.quot(expr.args[1]))
args = [parse_term(e, esc) for e in expr.args[2:end]]
return :(Compound($name, [$(args...)]))
elseif isa(expr, QuoteNode)
# Evaluate quoted expression within scope of caller
val = expr.value
return esc(val)
else
dump(expr)
error("syntax error in Julog term at $expr")
end
end
"Parse arguments of vector using Prolog-style list syntax."
function parse_list(args, esc=esc)
if (length(args) > 0 && isa(args[end], Expr) &&
args[end].head == :call && args[end].args[1] == :|)
# Handle [... | Tail] syntax for last element
tail = parse_term(args[end].args[3], esc)
pretail = parse_term(args[end].args[2], esc)
tail = :(Compound(:cons, [$pretail, $tail]))
args = args[1:end-1]
else
# Initialize tail to empty list
tail = :(Compound(:cend, []))
end
# Recursively build list using :cons
for a in Iterators.reverse(args)
e = parse_term(a, esc)
tail = :(Compound(:cons, [$e, $tail]))
end
return tail
end
"Parse body of Julog clause using Prolog-like syntax, with '&' replacing ','."
function parse_body(expr, esc=esc)
if expr == true
return []
elseif isa(expr, Symbol) || isa(expr, QuoteNode) ||
isa(expr, Expr) && expr.head in [:tuple, :vect, :$]
return [parse_term(expr, esc)]
elseif isa(expr, Expr) && expr.head == :call
if expr.args[1] == :&
# '&' is left-associative, so we descend the parse tree accordingly
return [parse_body(expr.args[2], esc);
parse_term(expr.args[3], esc)]
else
return [parse_term(expr, esc)]
end
else
dump(expr)
error("syntax error in body of Julog clause at $expr")
end
end
"""
Parse Julog expression using Prolog-like syntax. Set `esc` to `identity` to
avoid unnecessary escaping.
"""
function parse_julog(expr, esc=esc)
if !isa(expr, Expr)
return parse_term(expr, esc)
elseif expr.head == :<<=
head = parse_term(expr.args[1], esc)
body = parse_body(expr.args[2], esc)
return :(Clause($head, [$(body...)]))
elseif expr.head == Symbol("'")
head = parse_term(expr.args[1], esc)
return :(Clause($head, []))
elseif expr.head == :vect
exprs = [parse_julog(a, esc) for a in expr.args]
return :([$(exprs...)])
elseif expr.head == :ref && expr.args[1] == :Clause
exprs = [parse_julog(a, esc) for a in expr.args[2:end]]
return :(Clause[$(exprs...)])
elseif expr.head == :ref && expr.args[1] in [:Term, :Const, :Var, :Compound]
ty = expr.args[1]
exprs = [parse_term(a, esc) for a in expr.args[2:end]]
return :($ty[$(exprs...)])
elseif expr.head == :ref && expr.args[1] == :list
return parse_list(expr.args[2:end], esc)
else
return parse_term(expr, esc)
end
end
"""
@julog expr
Parse and return Julog expressions.
- `@julog <term>` parses a Prolog-style term.
- `@julog <term> <<= true` or `@julog <term>'` parses a fact (body-less clause).
- `@julog <head> <<= <body>` parses a definite clause.
- `@julog [<term|clause>, ...]` parses a vector of terms or clauses
- `@julog <T>[<term>, ...]` parses to a vector of type `T` (e.g. `Const`)
- `@julog list[<term>, ...]` parses a Prolog-style list directly to a term.
Additionally, the `\$` operator can be used to interpolate regular Julia
expressions as Julog constants, while the `:` operator can be used to
interpolate variables referring to pre-constructed Julog terms into
another Julog term or clause.
"""
macro julog(expr)
return parse_julog(expr)
end
"Parse Julog substitutions, e.g. {X => hello, Y => world}."
macro varsub(expr)
if !(isa(expr, Expr) && expr.head == :braces && all(isa.(expr.args, Expr))
&& all(a.head == :call && a.args[1] == :(=>) for a in expr.args))
error("Invalid format for Julog substitutions: $e.")
end
vars = [Expr(:call, Var, Meta.quot(a.args[2])) for a in expr.args]
terms = [parse_term(a.args[3]) for a in expr.args]
entries = [:($v => $t) for (v, t) in zip(vars, terms)]
return Expr(:call, Subst, entries...)
end
"Convert Prolog string to list of Julog strings."
function convert_prolog_to_julog(str::String)
clauses = String[]
# Match each clause (being careful to handle periods in lists + floats)
for m in eachmatch(r"((?:\d\.\d+|[^\.]|\.\()*)\.\s*", str)
clause = m.captures[1]
# Replace cuts, negations and implications
clause = replace(clause, "!" => "cut")
clause = replace(clause, "\\+" => "!")
clause = replace(clause, "->" => "=>")
clause = replace(clause, ".(" => "cons(")
# Try to match to definite clause
m = match(r"(.*):-(.*)", clause)
if isnothing(m)
# Push fact on to list of clauses
clause = clause * " <<= true"
push!(clauses, clause)
continue
end
# Handle definite clauses
head, body = m.captures[1:2]
# Handle disjunctions within the body
for bd in split(body, ";")
# Handle conjuctions within body (find commas outside of brackets)
br_count = 0
commas = [0]
for (idx, chr) in enumerate(bd)
if (chr == '(') br_count += 1
elseif (chr == ')') br_count -= 1
elseif (chr == ',') && br_count == 0 push!(commas, idx) end
end
push!(commas, length(bd)+1)
terms = [strip(bd[a+1:b-1]) for (a, b) in
zip(commas[1:end-1], commas[2:end])]
subclause = strip(head) * " <<= " * join(terms, " & ")
push!(clauses, subclause)
end
end
return clauses
end
"Parse Julog expression from string using standard Prolog syntax."
function parse_prolog(str::String)
strs = convert_prolog_to_julog(str)
exprs = [@julog($(Meta.parse(s))) for s in strs]
return exprs
end
"Write list of Julog clauses to Prolog string."
function write_prolog(clauses::Vector{Clause})
str = ""
for clause in clauses
clause = repr(clause)
clause = replace(clause, "!" => "\\+")
clause = replace(clause, "=>" => "->")
clause = replace(clause, " &" => ",")
clause = replace(clause, "<<=" => ":-")
str = str * clause * ".\n"
end
return str
end
"Parse Prolog program as a string and return a list of Julog clauses."
macro prolog(str::String)
strs = convert_prolog_to_julog(str)
exprs = [parse_julog(Meta.parse(s)) for s in strs]
return :([$(exprs...)])
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 3762 | """
Term
Represents a term or expression in first-order logic, including variables,
constants, or compound terms.
"""
abstract type Term end
"""
Const
Represents a named constant term with no arguments.
"""
struct Const <: Term
name::Any
end
"""
Var
Represents a variable in a first-order expression.
"""
struct Var <: Term
name::Union{Symbol,UInt}
end
"""
Compound
A `Compound` represents a term with zero or more arguments. When a `Compound`
has zero arguments, it is functionally equivalent to a `Const.`
"""
struct Compound <: Term
name::Symbol
args::Vector{Term}
end
"""
AbstractClause
Abstract type for clauses in a logic program.
"""
abstract type AbstractClause end
"""
Clause
A definite Horn clause of the form `[head] <<= [body]`.
"""
struct Clause <: AbstractClause
head::Term
body::Vector{Term}
end
"""
Subst
Substitution mapping from variables to terms. Alias for `Dict{Var,Term}`.
"""
const Subst = Dict{Var,Term}
Base.:(==)(t1::Term, t2::Term) = false
Base.:(==)(t1::Const, t2::Const) = t1.name == t2.name
Base.:(==)(t1::Var, t2::Var) = t1.name == t2.name
Base.:(==)(t1::Const, t2::Compound) = t1.name == t2.name && isempty(t2.args)
Base.:(==)(t1::Compound, t2::Const) = t1.name == t2.name && isempty(t1.args)
Base.:(==)(t1::Compound, t2::Compound) =
(t1.name == t2.name && length(t1.args) == length(t2.args) &&
all(a1 == a2 for (a1, a2) in zip(t1.args, t2.args)))
Base.hash(t::Term, h::UInt) = error("Not implemented.")
Base.hash(t::Const, h::UInt) = hash(t.name, h)
Base.hash(t::Var, h::UInt) = hash(t.name, h)
Base.hash(t::Compound, h::UInt) = isempty(t.args) ?
hash(t.name, h) : hash(t.name, hash(Tuple(t.args), h))
Base.:(==)(c1::Clause, c2::Clause) =
(c1.head == c2.head && length(c1.body) == length(c2.body) &&
all(t1 == t2 for (t1, t2) in zip(c1.body, c2.body)))
Base.hash(c::Clause, h::UInt) = hash(c.head, hash(Tuple(c.body), h))
Base.convert(::Type{Clause}, term::Term) = Clause(term, [])
function Base.convert(::Type{Term}, clause::Clause)
if length(clause.body) == 0 return clause.head end
return Compound(:(=>), Term[Compound(:and, copy(clause.body)), clause.head])
end
function Base.show(io::IO, t::Term)
print(io, t.name)
end
function Base.show(io::IO, t::Var)
(t.name isa UInt) ? print(io, "#", t.name) : print(io, t.name)
end
function Base.show(io::IO, t::Compound)
if t.name == :cons && length(t.args) == 2
# Handle lists separately
head, tail = t.args[1], t.args[2]
if isa(tail, Var)
print(io, "[", repr(head), " | ", repr(tail), "]")
elseif isa(tail, Compound) && tail.name == :cend
print(io, "[", repr(head), "]")
else
print(io, "[", repr(head), ", ", repr(tail)[2:end-1], "]")
end
elseif isempty(t.args)
# Print zero-arity compounds as constants
t.name == :cend ? print(io, "[]") : print(io, t.name)
else
# Print compound term as "name(args...)"
print(io, t.name, "(", join([repr(a) for a in t.args], ", ")..., ")")
end
end
function Base.show(io::IO, c::Clause)
if length(c.body) == 0
print(io, c.head)
else
print(io, c.head, " <<= ", join([repr(t) for t in c.body], " & ")...)
end
end
function Base.show(io::IO, subst::Subst)
print(io, "{", join(["$k => $v" for (k, v) in subst], ", ")..., "}")
end
"Get arguments of a term."
get_args(term::Term) = Term[]
get_args(term::Compound) = term.args
Base.getproperty(t::Const, f::Symbol) = f == :args ? Term[] : getfield(t, f)
Base.getproperty(t::Var, f::Symbol) = f == :args ? Term[] : getfield(t, f)
Base.propertynames(t::Const) = (:name, :args)
Base.propertynames(t::Var) = (:name, :args)
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 10825 | @static if VERSION < v"1.1"
isnothing(::Any) = false
isnothing(::Nothing) = true
end
@static if VERSION < v"1.2"
function map!(f, iter::Base.ValueIterator)
dict = iter.dict
for (key, val) in pairs(dict)
dict[key] = f(val)
end
return iter
end
end
"Return all vars in a term."
get_vars(t::Term) = error("Not implemented.")
get_vars(t::Const) = Set{Var}()
get_vars(t::Var) = Set{Var}([t])
get_vars(t::Compound) =
length(t.args) > 0 ? union((get_vars(a) for a in t.args)...) : Set{Var}()
"Check if a term is ground (contains no variables)."
is_ground(t::Term) = error("Not implemented.")
is_ground(t::Const) = true
is_ground(t::Var) = false
is_ground(t::Compound) = all(is_ground(a) for a in t.args)
"Check whether a variable appears in a term."
occurs_in(v::Var, t::Term) = error("Not implemented.")
occurs_in(v::Var, t::Const) = false
occurs_in(v::Var, t::Var) = (v.name == t.name)
occurs_in(v::Var, t::Compound) = any(occurs_in(v, a) for a in t.args)
"Performs variable substitution of var by val in a term."
substitute(term::Term, var::Var, val::Term) = error("Not implemented.")
substitute(term::Const, var::Var, val::Term) = term
substitute(term::Var, var::Var, val::Term) = term.name == var.name ? val : term
function substitute(term::Compound, var::Var, val::Term)
args, ident = nothing, true
for (i, a) in enumerate(term.args)
b = substitute(a, var, val)
if ident && a !== b
args, ident = collect(term.args[1:i-1]), false
end
if !ident push!(args, b) end
end
return ident ? term : Compound(term.name, args)
end
"Apply substitution to a term."
substitute(term::Term, subst::Subst) = error("Not implemented.")
substitute(term::Const, subst::Subst) = term
substitute(term::Var, subst::Subst) = get(subst, term, term)
function substitute(term::Compound, subst::Subst)
args, ident = nothing, true
for (i, a) in enumerate(term.args)
b = substitute(a, subst)
if ident && a !== b
args, ident = collect(term.args[1:i-1]), false
end
if !ident push!(args, b) end
end
return ident ? term : Compound(term.name, args)
end
"Compose two substitutions (s2 after s1)."
function compose(s1::Subst, s2::Subst)
subst = Subst(var => substitute(val, s2) for (var, val) in s1)
return merge(s2, subst)
end
"Compose two substitutions (s2 after s1), modifying s1 in place."
function compose!(s1::Subst, s2::Subst)
map!(v -> substitute(v, s2), values(s1))
for (var, val) in s2 get!(s1, var, val) end
return s1
end
"Replace variables in a term or clause with fresh names."
function freshen(term::Term, vars::Set{Var})
vmap = Subst(v => Var(gensym(v.name)) for v in vars)
term = substitute(term, vmap)
return term, vmap
end
function freshen(clause::Clause, vars::Set{Var})
vmap = Subst(v => Var(gensym(v.name)) for v in vars)
clause = Clause(substitute(clause.head, vmap),
Term[substitute(t, vmap) for t in clause.body])
return clause, vmap
end
freshen(t::Term) = freshen!(t, Subst())
freshen(c::Clause) = freshen!(c, Subst())
freshen!(t::Const, vmap::Subst) = t
freshen!(t::Var, vmap::Subst) = get!(vmap, t, Var(gensym(t.name)))
freshen!(t::Compound, vmap::Subst) =
Compound(t.name, Term[freshen!(a, vmap) for a in t.args])
freshen!(c::Clause, vmap::Subst) =
Clause(freshen!(c.head, vmap), Term[freshen!(t, vmap) for t in c.body])
freshen!(t::Const, vmap::Subst, vcount::Ref{UInt}) = t
freshen!(t::Var, vmap::Subst, vcount::Ref{UInt}) =
get!(vmap, t, Var(vcount[] += 1))
freshen!(t::Compound, vmap::Subst, vcount::Ref{UInt}) =
Compound(t.name, Term[freshen!(a, vmap, vcount) for a in t.args])
freshen!(c::Clause, vmap::Subst, vcount::Ref{UInt}) =
Clause(freshen!(c.head, vmap, vcount),
Term[freshen!(t, vmap, vcount) for t in c.body])
"Check whether a term has a matching subterm."
function has_subterm(term::Term, subterm::Term)
if !isnothing(unify(term, subterm)) return true end
return any(has_subterm(arg, subterm) for arg in get_args(term))
end
"Find all matching subterms in a term."
function find_subterms(term::Term, subterm::Term)
init = !isnothing(unify(term, subterm)) ? Term[term] : Term[]
subterms = (find_subterms(a, subterm) for a in get_args(term))
return reduce(vcat, subterms; init=init)
end
"Convert a vector of Julia objects to a Julog list of constants."
to_const_list(v::Vector) =
foldr((i, j) -> Compound(:cons, [Const(i), j]), v; init=Compound(:cend, []))
"Convert a vector of Julog terms to a Julog list."
to_term_list(v::Vector{<:Term}) =
foldr((i, j) -> Compound(:cons, [i, j]), v; init=Compound(:cend, []))
"Convert a list of Julog terms to a vector of Julog terms.."
to_julia_list(list::Term) =
list.name == :cons ? [list.args[1]; to_julia_list(list.args[2])] : []
"Simplify by rewriting implications, flattening conjuctions and disjunctions."
function simplify(term::Compound)
if !(term.name in logicals) return term end
args = simplify.(term.args)
if term.name in (:imply, :(=>))
cond, body = args
return simplify(@julog or(not(:cond), and(:cond, :body)))
elseif term.name == :and
if length(args) == 1 return args[1]
elseif any(a -> a.name == false, args) return Const(false)
elseif all(a -> a.name == true, args) return Const(true)
else
args = flatten_conjs(filter!(a -> a.name != true, args))
term = Compound(term.name, unique!(args))
end
elseif term.name == :or
if length(args) == 1 return args[1]
elseif any(a -> a.name == true, args) return Const(true)
elseif all(a -> a.name == false, args) return Const(false)
else
args = flatten_disjs(filter!(a -> a.name != false, args))
term = Compound(term.name, unique!(args))
end
elseif term.name in (:not, :!)
if args[1].name == true return Const(false)
elseif args[1].name == false return Const(true)
else return Compound(:not, args) end
end
return length(term.args) == 1 ? term.args[1] : term
end
simplify(term::Const) = term
simplify(term::Var) = term
"Convert a term to negation normal form."
function to_nnf(term::Compound)
term = simplify(term)
if term.name in (:not, :!)
inner = term.args[1]
if inner.name in (:not, :!)
term = inner.args[1]
elseif inner.name in (true, false)
term = Const(!inner.name)
elseif inner.name in (:and, :or)
args = to_nnf.(@julog(not(:a)) for a in inner.args)
term = Compound(inner.name == :and ? :or : :and, args)
elseif inner.name in (:forall, :exists)
query, body = inner.args
query = to_nnf(query)
body = to_nnf(@julog(not(:body)))
name = inner.name == :forall ? :exists : :forall
term = Compound(name, Term[query, body])
end
elseif term.name in (true, false)
return term
elseif term.name in logicals
term = Compound(term.name, to_nnf.(term.args))
end
return term
end
to_nnf(term::Const) = term
to_nnf(term::Var) = term
"Convert a term to conjunctive normal form."
function to_cnf(term::Compound)
term = to_nnf(term)
if !(term.name in (:and, :or)) return @julog and(or(:term)) end
subterms = to_cnf.(term.args)
if term.name == :and
args = foldl(vcat, [a.args for a in subterms]; init=Compound[])
term = Compound(:and, args)
elseif term.name == :or
stack = Compound[@julog(or())]
for subterm in subterms
new_stack = Compound[]
for disj_i in stack
for disj_j in subterm.args
new_disj = Compound(:or, [disj_i.args; disj_j.args])
push!(new_stack, new_disj)
end
end
stack = new_stack
end
term = Compound(:and, stack)
end
return term
end
to_cnf(term::Const) = @julog and(or(:term))
to_cnf(term::Var) = @julog and(or(:term))
"Convert a term to disjunctive normal form."
function to_dnf(term::Compound)
term = to_nnf(term)
if !(term.name in (:and, :or)) return @julog or(and(:term)) end
subterms = to_dnf.(term.args)
if term.name == :or
args = foldl(vcat, (a.args for a in subterms); init=Compound[])
term = Compound(:or, args)
elseif term.name == :and
stack = Compound[@julog(and())]
for subterm in subterms
new_stack = Compound[]
for conj_i in stack
for conj_j in subterm.args
new_conj = Compound(:and, [conj_i.args; conj_j.args])
push!(new_stack, new_conj)
end
end
stack = new_stack
end
term = Compound(:or, stack)
end
return term
end
to_dnf(term::Const) = @julog or(and(:term))
to_dnf(term::Var) = @julog or(and(:term))
"Recursively flatten conjunctions in a term to a list."
flatten_conjs(t::Term) = t.name == :and ? flatten_conjs(get_args(t)) : Term[t]
flatten_conjs(t::Vector{<:Term}) = reduce(vcat, flatten_conjs.(t); init=Term[])
"Recursively flatten disjunctions in term to a list."
flatten_disjs(t::Term) = t.name == :or ? flatten_disjs(get_args(t)) : Term[t]
flatten_disjs(t::Vector{<:Term}) = reduce(vcat, flatten_disjs.(t); init=Term[])
"Instantiate universal quantifiers relative to a set of clauses."
function deuniversalize(term::Compound, clauses::Vector{Clause})
if term.name == :forall
cond, body = term.args
sat, subst = resolve(cond, clauses)
if !sat return Const(true) end
instantiated = unique!(Term[substitute(body, s) for s in subst])
return Compound(:and, instantiated)
elseif term.name in logicals
args = Term[deuniversalize(a, clauses) for a in term.args]
return Compound(term.name, args)
else
return term
end
end
deuniversalize(term::Const, ::Vector{Clause}) = term
deuniversalize(term::Var, ::Vector{Clause}) = term
deuniversalize(c::Clause, clauses::Vector{Clause}) =
Clause(c.head, [deuniversalize(t, clauses) for t in c.body])
"Convert any clauses with disjunctions in their bodies into a set of clauses."
function regularize_clauses(clauses::Vector{Clause}; instantiate::Bool=false)
regularized = Clause[]
for c in clauses
if length(c.body) == 0
push!(regularized, c)
else
body = Compound(:and, c.body)
if (instantiate == true) body = deuniversalize(body, clauses) end
for conj in to_dnf(body).args
push!(regularized, Clause(c.head, conj.args))
end
end
end
return regularized
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 5700 | @testset "Built-in predicates" begin
# Test handling of and/N and or/N
clauses = @julog [
shocked(P) <<= and(surprised(P), upset(P)),
upset(P) <<= or(unhappy(P), angry(P)),
]
# Avery is surprised. Are they shocked? (No.)
facts = @julog [surprised(avery) <<= true]
@test resolve(@julog(shocked(avery)), [facts; clauses])[1] == false
# Bailey is surprised and angry. Are they shocked? (Yes.)
facts = @julog [surprised(bailey) <<= true, angry(bailey) <<= true]
@test resolve(@julog(shocked(bailey)), [facts; clauses])[1] == true
# Casey is unhappy. Is anyone upset? (Yes, Casey.)
facts = @julog [unhappy(casey) <<= true]
@test @varsub({P => casey}) in resolve(@julog(upset(P)), [facts; clauses])[2]
# Test handling of unifies/2 and not/1
clauses = @julog [
child(zeus, kronos) <<= true,
child(hera, kronos) <<= true,
sibling(A, B) <<= child(A, C) & child(B, C) & not(unifies(A, B)),
]
# Is Hera her own sibling? (No)
@test resolve(@julog(sibling(hera, hera)), clauses)[1] == false
# Is Hera the sibling of Zeus? (Yes)
@test resolve(@julog(sibling(hera, zeus)), clauses)[1] == true
# Test the is/2 predicate (see also math_ops.jl for more tests)
clauses = @julog [
square(X, Y) <<= is(Y, X * X),
cube(X, Y) <<= is(Y, X * X * X)
]
# Is the cube of -1 the negation of its square? (Yes)
@test resolve(@julog([square(-1, S), cube(-1, C), S == -C]), clauses)[1] == true
# Is the cube of 2 twice its square? (Yes)
@test resolve(@julog([square(2, S), cube(2, C), C == 2*S]), clauses)[1] == true
# Test negation and double negation
clauses = @julog [red(roses) <<= true, blue(violets) <<= true]
@test resolve(@julog(not(red(roses))), clauses)[1] == false
@test resolve(@julog(not(blue(violets))), clauses)[1] == false
@test resolve(@julog(not(not(red(roses)))), clauses)[1] == true
@test resolve(@julog(not(not(blue(violets)))), clauses)[1] == true
# Test exists/2, forall/2, implies/2
clauses = @julog [
human(pythagoras) <<= true,
human(pyrrho) <<= true,
human(zeno) <<= true,
human(epicurus) <<= true,
human(aristotle) <<= true,
human(plato) <<= true,
god(hera) <<= true,
god(zeus) <<= true,
god(aphrodite) <<= true,
god(ares) <<= true,
person(X) <<= human(X),
person(X) <<= god(X),
mortal(X) <<= human(X),
immortal(X) <<= god(X)
]
# Is there a human who is mortal? (Yes.)
@test resolve(@julog(exists(human(X), mortal(X))), clauses)[1] == true
# Is there a god who is immortal? (Yes.)
@test resolve(@julog(exists(god(X), immortal(X))), clauses)[1] == true
# Is there a person who is mortal? (Yes.)
@test resolve(@julog(exists(person(X), mortal(X))), clauses)[1] == true
# Are all persons mortal? (No.)
@test resolve(@julog(forall(person(X), mortal(X))), clauses)[1] == false
# Are all humans mortal? (Yes.)
@test resolve(@julog(forall(human(X), mortal(X))), clauses)[1] == true
# Are all gods immortal? (Yes.)
@test resolve(@julog(forall(god(X), immortal(X))), clauses)[1] == true
# Is it true that if Hera is mortal, she's human? (Yes, since she's not mortal.)
@test resolve(@julog(imply(mortal(hera), human(hera))), clauses)[1] == true
# Is it true that if Hera is immortal, she's human? (No.)
@test resolve(@julog(imply(immortal(hera), human(hera))), clauses)[1] == false
# Is it true that for all people, being a god implies immortality? (Yes.)
@test resolve(@julog(forall(person(X), god(X) => immortal(X))), clauses)[1] == true
# Is it true that for all people, being a person implies immortality? (No.)
@test resolve(@julog(forall(person(X), person(X) => mortal(X))), clauses)[1] == false
# Of those who are persons, which are immortal?
sat, subst = resolve(@julog(person(X) => immortal(X)), clauses)
ans = Set([@varsub({X => hera}), @varsub({X => zeus}),
@varsub({X => aphrodite}), @varsub({X => ares})])
@test ans == Set(subst)
# Test findall/3 and countall/2
humans = @julog list[pythagoras, pyrrho, zeno, epicurus, aristotle, plato]
@test resolve(@julog(findall(X, human(X), :humans)), clauses)[1] == true
@test resolve(@julog(countall(human(X), 6)), clauses)[1] == true
gods = @julog list[hera, zeus, aphrodite, ares]
@test resolve(@julog(findall(X, god(X), :gods)), clauses)[1] == true
@test resolve(@julog(countall(god(X), 4)), clauses)[1] == true
persons = @julog list[pythagoras, pyrrho, zeno, epicurus, aristotle, plato,
hera, zeus, aphrodite, ares]
@test resolve(@julog(findall(X, person(X), :persons)), clauses)[1] == true
@test resolve(@julog(countall(person(X), 10)), clauses)[1] == true
# Test cut and fail by preventing infinite loops
clauses = @julog [
fakeloop1(A) <<= fakeloop1(B),
fakeloop1(A) <<= cut,
fakeloop2(A) <<= fail & fakeloop2(B),
]
@test resolve(@julog(fakeloop1(0)), clauses)[1] == true
@test resolve(@julog(fakeloop2(0)), clauses)[1] == false
# Test the meta-call predicate call/N
clauses = @julog [
test(x, y) <<= true,
pred(test) <<= true,
metatest1(A, B, C) <<= call(A, B, C),
metatest2(A, B, C) <<= pred(A) & call(A, B, C)
]
@test_throws Exception resolve(@julog(call(P, A, B)), clauses)
@test @varsub({A => x, B => y}) in resolve(@julog(call(test, A, B)), clauses)[2]
@test @varsub({A => x, B => y}) in resolve(@julog(call(test(A), B)), clauses)[2]
@test @varsub({B => y}) in resolve(@julog(call(test(x), B)), clauses)[2]
@test @varsub({A => x}) in resolve(@julog(call(test(A), y)), clauses)[2]
@test_throws Exception resolve(@julog(metatest1(P, x, y)), clauses)
@test @varsub({B => y}) in resolve(@julog(metatest1(test, x, B)), clauses)[2]
@test @varsub({P => test}) in resolve(@julog(metatest2(P, x, y)), clauses)[2]
@test @varsub({B => y}) in resolve(@julog(metatest2(test, x, B)), clauses)[2]
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 2592 | @testset "Logical form conversions" begin
@test to_nnf(@julog(a)) == @julog a
@test to_nnf(@julog(and())) == @julog true
@test to_nnf(@julog(or())) == @julog false
@test to_nnf(@julog(and(a))) == @julog a
@test to_nnf(@julog(true => not(and(not(!a), b, or(not(c), false))))) ==
@julog(or(not(a), not(b), c))
@test to_nnf(@julog(not(forall(human(X), mortal(X))))) ==
@julog(exists(human(X), not(mortal(X))))
@test to_nnf(@julog(not(exists(god(X), mortal(X))))) ==
@julog(forall(god(X), not(mortal(X))))
@test to_cnf(@julog(and(a))) == @julog and(or(a))
@test to_cnf(@julog(and(and(or(a, and(b, or(c, d))), or(e, f)), and(not(x), or(y, z))))) ==
@julog(and(or(a, b), or(a, c, d), or(e, f), or(not(x)), or(y, z)))
@test to_cnf(@julog(true => not(and(not(!a), b, or(not(c), false))))) ==
@julog(and(or(not(a), not(b), c)))
@test to_dnf(@julog(and(a))) == @julog or(and(a))
@test to_dnf(@julog(or(or(and(a, or(b, and(c, d))), and(e, f)), or(not(x), and(y, z))))) ==
@julog(or(and(a, b), and(a, c, d), and(e, f), and(not(x)), and(y, z)))
@test to_dnf(@julog(true => not(and(not(!a), b, or(not(c), false))))) ==
@julog(or(and(not(a)), and(not(b)), and(c)))
# Test flattening of conjuctions and disjunctions
@test flatten_conjs(@julog(and(a, and(b, c)))) == @julog Const[a, b, c]
@test flatten_conjs(@julog([a, and(b, c)])) == @julog Const[a, b, c]
@test flatten_disjs(@julog(or(a, or(b, c)))) == @julog Const[a, b, c]
@test flatten_disjs(@julog([a, or(b, c)])) == @julog Const[a, b, c]
# Test instantiation of universal quantifiers
clauses = @julog [
block(a) <<= true,
block(b) <<= true,
block(c) <<= true,
holding(a) <<= true
]
universal_term = @julog(forall(block(X), not(holding(X))))
@test deuniversalize(universal_term, clauses) ==
@julog and(not(holding(a)), not(holding(b)), not(holding(c)))
universal_clause = Clause(@julog(handempty), [universal_term])
@test deuniversalize(universal_clause, clauses) ==
@julog handempty <<= and(not(holding(a)), not(holding(b)), not(holding(c)))
# Test regularization of clause bodies
clauses = @julog [
binary(X) <<= or(woman(X), man(X)) & not(nonbinary(X)),
bigender(X) <<= and(woman(X), man(X)),
nonbinary(X) <<= or(genderqueer(X), agender(X), thirdgender(X))
]
regularized = @julog [
binary(X) <<= woman(X) & not(nonbinary(X)),
binary(X) <<= man(X) & not(nonbinary(X)),
bigender(X) <<= woman(X) & man(X),
nonbinary(X) <<= genderqueer(X),
nonbinary(X) <<= agender(X),
nonbinary(X) <<= thirdgender(X)
]
@test regularize_clauses(clauses) == regularized
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1722 | @testset "Custom function evaluation" begin
funcs = Dict()
funcs[:pi] = pi
funcs[:zero] = () -> 0
funcs[:sin] = sin
funcs[:cos] = cos
funcs[:square] = x -> x * x
funcs[:dup] = x -> (x, x)
funcs[:pair] = (x, y) -> (x, y)
funcs[:fst] = tup -> tup[1]
funcs[:snd] = tup -> tup[2]
funcs[:fakesum] = Dict((1, 1) => 2, (2, 2) => 4)
@test resolve(@julog(zero == 0), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(sin(pi / 2) == 1), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(cos(pi) == -1), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(square(5) == 25), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(dup(6) == pair(6, 6)), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(fakesum(1, 1) == 2), Clause[], funcs=funcs)[1] == true
@test resolve(@julog(fakesum(2, 2) == 4), Clause[], funcs=funcs)[1] == true
clauses = @julog [
even(X) <<= mod(X, 2) == 0,
is_dup(X) <<= fst(X) == snd(X),
is_square(5, 5, 25) <<= true
]
@test resolve(@julog(even(fakesum(1, 1))), clauses, funcs=funcs)[1] == true
@test resolve(@julog(is_dup(dup(8))), clauses, funcs=funcs)[1] == true
@test resolve(@julog(is_square(5, X, square(5))), clauses, funcs=funcs)[1] == true
clauses = @julog [
on_circ(Rad, Pt) <<= square(fst(Pt)) + square(snd(Pt)) == square(Rad),
on_diag(X, Y) <<= dup(X) == pair(X, Y)
]
# Is the point (3, -4) on the circle of radius 5?
@test resolve(@julog(on_circ(5, (3, -4))), clauses, funcs=funcs)[1] == true
# How about the point (5 * sin(1), 5 * cos(1))?
@test resolve(@julog(on_circ(5, pair(5*sin(1), 5*cos(1)))), clauses, funcs=funcs)[1] == true
# Is the point (10, 10) on the line X=Y?
@test resolve(@julog(on_diag(10, 10)), clauses, funcs=funcs)[1] == true
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1573 | @testset "Zen lineage (example)" begin
# Test composition and transitive relations using the traditional Zen lineage
clauses = @julog [
ancestor(sakyamuni, bodhidharma) <<= true,
teacher(bodhidharma, huike) <<= true,
teacher(huike, sengcan) <<= true,
teacher(sengcan, daoxin) <<= true,
teacher(daoxin, hongren) <<= true,
teacher(hongren, huineng) <<= true,
ancestor(A, B) <<= teacher(A, B),
ancestor(A, C) <<= teacher(B, C) & ancestor(A, B),
grandteacher(A, C) <<= teacher(A, B) & teacher(B, C)
]
# Is Sakyamuni the dharma ancestor of Huineng?
goals = @julog [ancestor(sakyamuni, huineng)]
sat, subst = resolve(goals, clauses);
@test sat == true
# Who are the grandteachers of whom?
goals = @julog [grandteacher(X, Y)]
sat, subst = resolve(goals, clauses)
subst = Set(subst)
@test @varsub({X => bodhidharma, Y => sengcan}) in subst
@test @varsub({X => huike, Y => daoxin}) in subst
@test @varsub({X => sengcan, Y => hongren}) in subst
@test @varsub({X => daoxin, Y => huineng}) in subst
# Test that forward chaining produces the same / correct results
fwd_sat, fwd_subst = derive(goals, clauses)
@test fwd_sat == sat
@test Set(fwd_subst) == subst
n_init = 6
n_ancestor = 5 + 15
n_grandteacher = 4
@test length(derivations(clauses, Inf)) == n_ancestor + n_grandteacher + n_init
# Test clause table manipulation
table = index_clauses(clauses[1:4])
table = insert_clauses!(table, clauses[4:end])
@test table == index_clauses(clauses)
subtract_clauses!(table, clauses[5:end])
@test Set(deindex_clauses(table)) == Set(clauses[1:4])
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1356 | @testset "List manipulation" begin
# Test list parsing
@test @julog(cons(x, cons(y, cons(z, cend())))) == @julog(list[x, y, z])
@test @julog(cons(x, cons(y, cons(z, W)))) == @julog(list[x, y, z | W])
@test @julog(list[x|[y|[z]]]) == @julog(list[x, y, z])
# Test list functionality with some basic list operations
clauses = @julog [
member(X, [X | Y]) <<= true,
member(X, [Y | YS]) <<= member(X, YS),
append([], L, L) <<= true,
append([X | XS], YS, [X | ZS]) <<= append(XS, YS, ZS),
reverse(X, Y) <<= reverse(X, [], Y),
reverse([], YS, YS) <<= true,
reverse([X | XS], Accu, YS) <<= reverse(XS, [X | Accu], YS)
]
# Test list membership
@test resolve(@julog(member(banana, [avocado, banana, coconut])), clauses)[1] == true
@test resolve(@julog(member(durian, [avocado, banana, coconut])), clauses)[1] == false
# Test list appending
@test resolve(@julog(append([h,e,l,l], [o], [h,e,l,l,o])), clauses)[1] == true
@test resolve(@julog(append([o], [h,e,l,l], [h,e,l,l,o])), clauses)[1] == false
# Test list reversal
@test resolve(@julog(reverse([r,e,g,a,l], [l,a,g,e,r])), clauses)[1] == true
# A palindrome!
@test resolve(@julog(reverse([d,e,l,e,v,e,l,e,d], [d,e,l,e,v,e,l,e,d])), clauses)[1] == true
# Not a palindrome (but yes an ambigram)
@test resolve(@julog(reverse([p,a,s,s,e,d], [p,a,s,s,e,d])), clauses)[1] == false
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1672 | @testset "Math operators" begin
# Test built-in math and comparison operators
@test resolve(@julog(1 == 1), Clause[])[1] == true
@test resolve(@julog(1 == 2), Clause[])[1] == false
@test resolve(@julog(1 != 2), Clause[])[1] == true
@test resolve(@julog(1 < 2), Clause[])[1] == true
@test resolve(@julog(3 > 2), Clause[])[1] == true
@test resolve(@julog(3 <= 4), Clause[])[1] == true
@test resolve(@julog(5 >= 4), Clause[])[1] == true
@test resolve(@julog(1 + 1 == 2), Clause[])[1] == true
@test resolve(@julog(5 - 6 == -1), Clause[])[1] == true
@test resolve(@julog(6 * 9 != 42), Clause[])[1] == true
@test resolve(@julog(8 * 8 > 7 * 9), Clause[])[1] == true
@test resolve(@julog(5 / 2 == 2.5), Clause[])[1] == true
@test resolve(@julog(mod(5, 2) == 1), Clause[])[1] == true
# Define addition using built-in operators
clauses = @julog [
add(X, Y, Z) <<= is(Z, X + Y),
add(X, Y, Z) <<= is(X, Z - Y),
add(X, Y, Z) <<= is(Y, Z - X)
]
# Is 1 + 1 = 2?
@test resolve(@julog(add(1, 1, 2)), clauses)[1] == true
# What is 2 + 3?
@test @varsub({Z => 5}) in resolve(@julog(add(2, 3, Z)), clauses)[2]
# What is 5 - 2?
@test @varsub({X => 2}) in resolve(@julog(add(X, 3, 5)), clauses)[2]
# What is 5 - 3?
@test @varsub({Y => 3}) in resolve(@julog(add(2, Y, 5)), clauses)[2]
# Using is/2 doesn't allow us ask for all the ways to add to 5
@test resolve(@julog(add(X, Y, 5)), clauses)[1] == false
# Test normal evaluation of operators
query = @julog [is(X, 1), is(Y, 2), (X < Y)]
@test resolve(query, Clause[])[1] == true
# Test deferred evaluation of operators
query = @julog [(X < Y), is(X, 1), is(Y, 2)]
@test resolve(query, Clause[]; defer_eval=true)[1] == true
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 842 | @testset "Natural numbers (example)" begin
# Test the natural numbers and addition
clauses = @julog [
nat(0) <<= true,
nat(s(N)) <<= nat(N),
add(0, Y, Y) <<= true,
add(s(X), Y, s(Z)) <<= add(X, Y, Z)
]
# Is 1 a natural number?
sat, subst = resolve(@julog(nat(s(0))), clauses)
@test sat == true
# Is 5 a natural number?
sat, subst = resolve(@julog(nat(s(s(s(s(s(0))))))), clauses)
@test sat == true
# Is 1 + 1 = 2?
sat, subst = resolve(@julog(add(s(0), s(0), s(s(0)))), clauses)
@test sat == true
# What are all the ways to add up to 3?
sat, subst = resolve(@julog(add(A, B, s(s(s(0))))), clauses)
subst = Set(subst)
@test @varsub({A => 0, B => s(s(s(0)))}) in subst
@test @varsub({A => s(0), B => s(s(0))}) in subst
@test @varsub({A => s(s(0)), B => s(0)}) in subst
@test @varsub({A => s(s(s(0))), B => 0}) in subst
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1643 | @testset "Parsing" begin
# Parsing of terms
@test Const(:atom) == @julog atom
@test Const(1) == @julog 1
@test Const((2,3)) == @julog (2,3)
@test Const("foo") == @julog "foo"
@test Var(:Variable) == @julog Variable
@test Compound(:functor, Term[Const(:a), Var(:B)]) == @julog functor(a, B)
# Parsing of clauses and facts
@test Clause(Const(:head), [Const(:body)]) == @julog head <<= body
@test Clause(Const(:head), [Const(:t1), Const(:t2)]) == @julog head <<= t1 & t2
@test Clause(Const(:head), []) == @julog head <<= true
@test Clause(Const(:head), []) == @julog head'
# Parsing of lists of terms or clauses
@test [Clause(Const(:fact), []), Const(:term)] == @julog [fact', term]
@test [Clause(Const(:a), [Const(:b)])] == @julog Clause[a <<= b]
@test Const[Const(:a), Const(:b)] == @julog [a, b]
@test Term[Const(:a), Const(:b)] == @julog Term[a, b]
@test Const[Const(:a), Const(:b)] == @julog Const[a, b]
@test Var[Var(:A), Var(:B)] == @julog Var[A, B]
@test Compound[Compound(:f, [Const(:arg)])] == @julog Compound[f(arg)]
# Interpolation of constants and Julog expressions
x, y = 2, Const(3)
@test Compound(:even, [Const(x)]) == @julog even($x)
@test Compound(:odd, [y]) == @julog odd(:y)
not_even = Compound(:not, [Compound(:even, [Var(:X)])])
odd_if_not_even = Clause(Compound(:odd, [Var(:X)]), [not_even])
@test odd_if_not_even == @julog odd(X) <<= :not_even
let f = :f
@test @julog($f(x)) == @julog(f(x))
end
# Test parsing and interpolation in @varsub macro
a, b = :alice, Const(:bob)
s1 = Subst(Var(:A) => Const(a), Var(:B) => b)
s2 = @varsub {A => alice, B => bob}
s3 = @varsub {A => $a, B => :b}
@test s1 == s2 == s3
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 623 | @testset "Permutation generation (example)" begin
clauses = @julog [
permutations(T) <<=
unifies(T, [_, _ ,_]) &
subset([1,2,3], T),
member(X, [X | Y]) <<= true,
member(X, [Y | YS]) <<= member(X, YS),
subset([], _) <<= true,
subset([X | XS], L) <<= member(X,L) & subset(XS,L),
]
sat, subst = resolve(@julog(permutations(T)),clauses)
@test @varsub({T => [1, 2, 3]}) in subst
@test @varsub({T => [1, 3, 2]}) in subst
@test @varsub({T => [2, 1, 3]}) in subst
@test @varsub({T => [2, 3, 1]}) in subst
@test @varsub({T => [3, 1, 2]}) in subst
@test @varsub({T => [3, 2, 1]}) in subst
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1386 | @testset "Prolog syntax conversion" begin
pl_input = @prolog """
member(X, [X | Y]).
member(X, [Y | YS]) :- member(X, YS).
vertebrate(A) :- fish(A) ; amphibian(A) ; reptile(A) ; bird(A) ; mammal(A).
bird(A) :- dinosaur(A), \\+reptile(A).
reptile(A) :- member(A, .(stegosaurus, .(triceratops, []))).
dinosaur(A) :- member(A, [archaeopteryx, stegosaurus, triceratops]).
"""
julog_clauses = @julog [
member(X, [X | Y]) <<= true,
member(X, [Y | YS]) <<= member(X, YS),
vertebrate(A) <<= fish(A),
vertebrate(A) <<= amphibian(A),
vertebrate(A) <<= reptile(A),
vertebrate(A) <<= bird(A),
vertebrate(A) <<= mammal(A),
bird(A) <<= dinosaur(A) & !reptile(A),
reptile(A) <<= member(A, cons(stegosaurus, cons(triceratops, []))),
dinosaur(A) <<= member(A, [archaeopteryx, stegosaurus, triceratops])
]
@test pl_input == julog_clauses
@test resolve(@prolog("bird(archaeopteryx)."), pl_input)[1] == true
pl_output = """
member(X, [X | Y]).
member(X, [Y | YS]) :- member(X, YS).
vertebrate(A) :- fish(A).
vertebrate(A) :- amphibian(A).
vertebrate(A) :- reptile(A).
vertebrate(A) :- bird(A).
vertebrate(A) :- mammal(A).
bird(A) :- dinosaur(A), \\+(reptile(A)).
reptile(A) :- member(A, [stegosaurus, triceratops]).
dinosaur(A) :- member(A, [archaeopteryx, stegosaurus, triceratops]).
"""
@test write_prolog(pl_input) == pl_output
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 276 | using Julog
using Test
include("parse.jl")
include("unify.jl")
include("builtins.jl")
include("math_ops.jl")
include("lists.jl")
include("custom_funcs.jl")
include("prolog.jl")
include("conversions.jl")
include("lineage.jl")
include("naturals.jl")
include("permutations.jl")
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | code | 1988 | @testset "Unification" begin
# Test unification of constant with zero-arity compound
subst = unify(@julog(constant), @julog(constant()))
@test subst == @varsub {}
# Test unification of nested terms
subst = unify(@julog(f(g(X, h(X, b)), Z)), @julog(f(g(a, Z), Y)))
@test subst == @varsub {X => a, Z => h(a, b), Y => h(a, b)}
# Test occurs check during unification
@test unify(@julog(A), @julog(functor(A)), false) == @varsub {A => functor(A)}
@test unify(@julog(A), @julog(functor(A)), true) === nothing
# Test extended unification of arithmetic functions (Prolog can't do this!)
# X unifies to 4, Y unifies to 5, so *(X, Y) unifies by evaluation to 20
@test unify(@julog(f(X, X*Y, Y)), @julog(f(4, 20, 5))) == @varsub {Y => 5, X => 4}
# X unifies to 4, Y unifies to /(20,4), so *(X, Y) unifies by evaluation to 20
@test unify(@julog(f(X, X*Y, Y)), @julog(f(4, 20, 20/4))) == @varsub {Y => /(20, 4), X => 4}
# X unifies to 4, Y unifies to 5, Z unifies to *(X, Y) === *(4, 5) post substitution
@test unify(@julog(f(X, X*Y, Y)), @julog(f(4, Z, 5))) == @varsub {Y => 5, X => 4, Z => *(4, 5)}
# X unifies to X, Y unifies to 5, X*Y cannot be evaluated and so fails to unify with 20
@test unify(@julog(f(X, X*Y, Y)), @julog(f(X, 20, 5))) === nothing
# Test subterm detection
@test has_subterm(@julog(atom), @julog(Var)) == true
@test has_subterm(@julog(functor(functor(atom))), @julog(functor)) == false
@test has_subterm(@julog(functor(functor(atom))), @julog(atom)) == true
@test has_subterm(@julog(functor(functor(atom))), @julog(functor(Var))) == true
@test has_subterm(@julog(list[a, b, c, d]), @julog(b)) == true
@test has_subterm(@julog(list[a, b, c, d]), @julog(list[a, b])) == false
@test has_subterm(@julog(list[a, b, c, d]), @julog(list[c, d])) == true
@test has_subterm(@julog(f(g(X, h(X, b)), Z)), @julog(h(X, Y))) == true
subterms = find_subterms(@julog(foo(bar(1), bar(bar(2)))), @julog(bar(X)))
@test Set(subterms) == Set(@julog(Term[bar(1), bar(bar(2)), bar(2)]))
end
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"Apache-2.0"
] | 0.1.15 | 191e4f6de2ddf2dc60d5d90c412d066814f1655b | docs | 12279 | # Julog.jl



[](https://juliahub.com/docs/Julog)
A Julia package for Prolog-style logic programming.
## Installation
Enter the package manager by pressing `]` at the Julia REPL, then run:
```
add Julog
```
The latest development version can also be installed by running:
```
add <link to this git repository>
```
## Features
- [Prolog-like syntax](#syntax)
- [Interpolation of expressions](#interpolation)
- [Custom function support](#custom-functions)
- [Built-in predicates and logical connectives](#built-in-predicates)
- [Conversion utilities](#conversion-utilities)
## Usage
[Terms](http://www.dai.ed.ac.uk/groups/ssp/bookpages/quickprolog/node5.html) and [Horn clauses](https://en.wikipedia.org/wiki/Horn_clause) can be expressed in Prolog-like syntax using the
`@julog` macro:
```julia
# This creates a term
@julog teacher(bodhidharma, huike)
# This creates a fact (a term which is asserted to be true)
@julog teacher(bodhidharma, huike) <<= true
# This creates a definite clause
@julog grandteacher(A, C) <<= teacher(A, B) & teacher(B, C)
```
The `@julog` macro can be also applied to a list of clauses to create a
knowledge base. We use the traditional [Zen lineage chart](https://en.wikipedia.org/wiki/Zen_lineage_charts) as an example:
```julia
clauses = @julog [
ancestor(sakyamuni, bodhidharma) <<= true,
teacher(bodhidharma, huike) <<= true,
teacher(huike, sengcan) <<= true,
teacher(sengcan, daoxin) <<= true,
teacher(daoxin, hongren) <<= true,
teacher(hongren, huineng) <<= true,
ancestor(A, B) <<= teacher(A, B),
ancestor(A, C) <<= teacher(B, C) & ancestor(A, B),
grandteacher(A, C) <<= teacher(A, B) & teacher(B, C)
]
```
With the `resolve` function, we can query the knowledge base via [SLD resolution](https://en.wikipedia.org/wiki/SLD_resolution) (the form of backward-chaining proof search used by Prolog):
```julia
# Query: Is Sakyamuni the dharma ancestor of Huineng?
julia> goals = @julog [ancestor(sakyamuni, huineng)]; # List of terms to query or prove
julia> sat, subst = resolve(goals, clauses);
julia> sat
true
# Query: Who are the grandteachers of whom?
julia> goals = @julog [grandteacher(X, Y)];
julia> sat, subst = resolve(goals, clauses);
julia> subst
4-element Array{Any,1}:
{Y => sengcan, X => bodhidharma}
{Y => daoxin, X => huike}
{Y => hongren, X => sengcan}
{Y => huineng, X => daoxin}
```
Forward-chaining proof search is supported as well, using `derive`. We can also compute the list of n-step derivations with `derivations(clauses, n)`:
```julia
# Facts derivable from one iteration through the rules
julia> derivations(clauses, 1)
16-element Array{Clause,1}:
teacher(bodhidharma, huike)
⋮
ancestor(sakyamuni, huike)
# The set of all derivable facts (i.e. the closure / fixed-point)
julia> derivations(clauses, Inf)
30-element Array{Clause,1}:
teacher(bodhidharma, huike)
⋮
ancestor(sakyamuni, huineng)
```
More examples can be found in the [`test`](test) folder.
## Syntax
`Julog` uses syntax very similar to Prolog. In particular, users should
note that argument-free terms with initial capitals are parsed as variables,
whereas lowercase terms are parsed as constants:
```julia
julia> typeof(@julog(Person))
Var
julia> typeof(@julog(person))
Const
```
However, several important operators differ from Prolog, as shown by the examples below:
| Julog | Prolog | Meaning |
|------------------------------------------|----------------------------------------|-------------------------------------|
| `human(socrates) <<= true` | `human(socrates).` | Socrates is human. |
| `mortal(X) <<= human(X)` | `mortal(X) :- human(X).` | If X is human, X is mortal. |
| `!mortal(gaia)` | `\+mortal(gaia)` | Gaia is not mortal. |
| `mortal(X) <<= can_live(X) & can_die(X)` | `mortal(X) :- can_live(X), can_die(X)` | X is mortal if it can live and die. |
In words, `<<=` replaces the Prolog turnstile `:-`, `<<= true` or `'` replaces `.` when stating facts, `!` replaces `\+` for negation, there is no longer a special operator for `cut`, `&` replaces `,` in the bodies of definite clauses, and there is no `or` operator like the `;` in Prolog.
In addition, when constructing Prolog-style linked-lists, the syntax `@julog list[a, b, c]` should be used when the list is not nested within any other compound term. This is because the `@julog [a, b, c]` syntax is reserved for creating a *Julia* list of Julog objects, such as a list of Julog clauses. Lists which are nested within other term, e.g., `member(b, [a, b, c])`, are parsed in the same way as Prolog.
If Prolog syntax is preferred, the `@prolog` macro and `parse_prolog` functions can be used to convert Prolog strings directly to Julog constructs, while `write_prolog` converts a list of Julog clauses to a Prolog string. However, this conversion cannot presently handle all of Prolog syntax (e.g., nested infix operators or comparison operators such as `=:=`), and should be used with caution.
## Interpolation
Similar to [string interpolation](https://docs.julialang.org/en/latest/manual/strings/#string-interpolation-1) and [expression interpolation](https://docs.julialang.org/en/v1/manual/metaprogramming/#Expressions-and-evaluation-1) in Julia, you can interpolate Julia expressions when constructing `Julog` terms using the `@julog` macro. `Julog` supports two forms of interpolation. The first form is constant interpolation using the `$` operator, where ordinary Julia expressions are converted to `Const`s:
```julia
julia> e = exp(1)
2.718281828459045
julia> term = @julog irrational($e)
irrational(2.718281828459045)
julia> dump(term)
Compound
name: Symbol irrational
args: Array{Term}((1,))
1: Const
name: Float64 2.718281828459045
```
The second form is term interpolation using the `:` operator, where pre-constructed `Julog` terms are interpolated into a surrounding `Julog` expression:
```julia
julia> e = Const(exp(1))
2.718281828459045
julia> term = @julog irrational(:e)
irrational(2.718281828459045)
julia> dump(term)
Compound
name: Symbol irrational
args: Array{Term}((1,))
1: Const
name: Float64 2.718281828459045
```
Interpolation allows us to easily generate Julog knowledge bases programatically using Julia code:
```julia
julia> people = @julog [avery, bailey, casey, darcy];
julia> heights = [@julog(height(:p, cm($(rand(140:200))))) for p in people]
4-element Array{Compound,1}:
height(avery, cm(155))
height(bailey, cm(198))
height(casey, cm(161))
height(darcy, cm(175))
```
## Custom Functions
In addition to standard arithmetic functions, `Julog` supports the evaluation of custom functions during proof search, allowing users to leverage the full power of precompiled Julia code. This can be done by providing a dictionary of functions when calling `resolve`. This dictionary can also accept constants (allowing one to store, e.g., numeric-valued fluents), and lookup-tables. An example is shown below:
```julia
funcs = Dict()
funcs[:pi] = pi
funcs[:sin] = sin
funcs[:cos] = cos
funcs[:square] = x -> x * x
funcs[:lookup] = Dict((:foo,) => "hello", (:bar,) => "world")
@assert resolve(@julog(sin(pi / 2) == 1), Clause[], funcs=funcs)[1] == true
@assert resolve(@julog(cos(pi) == -1), Clause[], funcs=funcs)[1] == true
@assert resolve(@julog(lookup(foo) == "hello"), Clause[], funcs=funcs)[1] == true
@assert resolve(@julog(lookup(bar) == "world"), Clause[], funcs=funcs)[1] == true
```
See [`test/custom_funcs.jl`](test/custom_funcs.jl) for more examples.
Unlike Prolog, Julog also supports [extended unification](https://www.sciencedirect.com/science/article/pii/0743106687900021) via the evaluation of functional terms. In other words, the following terms unify:
```julia
julia> unify(@julog(f(X, X*Y, Y)), @julog(f(4, 20, 5)))
Dict{Var, Term} with 2 entries:
Y => 5
X => 4
```
However, the extent of such unification is limited. If variables used within a functional expression are not sufficiently instantiated at the time of evaluation, evaluation will be partial, causing unification to fail:
```julia
julia> unify(@julog(f(X, X*Y, Y)), @julog(f(X, 20, 5))) === nothing
true
```
## Built-in Predicates
`Julog` provides a number of built-in predicates for control-flow and convenience. Some of these are also part of ISO Prolog, but may not share the exact same behavior.
- `cons` and `cend` are reserved for lists. `[x, y, z]` is equivalent to `cons(x, cons(y, cons(z, cend()))`.
- `true` and `false` operate as one might expect.
- `and(A, B, C, ...)` is equivalent to `A & B & C & ...` in the body of an Julog clause.
- `or(A, B, C, ...)` is equivalent to `A ; B ; C ; ...` in Prolog-syntax.
- `not(X)` / `!X` is true if X cannot be proven (i.e. negation as failure).
- `unifies(X, Y)` / `X ≐ Y` is true if `X` unifies with `Y`.
- `exists(Cond, Act)` is true if `Act` is true for at least one binding of `Cond`.
- `forall(Cond, Act)` is true if `Act` is true for all possible bindings of `Cond` (beware infinite loops).
- `imply(Cond, Act)` / `Cond => Act` is true if either `Cond` is false, or both `Cond` and `Act` are true.
- `call(pred, A, B, ...)`, the meta-call predicate, is equivalent to `pred(A, B, ...)`.
- `findall(Template, Cond, List)` finds all instances where `Cond` is true, substitutes any variables into `Template`, and unifies `List` with the result.
- `countall(Cond, N)` counts the number of proofs of `Cond` and unifies `N` with the result.
- `fail` causes the current goal to fail (equivalent to `false`).
- `cut` causes the current goal to succeed and suppresses all other goals. However, this does not have the same effects as in Prolog because `Julog` uses breadth-first search during SLD-resolution, unlike most Prolog implementations, which use depth-first search.
See [`test/builtins.jl`](test/builtins.jl) for usage examples.
## Conversion Utilities
Julog provides some support for converting and manipulating logical formulae, for example, conversion to negation, conjunctive, or disjunctive normal form:
```julia
julia> formula = @julog and(not(and(a, not(b))), c)
julia> to_nnf(formula)
and(or(not(a), b), c)
julia> to_cnf(formula)
and(or(not(a), b), or(c))
julia> to_dnf(formula)
or(and(not(a), c), and(b, c))
```
This can be useful for downstream applications, such as classical planning. Note however that these conversions do not handle the implicit existential quantification in Prolog semantics, and hence are not guaranteed to preserve equivalence when free variables are involved. In particular, care should be taken with negations of conjunctions of unbound predicates. For example, the following expression states that "All ravens are black.":
```julia
@julog not(and(raven(X), not(black(X))))
```
However, `to_dnf` doesn't handle the implied existential quantifier over `X`, and gives the non-equivalent statement "Either there are no ravens, or there exist black things, or both.":
```julia
@julog or(and(not(raven(X))), and(black(X)))
```
## Related Packages
There are several other Julia packages related to Prolog and logic programming:
- [HerbSWIPL.jl](https://github.com/Herb-AI/HerbSWIPL.jl) is a wrapper around SWI-Prolog that uses the Julog parser and interface.
- [Problox.jl](https://github.com/femtomc/Problox.jl) is a lightweight Julia wrapper around [ProbLog](https://dtai.cs.kuleuven.be/problog/), a probabilistic variant of Prolog.
## Acknowledgements
This implementation was made with reference to Chris Meyer's [Python interpreter for Prolog](http://www.openbookproject.net/py4fun/prolog/intro.html), as well as the unification and SLD-resolution algorithms presented in [An Introduction to Prolog](https://link.springer.com/content/pdf/bbm%3A978-3-642-41464-0%2F1.pdf) by Pierre M. Nugues.
| Julog | https://github.com/ztangent/Julog.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1495 | using AbstractDifferentiation
import AbstractDifferentiation as AD
using Documenter
DocMeta.setdocmeta!(
AbstractDifferentiation,
:DocTestSetup,
:(import AbstractDifferentiation as AD);
recursive=true,
)
generated_path = joinpath(@__DIR__, "src")
base_url = "https://github.com/JuliaDiff/AbstractDifferentiation.jl/blob/master/"
isdir(generated_path) || mkdir(generated_path)
open(joinpath(generated_path, "index.md"), "w") do io
# Point to source license file
println(
io,
"""
```@meta
EditURL = "$(base_url)README.md"
```
""",
)
# Write the contents out below the meta block
for line in eachline(joinpath(dirname(@__DIR__), "README.md"))
println(io, line)
end
end
makedocs(;
modules=[AbstractDifferentiation],
authors="Mohamed Tarek <[email protected]> and contributors",
sitename="AbstractDifferentiation.jl",
format=Documenter.HTML(;
repolink="https://github.com/JuliaDiff/AbstractDifferentiation.jl",
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://JuliaDiff.github.io/AbstractDifferentiation.jl",
edit_link="master",
assets=String[],
),
pages=[
"Home" => "index.md",
"User guide" => "user_guide.md",
"Implementer guide" => "implementer_guide.md",
],
)
deploydocs(;
repo="github.com/JuliaDiff/AbstractDifferentiation.jl",
devbranch="master",
push_preview=true,
)
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 539 | module AbstractDifferentiationChainRulesCoreExt
import AbstractDifferentiation as AD
using ChainRulesCore: ChainRulesCore
AD.@primitive function value_and_pullback_function(
ba::AD.ReverseRuleConfigBackend, f, xs...
)
value, back = ChainRulesCore.rrule_via_ad(AD.ruleconfig(ba), f, xs...)
function rrule_pullback(vs)
_vs = if vs isa Tuple && !(value isa Tuple)
only(vs)
else
vs
end
return Base.tail(back(_vs))
end
return value, rrule_pullback
end
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1664 | module AbstractDifferentiationFiniteDifferencesExt
if isdefined(Base, :get_extension)
import AbstractDifferentiation as AD
using FiniteDifferences: FiniteDifferences
else
import ..AbstractDifferentiation as AD
using ..FiniteDifferences: FiniteDifferences
end
"""
FiniteDifferencesBackend(method=FiniteDifferences.central_fdm(5, 1))
Create an AD backend that uses forward mode with FiniteDifferences.jl.
"""
AD.FiniteDifferencesBackend() =
AD.FiniteDifferencesBackend(FiniteDifferences.central_fdm(5, 1))
function AD.jacobian(ba::AD.FiniteDifferencesBackend, f, xs...)
return FiniteDifferences.jacobian(ba.method, f, xs...)
end
function AD.gradient(ba::AD.FiniteDifferencesBackend, f, xs...)
return FiniteDifferences.grad(ba.method, f, xs...)
end
function AD.pushforward_function(ba::AD.FiniteDifferencesBackend, f, xs...)
return function pushforward(vs)
ws = FiniteDifferences.jvp(ba.method, f, tuple.(xs, vs)...)
return length(xs) == 1 ? (ws,) : ws
end
end
function AD.pullback_function(ba::AD.FiniteDifferencesBackend, f, xs...)
function pullback(vs)
return FiniteDifferences.j′vp(ba.method, f, vs, xs...)
end
end
# Ensure consistency with `value_and_pullback` function
function AD.value_and_pullback_function(ba::AD.FiniteDifferencesBackend, f, xs...)
value = f(xs...)
function fd_pullback(vs)
return FiniteDifferences.j′vp(ba.method, f, vs, xs...)
end
return value, fd_pullback
end
# Better performance: issue #87
function AD.derivative(ba::AD.FiniteDifferencesBackend, f::TF, x::Real) where {TF<:Function}
return (ba.method(f, x),)
end
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 4432 | module AbstractDifferentiationForwardDiffExt
if isdefined(Base, :get_extension)
import AbstractDifferentiation as AD
using DiffResults: DiffResults
using ForwardDiff: ForwardDiff
else
import ..AbstractDifferentiation as AD
using ..DiffResults: DiffResults
using ..ForwardDiff: ForwardDiff
end
"""
ForwardDiffBackend(; chunksize::Union{Val,Nothing}=nothing)
Create an AD backend that uses forward mode with ForwardDiff.jl.
If the `chunksize` of the differentiation algorithm is set to `nothing` (the default), then
ForwarddDiff uses a heuristic to set the chunk size based on the input. Alternatively, if
`chunksize=Val{N}()`, then the chunk size is set to `N`.
See also: [ForwardDiff.jl: Configuring Chunk Size](https://juliadiff.org/ForwardDiff.jl/dev/user/advanced/#Configuring-Chunk-Size)
"""
function AD.ForwardDiffBackend(; chunksize::Union{Val,Nothing}=nothing)
return AD.ForwardDiffBackend{getchunksize(chunksize)}()
end
AD.@primitive function pushforward_function(ba::AD.ForwardDiffBackend, f, xs...)
return function pushforward(vs)
if length(xs) == 1
v = vs isa Tuple ? only(vs) : vs
return (ForwardDiff.derivative(h -> f(step_toward(xs[1], v, h)), 0),)
else
return ForwardDiff.derivative(h -> f(step_toward.(xs, vs, h)...), 0)
end
end
end
AD.primal_value(x::ForwardDiff.Dual) = ForwardDiff.value(x)
AD.primal_value(x::AbstractArray{<:ForwardDiff.Dual}) = ForwardDiff.value.(x)
# these implementations are more efficient than the fallbacks
function AD.derivative(::AD.ForwardDiffBackend, f, x::Real)
return (ForwardDiff.derivative(f, x),)
end
function AD.gradient(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
cfg = ForwardDiff.GradientConfig(f, x, chunk(ba, x))
return (ForwardDiff.gradient(f, x, cfg),)
end
function AD.jacobian(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
cfg = ForwardDiff.JacobianConfig(AD.asarray ∘ f, x, chunk(ba, x))
return (ForwardDiff.jacobian(AD.asarray ∘ f, x, cfg),)
end
AD.jacobian(::AD.ForwardDiffBackend, f, x::Real) = (ForwardDiff.derivative(f, x),)
function AD.hessian(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
cfg = ForwardDiff.HessianConfig(f, x, chunk(ba, x))
return (ForwardDiff.hessian(f, x, cfg),)
end
function AD.value_and_derivative(::AD.ForwardDiffBackend, f, x::Real)
T = typeof(ForwardDiff.Tag(f, typeof(x)))
ydual = f(ForwardDiff.Dual{T}(x, one(x)))
return ForwardDiff.value(T, ydual), (ForwardDiff.partials(T, ydual, 1),)
end
function AD.value_and_gradient(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
result = DiffResults.GradientResult(x)
cfg = ForwardDiff.GradientConfig(f, x, chunk(ba, x))
ForwardDiff.gradient!(result, f, x, cfg)
return DiffResults.value(result), (DiffResults.derivative(result),)
end
function AD.value_and_second_derivative(ba::AD.ForwardDiffBackend, f, x::Real)
T = typeof(ForwardDiff.Tag(f, typeof(x)))
xdual = ForwardDiff.Dual{T}(x, one(x))
T2 = typeof(ForwardDiff.Tag(f, typeof(xdual)))
ydual = f(ForwardDiff.Dual{T2}(xdual, one(xdual)))
v = ForwardDiff.value(T, ForwardDiff.value(T2, ydual))
d2 = ForwardDiff.partials(T, ForwardDiff.partials(T2, ydual, 1), 1)
return v, (d2,)
end
function AD.value_and_hessian(ba::AD.ForwardDiffBackend, f, x)
result = DiffResults.HessianResult(x)
cfg = ForwardDiff.HessianConfig(f, result, x, chunk(ba, x))
ForwardDiff.hessian!(result, f, x, cfg)
return DiffResults.value(result), (DiffResults.hessian(result),)
end
function AD.value_derivative_and_second_derivative(ba::AD.ForwardDiffBackend, f, x::Real)
T = typeof(ForwardDiff.Tag(f, typeof(x)))
xdual = ForwardDiff.Dual{T}(x, one(x))
T2 = typeof(ForwardDiff.Tag(f, typeof(xdual)))
ydual = f(ForwardDiff.Dual{T2}(xdual, one(xdual)))
v = ForwardDiff.value(T, ForwardDiff.value(T2, ydual))
d = ForwardDiff.partials(T, ForwardDiff.value(T2, ydual), 1)
d2 = ForwardDiff.partials(T, ForwardDiff.partials(T2, ydual, 1), 1)
return v, (d,), (d2,)
end
@inline step_toward(x::Number, v::Number, h) = x + h * v
# support arrays and tuples
@noinline step_toward(x, v, h) = x .+ h .* v
getchunksize(::Nothing) = Nothing
getchunksize(::Val{N}) where {N} = N
chunk(::AD.ForwardDiffBackend{Nothing}, x) = ForwardDiff.Chunk(x)
chunk(::AD.ForwardDiffBackend{N}, _) where {N} = ForwardDiff.Chunk{N}()
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 2244 | module AbstractDifferentiationReverseDiffExt
if isdefined(Base, :get_extension)
import AbstractDifferentiation as AD
using DiffResults: DiffResults
using ReverseDiff: ReverseDiff
else
import ..AbstractDifferentiation as AD
using ..DiffResults: DiffResults
using ..ReverseDiff: ReverseDiff
end
AD.primal_value(x::ReverseDiff.TrackedReal) = ReverseDiff.value(x)
AD.primal_value(x::AbstractArray{<:ReverseDiff.TrackedReal}) = ReverseDiff.value.(x)
AD.primal_value(x::ReverseDiff.TrackedArray) = ReverseDiff.value(x)
function AD.jacobian(ba::AD.ReverseDiffBackend, f, xs...)
xs_arr = map(AD.asarray, xs)
tape = ReverseDiff.JacobianTape(xs_arr) do (xs_arr...)
xs_new = map(xs, xs_arr) do x, x_arr
return x isa Number ? only(x_arr) : x_arr
end
return AD.asarray(f(xs_new...))
end
results = ReverseDiff.jacobian!(tape, xs_arr)
return map(xs, results) do x, result
return x isa Number ? vec(result) : result
end
end
function AD.jacobian(::AD.ReverseDiffBackend, f, xs::AbstractArray...)
return ReverseDiff.jacobian(AD.asarray ∘ f, xs)
end
function AD.derivative(::AD.ReverseDiffBackend, f, xs::Number...)
tape = ReverseDiff.InstructionTape()
xs_tracked = ReverseDiff.TrackedReal.(xs, zero.(xs), Ref(tape))
y_tracked = f(xs_tracked...)
ReverseDiff.seed!(y_tracked)
ReverseDiff.reverse_pass!(tape)
return ReverseDiff.deriv.(xs_tracked)
end
function AD.gradient(::AD.ReverseDiffBackend, f, xs::AbstractArray...)
return ReverseDiff.gradient(f, xs)
end
function AD.hessian(::AD.ReverseDiffBackend, f, x::AbstractArray)
return (ReverseDiff.hessian(f, x),)
end
function AD.value_and_gradient(::AD.ReverseDiffBackend, f, x::AbstractArray)
result = DiffResults.GradientResult(x)
cfg = ReverseDiff.GradientConfig(x)
ReverseDiff.gradient!(result, f, x, cfg)
return DiffResults.value(result), (DiffResults.derivative(result),)
end
function AD.value_and_hessian(::AD.ReverseDiffBackend, f, x)
result = DiffResults.HessianResult(x)
cfg = ReverseDiff.HessianConfig(result, x)
ReverseDiff.hessian!(result, f, x, cfg)
return DiffResults.value(result), (DiffResults.hessian(result),)
end
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1230 | module AbstractDifferentiationTrackerExt
if isdefined(Base, :get_extension)
import AbstractDifferentiation as AD
using Tracker: Tracker
else
import ..AbstractDifferentiation as AD
using ..Tracker: Tracker
end
function AD.second_lowest(::AD.TrackerBackend)
return throw(ArgumentError("Tracker backend does not support nested differentiation."))
end
AD.primal_value(x::Tracker.TrackedReal) = Tracker.data(x)
AD.primal_value(x::Tracker.TrackedArray) = Tracker.data(x)
AD.primal_value(x::AbstractArray{<:Tracker.TrackedReal}) = Tracker.data.(x)
AD.@primitive function value_and_pullback_function(ba::AD.TrackerBackend, f, xs...)
_value, back = Tracker.forward(f, xs...)
value = map(Tracker.data, _value)
function tracker_pullback(ws)
_ws = if ws isa Tuple && !(value isa Tuple)
only(ws)
else
ws
end
return map(Tracker.data, back(_ws))
end
return value, tracker_pullback
end
function AD.derivative(::AD.TrackerBackend, f, xs::Number...)
return Tracker.data.(Tracker.gradient(f, xs...))
end
function AD.gradient(::AD.TrackerBackend, f, xs::AbstractVector...)
return Tracker.data.(Tracker.gradient(f, xs...))
end
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 502 | module AbstractDifferentiationZygoteExt
if isdefined(Base, :get_extension)
import AbstractDifferentiation as AD
using Zygote: Zygote
else
import ..AbstractDifferentiation as AD
using ..Zygote: Zygote
end
AD.ZygoteBackend() = AD.ReverseRuleConfigBackend(Zygote.ZygoteRuleConfig())
# Context should not persist between different AD calls: fixes #69
function AD.ruleconfig(::AD.ReverseRuleConfigBackend{<:Zygote.ZygoteRuleConfig})
return Zygote.ZygoteRuleConfig()
end
end # module
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 23781 | module AbstractDifferentiation
using LinearAlgebra, ExprTools
abstract type AbstractBackend end
abstract type AbstractFiniteDifference <: AbstractBackend end
abstract type AbstractForwardMode <: AbstractBackend end
abstract type AbstractReverseMode <: AbstractBackend end
"""
AD.HigherOrderBackend{B}
Let `ab_f` be a forward-mode automatic differentiation backend and let `ab_r` be a reverse-mode automatic differentiation backend.
To construct a higher order backend for doing forward-over-reverse-mode automatic differentiation, use `AD.HigherOrderBackend((ab_f, ab_r))`.
To construct a higher order backend for doing reverse-over-forward-mode automatic differentiation, use `AD.HigherOrderBackend((ab_r, ab_f))`.
# Fields
- `backends::B`
"""
struct HigherOrderBackend{B} <: AbstractBackend
backends::B
end
reduce_order(b::AbstractBackend) = b
function reduce_order(b::HigherOrderBackend)
if length(b.backends) == 1
return lowest(b) # prevent zero tuple and subsequent error when reducing over HigherOrderBackend
else
return HigherOrderBackend(reverse(Base.tail(reverse(b.backends))))
end
end
lowest(b::AbstractBackend) = b
lowest(b::HigherOrderBackend) = b.backends[end]
second_lowest(b::AbstractBackend) = b
second_lowest(b::HigherOrderBackend) = lowest(reduce_order(b))
# If the primal value is in y, extract it.
# Otherwise, re-compute it, e.g. in finite diff.
primal_value(::AbstractFiniteDifference, ::Any, f, xs) = f(xs...)
primal_value(::AbstractBackend, ys, ::Any, ::Any) = primal_value(ys)
primal_value(x::Tuple) = map(primal_value, x)
primal_value(x) = x
"""
AD.derivative(ab::AD.AbstractBackend, f, xs::Number...)
Compute the derivatives of `f` with respect to the numbers `xs` using the backend `ab`.
The function returns a `Tuple` of derivatives, one for each element in `xs`.
"""
function derivative(ab::AbstractBackend, f, xs::Number...)
der = getindex.(jacobian(lowest(ab), f, xs...), 1)
if der isa Tuple
return der
else
return (der,)
end
end
"""
AD.gradient(ab::AD.AbstractBackend, f, xs...)
Compute the gradients of `f` with respect to the inputs `xs` using the backend `ab`.
The function returns a `Tuple` of gradients, one for each element in `xs`.
"""
function gradient(ab::AbstractBackend, f, xs...)
return reshape.(adjoint.(jacobian(lowest(ab), f, xs...)), size.(xs))
end
"""
AD.jacobian(ab::AD.AbstractBackend, f, xs...)
Compute the Jacobians of `f` with respect to the inputs `xs` using the backend `ab`.
The function returns a `Tuple` of Jacobians, one for each element in `xs`.
"""
function jacobian(ab::AbstractBackend, f, xs...) end
function jacobian(ab::HigherOrderBackend, f, xs...)
return jacobian(lowest(ab), f, xs...)
end
"""
AD.second_derivative(ab::AD.AbstractBackend, f, x)
Compute the second derivative of `f` with respect to the input `x` using the backend `ab`.
The function returns a single value because `second_derivative` currently only supports a single input.
"""
function second_derivative(ab::AbstractBackend, f, x)
if x isa Tuple
# only support computation of second derivative for functions with single input argument
x = only(x)
end
return derivative(second_lowest(ab), x -> begin
d = derivative(lowest(ab), f, x)
return d[1] # derivative returns a tuple
end, x)
end
"""
AD.hessian(ab::AD.AbstractBackend, f, x)
Compute the Hessian of `f` wrt the input `x` using the backend `ab`.
The function returns a single matrix because `hessian` currently only supports a single input.
"""
function hessian(ab::AbstractBackend, f, x)
if x isa Tuple
# only support computation of Hessian for functions with single input argument
x = only(x)
end
return jacobian(second_lowest(ab), x -> begin
gradient(lowest(ab), f, x)[1] # gradient returns a tuple
end, x)
end
"""
AD.value_and_derivative(ab::AD.AbstractBackend, f, xs::Number...)
Return the tuple `(v, ds)` of the function value `v = f(xs...)` and the derivatives `ds = AD.derivative(ab, f, xs...)`.
See also [`AbstractDifferentiation.derivative`](@ref).
"""
function value_and_derivative(ab::AbstractBackend, f, xs::Number...)
value, jacs = value_and_jacobian(lowest(ab), f, xs...)
return value[1], getindex.(jacs, 1)
end
"""
AD.value_and_gradient(ab::AD.AbstractBackend, f, xs...)
Return the tuple `(v, gs)` of the function value `v = f(xs...)` and the gradients `gs = AD.gradient(ab, f, xs...)`.
See also [`AbstractDifferentiation.gradient`](@ref).
"""
function value_and_gradient(ab::AbstractBackend, f, xs...)
value, jacs = value_and_jacobian(lowest(ab), f, xs...)
return value, reshape.(adjoint.(jacs), size.(xs))
end
"""
AD.value_and_jacobian(ab::AD.AbstractBackend, f, xs...)
Return the tuple `(v, Js)` of the function value `v = f(xs...)` and the Jacobians `Js = AD.jacobian(ab, f, xs...)`.
See also [`AbstractDifferentiation.jacobian`](@ref).
"""
function value_and_jacobian(ab::AbstractBackend, f, xs...)
value = f(xs...)
jacs = jacobian(lowest(ab), f, xs...)
return value, jacs
end
"""
AD.value_and_second_derivative(ab::AD.AbstractBackend, f, x)
Return the tuple `(v, d2)` of the function value `v = f(x)` and the second derivative `d2 = AD.second_derivative(ab, f, x)`.
See also [`AbstractDifferentiation.second_derivative`](@ref)
"""
function value_and_second_derivative(ab::AbstractBackend, f, x)
return f(x), second_derivative(ab, f, x)
end
"""
AD.value_and_hessian(ab::AD.AbstractBackend, f, x)
Return the tuple `(v, H)` of the function value `v = f(x)` and the Hessian `H = AD.hessian(ab, f, x)`.
See also [`AbstractDifferentiation.hessian`](@ref).
"""
function value_and_hessian(ab::AbstractBackend, f, x)
if x isa Tuple
# only support computation of Hessian for functions with single input argument
x = only(x)
end
value = f(x)
hess = jacobian(second_lowest(ab), _x -> begin
g = gradient(lowest(ab), f, _x)
return g[1] # gradient returns a tuple
end, x)
return value, hess
end
"""
AD.value_derivative_and_second_derivative(ab::AD.AbstractBackend, f, x)
Return the tuple `(v, d, d2)` of the function value `v = f(x)`, the first derivative `d = AD.derivative(ab, f, x)`, and the second derivative `d2 = AD.second_derivative(ab, f, x)`.
"""
function value_derivative_and_second_derivative(ab::AbstractBackend, f, x)
if x isa Tuple
# only support computation of Hessian for functions with single input argument
x = only(x)
end
value = f(x)
deriv, secondderiv = value_and_derivative(
second_lowest(ab), _x -> begin
d = derivative(lowest(ab), f, _x)
return d[1] # derivative returns a tuple
end, x
)
return value, (deriv,), secondderiv
end
"""
AD.value_gradient_and_hessian(ab::AD.AbstractBackend, f, x)
Return the tuple `(v, g, H)` of the function value `v = f(x)`, the gradient `g = AD.gradient(ab, f, x)`, and the Hessian `H = AD.hessian(ab, f, x)`.
See also [`AbstractDifferentiation.gradient`](@ref) and [`AbstractDifferentiation.hessian`](@ref).
"""
function value_gradient_and_hessian(ab::AbstractBackend, f, x)
if x isa Tuple
# only support computation of Hessian for functions with single input argument
x = only(x)
end
value = f(x)
grads, hess = value_and_jacobian(
second_lowest(ab), _x -> begin
g = gradient(lowest(ab), f, _x)
return g[1] # gradient returns a tuple
end, x
)
return value, (grads,), hess
end
"""
AD.pushforward_function(ab::AD.AbstractBackend, f, xs...)
Return the pushforward function `pff` of the function `f` at the inputs `xs` using backend `ab`.
The pushfoward function `pff` accepts as input a `Tuple` of tangents, one for each element in `xs`.
If `xs` consists of a single element, `pff` can also accept a single tangent instead of a 1-tuple.
"""
function pushforward_function(ab::AbstractBackend, f, xs...)
function pff(ds)
function pff_aux(xds...)
if ds isa Tuple
@assert length(xs) == length(ds)
newxs = xs .+ ds .* xds
return f(newxs...)
else
newx = only(xs) + ds * only(xds)
return f(newx)
end
end
return jacobian(lowest(ab), pff_aux, _zero.(xs, ds)...)
end
return pff
end
"""
AD.value_and_pushforward_function(ab::AD.AbstractBackend, f, xs...)
Return a single function `vpff` which, given tangents `ts`, computes the tuple `(v, p) = vpff(ts)` composed of
- the function value `v = f(xs...)`
- the pushforward value `p = pff(ts)` given by the pushforward function `pff = AD.pushforward_function(ab, f, xs...)` applied to `ts`.
See also [`AbstractDifferentiation.pushforward_function`](@ref).
!!! warning
This name should be understood as "(value and pushforward) function", and thus is not aligned with the reverse mode counterpart [`AbstractDifferentiation.value_and_pullback_function`](@ref).
"""
function value_and_pushforward_function(ab::AbstractBackend, f, xs...)
n = length(xs)
value = f(xs...)
pff = pushforward_function(lowest(ab), f, xs...)
function vpff(ds)
if !(ds isa Tuple)
ds = (ds,)
end
@assert length(ds) == n
return value, pff(ds)
end
return vpff
end
_zero(::Number, d::Number) = zero(d)
_zero(::Number, d::AbstractVector) = zero(d)
_zero(::AbstractVector, d::AbstractVector) = zero(eltype(d))
_zero(::AbstractVector, d::AbstractMatrix) = zero(similar(d, size(d, 2)))
_zero(::AbstractMatrix, d::AbstractMatrix) = zero(d)
_zero(::Any, d::Any) = zero(d)
@inline _dot(x, y) = dot(x, y)
@inline function _dot(x::AbstractVector, y::UniformScaling)
return @inbounds dot(only(x), y.λ)
end
@inline function _dot(x::AbstractVector, y::AbstractMatrix)
@assert size(y, 2) == 1
return dot(x, y)
end
"""
AD.pullback_function(ab::AD.AbstractBackend, f, xs...)
Return the pullback function `pbf` of the function `f` at the inputs `xs` using backend `ab`.
The pullback function `pbf` accepts as input a `Tuple` of cotangents, one for each output of `f`.
If `f` has a single output, `pbf` can also accept a single input instead of a 1-tuple.
"""
function pullback_function(ab::AbstractBackend, f, xs...)
_, pbf = value_and_pullback_function(ab, f, xs...)
return pbf
end
"""
AD.value_and_pullback_function(ab::AD.AbstractBackend, f, xs...)
Return a tuple `(v, pbf)` of the function value `v = f(xs...)` and the pullback function `pbf = AD.pullback_function(ab, f, xs...)`.
See also [`AbstractDifferentiation.pullback_function`](@ref).
!!! warning
This name should be understood as "value and (pullback function)", and thus is not aligned with the forward mode counterpart [`AbstractDifferentiation.value_and_pushforward_function`](@ref).
"""
function value_and_pullback_function(ab::AbstractBackend, f, xs...)
value = f(xs...)
function pbf(ws)
function pbf_aux(_xs...)
vs = f(_xs...)
if ws isa Tuple
@assert length(vs) == length(ws)
return sum(Base.splat(_dot), zip(ws, vs))
else
return _dot(vs, ws)
end
end
return gradient(lowest(ab), pbf_aux, xs...)
end
return value, pbf
end
struct LazyDerivative{B,F,X}
backend::B
f::F
xs::X
end
function Base.:*(d::LazyDerivative, y)
return derivative(d.backend, d.f, d.xs...) * y
end
function Base.:*(y, d::LazyDerivative)
return y * derivative(d.backend, d.f, d.xs...)
end
function Base.:*(d::LazyDerivative, y::Union{Number,Tuple})
if y isa Tuple && d.xs isa Tuple
@assert length(y) == length(d.xs)
end
return derivative(d.backend, d.f, d.xs...) .* y
end
function Base.:*(y::Union{Number,Tuple}, d::LazyDerivative)
if y isa Tuple && d.xs isa Tuple
@assert length(y) == length(d.xs)
end
return y .* derivative(d.backend, d.f, d.xs...)
end
function Base.:*(d::LazyDerivative, y::AbstractArray)
return map((d) -> d * y, derivative(d.backend, d.f, d.xs...))
end
function Base.:*(y::AbstractArray, d::LazyDerivative)
return map((d) -> y * d, derivative(d.backend, d.f, d.xs...))
end
struct LazyGradient{B,F,X}
backend::B
f::F
xs::X
end
Base.:*(d::LazyGradient, y) = gradient(d.backend, d.f, d.xs...) * y
Base.:*(y, d::LazyGradient) = y * gradient(d.backend, d.f, d.xs...)
function Base.:*(d::LazyGradient, y::Union{Number,Tuple})
if y isa Tuple && d.xs isa Tuple
@assert length(y) == length(d.xs)
end
if d.xs isa Tuple
return gradient(d.backend, d.f, d.xs...) .* y
else
return gradient(d.backend, d.f, d.xs) .* y
end
end
function Base.:*(y::Union{Number,Tuple}, d::LazyGradient)
if y isa Tuple && d.xs isa Tuple
@assert length(y) == length(d.xs)
end
if d.xs isa Tuple
return y .* gradient(d.backend, d.f, d.xs...)
else
return y .* gradient(d.backend, d.f, d.xs)
end
end
struct LazyJacobian{B,F,X}
backend::B
f::F
xs::X
end
function Base.:*(d::LazyJacobian, ys)
if !(ys isa Tuple)
ys = (ys,)
end
if d.xs isa Tuple
vjp = pushforward_function(d.backend, d.f, d.xs...)(ys)
else
vjp = pushforward_function(d.backend, d.f, d.xs)(ys)
end
if vjp isa Tuple
return vjp
else
return (vjp,)
end
end
function Base.:*(ys, d::LazyJacobian)
if ys isa Tuple
ya = adjoint.(ys)
else
ya = adjoint(ys)
end
if d.xs isa Tuple
return pullback_function(d.backend, d.f, d.xs...)(ya)
else
return pullback_function(d.backend, d.f, d.xs)(ya)
end
end
function Base.:*(d::LazyJacobian, ys::Number)
if d.xs isa Tuple
return jacobian(d.backend, d.f, d.xs...) .* ys
else
return jacobian(d.backend, d.f, d.xs) .* ys
end
end
function Base.:*(ys::Number, d::LazyJacobian)
if d.xs isa Tuple
return jacobian(d.backend, d.f, d.xs...) .* ys
else
return jacobian(d.backend, d.f, d.xs) .* ys
end
end
struct LazyHessian{B,F,X}
backend::B
f::F
xs::X
end
function Base.:*(d::LazyHessian, ys)
if !(ys isa Tuple)
ys = (ys,)
end
if d.xs isa Tuple
res = pushforward_function(
second_lowest(d.backend),
(xs...,) -> gradient(lowest(d.backend), d.f, xs...)[1],
d.xs...,
)(
ys
) # [1] because gradient returns a tuple
else
res = pushforward_function(
second_lowest(d.backend), (xs,) -> gradient(lowest(d.backend), d.f, xs)[1], d.xs
)(
ys
) # gradient returns a tuple
end
if res isa Tuple
return res
else
return (res,)
end
end
function Base.:*(ys, d::LazyHessian)
if ys isa Tuple
ya = adjoint.(ys)
else
ya = adjoint(ys)
end
if d.xs isa Tuple
return pullback_function(
second_lowest(d.backend),
(xs...,) -> gradient(lowest(d.backend), d.f, xs...),
d.xs...,
)(
ya
)
else
return pullback_function(
second_lowest(d.backend), (xs,) -> gradient(lowest(d.backend), d.f, xs)[1], d.xs
)(
ya
)
end
end
function Base.:*(d::LazyHessian, ys::Number)
if d.xs isa Tuple
return hessian(d.backend, d.f, d.xs...) .* ys
else
return hessian(d.backend, d.f, d.xs) .* ys
end
end
function Base.:*(ys::Number, d::LazyHessian)
if d.xs isa Tuple
return ys .* hessian(d.backend, d.f, d.xs...)
else
return ys .* hessian(d.backend, d.f, d.xs)
end
end
"""
AD.lazy_derivative(ab::AbstractBackend, f, xs::Number...)
Return an operator `ld` for multiplying by the derivative of `f` at `xs`.
You can apply the operator by multiplication e.g. `ld * y` where `y` is a number if `f` has a single input, a tuple of the same length as `xs` if `f` has multiple inputs, or an array of numbers/tuples.
"""
function lazy_derivative(ab::AbstractBackend, f, xs::Number...)
return LazyDerivative(ab, f, xs)
end
"""
AD.lazy_gradient(ab::AbstractBackend, f, xs...)
Return an operator `lg` for multiplying by the gradient of `f` at `xs`.
You can apply the operator by multiplication e.g. `lg * y` where `y` is a number if `f` has a single input or a tuple of the same length as `xs` if `f` has multiple inputs.
"""
function lazy_gradient(ab::AbstractBackend, f, xs...)
return LazyGradient(ab, f, xs)
end
"""
AD.lazy_hessian(ab::AbstractBackend, f, x)
Return an operator `lh` for multiplying by the Hessian of the scalar-valued function `f` at `x`.
You can apply the operator by multiplication e.g. `lh * y` or `y' * lh` where `y` is a number or a vector of the appropriate length.
"""
function lazy_hessian(ab::AbstractBackend, f, xs...)
return LazyHessian(ab, f, xs)
end
"""
AD.lazy_jacobian(ab::AbstractBackend, f, xs...)
Return an operator `lj` for multiplying by the Jacobian of `f` at `xs`.
You can apply the operator by multiplication e.g. `lj * y` or `y' * lj` where `y` is a number, vector or tuple of numbers and/or vectors.
If `f` has multiple inputs, `y` in `lj * y` should be a tuple.
If `f` has multiple outputs, `y` in `y' * lj` should be a tuple.
Otherwise, it should be a scalar or a vector of the appropriate length.
"""
function lazy_jacobian(ab::AbstractBackend, f, xs...)
return LazyJacobian(ab, f, xs)
end
struct D{B,F}
backend::B
f::F
end
D(b::AbstractBackend, d::D) = H(HigherOrderBackend((b, d.b)), d.f)
D(d::D) = H(HigherOrderBackend((d.backend, d.backend)), d.f)
function (d::D)(xs...; lazy=true)
if lazy
return lazy_jacobian(d.ab, d.f, xs...)
else
return jacobian(d.ab, d.f, xs...)
end
end
struct H{B,F}
backend::B
f::F
end
function (h::H)(xs...; lazy=true)
if lazy
return lazy_hessian(h.ab, h.f, xs...)
else
return hessian(h.ab, h.f, xs...)
end
end
macro primitive(expr)
fdef = ExprTools.splitdef(expr)
name = fdef[:name]
if name == :pushforward_function
return esc(define_pushforward_function_and_friends(fdef))
elseif name == :value_and_pullback_function
return esc(define_value_and_pullback_function_and_friends(fdef))
else
throw("Unsupported AD primitive.")
end
end
function define_pushforward_function_and_friends(fdef)
fdef[:name] = :($(AbstractDifferentiation).pushforward_function)
args = fdef[:args]
funcs = quote
$(ExprTools.combinedef(fdef))
function $(AbstractDifferentiation).jacobian($(args...))
identity_like = $(identity_matrix_like)($(args[3:end]...))
pff = $(pushforward_function)($(args...))
if eltype(identity_like) <: Tuple{Vararg{Union{AbstractMatrix,Number}}}
return map(identity_like) do identity_like_i
return mapreduce(hcat, $(_eachcol).(identity_like_i)...) do (cols...)
pff(cols)
end
end
elseif eltype(identity_like) <: AbstractMatrix
# needed for the computation of the Hessian and Jacobian
ret = hcat.(mapslices(identity_like[1]; dims=1) do cols
# cols loop over basis states
pf = pff((cols,))
if typeof(pf) <: AbstractVector
# to make the hcat. work / get correct matrix-like, non-flat output dimension
return (pf,)
else
return pf
end
end...)
return ret isa Tuple ? ret : (ret,)
else
return pff(identity_like)
end
end
end
return funcs
end
function define_value_and_pullback_function_and_friends(fdef)
fdef[:name] = :($(AbstractDifferentiation).value_and_pullback_function)
args = fdef[:args]
funcs = quote
$(ExprTools.combinedef(fdef))
function $(AbstractDifferentiation).jacobian($(args...))
value, pbf = $(value_and_pullback_function)($(args...))
identity_like = $(identity_matrix_like)(value)
if eltype(identity_like) <: Tuple{Vararg{AbstractMatrix}}
return map(identity_like) do identity_like_i
return mapreduce(vcat, $(_eachcol).(identity_like_i)...) do (cols...)
pbf(cols)'
end
end
elseif eltype(identity_like) <: AbstractMatrix
# needed for Hessian computation:
# value is a (grad,). Then, identity_like is a (matrix,).
# cols loops over columns of the matrix
return vcat.(mapslices(identity_like[1]; dims=1) do cols
adjoint.(pbf((cols,)))
end...)
else
return adjoint.(pbf(identity_like))
end
end
end
return funcs
end
_eachcol(a::Number) = (a,)
_eachcol(a) = eachcol(a)
function identity_matrix_like(x)
throw("The function `identity_matrix_like` is not defined for the type $(typeof(x)).")
end
function identity_matrix_like(x::AbstractVector)
return (Matrix{eltype(x)}(I, length(x), length(x)),)
end
function identity_matrix_like(x::Number)
return (one(x),)
end
identity_matrix_like(x::Tuple) = identity_matrix_like(x...)
@generated function identity_matrix_like(x...)
expr = :(())
for i in 1:length(x)
push!(expr.args, :(()))
for j in 1:(i - 1)
push!(expr.args[i].args, :((zero_matrix_like(x[$j])[1])))
end
push!(expr.args[i].args, :((identity_matrix_like(x[$i]))[1]))
for j in (i + 1):length(x)
push!(expr.args[i].args, :(zero_matrix_like(x[$j])[1]))
end
end
return expr
end
zero_matrix_like(x::Tuple) = zero_matrix_like(x...)
zero_matrix_like(x...) = map(zero_matrix_like, x)
zero_matrix_like(x::AbstractVector) = (zero(similar(x, length(x), length(x))),)
zero_matrix_like(x::Number) = (zero(x),)
function zero_matrix_like(x)
throw("The function `zero_matrix_like` is not defined for the type $(typeof(x)).")
end
@inline asarray(x) = [x]
@inline asarray(x::AbstractArray) = x
include("backends.jl")
# TODO: Replace with proper version
const EXTENSIONS_SUPPORTED = isdefined(Base, :get_extension)
if !EXTENSIONS_SUPPORTED
using Requires: @require
include("../ext/AbstractDifferentiationChainRulesCoreExt.jl")
end
@static if !EXTENSIONS_SUPPORTED
function __init__()
@require DiffResults = "163ba53b-c6d8-5494-b064-1a9d43ac40c5" begin
@require ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" include(
"../ext/AbstractDifferentiationForwardDiffExt.jl"
)
@require ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" include(
"../ext/AbstractDifferentiationReverseDiffExt.jl"
)
end
@require FiniteDifferences = "26cc04aa-876d-5657-8c51-4c34ba976000" include(
"../ext/AbstractDifferentiationFiniteDifferencesExt.jl"
)
@require Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c" include(
"../ext/AbstractDifferentiationTrackerExt.jl"
)
@require Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" include(
"../ext/AbstractDifferentiationZygoteExt.jl"
)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 2614 | """
FiniteDifferencesBackend{M}
AD backend that uses forward mode with [FiniteDifferences.jl](https://github.com/JuliaDiff/FiniteDifferences.jl).
The type parameter `M` is the type of the method used to perform finite differences.
!!! note
To be able to use this backend, you have to load FiniteDifferences.
"""
struct FiniteDifferencesBackend{M} <: AbstractFiniteDifference
method::M
end
"""
ForwardDiffBackend{CS}
AD backend that uses forward mode with [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl).
The type parameter `CS` denotes the chunk size of the differentiation algorithm.
If it is `Nothing`, then ForwardiffDiff uses a heuristic to set the chunk size based on the input.
See also: [ForwardDiff.jl: Configuring Chunk Size](https://juliadiff.org/ForwardDiff.jl/dev/user/advanced/#Configuring-Chunk-Size)
!!! note
To be able to use this backend, you have to load ForwardDiff.
"""
struct ForwardDiffBackend{CS} <: AbstractForwardMode end
"""
ReverseDiffBackend
AD backend that uses reverse mode with [ReverseDiff.jl](https://github.com/JuliaDiff/ReverseDiff.jl).
!!! note
To be able to use this backend, you have to load ReverseDiff.
"""
struct ReverseDiffBackend <: AbstractReverseMode end
"""
TrackerBackend
AD backend that uses reverse mode with [Tracker.jl](https://github.com/FluxML/Tracker.jl).
!!! note
To be able to use this backend, you have to load Tracker.
"""
struct TrackerBackend <: AbstractReverseMode end
"""
ReverseRuleConfigBackend
AD backend that uses reverse mode with any [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl)-compatible reverse-mode AD package.
Constructed with a [`RuleConfig`](https://juliadiff.org/ChainRulesCore.jl/stable/rule_author/superpowers/ruleconfig.html) object:
```julia
backend = AD.ReverseRuleConfigBackend(rc)
```
!!! note
On Julia >= 1.9, you have to load ChainRulesCore (possibly implicitly by loading a ChainRules-compatible AD package) to be able to use this backend.
"""
struct ReverseRuleConfigBackend{RC} <: AbstractReverseMode
ruleconfig::RC
end
# internal function for extracting the rule config
# falls back to returning the wrapped `ruleconfig` but can be specialized
# e.g., for Zygote to fix #69
ruleconfig(ba::ReverseRuleConfigBackend) = ba.ruleconfig
"""
ZygoteBackend()
Create an AD backend that uses reverse mode with [Zygote.jl](https://github.com/FluxML/Zygote.jl).
It is a special case of [`ReverseRuleConfigBackend`](@ref).
!!! note
To be able to use this backend, you have to load Zygote.
"""
function ZygoteBackend end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 8471 | using AbstractDifferentiation
using Test
using FiniteDifferences, ForwardDiff, Zygote
const AD = AbstractDifferentiation
const FDM = FiniteDifferences
## FiniteDifferences
struct FDMBackend1{A} <: AD.AbstractFiniteDifference
alg::A
end
FDMBackend1() = FDMBackend1(central_fdm(5, 1))
const fdm_backend1 = FDMBackend1()
# Minimal interface
function AD.jacobian(ab::FDMBackend1, f, xs...)
return FDM.jacobian(ab.alg, f, xs...)
end
struct FDMBackend2{A} <: AD.AbstractFiniteDifference
alg::A
end
FDMBackend2() = FDMBackend2(central_fdm(5, 1))
const fdm_backend2 = FDMBackend2()
AD.@primitive function pushforward_function(ab::FDMBackend2, f, xs...)
return function (vs)
ws = FDM.jvp(ab.alg, f, tuple.(xs, vs)...)
return length(xs) == 1 ? (ws,) : ws
end
end
struct FDMBackend3{A} <: AD.AbstractFiniteDifference
alg::A
end
FDMBackend3() = FDMBackend3(central_fdm(5, 1))
const fdm_backend3 = FDMBackend3()
AD.@primitive function value_and_pullback_function(ab::FDMBackend3, f, xs...)
value = f(xs...)
function fd3_pullback(vs)
# Supports only single output
_vs = vs isa AbstractVector ? vs : only(vs)
return FDM.j′vp(ab.alg, f, _vs, xs...)
end
return value, fd3_pullback
end
##
## ForwardDiff
struct ForwardDiffBackend1 <: AD.AbstractForwardMode end
const forwarddiff_backend1 = ForwardDiffBackend1()
function AD.jacobian(ab::ForwardDiffBackend1, f, xs)
if xs isa Number
return (ForwardDiff.derivative(f, xs),)
elseif xs isa AbstractArray
out = f(xs)
if out isa Number
return (adjoint(ForwardDiff.gradient(f, xs)),)
else
return (ForwardDiff.jacobian(f, xs),)
end
elseif xs isa Tuple
error(typeof(xs))
else
error(typeof(xs))
end
end
AD.primal_value(::ForwardDiffBackend1, ::Any, f, xs) = ForwardDiff.value.(f(xs...))
struct ForwardDiffBackend2 <: AD.AbstractForwardMode end
const forwarddiff_backend2 = ForwardDiffBackend2()
AD.@primitive function pushforward_function(ab::ForwardDiffBackend2, f, xs...)
# jvp = f'(x)*v, i.e., differentiate f(x + h*v) wrt h at 0
return function (vs)
if xs isa Tuple
@assert length(xs) <= 2
if length(xs) == 1
(ForwardDiff.derivative(h -> f(xs[1] + h * vs[1]), 0),)
else
ForwardDiff.derivative(h -> f(xs[1] + h * vs[1], xs[2] + h * vs[2]), 0)
end
else
ForwardDiff.derivative(h -> f(xs + h * vs), 0)
end
end
end
AD.primal_value(::ForwardDiffBackend2, ::Any, f, xs) = ForwardDiff.value.(f(xs...))
##
## Zygote
struct ZygoteBackend1 <: AD.AbstractReverseMode end
const zygote_backend1 = ZygoteBackend1()
AD.@primitive function value_and_pullback_function(ab::ZygoteBackend1, f, xs...)
# Supports only single output
value, back = Zygote.pullback(f, xs...)
function zygote_pullback(vs)
_vs = vs isa AbstractVector ? vs : only(vs)
return back(_vs)
end
return value, zygote_pullback
end
@testset "defaults" begin
@testset "Utils" begin
test_higher_order_backend(
fdm_backend1, fdm_backend2, fdm_backend3, zygote_backend1, forwarddiff_backend2
)
end
@testset "FiniteDifferences" begin
@testset "Derivative" begin
test_derivatives(fdm_backend1)
test_derivatives(fdm_backend2)
test_derivatives(fdm_backend3)
end
@testset "Gradient" begin
test_gradients(fdm_backend1)
test_gradients(fdm_backend2)
test_gradients(fdm_backend3)
end
@testset "Jacobian" begin
test_jacobians(fdm_backend1)
test_jacobians(fdm_backend2)
test_jacobians(fdm_backend3)
end
@testset "Hessian" begin
test_hessians(fdm_backend1)
test_hessians(fdm_backend2)
test_hessians(fdm_backend3)
end
@testset "jvp" begin
test_jvp(fdm_backend1; test_types=false)
test_jvp(fdm_backend2; vaugmented=true)
test_jvp(fdm_backend3)
end
@testset "j′vp" begin
test_j′vp(fdm_backend1)
test_j′vp(fdm_backend2)
test_j′vp(fdm_backend3)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(fdm_backend1)
test_lazy_derivatives(fdm_backend2)
test_lazy_derivatives(fdm_backend3)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(fdm_backend1)
test_lazy_gradients(fdm_backend2)
test_lazy_gradients(fdm_backend3)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(fdm_backend1)
test_lazy_jacobians(fdm_backend2; vaugmented=true)
test_lazy_jacobians(fdm_backend3)
end
@testset "Lazy Hessian" begin
test_lazy_hessians(fdm_backend1)
test_lazy_hessians(fdm_backend2)
test_lazy_hessians(fdm_backend3)
end
end
@testset "ForwardDiff" begin
@testset "Derivative" begin
test_derivatives(forwarddiff_backend1; multiple_inputs=false)
test_derivatives(forwarddiff_backend2)
end
@testset "Gradient" begin
test_gradients(forwarddiff_backend1; multiple_inputs=false)
test_gradients(forwarddiff_backend2)
end
@testset "Jacobian" begin
test_jacobians(forwarddiff_backend1; multiple_inputs=false)
test_jacobians(forwarddiff_backend2)
end
@testset "Hessian" begin
test_hessians(forwarddiff_backend1; multiple_inputs=false)
test_hessians(forwarddiff_backend2)
end
@testset "jvp" begin
test_jvp(forwarddiff_backend1; multiple_inputs=false)
test_jvp(forwarddiff_backend2; vaugmented=true)
end
@testset "j′vp" begin
test_j′vp(forwarddiff_backend1; multiple_inputs=false)
test_j′vp(forwarddiff_backend2)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(forwarddiff_backend1; multiple_inputs=false)
test_lazy_derivatives(forwarddiff_backend2)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(forwarddiff_backend1; multiple_inputs=false)
test_lazy_gradients(forwarddiff_backend2)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(forwarddiff_backend1; multiple_inputs=false)
test_lazy_jacobians(forwarddiff_backend2; vaugmented=true)
end
@testset "Lazy Hessian" begin
test_lazy_hessians(forwarddiff_backend1; multiple_inputs=false)
test_lazy_hessians(forwarddiff_backend2)
end
end
@testset "Zygote" begin
@testset "Derivative" begin
test_derivatives(zygote_backend1)
end
@testset "Gradient" begin
test_gradients(zygote_backend1)
end
@testset "Jacobian" begin
test_jacobians(zygote_backend1)
end
@testset "Hessian" begin
# Zygote over Zygote problems
backends = AD.HigherOrderBackend((forwarddiff_backend2, zygote_backend1))
test_hessians(backends)
backends = AD.HigherOrderBackend((zygote_backend1, forwarddiff_backend1))
test_hessians(backends)
# fails:
# backends = AD.HigherOrderBackend((zygote_backend1,forwarddiff_backend2))
# test_hessians(backends)
end
@testset "jvp" begin
test_jvp(zygote_backend1)
end
@testset "j′vp" begin
test_j′vp(zygote_backend1)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(zygote_backend1)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(zygote_backend1)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(zygote_backend1)
end
@testset "Lazy Hessian" begin
# Zygote over Zygote problems
backends = AD.HigherOrderBackend((forwarddiff_backend2, zygote_backend1))
test_lazy_hessians(backends)
backends = AD.HigherOrderBackend((zygote_backend1, forwarddiff_backend1))
test_lazy_hessians(backends)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1445 | using AbstractDifferentiation
using Test
using FiniteDifferences
@testset "FiniteDifferencesBackend" begin
method = FiniteDifferences.central_fdm(6, 1)
# `central_fdm(5, 1)` is not type-inferrable, so only check inferrability
# with user-specified method
backends = [
AD.FiniteDifferencesBackend(), @inferred(AD.FiniteDifferencesBackend(method))
]
@test backends[2].method === method
@testset for backend in backends
@testset "Derivative" begin
test_derivatives(backend)
end
@testset "Gradient" begin
test_gradients(backend)
end
@testset "Jacobian" begin
test_jacobians(backend)
end
@testset "Second derivative" begin
test_second_derivatives(backend)
end
@testset "Hessian" begin
test_hessians(backend)
end
@testset "jvp" begin
test_jvp(backend; vaugmented=true)
end
@testset "j′vp" begin
test_j′vp(backend)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(backend)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(backend)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(backend; vaugmented=true)
end
@testset "Lazy Hessian" begin
test_lazy_hessians(backend)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1302 | using AbstractDifferentiation
using Test
using ForwardDiff
@testset "ForwardDiffBackend" begin
backends = [
@inferred(AD.ForwardDiffBackend())
@inferred(AD.ForwardDiffBackend(; chunksize=Val{1}()))
]
@testset for backend in backends
@test backend isa AD.AbstractForwardMode
@testset "Derivative" begin
test_derivatives(backend)
end
@testset "Gradient" begin
test_gradients(backend)
end
@testset "Jacobian" begin
test_jacobians(backend)
end
@testset "Second derivative" begin
test_second_derivatives(backend)
end
@testset "Hessian" begin
test_hessians(backend)
end
@testset "jvp" begin
test_jvp(backend; vaugmented=true)
end
@testset "j′vp" begin
test_j′vp(backend)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(backend)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(backend)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(backend; vaugmented=true)
end
@testset "Lazy Hessian" begin
test_lazy_hessians(backend)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1141 | using AbstractDifferentiation
using Test
using ReverseDiff
@testset "ReverseDiffBackend" begin
backends = [@inferred(AD.ReverseDiffBackend())]
@testset for backend in backends
@testset "Derivative" begin
test_derivatives(backend)
end
@testset "Gradient" begin
test_gradients(backend)
end
@testset "Jacobian" begin
test_jacobians(backend)
end
@testset "Second derivative" begin
test_second_derivatives(backend)
end
@testset "Hessian" begin
test_hessians(backend)
end
@testset "jvp" begin
test_jvp(backend)
end
@testset "j′vp" begin
test_j′vp(backend)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(backend)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(backend)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(backend)
end
@testset "Lazy Hessian" begin
test_lazy_hessians(backend)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 2260 | using AbstractDifferentiation
using ChainRulesCore
using Test
using Zygote
@testset "ReverseRuleConfigBackend(ZygoteRuleConfig())" begin
backends = [@inferred(AD.ZygoteBackend())]
@testset for backend in backends
@testset "Derivative" begin
test_derivatives(backend)
end
@testset "Gradient" begin
test_gradients(backend)
end
@testset "Jacobian" begin
test_jacobians(backend)
end
@testset "jvp" begin
test_jvp(backend)
end
@testset "j′vp" begin
test_j′vp(backend)
end
@testset "Second derivative" begin
test_second_derivatives(backend)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(backend)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(backend)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(backend)
end
end
# issue #69
@testset "Zygote context" begin
ad = AD.ZygoteBackend()
# example in #69: context is not mutated
@test ad.ruleconfig.context.cache === nothing
@test AD.derivative(ad, exp, 1.0) === (exp(1.0),)
@test ad.ruleconfig.context.cache === nothing
@test AD.derivative(ad, exp, 1.0) === (exp(1.0),)
@test ad.ruleconfig.context.cache === nothing
# Jacobian computation still works
# https://github.com/JuliaDiff/AbstractDifferentiation.jl/pull/70#issuecomment-1449481724
function f(x, a)
r = Ref(x)
r[] = r[] + r[]
r[] = r[] * a
return r[]
end
@test AD.jacobian(ad, f, [1, 2, 3], 3) ==
([6.0 0.0 0.0; 0.0 6.0 0.0; 0.0 0.0 6.0], [2.0, 4.0, 6.0])
end
# issue #57
@testset "primal computation in rrule" begin
function myfunc(x)
@info "This should not be logged if I have an rrule"
return x
end
ChainRulesCore.rrule(::typeof(myfunc), x) = (x, (y -> (NoTangent(), y)))
@test_logs Zygote.gradient(myfunc, 1) # nothing is logged
@test_logs AD.derivative(AD.ZygoteBackend(), myfunc, 1) # nothing is logged
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 366 | using AbstractDifferentiation
using Documenter
using Test
@testset verbose = true "AbstractDifferentiation.jl" begin
doctest(AbstractDifferentiation)
include("test_utils.jl")
include("defaults.jl")
include("forwarddiff.jl")
include("reversediff.jl")
include("finitedifferences.jl")
include("tracker.jl")
include("ruleconfig.jl")
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 18152 | using AbstractDifferentiation
using Test, LinearAlgebra
using Random
Random.seed!(1234)
fder(x, y) = exp(y) * x + y * log(x)
dfderdx(x, y) = exp(y) + y * 1 / x
dfderdy(x, y) = exp(y) * x + log(x)
dfderdxdx(x, y) = -y / x^2
fgrad(x, y) = prod(x) + sum(y ./ (1:length(y)))
dfgraddx(x, y) = prod(x) ./ x
dfgraddy(x, y) = one(eltype(y)) ./ (1:length(y))
dfgraddxdx(x, y) = prod(x) ./ (x * x') - Diagonal(diag(prod(x) ./ (x * x')))
dfgraddydy(x, y) = zeros(length(y), length(y))
function fjac(x, y)
return x + -3 * y + [y[2:end]; zero(y[end])] / 2# Bidiagonal(-ones(length(y)) * 3, ones(length(y) - 1) / 2, :U) * y
end
dfjacdx(x, y) = I(length(x))
dfjacdy(x, y) = Bidiagonal(-ones(length(y)) * 3, ones(length(y) - 1) / 2, :U)
# Jvp
jxvp(x, y, v) = dfjacdx(x, y) * v
jyvp(x, y, v) = dfjacdy(x, y) * v
# vJp
vJxp(x, y, v) = dfjacdx(x, y)' * v
vJyp(x, y, v) = dfjacdy(x, y)' * v
const xscalar = rand()
const yscalar = rand()
const xvec = rand(5)
const yvec = rand(5)
# to check if vectors get mutated
xvec2 = deepcopy(xvec)
yvec2 = deepcopy(yvec)
function test_higher_order_backend(backends...)
ADbackends = AD.HigherOrderBackend(backends)
@test backends[end] == AD.lowest(ADbackends)
@test backends[end - 1] == AD.second_lowest(ADbackends)
for i in length(backends):-1:1
@test backends[i] == AD.lowest(ADbackends)
ADbackends = AD.reduce_order(ADbackends)
end
return backends[1] == AD.reduce_order(ADbackends)
end
function test_derivatives(backend; multiple_inputs=true, test_types=true)
# test with respect to analytical solution
der_exact = (dfderdx(xscalar, yscalar), dfderdy(xscalar, yscalar))
if multiple_inputs
der1 = AD.derivative(backend, fder, xscalar, yscalar)
@test minimum(isapprox.(der_exact, der1, rtol=1e-10))
valscalar, der2 = AD.value_and_derivative(backend, fder, xscalar, yscalar)
@test valscalar == fder(xscalar, yscalar)
@test der2 .- der1 == (0, 0)
end
# test if single input (no tuple works)
valscalara, dera = AD.value_and_derivative(backend, x -> fder(x, yscalar), xscalar)
valscalarb, derb = AD.value_and_derivative(backend, y -> fder(xscalar, y), yscalar)
if test_types
@test valscalara isa Float64
@test valscalarb isa Float64
@test dera[1] isa Float64
@test derb[1] isa Float64
end
@test fder(xscalar, yscalar) == valscalara
@test fder(xscalar, yscalar) == valscalarb
@test isapprox(dera[1], der_exact[1], rtol=1e-10)
@test isapprox(derb[1], der_exact[2], rtol=1e-10)
end
function test_gradients(backend; multiple_inputs=true, test_types=true)
# test with respect to analytical solution
grad_exact = (dfgraddx(xvec, yvec), dfgraddy(xvec, yvec))
if multiple_inputs
grad1 = AD.gradient(backend, fgrad, xvec, yvec)
@test minimum(isapprox.(grad_exact, grad1, rtol=1e-10))
valscalar, grad2 = AD.value_and_gradient(backend, fgrad, xvec, yvec)
if test_types
@test valscalar isa Float64
@test grad1[1] isa AbstractVector{Float64}
@test grad1[2] isa AbstractVector{Float64}
@test grad2[1] isa AbstractVector{Float64}
@test grad2[2] isa AbstractVector{Float64}
end
@test valscalar == fgrad(xvec, yvec)
@test norm.(grad2 .- grad1) == (0, 0)
end
# test if single input (no tuple works)
valscalara, grada = AD.value_and_gradient(backend, x -> fgrad(x, yvec), xvec)
valscalarb, gradb = AD.value_and_gradient(backend, y -> fgrad(xvec, y), yvec)
if test_types
@test valscalara isa Float64
@test valscalarb isa Float64
@test grada[1] isa AbstractVector{Float64}
@test gradb[1] isa AbstractVector{Float64}
end
@test fgrad(xvec, yvec) == valscalara
@test fgrad(xvec, yvec) == valscalarb
@test isapprox(grada[1], grad_exact[1], rtol=1e-10)
@test isapprox(gradb[1], grad_exact[2], rtol=1e-10)
@test xvec == xvec2
@test yvec == yvec2
end
function test_jacobians(backend; multiple_inputs=true, test_types=true)
# test with respect to analytical solution
jac_exact = (dfjacdx(xvec, yvec), dfjacdy(xvec, yvec))
if multiple_inputs
jac1 = AD.jacobian(backend, fjac, xvec, yvec)
@test minimum(isapprox.(jac_exact, jac1, rtol=1e-10))
valvec, jac2 = AD.value_and_jacobian(backend, fjac, xvec, yvec)
if test_types
@test valvec isa Vector{Float64}
@test jac1[1] isa Matrix{Float64}
@test jac1[2] isa Matrix{Float64}
@test jac2[1] isa Matrix{Float64}
@test jac2[2] isa Matrix{Float64}
end
@test valvec == fjac(xvec, yvec)
@test norm.(jac2 .- jac1) == (0, 0)
end
# test if single input (no tuple works)
valveca, jaca = AD.value_and_jacobian(backend, x -> fjac(x, yvec), xvec)
valvecb, jacb = AD.value_and_jacobian(backend, y -> fjac(xvec, y), yvec)
if test_types
@test valveca isa Vector{Float64}
@test valvecb isa Vector{Float64}
@test jaca[1] isa Matrix{Float64}
@test jacb[1] isa Matrix{Float64}
end
@test fjac(xvec, yvec) == valveca
@test fjac(xvec, yvec) == valvecb
@test isapprox(jaca[1], jac_exact[1], rtol=1e-10)
@test isapprox(jacb[1], jac_exact[2], rtol=1e-10)
@test xvec == xvec2
@test yvec == yvec2
end
function test_second_derivatives(backend; test_types=true)
# explicit test that AbstractDifferentiation throws an error
# don't support tuple of second derivatives
@test_throws ArgumentError AD.second_derivative(
backend, x -> fder(x, yscalar), (xscalar, yscalar)
)
@test_throws MethodError AD.second_derivative(
backend, x -> fder(x, yscalar), xscalar, yscalar
)
# test if single input (no tuple works)
dder1 = AD.second_derivative(backend, x -> fder(x, yscalar), xscalar)
if test_types
@test only(dder1) isa Float64
end
@test dfderdxdx(xscalar, yscalar) ≈ only(dder1) atol = 1e-8
valscalar, dder2 = AD.value_and_second_derivative(
backend, x -> fder(x, yscalar), xscalar
)
if test_types
@test valscalar isa Float64
@test only(dder2) isa Float64
end
@test valscalar == fder(xscalar, yscalar)
@test dder2 == dder1
valscalar, der, dder3 = AD.value_derivative_and_second_derivative(
backend, x -> fder(x, yscalar), xscalar
)
if test_types
@test valscalar isa Float64
@test only(der) isa Float64
@test only(dder3) isa Float64
end
@test valscalar == fder(xscalar, yscalar)
@test der == AD.derivative(backend, x -> fder(x, yscalar), xscalar)
@test dder3 == dder1
end
function test_hessians(backend; multiple_inputs=false, test_types=true)
if multiple_inputs
# ... but
error("multiple_inputs=true is not supported.")
else
# explicit test that AbstractDifferentiation throws an error
# don't support tuple of Hessians
@test_throws ArgumentError AD.hessian(backend, fgrad, (xvec, yvec))
@test_throws MethodError AD.hessian(backend, fgrad, xvec, yvec)
end
# @test dfgraddxdx(xvec,yvec) ≈ H1[1] atol=1e-10
# @test dfgraddydy(xvec,yvec) ≈ H1[2] atol=1e-10
# test if single input (no tuple works)
fhess = x -> fgrad(x, yvec)
hess1 = AD.hessian(backend, fhess, xvec)
if test_types
@test hess1[1] isa Matrix{Float64}
end
# test with respect to analytical solution
@test dfgraddxdx(xvec, yvec) ≈ hess1[1] atol = 1e-10
valscalar, hess2 = AD.value_and_hessian(backend, fhess, xvec)
if test_types
@test valscalar isa Float64
@test hess2[1] isa Matrix{Float64}
end
@test valscalar == fgrad(xvec, yvec)
@test norm.(hess2 .- hess1) == (0,)
valscalar, grad, hess3 = AD.value_gradient_and_hessian(backend, fhess, xvec)
if test_types
@test valscalar isa Float64
@test grad[1] isa AbstractVector{Float64}
@test hess3[1] isa Matrix{Float64}
end
@test valscalar == fgrad(xvec, yvec)
@test norm.(grad .- AD.gradient(backend, fhess, xvec)) == (0,)
@test norm.(hess3 .- hess1) == (0,)
@test xvec == xvec2
@test yvec == yvec2
fhess2 = x -> dfgraddx(x, yvec)
hess4 = AD.jacobian(backend, fhess2, xvec)
if test_types
@test hess4[1] isa Matrix{Float64}
end
@test minimum(isapprox.(hess4, hess1, atol=1e-10))
end
function test_jvp(
backend; multiple_inputs=true, vaugmented=false, rng=Random.GLOBAL_RNG, test_types=true
)
v = (rand(rng, length(xvec)), rand(rng, length(yvec)))
if multiple_inputs
if vaugmented
identity_like = AD.identity_matrix_like(v)
vaug = map(identity_like) do identity_like_i
identity_like_i .* v
end
pf1 = map(v -> AD.pushforward_function(backend, fjac, xvec, yvec)(v), vaug)
((valvec1, pf2x), (valvec2, pf2y)) = map(
v -> AD.value_and_pushforward_function(backend, fjac, xvec, yvec)(v), vaug
)
else
pf1 = AD.pushforward_function(backend, fjac, xvec, yvec)(v)
valvec, pf2 = AD.value_and_pushforward_function(backend, fjac, xvec, yvec)(v)
((valvec1, pf2x), (valvec2, pf2y)) = (valvec, pf2[1]), (valvec, pf2[2])
end
if test_types
@test valvec1 isa Vector{Float64}
@test valvec2 isa Vector{Float64}
@test pf1[1] isa Vector{Float64}
@test pf1[2] isa Vector{Float64}
@test pf2x isa Vector{Float64}
@test pf2y isa Vector{Float64}
end
@test valvec1 == fjac(xvec, yvec)
@test valvec2 == fjac(xvec, yvec)
@test norm.((pf2x, pf2y) .- pf1) == (0, 0)
# test with respect to analytical solution
@test minimum(
isapprox.(pf1, (jxvp(xvec, yvec, v[1]), jyvp(xvec, yvec, v[2])), atol=1e-10)
)
@test xvec == xvec2
@test yvec == yvec2
end
valvec1, pf1 = AD.value_and_pushforward_function(backend, x -> fjac(x, yvec), xvec)(
v[1]
)
valvec2, pf2 = AD.value_and_pushforward_function(backend, y -> fjac(xvec, y), yvec)(
v[2]
)
if test_types
@test valvec1 isa Vector{Float64}
@test valvec2 isa Vector{Float64}
@test pf1[1] isa Vector{Float64}
@test pf2[1] isa Vector{Float64}
end
@test valvec1 == fjac(xvec, yvec)
@test valvec2 == fjac(xvec, yvec)
@test minimum(
isapprox.(
(pf1[1], pf2[1]), (jxvp(xvec, yvec, v[1]), jyvp(xvec, yvec, v[2])), atol=1e-10
),
)
end
function test_j′vp(backend; multiple_inputs=true, rng=Random.GLOBAL_RNG, test_types=true)
# test with respect to analytical solution
w = rand(rng, length(fjac(xvec, yvec)))
if multiple_inputs
pb1 = AD.pullback_function(backend, fjac, xvec, yvec)(w)
valvec, pbf2 = AD.value_and_pullback_function(backend, fjac, xvec, yvec)
pb2 = pbf2(w)
if test_types
@test valvec isa Vector{Float64}
@test pb1[1] isa AbstractVector{Float64}
@test pb1[2] isa AbstractVector{Float64}
@test pb2[1] isa AbstractVector{Float64}
@test pb2[2] isa AbstractVector{Float64}
end
@test valvec == fjac(xvec, yvec)
@test norm.(pb2 .- pb1) == (0, 0)
@test minimum(
isapprox.(pb1, (vJxp(xvec, yvec, w), vJyp(xvec, yvec, w)), atol=1e-10)
)
@test xvec == xvec2
@test yvec == yvec2
end
valvec1, pbf1 = AD.value_and_pullback_function(backend, x -> fjac(x, yvec), xvec)
pb1 = pbf1(w)
valvec2, pbf2 = AD.value_and_pullback_function(backend, y -> fjac(xvec, y), yvec)
pb2 = pbf2(w)
if test_types
@test valvec1 isa Vector{Float64}
@test valvec2 isa Vector{Float64}
@test pb1[1] isa AbstractVector{Float64}
@test pb2[1] isa AbstractVector{Float64}
end
@test valvec1 == fjac(xvec, yvec)
@test valvec2 == fjac(xvec, yvec)
@test minimum(
isapprox.((pb1[1], pb2[1]), (vJxp(xvec, yvec, w), vJyp(xvec, yvec, w)), atol=1e-10)
)
end
function test_lazy_derivatives(backend; multiple_inputs=true)
# single input function
der1 = AD.derivative(backend, x -> fder(x, yscalar), xscalar)
lazyder = AD.LazyDerivative(backend, x -> fder(x, yscalar), xscalar)
# multiplication with scalar
@test lazyder * yscalar == der1 .* yscalar
@test lazyder * yscalar isa Tuple
@test yscalar * lazyder == yscalar .* der1
@test yscalar * lazyder isa Tuple
# multiplication with array
@test lazyder * yvec == (der1 .* yvec,)
@test lazyder * yvec isa Tuple
@test yvec * lazyder == (yvec .* der1,)
@test yvec * lazyder isa Tuple
# multiplication with tuple
@test lazyder * (yscalar,) == lazyder * yscalar
@test lazyder * (yvec,) == lazyder * yvec
@test (yscalar,) * lazyder == yscalar * lazyder
@test (yvec,) * lazyder == yvec * lazyder
# two input function
if multiple_inputs
der1 = AD.derivative(backend, fder, xscalar, yscalar)
lazyder = AD.LazyDerivative(backend, fder, (xscalar, yscalar))
# multiplication with scalar
@test lazyder * yscalar == der1 .* yscalar
@test lazyder * yscalar isa Tuple
@test yscalar * lazyder == yscalar .* der1
@test yscalar * lazyder isa Tuple
# multiplication with array
@test lazyder * yvec == (der1[1] * yvec, der1[2] * yvec)
@test lazyder * yvec isa Tuple
@test yvec * lazyder == (yvec * der1[1], yvec * der1[2])
@test lazyder * yvec isa Tuple
# multiplication with tuple
@test_throws AssertionError lazyder * (yscalar,)
@test_throws AssertionError lazyder * (yvec,)
@test_throws AssertionError (yscalar,) * lazyder
@test_throws AssertionError (yvec,) * lazyder
end
end
function test_lazy_gradients(backend; multiple_inputs=true)
# single input function
grad1 = AD.gradient(backend, x -> fgrad(x, yvec), xvec)
lazygrad = AD.LazyGradient(backend, x -> fgrad(x, yvec), xvec)
# multiplication with scalar
@test norm.(lazygrad * yscalar .- grad1 .* yscalar) == (0,)
@test lazygrad * yscalar isa Tuple
@test norm.(yscalar * lazygrad .- yscalar .* grad1) == (0,)
@test yscalar * lazygrad isa Tuple
# multiplication with tuple
@test lazygrad * (yscalar,) == lazygrad * yscalar
@test (yscalar,) * lazygrad == yscalar * lazygrad
# two input function
if multiple_inputs
grad1 = AD.gradient(backend, fgrad, xvec, yvec)
lazygrad = AD.LazyGradient(backend, fgrad, (xvec, yvec))
# multiplication with scalar
@test norm.(lazygrad * yscalar .- grad1 .* yscalar) == (0, 0)
@test lazygrad * yscalar isa Tuple
@test norm.(yscalar * lazygrad .- yscalar .* grad1) == (0, 0)
@test yscalar * lazygrad isa Tuple
# multiplication with tuple
@test_throws AssertionError lazygrad * (yscalar,) == lazygrad * yscalar
@test_throws AssertionError (yscalar,) * lazygrad == yscalar * lazygrad
end
end
function test_lazy_jacobians(
backend; multiple_inputs=true, vaugmented=false, rng=Random.GLOBAL_RNG
)
# single input function
jac1 = AD.jacobian(backend, x -> fjac(x, yvec), xvec)
lazyjac = AD.LazyJacobian(backend, x -> fjac(x, yvec), xvec)
# multiplication with scalar
@test norm.(lazyjac * yscalar .- jac1 .* yscalar) == (0,)
@test lazyjac * yscalar isa Tuple
@test norm.(yscalar * lazyjac .- yscalar .* jac1) == (0,)
@test yscalar * lazyjac isa Tuple
w = rand(rng, length(fjac(xvec, yvec)))
v = (rand(rng, length(xvec)), rand(rng, length(xvec)))
# vjp
pb1 = (vJxp(xvec, yvec, w),)
res = w' * lazyjac
@test minimum(isapprox.(pb1, res, atol=1e-10))
@test res isa Tuple
# jvp
pf1 = (jxvp(xvec, yvec, v[1]),)
res = lazyjac * v[1]
@test minimum(isapprox.(pf1, res, atol=1e-10))
@test res isa Tuple
# two input function
if multiple_inputs
jac1 = AD.jacobian(backend, fjac, xvec, yvec)
lazyjac = AD.LazyJacobian(backend, fjac, (xvec, yvec))
# multiplication with scalar
@test norm.(lazyjac * yscalar .- jac1 .* yscalar) == (0, 0)
@test lazyjac * yscalar isa Tuple
@test norm.(yscalar * lazyjac .- yscalar .* jac1) == (0, 0)
@test yscalar * lazyjac isa Tuple
# vjp
pb1 = (vJxp(xvec, yvec, w), vJyp(xvec, yvec, w))
res = w'lazyjac
@test minimum(isapprox.(pb1, res, atol=1e-10))
@test res isa Tuple
# jvp
pf1 = (jxvp(xvec, yvec, v[1]), jyvp(xvec, yvec, v[2]))
if vaugmented
identity_like = AD.identity_matrix_like(v)
vaug = map(identity_like) do identity_like_i
identity_like_i .* v
end
res = map(v -> (lazyjac * v)[1], vaug)
else
res = lazyjac * v
end
@test minimum(isapprox.(pf1, res, atol=1e-10))
@test res isa Tuple
end
end
function test_lazy_hessians(backend; multiple_inputs=true, rng=Random.GLOBAL_RNG)
# fdm_backend not used here yet..
# single input function
fhess = x -> fgrad(x, yvec)
hess1 = (dfgraddxdx(xvec, yvec),)
lazyhess = AD.LazyHessian(backend, fhess, xvec)
# multiplication with scalar
@test minimum(isapprox.(lazyhess * yscalar, hess1 .* yscalar, atol=1e-10))
@test lazyhess * yscalar isa Tuple
# multiplication with scalar
@test minimum(isapprox.(yscalar * lazyhess, yscalar .* hess1, atol=1e-10))
@test yscalar * lazyhess isa Tuple
w = rand(rng, length(xvec))
v = rand(rng, length(xvec))
# Hvp
Hv = map(h -> h * v, hess1)
res = lazyhess * v
@test minimum(isapprox.(Hv, res, atol=1e-10))
@test res isa Tuple
# H′vp
wH = map(h -> h' * w, hess1)
res = w' * lazyhess
@test minimum(isapprox.(wH, res, atol=1e-10))
@test res isa Tuple
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | code | 1305 | using AbstractDifferentiation
using Test
using Tracker
@testset "TrackerBackend" begin
backends = [@inferred(AD.TrackerBackend())]
@testset for backend in backends
@testset "errors when nested" begin
@test_throws ArgumentError AD.second_lowest(backend)
@test_throws ArgumentError AD.hessian(backend, sum, randn(3))
end
@testset "primal_value for array of tracked reals" begin
@test AD.primal_value([Tracker.TrackedReal(1.0)]) isa Vector{Float64}
@test AD.primal_value(fill(Tracker.TrackedReal(1.0), 1, 1)) isa Matrix{Float64}
end
@testset "Derivative" begin
test_derivatives(backend)
end
@testset "Gradient" begin
test_gradients(backend)
end
@testset "Jacobian" begin
test_jacobians(backend)
end
@testset "jvp" begin
test_jvp(backend)
end
@testset "j′vp" begin
test_j′vp(backend)
end
@testset "Lazy Derivative" begin
test_lazy_derivatives(backend)
end
@testset "Lazy Gradient" begin
test_lazy_gradients(backend)
end
@testset "Lazy Jacobian" begin
test_lazy_jacobians(backend)
end
end
end
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | docs | 2553 | # AbstractDifferentiation
[](https://JuliaDiff.github.io/AbstractDifferentiation.jl/stable)
[](https://JuliaDiff.github.io/AbstractDifferentiation.jl/dev)
[](https://github.com/JuliaDiff/AbstractDifferentiation.jl/actions/workflows/CI.yml?query=branch%3Amaster)
[](https://codecov.io/gh/JuliaDiff/AbstractDifferentiation.jl)
[](https://github.com/invenia/BlueStyle)
[](https://github.com/SciML/ColPrac)
## Motivation
This is a package that implements an abstract interface for differentiation in Julia. This is particularly useful for implementing abstract algorithms requiring derivatives, gradients, jacobians, Hessians or multiple of those without depending on specific automatic differentiation packages' user interfaces.
Julia has more (automatic) differentiation packages than you can count on 2 hands. Different packages have different user interfaces. Therefore, having a backend-agnostic interface to request the function value and its gradient for example is necessary to avoid a combinatorial explosion of code when trying to support every differentiation package in Julia in every algorithm package requiring gradients. For higher order derivatives, the situation is even more dire since you can combine any 2 differentiation backends together to create a new higher-order backend.
## Getting started
- If you are an autodiff user and want to write code in a backend-agnostic way, read the _user guide_ in the docs.
- If you are an autodiff developer and want your backend to implement the interface, read the _implementer guide_ in the docs (still in construction).
## Citing this package
If you use this package in your work, please cite the package:
```bib
@article{schafer2021abstractdifferentiation,
title={AbstractDifferentiation. jl: Backend-Agnostic Differentiable Programming in Julia},
author={Sch{\"a}fer, Frank and Tarek, Mohamed and White, Lyndon and Rackauckas, Chris},
journal={NeurIPS 2021 Differentiable Programming Workshop},
year={2021}
}
```
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | docs | 1857 | # Implementer guide
!!! warning "Work in progress"
Come back later!
## The macro `@primitive`
To implement the `AbstractDifferentiation` interface for your backend, you only _need_ to provide a "primitive" from which the rest of the functions can be deduced.
However, for performance reasons, you _can_ implement more of the interface to make certain calls faster.
At the moment, the only primitives supported are `AD.pushforward_function` and `AD.value_and_pullback_function`.
The `AD.@primitive` macro uses the provided function to implement `AD.jacobian`, and all the other functions follow.
```julia
AD.@primitive function AD.myprimitive(ab::MyBackend, f, xs...)
# write your code here
end
```
See the backend-specific extensions in the `ext/` folder of the repository for example implementations.
## Function dependency graph
These details are not part of the public API and are expected to change.
They are just listed here to help readers figure out the code structure:
- `jacobian` has no default implementation
- `derivative` calls `jacobian`
- `gradient` calls `jacobian`
- `hessian` calls `jacobian` and `gradient`
- `second_derivative` calls `derivative`
- `value_and_jacobian` calls `jacobian`
- `value_and_derivative` calls `value_and_jacobian`
- `value_and_gradient` calls `value_and_jacobian`
- `value_and_hessian` calls `jacobian` and `gradient`
- `value_and_second_derivative` calls `second_derivative`
- `value_gradient_and_hessian` calls `value_and_jacobian` and `gradient`
- `value_derivative_and_second_derivative` calls `value_and_derivative` and `second_derivative`
- `pushforward_function` calls `jacobian`
- `value_and_pushforward_function` calls `pushforward_function`
- `pullback_function` calls `value_and_pullback_function`
- `value_and_pullback_function` calls `gradient`
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"MIT"
] | 0.6.2 | d29ce82ed1d4c37135095e1a4d799c93d7be2361 | docs | 5025 | # User guide
The list of functions on this page is the officially supported differentiation interface in `AbstractDifferentiation`.
## Loading `AbstractDifferentiation`
To load `AbstractDifferentiation`, it is recommended to use
```julia
import AbstractDifferentiation as AD
```
With the `AD` alias you can access names inside of `AbstractDifferentiation` using `AD.<>` instead of typing the long name `AbstractDifferentiation`.
## `AbstractDifferentiation` backends
To use `AbstractDifferentiation`, first construct a backend instance `ab::AD.AbstractBackend` using your favorite differentiation package in Julia that supports `AbstractDifferentiation`.
Here's an example:
```jldoctest
julia> import AbstractDifferentiation as AD, Zygote
julia> backend = AD.ZygoteBackend();
julia> f(x) = log(sum(exp, x));
julia> AD.gradient(backend, f, collect(1:3))
([0.09003057317038046, 0.2447284710547977, 0.665240955774822],)
```
The following backends are temporarily made available by `AbstractDifferentiation` as soon as their corresponding package is loaded (thanks to [weak dependencies](https://pkgdocs.julialang.org/dev/creating-packages/#Weak-dependencies) on Julia ≥ 1.9 and [Requires.jl](https://github.com/JuliaPackaging/Requires.jl) on older Julia versions):
```@docs
AbstractDifferentiation.ReverseDiffBackend
AbstractDifferentiation.ReverseRuleConfigBackend
AbstractDifferentiation.FiniteDifferencesBackend
AbstractDifferentiation.ZygoteBackend
AbstractDifferentiation.ForwardDiffBackend
AbstractDifferentiation.TrackerBackend
```
In the long term, these backend objects (and many more) will be defined within their respective packages to enforce the `AbstractDifferentiation` interface.
This is already the case for:
- `Diffractor.DiffractorForwardBackend()` for [Diffractor.jl](https://github.com/JuliaDiff/Diffractor.jl) in forward mode
For higher order derivatives, you can build higher order backends using `AD.HigherOrderBackend`.
```@docs
AbstractDifferentiation.HigherOrderBackend
```
## Derivatives
The following list of functions can be used to request the derivative, gradient, Jacobian, second derivative or Hessian without the function value.
```@docs
AbstractDifferentiation.derivative
AbstractDifferentiation.gradient
AbstractDifferentiation.jacobian
AbstractDifferentiation.second_derivative
AbstractDifferentiation.hessian
```
## Value and derivatives
The following list of functions can be used to request the function value along with its derivative, gradient, Jacobian, second derivative, or Hessian. You can also request the function value, its derivative (or its gradient) and its second derivative (or Hessian) for single-input functions.
```@docs
AbstractDifferentiation.value_and_derivative
AbstractDifferentiation.value_and_gradient
AbstractDifferentiation.value_and_jacobian
AbstractDifferentiation.value_and_second_derivative
AbstractDifferentiation.value_and_hessian
AbstractDifferentiation.value_derivative_and_second_derivative
AbstractDifferentiation.value_gradient_and_hessian
```
## Jacobian-vector products
This operation goes by a few names, like "pushforward". Refer to the [ChainRules documentation](https://juliadiff.org/ChainRulesCore.jl/stable/#The-propagators:-pushforward-and-pullback) for more on terminology. For a single input, single output function `f` with a Jacobian `J`, the pushforward operator `pf_f` is equivalent to applying the function `v -> J * v` on a (tangent) vector `v`.
The following functions can be used to request a function that returns the pushforward operator/function. In order to request the pushforward function `pf_f` of a function `f` at the inputs `xs`, you can use either of:
```@docs
AbstractDifferentiation.pushforward_function
AbstractDifferentiation.value_and_pushforward_function
```
## Vector-Jacobian products
This operation goes by a few names, like "pullback". Refer to the [ChainRules documentation](https://juliadiff.org/ChainRulesCore.jl/stable/#The-propagators:-pushforward-and-pullback) for more on terminology. For a single input, single output function `f` with a Jacobian `J`, the pullback operator `pb_f` is equivalent to applying the function `v -> v' * J` on a (co-tangent) vector `v`.
The following functions can be used to request the pullback operator/function with or without the function value. In order to request the pullback function `pb_f` of a function `f` at the inputs `xs`, you can use either of:
```@docs
AbstractDifferentiation.pullback_function
AbstractDifferentiation.value_and_pullback_function
```
## Lazy operators
You can also get a struct for the lazy derivative/gradient/Jacobian/Hessian of a function. You can then use the `*` operator to apply the lazy operator on a value or tuple of the correct shape. To get a lazy derivative/gradient/Jacobian/Hessian use any one of:
```@docs
AbstractDifferentiation.lazy_derivative
AbstractDifferentiation.lazy_gradient
AbstractDifferentiation.lazy_jacobian
AbstractDifferentiation.lazy_hessian
```
## Index
```@index
```
| AbstractDifferentiation | https://github.com/JuliaDiff/AbstractDifferentiation.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | code | 559 | using Coverage
# process '*.cov' files
coverage = process_folder() # defaults to src/; alternatively, supply the folder name as argument
LCOV.writefile("lcov.info", coverage)
# process '*.info' files
coverage = merge_coverage_counts(
coverage,
filter!(
let prefixes = (joinpath(pwd(), "src", ""),)
c -> any(p -> startswith(c.filename, p), prefixes)
end,
LCOV.readfolder("test"),
),
)
# Get total coverage for all Julia files
covered_lines, total_lines = get_summary(coverage)
@show covered_lines, total_lines
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | code | 1399 | using DeprecateKeywords
using Documenter
DocMeta.setdocmeta!(DeprecateKeywords, :DocTestSetup, :(using DeprecateKeywords); recursive=true)
readme = open(dirname(@__FILE__) * "/../README.md") do io
read(io, String)
end
# We replace every instance of <img src="IMAGE" ...> with .
readme = replace(readme, r"<img src=\"([^\"]+)\"[^>]+>.*" => s"")
# Then, we remove any line with "<div" on it:
readme = replace(readme, r"<[/]?div.*" => s"")
# Finally, we read in file docs/src/index_base.md:
index_base = open(dirname(@__FILE__) * "/src/index_base.md") do io
read(io, String)
end
# And then we create "/src/index.md":
open(dirname(@__FILE__) * "/src/index.md", "w") do io
write(io, readme)
write(io, "\n")
write(io, index_base)
end
makedocs(;
modules=[DeprecateKeywords],
authors="MilesCranmer <[email protected]> and contributors",
repo="https://github.com/MilesCranmer/DeprecateKeywords.jl/blob/{commit}{path}#{line}",
sitename="DeprecateKeywords.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://astroautomata.com/DeprecateKeywords.jl",
edit_link="master",
assets=String[]
),
pages=[
"Home" => "index.md",
"API" => "api.md",
]
)
deploydocs(;
repo="github.com/MilesCranmer/DeprecateKeywords.jl",
devbranch="master"
)
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | code | 4153 | module DeprecateKeywords
export @depkws
using MacroTools
"""
@depkws def
Macro to deprecate keyword arguments. Use by wrapping a function signature,
while using `@deprecate(old_kw, new_kw)` within the function signature to deprecate.
# Examples
```julia
@depkws function f(; a=2, @deprecate(b, a))
a
end
```
"""
macro depkws(def)
return esc(_depkws(def))
end
abstract type DeprecatedDefault end
function _depkws(def)
sdef = splitdef(def)
func_symbol = Expr(:quote, sdef[:name]) # Double quote for expansion
new_symbols = Symbol[]
deprecated_symbols = Symbol[]
kwargs_to_remove = Int[]
for (i, param) in enumerate(sdef[:kwargs])
isa(param, Symbol) && continue
# Look for @deprecated macro:
if param.head == :macrocall && param.args[1] == Symbol("@deprecate")
# e.g., params.args[2] is the line number
deprecated_symbol = param.args[end-1]
new_symbol = param.args[end]
if !isa(new_symbol, Symbol)
# Remove line numbers nodes:
clean_param = deepcopy(param)
filter!(x -> !isa(x, LineNumberNode), clean_param.args)
error(
"The expression\n $(clean_param)\ndoes not appear to be two symbols in a `@deprecate`. This can happen if you use `@deprecate` in a function " *
"definition without " *
"parentheses, such as `f(; @deprecate a b, c=2)`. Instead, you should write `f(; (@deprecate a b), c=2)` or alternatively " *
"`f(; @deprecate(a, b), c=2)`.)"
)
end
push!(deprecated_symbols, deprecated_symbol)
push!(new_symbols, new_symbol)
push!(kwargs_to_remove, i)
end
end
deleteat!(sdef[:kwargs], kwargs_to_remove)
# Add deprecated kws:
for deprecated_symbol in deprecated_symbols
pushfirst!(sdef[:kwargs], Expr(:kw, deprecated_symbol, DeprecatedDefault))
end
symbol_mapping = Dict(new_symbols .=> deprecated_symbols)
# Update new symbols to use deprecated kws if passed:
for (i, kw) in enumerate(sdef[:kwargs])
no_default_type_assertion = !isa(kw, Symbol) && kw.head != :kw
no_default_naked = isa(kw, Symbol)
no_default = no_default_naked || no_default_type_assertion
(kw, type_assertion) = if no_default_type_assertion
@assert kw.head == :(::)
# Remove type assertion from keyword; we will
# assert it later.
kw.args
else
(kw, Nothing)
end
new_kw, default = if no_default
(kw, DeprecatedDefault)
else
(kw.args[1], kw.args[2])
end
_get_symbol(new_kw) in deprecated_symbols && continue
!(_get_symbol(new_kw) in new_symbols) && continue
deprecated_symbol = symbol_mapping[_get_symbol(new_kw)]
depwarn_string = "Keyword argument `$(deprecated_symbol)` is deprecated. Use `$(_get_symbol(new_kw))` instead."
new_kwcall = quote
if $deprecated_symbol !== $(DeprecatedDefault)
Base.depwarn($depwarn_string, $func_symbol)
$deprecated_symbol
else
$default
end
end
sdef[:kwargs][i] = Expr(:kw, new_kw, new_kwcall)
if no_default_type_assertion
pushfirst!(
sdef[:body].args,
Expr(:(::), _get_symbol(new_kw), type_assertion)
)
end
if no_default
# Propagate UndefKeywordError
pushfirst!(
sdef[:body].args,
Expr(:if,
Expr(:call, :(===), _get_symbol(new_kw), DeprecatedDefault),
Expr(:call, :throw,
Expr(:call, :UndefKeywordError, QuoteNode(_get_symbol(new_kw)))
)
)
)
end
end
return combinedef(sdef)
end
# This is used to go from a::Int to a
_get_symbol(e::Expr) = first(map(_get_symbol, e.args))
_get_symbol(e::Symbol) = e
end
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | code | 1740 | using Test
using DeprecateKeywords
@testset "Basic" begin
@depkws function f(; a=2, @deprecate b a)
a
end
@test f(a=1) === 1
VERSION >= v"1.8" && @test_warn "Keyword argument `b` is deprecated. Use `a` instead." (@test f(b=1) == 1)
@test f(b=nothing) === nothing
end
@testset "Multi-param" begin
@depkws function g(; α=2, γ=4, @deprecate(β, α), @deprecate(δ, γ))
α + γ
end
@test g() === 6
@test g(α=1, γ=3) === 4
if VERSION >= v"1.8"
@test_warn "Keyword argument" (@test g(β=1, γ=3) === 4)
@test_warn "Keyword argument" (@test g(α=1, δ=3) === 4)
@test_warn "Keyword argument `β`" (@test g(β=1, δ=3) === 4)
end
end
@testset "With types" begin
@depkws h(; (@deprecate old_kw new_kw), new_kw::Int=3) = new_kw
@test h() === 3
@test h(new_kw=1) === 1
VERSION >= v"1.8" && @test_warn "Keyword argument" (@test h(old_kw=1) === 1)
end
@testset "Error catching" begin
if VERSION >= v"1.8"
# Incorrect scope:
@test_throws LoadError (@eval @depkws k(; @deprecate a b, b = 10) = b)
end
# Use type assertion with no default set:
@depkws y(; a::Int, (@deprecate b a)) = a
@test y(a=1) == 1
VERSION >= v"1.8" && @test_warn "Keyword argument" (@test y(b=1) == 1)
# Type assertion should still work:
@test_throws TypeError y(a=1.0)
# We shouldn't interfere with regular kwargs:
@depkws y2(; a::Int) = a
@test y2(a=1) == 1
end
@testset "No default set" begin
@depkws k(x; (@deprecate a b), b) = x + b
VERSION >= v"1.8" && @test_throws UndefKeywordError k(1.0)
VERSION >= v"1.8" && @test_warn "Keyword argument" (@test k(1.0; a=2.0) == 3.0)
@test k(1.0; b=2.0) == 3.0
end
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | docs | 3458 | <div align="center">
# DeprecateKeywords.jl
[](https://astroautomata.com/DeprecateKeywords.jl/dev/)
[](https://github.com/MilesCranmer/DeprecateKeywords.jl/actions/workflows/CI.yml?query=branch%3Amaster)
[](https://coveralls.io/github/MilesCranmer/DeprecateKeywords.jl?branch=master)
</div>
[DeprecateKeywords.jl](https://github.com/MilesCranmer/DeprecateKeywords.jl) is a tiny package (77 lines) which defines a macro for keyword deprecation.
While normally you can use `Base.@deprecate` for deprecating functions and *arguments*, because multiple dispatch does not apply to keywords, you actually need a separate macro for using at the original function signature.
For example, let's say we wish to deprecate the keyword `old_kw1` in favor of `new_kw1`, and
and `old_kw2` in favor of `new_kw2`:
```julia
using DeprecateKeywords
@depkws function foo(; new_kw1=2, new_kw2=3,
@deprecate(old_kw1, new_kw1),
@deprecate(old_kw2, new_kw2))
return new_kw1 + new_kw2
end
```
The use of normal `@deprecate` in here is syntactic sugar to help make the signature more intuitive. The `@depkws` will simply consume the `@deprecate`s and and interpret their contents.
With this, we can use both the old and new keywords. If using the old keyword, it will automatically be passed to the new keyword, but with a deprecation warning.
```julia
julia> foo(new_kw1=1, new_kw2=2)
3
julia> foo(old_kw1=1, new_kw2=2)
┌ Warning: Keyword argument `old_kw1` is deprecated. Use `new_kw1` instead.
│ caller = top-level scope at REPL[5]:1
└ @ Core REPL[5]:1
3
```
(The warning uses `depwarn`, so is only visible if one starts with `--depwarn=yes`)
Here's what this actually gets expanded to:
```julia
function foo(; old_kw2 = DeprecatedDefault, old_kw1 = DeprecatedDefault, new_kw1 = begin
if old_kw1 !== DeprecatedDefault
Base.depwarn("Keyword argument `old_kw1` is deprecated. Use `new_kw1` instead.", :foo)
old_kw1
else
2
end
end, new_kw2 = begin
if old_kw2 !== DeprecatedDefault
Base.depwarn("Keyword argument `old_kw2` is deprecated. Use `new_kw2` instead.", :foo)
old_kw2
else
3
end
end)
new_kw1 + new_kw2
end
```
### Other notes/warnings
- I'm not 100% sure if/when this might prevent Julia from specializing to types, or if it is different from how you would set this up manually. So just be wary of major type inference issues when passing the deprecated keywords.
- This does not check whether the user passes both keyword arguments. (It might be better to use `kws...` and then pass through the old keywords within the function body. I didn't do this in my current approach so that the user could still use `kws...` in the signature if they wish.)
- This uses the very nice [MacroTools.jl](https://github.com/FluxML/MacroTools.jl) package to help make the macro generic.
Contributions very much appreciated. I'm also open to better syntax suggestions!
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"Apache-2.0"
] | 0.4.0 | 86947d8739d1a9f53612ab0a6023d4fbf214e3c9 | docs | 30 | # Usage
```@docs
@depkws
```
| DeprecateKeywords | https://github.com/MilesCranmer/DeprecateKeywords.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 870 | using PrettyTests
using Documenter
using DocumenterInterLinks
DocMeta.setdocmeta!(PrettyTests, :DocTestSetup, :(using PrettyTests; PrettyTests.disable_failure_styling()); recursive=true)
links = InterLinks(
"Julia" => "https://docs.julialang.org/en/v1/",
"numpy" => "https://numpy.org/doc/stable/",
"python" => "https://docs.python.org/3/"
);
makedocs(;
modules=[PrettyTests],
authors="Ted Papalexopoulos",
sitename="PrettyTests.jl",
doctest = true,
checkdocs = :exports,
format=Documenter.HTML(;
prettyurls = true,
canonical="https://tpapalex.github.io/PrettyTests.jl",
edit_link="dev",
assets=String[],
),
pages=[
"Home" => "index.md",
"Reference" => "reference.md",
],
plugins=[
links
]
)
deploydocs(;
repo="github.com/tpapalex/PrettyTests.jl"
)
| PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 321 | module PrettyTests
using Test, Format
using Base.Meta: isexpr
using Test: Returned, Threw, Broken
using Test: get_testset, record
using Test: do_test, do_broken_test
export @test_sets
export @test_all
include("helpers.jl")
include("test_sets.jl")
include("test_all.jl")
end | PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 4640 | ################### Global behavior variables ##################
# Whether expressions should be color coded in the output.
const STYLED_FAILURES = Ref{Bool}(get(stdout, :color, false))
# Color cycle used for expression coloring
const EXPRESSION_COLORS = (
:light_cyan,
:light_magenta,
:light_blue,
:light_green,
)
# Utility to extract the i'th color of the cycle:
get_color(i::Integer) = EXPRESSION_COLORS[(i - 1) % length(EXPRESSION_COLORS) + 1]
"""
disable_failure_styling()
Globally disable ANSI color styling in macro failure messages.
All tests macros that are run after this function will print failure messages
in plain text (or until `enable_failure_styling()` is called).
The function can be called when the module is loaded, e.g. in a `runtests.jl` file, to
disable styling throughout a test suite. Alternatively, it can be called at the beginning
of a specific [`@testset`](@extref Julia Test.@testset) and renabled at the end to disable
styling for that specific test set.
See also [`enable_failure_styling`](@ref).
"""
function disable_failure_styling()
STYLED_FAILURES[] = false
end
"""
enable_failure_styling()
Globally enable ANSI color styling in macro failure messages.
All test macros that are run after this function will print failure messages
with ANSI color styling for readability (or until `disable_failure_styling()` is called).
See also [`disable_failure_styling`](@ref).
"""
function enable_failure_styling()
STYLED_FAILURES[] = true
end
# Number of failures that are printed in a `@test_all` failures (via `print_failures()`).
const MAX_PRINT_FAILURES = Ref{Int}(10)
"""
set_max_print_failures(n=10)
Globaly sets the maximum number of individual failures that will be printed in a
failed [`@test_all`](@ref) test to `n`. If `n` is `nothing`, all failures are printed.
If `n == 0`, only a summary is printed.
By default, if there are more than `n=10` failing elements in a `@test_all`, the macro
only shows messages for the first and last `5`. Calling this function changes `n`
globally for all subsequent tests, or until the function is called again.
The function returns the previous value of `n` so that it can be restored if desired.
# Examples
```@julia-repl
julia> @test_all 1:3 .== 0
Test Failed at none:1
Expression: all(1:3 .== 0)
Evaluated: false
Argument: 3-element BitVector, 3 failures:
[1]: 1 == 0 ===> false
[2]: 2 == 0 ===> false
[3]: 3 == 0 ===> false
julia> set_max_print_failures(0);
julia> @test_all 1:3 .== 0
Test Failed at none:1
Expression: all(1:3 .== 0)
Evaluated: false
Argument: 3-element BitVector, 3 failures
```
"""
function set_max_print_failures(n::Integer=10)
@assert n >= 0
old_n = MAX_PRINT_FAILURES[]
MAX_PRINT_FAILURES[] = n
return old_n
end
set_max_print_failures(::Nothing) = set_max_print_failures(typemax(Int))
# Function to create a new IOBuffer() wrapped in an IOContext for creating
# failure messages.
function failure_ioc(;
compact::Bool=true,
limit::Bool=true,
override_color::Bool=false,
typeinfo=nothing
)
io = IOBuffer()
if typeinfo === nothing
io = IOContext(io,
:compact => compact,
:limit => limit,
:color => STYLED_FAILURES[] || override_color
)
else
io = IOContext(io,
:compact => compact,
:limit => limit,
:typeinfo => typeinfo,
:color => STYLED_FAILURES[] || override_color
)
end
return io
end
stringify!(io::IOContext) = String(take!(io.io))
# Internal function called on a test macros kws... to extract broken and skip keywords.
# Modified from Test.@test macro processing
function extract_broken_skip_keywords(kws...)
# Collect the broken/skip keywords and remove them from the rest of keywords
broken = [kw.args[2] for kw in kws
if isa(kw, Expr) && kw.head == :(=) && kw.args[1] === :broken]
skip = [kw.args[2] for kw in kws
if isa(kw, Expr) && kw.head == :(=) && kw.args[1] === :skip]
kws = filter(kw -> !isa(kw, Expr) || (kw.args[1] ∉ (:skip, :broken)), kws)
# Validation of broken/skip keywords
for (kw, name) in ((broken, :broken), (skip, :skip))
if length(kw) > 1
error("invalid test macro call: cannot set $(name) keyword multiple times")
end
end
if length(skip) > 0 && length(broken) > 0
error("invalid test macro call: cannot set both skip and broken keywords")
end
return kws, broken, skip
end
| PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 26197 | const DISPLAYABLE_FUNCS = Set{Symbol}([
:isequal,
:isapprox,
:occursin,
:startswith,
:endswith,
:isempty,
:contains,
:ismissing,
:isnan,
:isinf,
:isfinite,
:iseven,
:isodd,
:isreal,
:isa,
:ifelse,
:≈,
:≉,
])
const COMPARISON_PREC = Base.operator_precedence(:(==))
const OPS_LOGICAL = (:.&, :.|, :.⊻, :.⊽)
const OPS_APPROX = (:.≈, :.≉)
@nospecialize
#################### Pre-processing expressions ###################
# Functions to preprocess expressions for `@test_all` macro.
isvecoperator(x::Symbol) = Meta.isoperator(x) && first(string(x)) == '.'
function unvecoperator_string(x::Symbol)
sx = string(x)
if startswith(sx, ".")
return sx[2:end]
else
return sx
end
end
# Used only on :call or :. args to check if args expression is displayable:
isdisplayableargexpr(ex) = !isexpr(ex, (:kw, :parameters, :...))
# Preprocess `@test_all` expressions of function calls with trailing keyword arguments,
# so that e.g. `@test_all a .≈ b atol=ε` means `@test_all .≈(a, b, atol=ε)`.
# If `ex` is a negation expression (either a `!` or `.!` call), keyword arguments will
# be added to the inner expression, so that `@test_all .!(a .≈ b) atol=ε` means
# `@test_all .!(.≈(a, b, atol=ε))`.
pushkeywords!(ex) = ex
function pushkeywords!(ex, kws...)
# Recursively dive through negations
orig_ex = ex
if isexpr(ex, :call, 2) && (ex.args[1] === :! || ex.args[1] === :.!)
ex = ex.args[2]
end
# Check that inner expression is a :call or :.
if !isexpr(ex, (:call, :.))
error("invalid test macro call: @test_all $ex does not accept keyword arguments")
end
# Push keywords to the end of arguments as keyword expressions
args = ex.head === :call ? ex.args : ex.args[2].args
for kw in kws
if isexpr(kw, :(=))
kw.head = :kw
push!(args, kw)
else
error("invalid test macro call: $kw is not valid keyword syntax")
end
end
return orig_ex
end
# An internal function, recursively called on the @test_all expression to normalize it.
function preprocess_test_all(ex)
# Normalize dot comparison operator calls to :comparison expressions.
# Do not if there are extra arguments or there are splats.
if Meta.isexpr(ex, :call, 3) &&
isvecoperator(ex.args[1]::Symbol) &&
Base.operator_precedence(ex.args[1]) == COMPARISON_PREC &&
isdisplayableargexpr(ex.args[2]) &&
isdisplayableargexpr(ex.args[3])
ex = Expr(:comparison, ex.args[2], ex.args[1], ex.args[3])
# For displayable :call or :. expressions, push :kw expressions in :parameters to
# end of arguments.
elseif isexpr(ex, (:call, :.)) &&
((ex.args[1]::Symbol ∈ OPS_APPROX) || (ex.args[1]::Symbol ∈ DISPLAYABLE_FUNCS))
# For :call arguments start at i = 2
# For :. they start at i = 1, inside the ex.args[2] :tuple expression
args, i = ex.head === :call ? (ex.args, 2) : (ex.args[2].args, 1)
# Push any :kw expressions in :parameters as trailing keywords
if length(args) != 0 && isexpr(args[i], :parameters)
parex = args[i]
new_args = args[i+1:end]
new_parex_args = []
for a in parex.args
if isexpr(a, :kw)
push!(new_args, a)
else
push!(new_parex_args)
end
end
# If remaining :parameters, readd at beginning of args
if length(new_parex_args) > 0
insert!(new_args, 1, Expr(:parameters, new_parex_args...))
end
# Depending on head, recreate expression
if ex.head === :call
ex = Expr(:call, ex.args[1], new_args...)
else
ex = Expr(:., ex.args[1], Expr(:tuple, new_args...))
end
end
end
return ex
end
#################### Classifying expressions ###################
# The following internal functions are used to classify expressions into
# certain groups that will be displayed differently by `@test_all`.
# NOT expressions, e.g. !a
isvecnegationexpr(ex) = isexpr(ex, :call, 2) && ex.args[1]::Symbol === :.!
# Vectorized AND or OR expressions, e.g, a .&& b, a .|| c
isveclogicalexpr(ex) = isexpr(ex, :call) && ex.args[1]::Symbol ∈ OPS_LOGICAL
# Vectorized comparison expressions, e.g. a .== b, a .<= b .> c, a .≈ B. Note that :call
# expressions with comparison ops are changed to :comparison in preprocess_test_all().
function isveccomparisonexpr(ex)
if isexpr(ex, :comparison)
for i in 2:2:length(ex.args)
if !isvecoperator(ex.args[i]::Symbol)
return false
end
end
return true
else
return false
end
end
# Special case of .≈ or .≉ calls with kws (and no splats), for formatting as comparison
function isvecapproxexpr(ex)
return isexpr(ex, :call) &&
ex.args[1]::Symbol ∈ OPS_APPROX &&
isdisplayableargexpr(ex.args[2]) &&
isdisplayableargexpr(ex.args[3])
end
# Vectorized :. call to displayable function (with no splats)
function isvecdisplayexpr(ex)
if isexpr(ex, :., 2) &&
ex.args[1]::Symbol ∈ DISPLAYABLE_FUNCS &&
isexpr(ex.args[2], :tuple)
for a in ex.args[2].args
if isexpr(a, :...)
return false
end
end
return true
else
return false
end
end
#################### Pretty-printing utilities ###################
# An internal, IO-like object, used to dynamically produce a `Format.FormatExpr`-like
# string representation of the unvectorized @test_all expression.
struct Formatter
ioc::IOContext{IOBuffer}
parens::Bool
function Formatter(parens::Bool)
ioc = failure_ioc()
parens && print(ioc, "(")
return new(ioc, parens)
end
end
function stringify!(fmt::Formatter)
fmt.parens && print(fmt.ioc, ")")
return stringify!(fmt.ioc)
end
function Base.print(fmt::Formatter, strs::AbstractString...; i::Integer=0)
if i == 0
print(fmt.ioc, strs...)
else
printstyled(fmt.ioc, strs..., color=get_color(i))
end
end
function Base.print(fmt::Formatter, innerfmt::Formatter)
print(fmt.ioc, stringify!(innerfmt))
close(innerfmt.ioc)
end
function Base.print(fmt::Formatter, s; i::Integer=0)
print(fmt, string(s); i=i)
end
# Matches indenteation of TypeError in @test_all error message
const _INDENT_TYPEERROR = " ";
# Matches indenteation of "Evaluated:" expression in @test_all fail message
const _INDENT_EVALUATED = " ";
# Stringifies indices returned by findall() for pretty printing
function stringify_idxs(idxs::Vector{CartesianIndex{D}}) where D
maxlens = [maximum(idx -> ndigits(idx.I[d]), idxs) for d in 1:D]
to_str = idx -> join(map(i -> lpad(idx.I[i], maxlens[i]), 1:D), ",")
return map(to_str, idxs)
end
function stringify_idxs(idxs::AbstractVector{<:Integer})
maxlen = maximum(ndigits, idxs)
return lpad.(string.(idxs), maxlen)
end
function stringify_idxs(idxs::AbstractVector)
ss = string.(idxs)
maxlen = maximum(length, ss)
return lpad.(ss, maxlen)
end
# Prints the individual failures in a @test_all test, given the indices of the failures
# and a function to print an individual failure.
function print_failures(
io::IO,
idxs::AbstractVector,
print_idx_failure,
prefix=""
)
# Depending on MAX_PRINT_FAILURES, filter the failiing indices to some subset.
MAX_PRINT_FAILURES[] == 0 && return
if length(idxs) > MAX_PRINT_FAILURES[]
i_dots = (MAX_PRINT_FAILURES[] ÷ 2)
if MAX_PRINT_FAILURES[] % 2 == 1
i_dots = i_dots + 1
idxs = idxs[[1:i_dots; end-i_dots+2:end]]
else
idxs = idxs[[1:i_dots; end-i_dots+1:end]]
end
else
i_dots = 0
end
# Pretty print the failures with the provided function
str_idxs = stringify_idxs(idxs)
for (i, idx) in enumerate(idxs)
print(io, "\n", prefix, "[", str_idxs[i], "]: ")
print_idx_failure(io, idx)
if i == i_dots
print(io, "\n", prefix, "⋮")
end
end
return
end
# An internal exception type, thrown (and later caught by the `Test` infrastructure), when
# non-Boolean, non-Missing values are encountered in an evaluated `@test_all` expression.
# It's constructed directly from the result of evaluting the expression, and pretty-prints
# the non-Boolean values.
struct NonBoolTypeError <: Exception
msg::String
# Constructor when the evaluated expression is a vector or array: pretty-print the
# the non-Boolean indices.
function NonBoolTypeError(evaled::AbstractArray)
io = failure_ioc(typeinfo = eltype(evaled))
# First print the summary:
n_nonbool = sum(x -> x !== true && x !== false && x !== missing, evaled, init=0)
summary(io, evaled)
print(io, " with ", n_nonbool, " non-Boolean value", n_nonbool == 1 ? "" : "s")
if MAX_PRINT_FAILURES[] == 0
return new(stringify!(io))
end
# Avoid allocating vector with `findall()` if only a few failures need to be
# printed.
print(io, ":")
if MAX_PRINT_FAILURES[] == 1
idxs = [findfirst(x -> x !== true && x !== false && x !== missing, evaled)]
else
idxs = findall(x -> x !== true && x !== false && x !== missing, evaled)
end
# Get the pretty-printing function for each index
print_idx_failure = (io, idx) -> begin
if evaled[idx] isa Union{Symbol,AbstractString}
print(io, repr(evaled[idx]))
else
print(io, evaled[idx])
end
printstyled(io, " ===> ", typeof(evaled[idx]), color=:light_yellow)
end
print_failures(io, idxs, print_idx_failure, _INDENT_TYPEERROR)
return new(stringify!(io))
end
function NonBoolTypeError(evaled)
io = failure_ioc(typeinfo = typeof(evaled))
print(io, evaled)
printstyled(io, " ===> ", typeof(evaled), color=:light_yellow)
return new(stringify!(io))
end
end
function Base.showerror(io::IO, err::NonBoolTypeError)
print(io, " TypeError: non-boolean used in boolean context")
if err.msg != ""
print(io, "\n Argument: ", err.msg)
end
end
#################### Escaping arguments ###################
# Internal functions to process an expression `ex` for use in `@test_all`. Recursively
# builds `escargs`, the vector of "broadcasted" sub-expressions. Returns a modified
# expression `ex` with references to `ARG[i]`, and two `Formatter` objects: one with
# a pretty-printed string representation of `ex`, and one with python-like format
# entries ("{i:s}"), that can be used to pretty-print individual failure messages.
# Example: a .== b
# 1) Adds `a` and `b` as escaped expressions to `escargs`
# 2) Return [1] is a modified `ex` as `ARG[1] .== ARG[2]`
# 3) Return [2] a Formatter with the pretty-printed string "a .== b"
# 4) Return [3] a Formatter with the format string "{1:s} == {2:s}"
function recurse_process!(ex, escargs::Vector{Expr}; outmost::Bool=false)
ex = preprocess_test_all(ex)
if isexpr(ex, :kw)
return recurse_process_keyword!(ex, escargs, outmost=outmost)
elseif isvecnegationexpr(ex)
return recurse_process_negation!(ex, escargs, outmost=outmost)
elseif isveclogicalexpr(ex)
return recurse_process_logical!(ex, escargs, outmost=outmost)
elseif isveccomparisonexpr(ex)
return recurse_process_comparison!(ex, escargs, outmost=outmost)
elseif isvecapproxexpr(ex)
return recurse_process_approx!(ex, escargs, outmost=outmost)
elseif isvecdisplayexpr(ex)
return recurse_process_displayfunc!(ex, escargs, outmost=outmost)
else
return recurse_process_basecase!(ex, escargs, outmost=outmost)
end
end
function recurse_process_basecase!(ex, escargs::Vector{Expr}; outmost::Bool=false)
# Escape entire expression to args
push!(escargs, esc(ex))
# Determine if parens are needed around the pretty-printed expression:
parens = if outmost
false
elseif isexpr(ex, :call) && Meta.isbinaryoperator(ex.args[1]::Symbol)
# Range definition, e.g. 1:5
if ex.args[1] === :(:)
false
# scalar multiplication, e.g. 100x
elseif ex.args[1] === :* &&
length(ex.args) == 3 &&
isa(ex.args[2], Union{Int, Int64, Float32, Float64}) &&
isa(ex.args[3], Symbol)
false
# Other binary operator expressions
else
true
end
elseif isexpr(ex, (:&&, :||))
true
else
false
end
# Pretty-print the expression using Base.show_unquoted for the base-case:
str = Formatter(parens)
print(str, sprint(Base.show_unquoted, ex), i=length(escargs))
# Simplest format string {i:s} for the base-case (no parens since evaluated value
# will be printed):
fmt = Formatter(false)
print(fmt, "{$(length(escargs)):s}", i=length(escargs))
# Replace the expression with ARG[i]
ex = :(ARG[$(length(escargs))])
return ex, str, fmt
end
function recurse_process_keyword!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
# Keyword argument values are pushed to escaped `args`, but should be
# wrapped in a Ref() call to avoid broadcasting.
push!(escargs, esc(Expr(:call, :Ref, ex.args[2])))
str = Formatter(false)
print(str, ex.args[1])
print(str, "=")
print(str, sprint(Base.show_unquoted, ex.args[2]), i=length(escargs))
fmt = Formatter(false)
print(fmt, ex.args[1])
print(fmt, "=")
print(fmt, "{$(length(escargs)):s}", i=length(escargs))
# Replace keyword argument with ARG[i].x to un-Ref() in evaluation
ex.args[2] = :(ARG[$(length(escargs))].x)
return ex, str, fmt
end
function recurse_process_negation!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
# Recursively update the second argument
ex.args[2], str_arg, fmt_arg = recurse_process!(ex.args[2], escargs)
# Never requires parentheses outside the negation
str = Formatter(false)
print(str, ex.args[1])
print(str, str_arg)
fmt = Formatter(false)
print(fmt, "!")
print(fmt, fmt_arg)
# Escape negation operator
ex.args[1] = esc(ex.args[1])
return ex, str, fmt
end
function recurse_process_logical!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
str = Formatter(!outmost)
fmt = Formatter(!outmost)
for i in 2:length(ex.args)
# Recursively update the two arguments. If a sub-expression is also logical,
# there is no need to parenthesize so consider it `outmost=true`.
ex.args[i], str_arg, fmt_arg = recurse_process!(
ex.args[i], escargs, outmost=isveclogicalexpr(ex.args[i]))
# Unless it's the first argument, print the operator
i == 2 || print(str, " ", string(ex.args[1]), " ")
i == 2 || print(fmt, " ", unvecoperator_string(ex.args[1]), " ")
print(str, str_arg)
print(fmt, fmt_arg)
end
# Escape the operator
ex.args[1] = esc(ex.args[1])
return ex, str, fmt
end
function recurse_process_comparison!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
str = Formatter(!outmost)
fmt = Formatter(!outmost)
# Recursively update every other argument (i.e. the terms), and
# escape the operators.
for i in eachindex(ex.args)
if i % 2 == 1 # Term
ex.args[i], str_arg, fmt_arg = recurse_process!(ex.args[i], escargs)
print(str, str_arg)
print(fmt, fmt_arg)
else # Operator
print(str, " ", string(ex.args[i]), " ")
print(fmt, " ", unvecoperator_string(ex.args[i]), " ")
ex.args[i] = esc(ex.args[i])
end
end
return ex, str, fmt
end
function recurse_process_approx!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
# Recursively update both positional arguments
ex.args[2], str_arg2, fmt_arg2 = recurse_process!(ex.args[2], escargs)
ex.args[3], str_arg3, fmt_arg3 = recurse_process!(ex.args[3], escargs)
# If outmost, format as comparison, otherwise as a function call
str = Formatter(false)
print(str, string(ex.args[1]))
print(str, "(")
print(str, str_arg2)
print(str, ", ")
print(str, str_arg3)
print(str, ", ")
fmt = Formatter(false)
if outmost
print(fmt, fmt_arg2)
print(fmt, " ", unvecoperator_string(ex.args[1]), " ")
print(fmt, fmt_arg3)
print(fmt, " (")
else
print(fmt, unvecoperator_string(ex.args[1]))
print(fmt, "(")
print(fmt, fmt_arg2)
print(fmt, ", ")
print(fmt, fmt_arg3)
print(fmt, ", ")
end
# Recursively update with keyword arguments
for i in 4:length(ex.args)
ex.args[i], str_arg, fmt_arg = recurse_process!(ex.args[i], escargs)
print(str, str_arg)
print(fmt, fmt_arg)
i == length(ex.args) || print(str, ", ")
i == length(ex.args) || print(fmt, ", ")
end
print(str, ")")
print(fmt, ")")
# Escape function
ex.args[1] = esc(ex.args[1])
return ex, str, fmt
end
function recurse_process_displayfunc!(ex::Expr, escargs::Vector{Expr}; outmost::Bool=false)
ex_args = ex.args[2].args
str = Formatter(false)
fmt = Formatter(false)
print(str, string(ex.args[1]), ".(")
print(fmt, string(ex.args[1]), "(")
for i in eachindex(ex_args)
ex_args[i], str_arg, fmt_arg = recurse_process!(ex_args[i], escargs, outmost=true)
print(str, str_arg)
print(fmt, fmt_arg)
i == length(ex_args) || print(str, ", ")
i == length(ex_args) || print(fmt, ", ")
end
print(str, ")")
print(fmt, ")")
# Escape the function name
ex.args[1] = esc(ex.args[1])
return ex, str, fmt
end
# Internal function used at `@test_all` runtime to get a `Returned` `Test.ExecutionResult`
# with nice failure messages. Used in the code generated by `get_test_all_result()` at
# compile time.
# - `evaled`: the result of evaluating the processed expression returned by
# `recurse_process!` (the one with references to `ARG[i]`)
# - `terms`: a vector of all terms that were broadcasted to produce `evaled`, which can
# be used to produce individual failure messages. It is the result of evaluating and
# concatenating the escaped arguments extracted by `recurse_process!()` into a vector.
# - `fmt_term`: a FormatExpr-like string for pretty-printing an individual failure. It is the
# result of `stringify!(f)` on the `Formatter` returned by `recurse_process!()`.
function eval_test_all(
@nospecialize(evaled),
@nospecialize(terms),
fmt::String,
source::LineNumberNode)
# If evaled contains non-Bool values, throw a NonBoolTypeError with pretty-printed
# message. Need the evaled !== missing check to avoid a MethodError for iterate(missing).
if evaled !== missing && any(x -> x !== true && x !== false && x !== missing, evaled)
throw(NonBoolTypeError(evaled))
end
# Compute the result of the all() call:
res = evaled === missing ? missing : all(evaled)
# If all() returns true, no need for pretty printing anything.
res === true && return Returned(true, nothing, source)
# Broadcast the input terms and compile the formatting expression for pretty printing.
# Wrap in a try catch/block, so that we can fallback to a simple message if the
# some terms are not broadcastable, or if the size of the broadcasted terms
# does not match the size of the evaluated result (I believe the latter should not
# happen, but better safe than sorry).
# try
broadcasted_terms = Base.broadcasted(tuple, terms...)
# size(broadcasted_terms) == size(evaled) || Broad)
fmt = FormatExpr(fmt)
# Print the evaluated result:
io = failure_ioc()
print(io, res)
print(io, "\n Argument: ")
# Print a nice message. If the evaluated result (evaled) is a Bool or Missing (not
# a vector or array), print a simple message:
if isa(evaled, Union{Bool,Missing})
terms = repr.(first(broadcasted_terms))
printfmt(io, fmt, terms...)
printstyled(io, " ===> ", evaled, color=:light_yellow)
# Otherwise, use pretty-printing with indices. Note that we are guaranteed that
# eltype(evaled) <: Union{Missing,Bool}.
else
# First, print type of inner expression and number of false/missing values
summary(io, evaled)
n_missing = sum(x -> ismissing(x), evaled)
n_false = sum(x -> !x, skipmissing(evaled), init=0)
print(io, ", ")
if n_missing > 0
print(io, n_missing, " missing")
n_false == 0 || print(io, " and ")
end
if n_false > 0
print(io, n_false, " failure", n_false == 1 ? "" : "s")
end
# Avoid allocating with `findall()` if only a few failures need to be printed.
if MAX_PRINT_FAILURES[] == 0
return Returned(false, stringify!(io), source)
end
idxs = try
if MAX_PRINT_FAILURES[] == 1
[findfirst(x -> x !== true, evaled)]
else
findall(x -> x !== true, evaled)
end
catch
return Returned(false, stringify!(io), source)
end
print(io, ": ")
print_idx_message = (io, idx) -> begin
printfmt(io, fmt, repr.(broadcasted_terms[idx])...)
printstyled(io, " ===> ", evaled[idx], color=:light_yellow)
end
print_failures(io, idxs, print_idx_message, _INDENT_EVALUATED)
end
return Returned(false, stringify!(io), source)
end
# Internal function used at compile time to generate code that will produce the final
# `@test_all` `Test.ExecutionResult`. Wraps `eval_test_all()` in a try/catch block
# so that exceptions can be returned as `Test.Threw` result.
function get_test_all_result(ex, source)
escaped_args = Expr[]
mod_ex, str, fmt = recurse_process!(ex, escaped_args; outmost=true)
str, fmt = stringify!(str), stringify!(fmt)
result = quote
try
let ARG = Any[$(escaped_args...)] # Use `let` for local scope on `ARG`
eval_test_all(
$(mod_ex),
ARG,
$(fmt),
$(QuoteNode(source))
)
end
catch _e
_e isa InterruptException && rethrow()
Threw(_e, Base.current_exceptions(), $(QuoteNode(source)))
end
end
return result, str
end
"""
@test_all ex
@test_all f(args...) key=val ...
@test_all ex broken=true
@test_all ex skip=true
Test that the expression `all(ex)` evaluates to `true`. Does not short-circuit at
the first `false` value, so that all `false` elements are shown in case of failure.
Same return behaviour as [`Test.@test`](@extref Julia), namely: if executed inside a
`@testset`, returns a `Pass` `Result` if `all(ex)` evaluates to `true`, a `Fail` `Result`
if it evaluates to `false` or `missing`, and an `Error` `Result` if it could not be
evaluated. If executed outside a `@testset`, throws an exception instead of returning
`Fail` or `Error`.
# Examples
```@julia-repl
julia> @test_all [1.0, 2.0] .== [1, 2]
Test Passed
julia> @test_all [1, 2, 3] .< 2
Test Failed at none:1
Expression: all([1, 2, 3] .< 2)
Evaluated: false
Argument: 3-element BitVector, 2 failures:
[2]: 2 < 2 ===> false
[3]: 3 < 2 ===> false
```
Similar to `@test`, the `@test_all f(args...) key=val...` form is equivalent to writing
`@test_all f(args...; key=val...)` which can be useful when the expression is a call
using infix syntax such as vectorized approximate comparisons:
```@julia-repl
julia> v = [0.99, 1.0, 1.01];
julia> @test_all v .≈ 1 atol=0.1
Test Passed
```
This is equivalent to the uglier test `@test_all .≈(v, 1, atol=0.1)`.
Keyword splicing also works through any negation operator:
```@julia-repl
julia> @test_all .!(v .≈ 1) atol=0.001
Test Failed at none:1
Expression: all(.!.≈(v, 1, atol=0.001))
Evaluated: false
Argument: 3-element BitVector, 1 failure:
[2]: !≈(1.0, 1, atol=0.001) ===> false
```
As with `@test`, it is an error to supply more than one expression unless
the first is a call (possibly broadcast `.` syntax) and the rest are
assignments (`k=v`).
The macro supports `broken=true` and `skip=true` keywords, with similar behavior
to [`Test.@test`](@extref Julia):
```@julia-repl
julia> @test_all [1, 2] .< 2 broken=true
Test Broken
Expression: all([1, 2] .< 2)
julia> @test_all [1, 2] .< 3 broken=true
Error During Test at none:1
Unexpected Pass
Expression: all([1, 2] .< 3)
Got correct result, please change to @test if no longer broken.
julia> @test_all [1, 2, 3] .< 2 skip=true
Test Broken
Skipped: all([1, 2, 3] .< 2)
```
"""
macro test_all(ex, kws...)
# Collect the broken/skip keywords and remove them from the rest of keywords:
kws, broken, skip = extract_broken_skip_keywords(kws...)
# Add keywords to the expression
ex = pushkeywords!(ex, kws...)
# Generate code to evaluate expression and return a `Test.ExecutionResult`
result, str_ex = get_test_all_result(ex, __source__)
str_ex = "all($str_ex)"
# Copy `Test` code to create `Test.Result` using `do_test` or `do_broken_test`
result = quote
if $(length(skip) > 0 && esc(skip[1]))
record(get_testset(), Broken(:skipped, $str_ex))
else
let _do = $(length(broken) > 0 && esc(broken[1])) ? do_broken_test : do_test
_do($result, $str_ex)
end
end
end
return result
end
@specialize | PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 10916 | # Set of valid operators for @test_sets
const OPS_SETCOMP = (
:(==),
:≠,
:⊆,
:⊇,
:⊊,
:⊋,
:∩,
)
# Additional valid operators that are converted in `preprocess`
const OPS_SETCOMP_CONVERTER = Dict(
:!= => :≠,
:⊂ => :⊆,
:⊃ => :⊇,
:|| => :∩,
:issetequal => :(==),
:isdisjoint => :∩,
:issubset => :⊆,
)
#################### Pretty printing utilities ###################
# Match indentation of @test "Evaluated: " line
const _INDENT_SETOP = " ";
function printLsepR(
io::IO,
L::AbstractString,
sep::AbstractString,
R::AbstractString,
suffixes::AbstractString...
)
printstyled(io, L, color=EXPRESSION_COLORS[1])
print(io, " ")
print(io, sep)
print(io, " ")
printstyled(io, R, color=EXPRESSION_COLORS[2])
print(io, suffixes...)
end
const LminusR = "L ∖ R"
const RminusL = "R ∖ L"
const LequalR = "L = R"
const LintersectR = "L ∩ R"
# Print a set or vector compactly, with a description:
function printset(io::IO, v::Union{AbstractVector, AbstractSet}, desc::AbstractString)
n = length(v)
print(io, "\n", _INDENT_SETOP)
print(io, desc)
print(io, " has ", n, " element", n == 1 ? ": " : "s: ")
Base.show_vector(IOContext(io, :typeinfo => typeof(v)), v)
end
function printset(io::IO, v, desc::AbstractString)
printset(io, collect(v), desc)
end
# Stringify a processed `@test_sets` expression, to be printed in the `@test`
# `Evaluated: ` line.
function stringify_expr_test_sets(ex)
suffix = ex.args[1] === :∩ ? " == ∅" : ""
str = sprint(
printLsepR,
sprint(Base.show_unquoted, ex.args[2]),
sprint(Base.show_unquoted, ex.args[1]),
sprint(Base.show_unquoted, ex.args[3]),
suffix,
context = :color => STYLED_FAILURES[]
)
return str
end
#################### Evaluating @test_sets ###################
# Internal function to process an expression `ex` for use in `@test_sets`. Validates
# the form `L <op> R` and convert any operator aliases to the canonical version.
function process_expr_test_sets(ex)
# Special case `a ∩ b == ∅` or `∅ == a ∩ b` gets converted to `a ∩ b`
if isexpr(ex, :call, 3) && ex.args[1] === :(==)
if isexpr(ex.args[2], :call, 3) && ex.args[2].args[1] === :∩ && ex.args[3] === :∅
ex = ex.args[2]
elseif isexpr(ex.args[3], :call, 3) && ex.args[3].args[1] === :∩ && ex.args[2] === :∅
ex = ex.args[3]
end
end
if isexpr(ex, :call, 3)
op, L, R = ex.args
op = get(OPS_SETCOMP_CONVERTER, op, op)
if op ∉ OPS_SETCOMP
if Meta.isoperator(op)
error("invalid test macro call: @test_set unsupported set operator $op")
else
error("invalid test macro call: @test_set $ex")
end
end
elseif isexpr(ex, :||, 2)
op = :∩
L, R = ex.args
else
error("invalid test macro call: @test_set $ex")
end
return Expr(:call, op, L, R)
end
# Internal function used at `@test_sets` runtime to get a `Returned` `Test.ExecutionResult`
# with nice failure messages. Used in the code generated by `get_test_sets_result()` at
# compile time.
# - `L`: the container on the left side of the operator
# - `op`: the operator, one of `OPS_SETCOMP`
# - `R`: the container on the right side of the operator
function eval_test_sets(L, op, R, source)
# Perform the desired set operation to get the boolean result:
if op === :(==)
res = issetequal(L, R)
elseif op === :≠
res = !issetequal(L, R)
elseif op === :∩
res = isdisjoint(L, R)
elseif op === :⊊
res = issubset(L, R) && !issetequal(L, R)
elseif op === :⊋
res = issubset(R, L) && !issetequal(L, R)
elseif op === :⊆
res = issubset(L, R)
elseif op === :⊇
res = issubset(R, L)
else
error("Unsupported operator $op.")
end
# If the result is false, create a custom failure message depending on the operator:
if res === false
io = failure_ioc()
if op === :(==) # issetequal(L, R)
printLsepR(io, "L", "and", "R", " are not equal.")
printset(io, setdiff(L, R), LminusR)
printset(io, setdiff(R, L), RminusL)
elseif op === :!= || op === :≠ # !issetequal(L, R)
printLsepR(io, "L", "and", "R", " are equal.")
printset(io, intersect(L, R), LequalR)
elseif op === :⊆ # issubset(L, R)
printLsepR(io, "L", "is not a subset of", "R", ".")
printset(io, setdiff(L, R), LminusR)
elseif op === :⊇ # issubset(R, L)
printLsepR(io, "L", "is not a superset of", "R", ".")
printset(io, setdiff(R, L), RminusL)
elseif op === :⊊ && issetequal(L, R) # L ⊊ R (failure b/c not *proper* subset)
printLsepR(io, "L", "is not a proper subset of", "R", ", it is equal.")
printset(io, intersect(L, R), LequalR)
elseif op === :⊊ # L ⊊ R (failure because L has extra elements)
printLsepR(io, "L", "is not a proper subset of", "R", ".")
printset(io, setdiff(L, R), LminusR)
elseif op === :⊋ && issetequal(L, R) # L ⊋ R (failure b/c not *proper* superset)
printLsepR(io, "L", "is not a proper superset of", "R", ", it is equal.")
printset(io, intersect(L, R), LequalR)
elseif op === :⊋ # L ⊋ R (failure because R has extra elements)
printLsepR(io, "L", "is not a proper superset of", "R", ".")
printset(io, setdiff(R, L), RminusL)
elseif op === :∩ # isdisjoint(L, R)
printLsepR(io, "L", "and", "R", " are not disjoint.")
printset(io, intersect(L, R), LintersectR)
else
error("Unsupported operator $op.")
end
return Returned(res, stringify!(io), source)
else # res === true
return Returned(res, nothing, source)
end
end
# Internal function used at compile time to generate code that will produce the final
# `@test_sets` `Test.ExecutionResults`. Wraps `eval_test_sets()` in a try/catch block
# so that exceptions can be returned as `Test.Threw` result.
function get_test_sets_result(ex, source)
op, L, R = ex.args
if L === :∅ L = :(Set()) end
if R === :∅ R = :(Set()) end
result = quote
try
eval_test_sets(
$(esc(L)),
$(QuoteNode(op)),
$(esc(R)),
$(QuoteNode(source))
)
catch _e
_e isa InterruptException && rethrow()
Threw(_e, Base.current_exceptions(), $(QuoteNode(source)))
end
end
result
end
"""
@test_sets L op R
@test_sets L op R broken=true
@test_sets L op R skip=true
Test that the expression `L op R` evaluates to `true`, where `op` is an infix operator
interpreted as a set-like comparison:
- `L == R` expands to `issetequal(L, R)`
- `L != R` or `L ≠ R` expands to `!issetequal(L, R)`
- `L ⊆ R` or `L ⊂ R` expands to `issubset(L, R)`
- `L ⊇ R` or `L ⊃ R` expands to `issubset(R, L)`
- `L ⊊ R` expands to `issubset(L, R) && !issetequal(L, R)`
- `L ⊋ R` expands to `issubset(R, L) && !issetequal(L, R)`
- `L ∩ R` or `L || R` expands to `isdisjoint(L, R)`
Same return behaviour as [`Test.@test`](@extref Julia), namely: if executed inside a
`@testset`, returns a `Pass` `Result` if expanded expression evaluates to `true`, a `Fail`
`Result` if it evaluates to `false`, and an `Error` `Result` if it could not be
evaluated. If executed outside a `@testset`, throws an exception instead of returning
`Fail` or `Error`.
You can use any `L` and `R` that work with the expanded expressions above (including
tuples, arrays, sets, dictionaries, strings, and more generable iterables). The `∅`
symbol can also be used as shorthand for `Set()`.
The only additional limitation is that `setdiff(L, R)` and `intersect(L, R)` must also
work, since they are used to generate informative failure messages in some cases.
See also: [`Base.issetequal`](@extref Julia), [`Base.issubset`](@extref Julia),
[`Base.isdisjoint`](@extref Julia), [`Base.setdiff`](@extref Julia),
[`Base.intersect`](@extref Julia).
!!! note "Disjointness"
The last form represents a slight abuse of notation, in that `isdisjoint(L, R)` is
better notated as `L ∩ R == ∅`. The macro also supports this syntax, in addition
to shorthand `L ∩ R` and `L || R`.
!!! note "Typing unicode characters"
Unicode operators can be typed in Julia editors by writing
`\\<name><tab>`. The ones supported by this macro are `≠` (`\\neq`),
`⊆` (`\\subseteq`), `⊇` (`\\supseteq`), `⊂` (`\\subset`), `⊃` (`\\supset`),
`⊊` (`\\subsetneq`), `⊋` (`\\supsetneq`), `∩` (`\\cap`), and `∅` (`\\emptyset`).
# Examples
```@julia-repl
julia> @test_sets (1, 2) == (2, 1, 1, 1)
Test Passed
julia> @test_sets ∅ ⊆ 1:5
Test Passed
julia> @test_sets 1:3 ⊇ 5
Test Failed at none:1
Expression: 1:3 ⊇ 5
Evaluated: L is not a superset of R.
R ∖ L has 1 element: [5]
julia> @test_sets [1, 2, 3] ∩ [2, 3, 4]
Test Failed at none:1
Expression: [1, 2, 3] ∩ [2, 3, 4] == ∅
Evaluated: L and R are not disjoint.
L ∩ R has 2 elements: [2, 3]
julia> @test_sets "baabaa" ≠ 'a':'b'
Test Failed at none:1
Expression: "baabaa" ≠ 'a':'b'
Evaluated: L and R are equal.
L = R has 2 elements: ['b', 'a']
```
The macro supports `broken=cond` and `skip=cond` keywords, with similar behavior
to [`Test.@test`](@extref Julia):
# Examples
```@julia-repl
julia> @test_sets [1] ⊆ [2, 3] broken=true
Test Broken
Expression: [1] ⊆ [2, 3]
julia> @test_sets [1] ⊆ [1, 2] broken=true
Error During Test at none:1
Unexpected Pass
Expression: [1] ⊆ [1, 2]
Got correct result, please change to @test if no longer broken.
julia> @test_sets [1] ⊆ [2, 3] skip=true
Test Broken
Skipped: [1] ⊆ [2, 3]
```
"""
macro test_sets(ex, kws...)
# Collect the broken/skip keywords and remove them from the rest of keywords:
kws, broken, skip = extract_broken_skip_keywords(kws...)
# Ensure that no other expressions are present
length(kws) == 0 || error("invalid test macro call: @test_sets $ex $(join(kws, " "))")
# Process expression and get stringified version
ex = process_expr_test_sets(ex)
str_ex = stringify_expr_test_sets(ex)
# Generate code to evaluate expression and return a `Test.ExecutionResult`
result = get_test_sets_result(ex, __source__)
result = quote
if $(length(skip) > 0 && esc(skip[1]))
record(get_testset(), Broken(:skipped, $str_ex))
else
let _do = $(length(broken) > 0 && esc(broken[1])) ? do_broken_test : do_test
_do($result, $str_ex)
end
end
end
end | PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
|
[
"MIT"
] | 0.1.1 | 731532d7a03845a784a5a5e4e9a7b4993830032c | code | 812 | @testset "helpers.jl" begin
@testset "failure_styling" begin
@test !PT.disable_failure_styling()
@test PT.STYLED_FAILURES[] === false
@test PT.enable_failure_styling()
@test PT.STYLED_FAILURES[] === true
@test !PT.disable_failure_styling()
@test PT.STYLED_FAILURES[] === false
end
@testset "max_print_failures" begin
PT.set_max_print_failures(0)
@test PT.MAX_PRINT_FAILURES[] == 0
@test PT.set_max_print_failures(5) == 0 # returns previous value
@test PT.MAX_PRINT_FAILURES[] == 5
@test PT.set_max_print_failures(nothing) == 5
@test PT.MAX_PRINT_FAILURES[] == typemax(Int)
@test PT.set_max_print_failures() == typemax(Int)
@test PT.MAX_PRINT_FAILURES[] == 10 # default is 10
end
end | PrettyTests | https://github.com/tpapalex/PrettyTests.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.