licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 6810 | """
Lattice
Struct containing the unitcell, sites and bonds of a lattice graph.
Additionally a set of sites to verify symmetry transformations is provided.
* `name :: String` : name of the lattice
* `size :: Int64` : bond truncation of the lattice
* `uc :: Unitcell` : unitcell of the lattice
* `test_sites :: Vector{Site}` : minimal set of test sites to verify symmetry transformations
* `sites :: Vector{Site}` : list of sites in the lattice
* `bonds :: Matrix{Bond}` : matrix encoding the interactions between arbitrary lattice sites
"""
struct Lattice
name :: String
size :: Int64
uc :: Unitcell
test_sites :: Vector{Site}
sites :: Vector{Site}
bonds :: Matrix{Bond}
end
"""
get_lattice(
name :: String,
size :: Int64
;
verbose :: Bool = true,
euclidean :: Bool = false
) :: Lattice
Returns lattice graph with maximum bond distance size from origin (Euclidean distance in units of the nearest neighbor norm for euclidean == true).
Use `lattice_avail` to print available lattices.
"""
function get_lattice(
name :: String,
size :: Int64
;
verbose :: Bool = true,
euclidean :: Bool = false
) :: Lattice
if verbose
if euclidean
println("Building lattice $(name) with maximum Euclidean distance $(size) ...")
else
println("Building lattice $(name) with maximum bond distance $(size) ...")
end
end
# get unitcell
uc = get_unitcell(name)
# get test sites
test_sites, metric = get_test_sites(uc, euclidean)
# assure that the lattice is at least as large as the test set
if euclidean
@assert metric <= size * norm(get_vec(test_sites[1].int + uc.bonds[1][1], uc)) "Lattice is too small to perform symmetry reduction."
else
@assert metric <= size "Lattice is too small to perform symmetry reduction."
end
# get list of sites
sites = get_sites(size, uc, euclidean)
num = length(sites)
# get empty bond matrix
bonds = Matrix{Bond}(undef, num, num)
for i in 1 : num
for j in 1 : num
bonds[i, j] = get_bond_empty(i, j)
end
end
# build lattice
l = Lattice(name, size, uc, test_sites, sites, bonds)
if verbose
println("Done. Lattice has $(length(l.sites)) sites.")
end
return l
end
# helper function to increase size of test set if required by model
function grow_test_sites!(
l :: Lattice,
metric :: Int64
;
euclidean :: Bool = false
) :: Nothing
if euclidean
# determine the maximum real space distance of the current test set
norm_current = maximum(Float64[norm(s.vec) for s in l.test_sites])
# determine nearest neighbor distance
nn_distance = norm(get_vec(l.sites[1].int + l.uc.bonds[1][1], l.uc))
# ensure that the test set is not shrunk
if norm_current < metric * nn_distance
println(" Increasing size of test set ...")
# get new test sites with required euclidean distance
test_sites_new = get_sites(metric, l.uc, euclidean)
# add to current test set
for s in test_sites_new
if is_in(s, l.test_sites) == false
push!(l.test_sites, s)
end
end
println(" Done. Lattice test sites have maximum euclidean distance $(metric).")
end
else
# determine the maximum bond distance of the current test set
metric_current = maximum(Int64[get_metric(l.test_sites[1], s, l.uc) for s in l.test_sites])
# ensure that the test set is not shrunk
if metric_current < metric
println(" Increasing size of test set ...")
# get new test sites with required bond distance
test_sites_new = get_sites(metric, l.uc, euclidean)
# add to current test set
for s in test_sites_new
if is_in(s, l.test_sites) == false
push!(l.test_sites, s)
end
end
println(" Done. Lattice test sites have maximum bond distance $(metric).")
end
end
return nothing
end
# load models
include("model_lib/model_heisenberg.jl")
include("model_lib/model_breathing.jl")
include("model_lib/model_triangular_dm_c3.jl")
# print available models
function model_avail() :: Nothing
println("##################")
println("su2 models")
println()
println("heisenberg")
println("breathing")
println("pyrochlore-breathing-c3")
println("##################")
println()
println("##################")
println("u1-dm models")
println()
println("triangular-dm-c3")
println("##################")
println()
println("Documentation provided by ?init_model_<model_name>!.")
return nothing
end
"""
init_model!(
name :: String,
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
Initialize model on a given lattice by modifying the respective bonds. Use `model_avail` to print available models.
Details about the layout of the coupling vector J can be found with `?init_model_<model_name>!`.
"""
function init_model!(
name :: String,
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
if name == "heisenberg"
init_model_heisenberg!(J, l)
elseif name == "breathing"
init_model_breathing!(J, l)
elseif name == "pyrochlore-breathing-c3"
init_model_pyrochlore_breathing_c3!(J, l)
elseif name == "triangular-dm-c3"
init_model_triangular_dm_c3!(J, l)
else
error("Model $(name) unknown.")
end
return nothing
end
"""
get_site(
vec :: SVector{3, Float64},
l :: Lattice
) :: Int64
Search for a site in lattice graph, returns respective index in l.sites or 0 in case of failure.
"""
function get_site(
vec :: SVector{3, Float64},
l :: Lattice
) :: Int64
index = 0
for i in eachindex(l.sites)
if norm(vec - l.sites[i].vec) <= 1e-8
index = i
break
end
end
return index
end
"""
get_bond(
s1 :: Site,
s2 :: Site,
l :: Lattice
) :: Bond
Returns bond between (s1, s2) from bond list of lattice graph.
"""
function get_bond(
s1 :: Site,
s2 :: Site,
l :: Lattice
) :: Bond
# get indices of the sites
i1 = get_site(s1.vec, l)
i2 = get_site(s2.vec, l)
# get bond from lattice bonds
b = l.bonds[i1, i2]
return b
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1213 | # save reduced lattice to HDF5 file (implicitly saves original lattice too)
function save!(
file :: HDF5.File,
r :: Reduced_lattice
) :: Nothing
# save name, size, model and coupling vector
file["reduced_lattice/name"] = r.name
file["reduced_lattice/size"] = r.size
file["reduced_lattice/model"] = r.model
for i in eachindex(r.J)
file["reduced_lattice/J/$(i)"] = r.J[i]
end
return nothing
end
"""
read_lattice(
file :: HDF5.File,
) :: Tuple{Lattice, Reduced_lattice}
Construct lattice and reduced lattice from HDF5 file.
"""
function read_lattice(
file :: HDF5.File,
) :: Tuple{Lattice, Reduced_lattice}
# read name, size, model and coupling vector
name = read(file, "reduced_lattice/name")
size = read(file, "reduced_lattice/size")
model = read(file, "reduced_lattice/model")
J = Vector{Float64}[]
for i in eachindex(keys(file["reduced_lattice/J"]))
push!(J, read(file, "reduced_lattice/J/$(i)"))
end
# build lattice and reduced lattice
l = get_lattice(name, size, verbose = false)
r = get_reduced_lattice(model, J, l, verbose = false)
return l, r
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 26361 | """
Reduced_lattice
Struct containing symmetry irreducible sites of a lattice graph.
* `name :: String` : name of the original lattice
* `size :: Int64` : bond truncation of the original lattice
* `model :: String` : name of the initialized model
* `J :: Vector{Vector{Float64}}` : coupling vector of the initialized model
* `sites :: Vector{Site}` : list of symmetry irreducible sites
* `overlap :: Vector{Matrix{Int64}}` : pairs of irreducible sites with their respective multiplicity in range of origin and another irreducible site
* `mult :: Vector{Int64}` : multiplicities of irreducible sites
* `exchange :: Vector{Int64}` : images of the pair (origin, irreducible site) under site exchange
* `project :: Matrix{Int64}` : projections of pairs (site1, site2) of the original lattice to pair (origin, irreducible site)
"""
struct Reduced_lattice
name :: String
size :: Int64
model :: String
J :: Vector{Vector{Float64}}
sites :: Vector{Site}
overlap :: Vector{Matrix{Int64}}
mult :: Vector{Int64}
exchange :: Vector{Int64}
project :: Matrix{Int64}
end
# check if matrix in list of matrices within numerical tolerance
function is_in(
e :: SMatrix{3, 3, Float64},
list :: Vector{SMatrix{3, 3, Float64}}
) :: Bool
in = false
for item in list
if maximum(abs.(item .- e)) <= 1e-8
in = true
break
end
end
return in
end
# rotate vector onto a reference vector using Rodrigues formula
function get_rotation(
vec :: SVector{3, Float64},
ref :: SVector{3, Float64}
) :: SMatrix{3, 3, Float64}
# buffer geometric information
a = vec ./ norm(vec)
b = ref ./ norm(ref)
n = cross(a, b)
s = norm(n)
c = dot(a, b)
# check if vectors are collinear
if s < 1e-8
# if vector are antiparallel do inversion
if c < 0.0
return SMatrix{3, 3, Float64}(-1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0)
# if vectors are parallel return unity
else
return SMatrix{3, 3, Float64}(+1.0, 0.0, 0.0, 0.0, +1.0, 0.0, 0.0, 0.0, +1.0)
end
# if vectors are non-collinear use Rodrigues formula
else
n = n ./ s
temp = SMatrix{3, 3, Float64}(0.0, n[3], -n[2], -n[3], 0.0, n[1], n[2], -n[1], 0.0)
mat = SMatrix{3, 3, Float64}(+1.0, 0.0, 0.0, 0.0, +1.0, 0.0, 0.0, 0.0, +1.0)
mat = mat .+ s .* temp .+ (1.0 - c) .* temp * temp
return mat
end
end
# try to rotate vector onto a reference vector around a given axis (return matrix of zeros in case of failure)
function get_rotation_for_axis(
vec :: SVector{3, Float64},
ref :: SVector{3, Float64},
axis :: SVector{3, Float64}
) :: SMatrix{3, 3, Float64}
# normalize vectors and axis
a = vec ./ norm(vec)
b = ref ./ norm(ref)
ax = axis ./ norm(axis)
# determine othogonal projections onto axis
ovec = vec .- dot(vec, ax) .* ax
ovec = ovec ./ norm(ovec)
oref = ref .- dot(ref, ax) .* ax
oref = oref ./ norm(oref)
# buffer geometric information
s = norm(cross(ovec, oref))
c = dot(ovec, oref)
# allocate rotation matrix
mat = SMatrix{3, 3, Float64}(ax[1]^2 + (1.0 - ax[1]^2) * c,
ax[1] * ax[2] * (1.0 - c) + ax[3] * s,
ax[1] * ax[3] * (1.0 - c) - ax[2] * s,
ax[1] * ax[2] * (1.0 - c) - ax[3] * s,
ax[2]^2 + (1.0 - ax[2]^2) * c,
ax[2] * ax[3] * (1.0 - c) + ax[1] * s,
ax[1] * ax[3] * (1.0 - c) + ax[2] * s,
ax[2] * ax[3] * (1.0 - c) - ax[1] * s,
ax[3]^2 + (1.0 - ax[3]^2) * c)
# check if rotation works as expected
if norm(mat * a .- b) > 1e-8
# check if sense of rotation has to be inverted
if norm(transpose(mat) * a .- b) < 1e-8
return transpose(mat)
# if algorithm fails return matrix of zeros
else
return SMatrix{3, 3, Float64}(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
end
# if sanity check is passed return rotation matrix
else
return mat
end
end
# try to obtain a rotation of (vec1, vec2) onto (ref1, ref2) (return matrix of zeros in case of failure)
function rotate(
vec1 :: SVector{3, Float64},
vec2 :: SVector{3, Float64},
ref1 :: SVector{3, Float64},
ref2 :: SVector{3, Float64}
) :: SMatrix{3, 3, Float64}
# rotate vec1 onto ref1
mat = get_rotation(vec1, ref1)
# try to rotate vec2 around ref1 onto ref2
mat = get_rotation_for_axis(mat * vec2, ref2, ref1) * mat
return mat
end
"""
get_trafos_orig(
l :: Lattice
) :: Vector{SMatrix{3, 3, Float64}}
Compute transformations which leave the origin of the lattice invariant (point group symmetries).
"""
function get_trafos_orig(
l :: Lattice
) :: Vector{SMatrix{3, 3, Float64}}
# allocate list for transformations, set reference site and its bonds
trafos = SMatrix{3, 3, Float64}[]
ref = l.sites[1]
con = l.uc.bonds[1]
# get a pair of non-collinear neighbors of origin
for i1 in eachindex(con)
for i2 in eachindex(con)
# check that sites are unequal
if i1 == i2
continue
end
# get connected sites in Bravais representation
int_i1 = ref.int .+ con[i1]
int_i2 = ref.int .+ con[i2]
# get connected sites in real space representation
vec_i1 = get_vec(int_i1, l.uc)
vec_i2 = get_vec(int_i2, l.uc)
# check that sites are non-collinear
if norm(cross(vec_i1, vec_i2)) <= 1e-8
continue
end
# get site structs
site_i1 = Site(int_i1, vec_i1)
site_i2 = Site(int_i2, vec_i2)
# get bonds
bond_i1 = get_bond(ref, site_i1, l)
bond_i2 = get_bond(ref, site_i2, l)
# get another pair of non-collinear neighbors of origin
for j1 in eachindex(con)
for j2 in eachindex(con)
# check that sites are unequal
if j1 == j2
continue
end
# get connected sites in Bravais representation
int_j1 = ref.int .+ con[j1]
int_j2 = ref.int .+ con[j2]
# get connected sites in real space representation
vec_j1 = get_vec(int_j1, l.uc)
vec_j2 = get_vec(int_j2, l.uc)
# check that sites are non-collinear
if norm(cross(vec_j1, vec_j2)) <= 1e-8
continue
end
# get site structs
site_j1 = Site(int_j1, vec_j1)
site_j2 = Site(int_j2, vec_j2)
# get bonds
bond_j1 = get_bond(ref, site_j1, l)
bond_j2 = get_bond(ref, site_j2, l)
# try to obtain rotation
mat = rotate(site_i1.vec, site_i2.vec, site_j1.vec, site_j2.vec)
# if successful, verify rotation on test set before saving it
if maximum(abs.(mat)) > 1e-8
# check if rotation is already known
if is_in(mat, trafos) == false
# verify rotation
valid = true
for n in eachindex(l.test_sites)
# apply transformation to lattice site
mapped_vec = mat * l.test_sites[n].vec
orig_bond = get_bond(ref, l.test_sites[n], l)
mapped_ind = get_site(mapped_vec, l)
# check if resulting site is in lattice and if the bonds match
if mapped_ind == 0
valid = false
else
valid = are_equal(orig_bond, get_bond(ref, l.sites[mapped_ind], l))
end
# break if test fails for one test site
if valid == false
break
end
end
# save transformation
if valid
push!(trafos, mat)
end
end
# check if rotation combined with inversion is already known
if is_in(-mat, trafos) == false
# verify rotation
valid = true
for n in eachindex(l.test_sites)
# apply transformation to lattice site
mapped_vec = -mat * l.test_sites[n].vec
orig_bond = get_bond(ref, l.test_sites[n], l)
mapped_ind = get_site(mapped_vec, l)
# check if resulting site is in lattice and if the bonds match
if mapped_ind == 0
valid = false
else
valid = are_equal(orig_bond, get_bond(ref, l.sites[mapped_ind], l))
end
# break if test fails for one test site
if valid == false
break
end
end
# save transformation
if valid
push!(trafos, -mat)
end
end
end
end
end
end
end
return trafos
end
# compute reduced representation of the lattice
function get_reduced(
l :: Lattice
) :: Vector{Int64}
# allocate a list of indices
reduced = Int64[i for i in eachindex(l.sites)]
# get transformations
trafos = get_trafos_orig(l)
# iterate over sites and try to find sites which are symmetry equivalent
for i in 2 : length(reduced)
# continue if index has already been replaced
if reduced[i] < i
continue
end
# apply all available transformations to current site and see where it is mapped
for j in eachindex(trafos)
mapped_vec = trafos[j] * l.sites[i].vec
# check that site is not mapped to itself
if norm(mapped_vec .- l.sites[i].vec) > 1e-8
# determine image of site
index = get_site(mapped_vec, l)
# assert that the image is valid, otherwise this is not a valid transformation and our algorithm failed
@assert index > 0 "Validity on test set could not be generalized."
# replace site in list if bonds match
if are_equal(l.bonds[1, i], get_bond(l.sites[1], l.sites[index], l))
reduced[index] = i
end
end
end
end
return reduced
end
"""
get_trafos_uc(
l :: Lattice
) :: Vector{Tuple{SMatrix{3, 3, Float64}, Bool}}
Compute mappings of a lattice's basis sites to the origin.
The mappings consist of a transformation matrix and a boolean indicating if an inversion was used or not.
"""
function get_trafos_uc(
l :: Lattice
) :: Vector{Tuple{SMatrix{3, 3, Float64}, Bool}}
# allocate list for transformations, set reference site and its bonds
trafos = Vector{Tuple{SMatrix{3, 3, Float64}, Bool}}(undef, length(l.uc.basis) - 1)
ref = l.sites[1]
con = l.uc.bonds[1]
# iterate over basis sites and find a symmetry for each of them
for b in 2 : length(l.uc.basis)
# set basis site and connections
int = SVector{4, Int64}(0, 0, 0, b)
basis = Site(int, get_vec(int, l.uc))
con_basis = l.uc.bonds[b]
# get a pair of non-collinear neighbors of basis
for b1 in eachindex(con_basis)
for b2 in eachindex(con_basis)
# check that sites are unequal
if b1 == b2
continue
end
# get connected sites in Bravais representation
int_b1 = basis.int .+ con_basis[b1]
int_b2 = basis.int .+ con_basis[b2]
# get connected sites in real space representation
vec_b1 = get_vec(int_b1, l.uc)
vec_b2 = get_vec(int_b2, l.uc)
# check that sites are non-collinear
if norm(cross(vec_b1 .- basis.vec, vec_b2 .- basis.vec)) <= 1e-8
continue
end
# get site structs
site_b1 = Site(int_b1, vec_b1)
site_b2 = Site(int_b2, vec_b2)
# get bonds
bond_b1 = get_bond(basis, site_b1, l)
bond_b2 = get_bond(basis, site_b2, l)
# get a pair of non-collinear neigbors of origin
for ref1 in eachindex(con)
for ref2 in eachindex(con)
# check that sites are unequal
if ref1 == ref2
continue
end
# get connected sites in Bravais representation
int_ref1 = ref.int .+ con[ref1]
int_ref2 = ref.int .+ con[ref2]
# get connected sites in real space representation
vec_ref1 = get_vec(int_ref1, l.uc)
vec_ref2 = get_vec(int_ref2, l.uc)
# check that sites are non-collinear
if norm(cross(vec_ref1, vec_ref2)) <= 1e-8
continue
end
# get site structs
site_ref1 = Site(int_ref1, vec_ref1)
site_ref2 = Site(int_ref2, vec_ref2)
# get bonds
bond_ref1 = get_bond(ref, site_ref1, l)
bond_ref2 = get_bond(ref, site_ref2, l)
# check that the bonds match
if are_equal(bond_b1, bond_ref1) == false || are_equal(bond_b2, bond_ref2) == false
continue
end
# try shift -> rotation
mat = rotate(site_b1.vec .- basis.vec, site_b2.vec .- basis.vec, site_ref1.vec, site_ref2.vec)
# if successful, verify tranformation on test set before saving it
if maximum(abs.(mat)) > 1e-8
valid = true
for n in eachindex(l.test_sites)
# test only those sites which are in range of basis
if get_metric(l.test_sites[n], basis, l.uc) <= l.size
# apply transformation to lattice site
mapped_vec = mat * (l.test_sites[n].vec .- basis.vec)
orig_bond = get_bond(basis, l.test_sites[n], l)
mapped_ind = get_site(mapped_vec, l)
# check if resulting site is in lattice and if bonds match
if mapped_ind == 0
valid = false
else
valid = are_equal(orig_bond, get_bond(ref, l.sites[mapped_ind], l))
end
# break if test fails for one test site
if valid == false
break
end
end
end
# save transformation
if valid
trafos[b - 1] = (mat, false)
break
break
break
break
end
end
# try inversion -> shift -> rotation
mat = rotate(-(site_b1.vec .- basis.vec), -(site_b2.vec .- basis.vec), site_ref1.vec, site_ref2.vec)
# if successful, verify tranformation on test set before saving it
if maximum(abs.(mat)) > 1e-8
valid = true
for n in eachindex(l.test_sites)
# test only those sites which are in range of basis
if get_metric(l.test_sites[n], basis, l.uc) <= l.size
# apply transformation to lattice site
mapped_vec = mat * (-l.test_sites[n].vec .+ basis.vec)
orig_bond = get_bond(basis, l.test_sites[n], l)
mapped_ind = get_site(mapped_vec, l)
# check if resulting site is in lattice and if bonds match
if mapped_ind == 0
valid = false
else
valid = are_equal(orig_bond, get_bond(ref, l.sites[mapped_ind], l))
end
# break if test fails for one test site
if valid == false
break
end
end
end
# save transformation
if valid
trafos[b - 1] = (mat, true)
break
break
break
break
end
end
end
end
end
end
end
return trafos
end
# apply transformation (i, j) -> (i0, j*), where i0 is the origin, to site j
function apply_trafo(
s :: Site,
b :: Int64,
shift :: SVector{3, Float64},
trafos :: Vector{Tuple{SMatrix{3, 3, Float64}, Bool}},
l :: Lattice
) :: SVector{3, Float64}
# check if equivalent to origin
if b != 1
# if inequivalent to origin use transformation inside unitcell
if trafos[b - 1][2]
return trafos[b - 1][1] * (shift .- s.vec .+ l.uc.basis[b])
else
return trafos[b - 1][1] * (s.vec .- shift .- l.uc.basis[b])
end
# if equivalent to origin, only shift along translation vectors needs to be performed
else
return s.vec .- shift
end
end
# compute mappings onto reduced lattice
function get_mappings(
l :: Lattice,
reduced :: Vector{Int64}
) :: Matrix{Int64}
# allocate matrix
num = length(l.sites)
mat = Matrix{Int64}(I, num, num)
# get transformations inside unitcell
trafos = get_trafos_uc(l)
# get distances to origin
dists = Float64[norm(l.sites[i].vec) for i in eachindex(l.sites)]
d_max = maximum(dists)
# group sites in shells
shell_dists = unique(trunc.(dists, digits = 8))
shells = Vector{Vector{Int64}}(undef, length(shell_dists))
for i in eachindex(shells)
shell = Int64[]
for j in eachindex(dists)
if abs(dists[j] - shell_dists[i]) < 1e-8
push!(shell, j)
end
end
shells[i] = shell
end
# compute entries of matrix
Threads.@threads for i in eachindex(l.sites)
# determine shift for second site
si = l.sites[i]
b = si.int[4]
shift = get_vec(SVector{4, Int64}(si.int[1], si.int[2], si.int[3], 1), l.uc)
for j in eachindex(l.sites)
# compute only off-diagonal entries
if i != j
# apply symmetry transformation
mapped_vec = apply_trafo(l.sites[j], b, shift, trafos, l)
# locate transformed site in lattice
index = 0
d_map = norm(mapped_vec)
# check if transformed site can be in lattice
if d_max - d_map > -1e-8
# find respective shell
shell = shells[argmin(abs.(shell_dists .- d_map))]
# find matching site in shell
for k in shell
if norm(mapped_vec .- l.sites[k].vec) < 1e-8
index = k
break
end
end
if index != 0
mat[i, j] = reduced[index]
end
end
end
end
end
return mat
end
# compute irreducible sites in overlap of two sites
function get_overlap(
l :: Lattice,
reduced :: Vector{Int64},
irreducible :: Vector{Int64},
mappings :: Matrix{Int64}
) :: Vector{Matrix{Int64}}
# allocate overlap
overlap = Vector{Matrix{Int64}}(undef, length(irreducible))
for i in eachindex(irreducible)
# collect all sites in range of irreducible and origin
temp = NTuple{2, Int64}[]
for j in eachindex(l.sites)
if mappings[irreducible[i], j] != 0
push!(temp, (reduced[j], mappings[j, irreducible[i]]))
end
end
# determine how often a certain pair occurs
pairs = unique(temp)
table = zeros(Int64, length(pairs), 3)
for j in eachindex(pairs)
# convert from original lattice index to new "irreducible" index
table[j, 1] = findall(index -> index == pairs[j][1], irreducible)[1]
table[j, 2] = findall(index -> index == pairs[j][2], irreducible)[1]
# count multiplicity
for k in eachindex(temp)
if pairs[j] == temp[k]
table[j, 3] += 1
end
end
end
# save into overlap
overlap[i] = table
end
return overlap
end
# compute multiplicity of irreducible sites
function get_mult(
reduced :: Vector{Int64},
irreducible :: Vector{Int64}
) :: Vector{Int64}
# allocate vector to store multiplicities
mult = zeros(Float64, length(irreducible))
for i in eachindex(mult)
for j in eachindex(reduced)
if reduced[j] == irreducible[i]
mult[i] += 1
end
end
end
return mult
end
# compute mappings under site exchange
function get_exchange(
irreducible :: Vector{Int64},
mappings :: Matrix{Int64}
) :: Vector{Int64}
# allocate exchange list
exchange = zeros(Int64, length(irreducible))
# determine mappings under site exchange
for i in eachindex(exchange)
exchange[i] = findall(index -> index == mappings[irreducible[i], 1], irreducible)[1]
end
return exchange
end
# convert mapping table entries to irreducible site indices
function get_project(
l :: Lattice,
irreducible :: Vector{Int64},
mappings :: Matrix{Int64}
) :: Matrix{Int64}
# allocate projections
project = zeros(Int64, length(l.sites), length(l.sites))
for i in eachindex(l.sites)
for j in eachindex(l.sites)
if mappings[i, j] != 0
project[i, j] = findall(index -> index == mappings[i, j], irreducible)[1]
end
end
end
return project
end
"""
get_reduced_lattice(
model :: String,
J :: Vector{Vector{Float64}},
l :: Lattice
;
verbose :: Bool = true
) :: Reduced_lattice
Compute symmetry reduced representation of a given lattice graph with spin interactions between sites.
The interactions are defined by passing a model's name and coupling vector.
"""
function get_reduced_lattice(
model :: String,
J :: Vector{Vector{Float64}},
l :: Lattice
;
verbose :: Bool = true
) :: Reduced_lattice
if verbose
println("Performing symmetry reduction ...")
end
# initialize model by modifying bond matrix of lattice
init_model!(model, J, l)
# get reduced representation of lattice
reduced = get_reduced(l)
irreducible = unique(reduced)
sites = Site[Site(l.sites[i].int, get_vec(l.sites[i].int, l.uc)) for i in irreducible]
# get mapping table
mappings = get_mappings(l, reduced)
# get overlap
overlap = get_overlap(l, reduced, irreducible, mappings)
# get multiplicities
mult = get_mult(reduced, irreducible)
# get exchanges
exchange = get_exchange(irreducible, mappings)
# get projections
project = get_project(l, irreducible, mappings)
# build reduced lattice
r = Reduced_lattice(l.name, l.size, model, J, sites, overlap, mult, exchange, project)
if verbose
println("Done. Reduced lattice has $(length(r.sites)) sites.")
end
return r
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 9745 | """
Site
Struct containing the coordinates, parametrized via primitive translations plus basis index and in real space form, of a lattice site.
* `int :: SVector{4, Int64}` : site given in term of primitive translation and basis index
* `vec :: SVector{3, Float64}` : site given in cartesian coordinates
"""
struct Site
int :: SVector{4, Int64}
vec :: SVector{3, Float64}
end
# transform int to vec representation
function get_vec(
int :: SVector{4, Int64},
uc :: Unitcell
) :: SVector{3, Float64}
vec_x = int[1] * uc.vectors[1][1] + int[2] * uc.vectors[2][1] + int[3] * uc.vectors[3][1] + uc.basis[int[4]][1]
vec_y = int[1] * uc.vectors[1][2] + int[2] * uc.vectors[2][2] + int[3] * uc.vectors[3][2] + uc.basis[int[4]][2]
vec_z = int[1] * uc.vectors[1][3] + int[2] * uc.vectors[2][3] + int[3] * uc.vectors[3][3] + uc.basis[int[4]][3]
vec = SVector{3, Float64}(vec_x, vec_y, vec_z)
return vec
end
# generate lattice sites from unitcell
function get_sites(
size :: Int64,
uc :: Unitcell,
euclidean :: Bool
) :: Vector{Site}
# init buffers
ints = SVector{4, Int64}[SVector{4, Int64}(0, 0, 0, 1)]
current = copy(ints)
touched = copy(ints)
# iteratively add sites with bond distance 1 until required Euclidean norm is reached
if euclidean
# compute nearest neighbor distance
nn_distance = norm(get_vec(ints[1] + uc.bonds[1][1], uc))
while true
# init list for new sites generated in this step
# new_ints contains sites inside sphere with radius corresponding to required Euclidean norm
# out_ints contains sites outside sphere with radius corresponding to required Euclidean norm
new_ints = SVector{4, Int64}[]
out_ints = SVector{4, Int64}[]
# add sites with bond distance 1 to new sites from last step
for int in current
for i in eachindex(uc.bonds[int[4]])
new_int = int .+ uc.bonds[int[4]][i]
# check if site was generated already
if in(new_int, touched) == false
if in(new_int, ints) == false
# check if site is inside sphere with required Euclidean norm
if norm(get_vec(new_int, uc)) <= size * nn_distance
push!(new_ints, new_int)
push!(ints, new_int)
else
push!(out_ints, new_int)
end
end
end
end
end
# if no site exceed Euclidean norm, update lists and proceed
if length(out_ints) == 0
touched = current
current = new_ints
# otherwise check if sites have reentrant neighbors
else
# init lists for possibles sites with reentrant neighbors
re_ints = SVector{4, Int64}[]
# add sites with bond distance 1 to sites outside sphere from last step
for int in out_ints
for i in eachindex(uc.bonds[int[4]])
new_int = int .+ uc.bonds[int[4]][i]
# check if site was generated already
if in(new_int, current) == false
if in(new_int, ints) == false
# check if site is inside sphere with required Euclidean norm
if norm(get_vec(new_int, uc)) <= size * nn_distance
push!(re_ints, int)
break
end
end
end
end
end
# if sites with reentrant neighbors exist, update lists and proceed
if length(re_ints) > 0
touched = current
current = vcat(new_ints, re_ints)
# otherwise terminate, if there are no more sites to add
else
if length(new_ints) > 0
touched = current
current = new_ints
else
break
end
end
end
end
# iteratively add sites with bond distance 1 until required bond distance is reached
else
# init metric
metric = 0
while metric < size
# init list for new sites generated in this step
new_ints = SVector{4, Int64}[]
# add sites with bond distance 1 to new sites from last step
for int in current
for i in eachindex(uc.bonds[int[4]])
new_int = int .+ uc.bonds[int[4]][i]
# check if site was generated already
if in(new_int, touched) == false
if in(new_int, ints) == false
push!(new_ints, new_int)
push!(ints, new_int)
end
end
end
end
# update lists and increment metric
touched = current
current = new_ints
metric += 1
end
end
# build sites
sites = Site[Site(int, get_vec(int, uc)) for int in ints]
return sites
end
"""
get_metric(
s1 :: Site,
s2 :: Site,
uc :: Unitcell
) :: Int64
Compute the bond metric (i.e. minimal number of bonds required to connect two sites within the lattice graph) for a given unitcell.
"""
function get_metric(
s1 :: Site,
s2 :: Site,
uc :: Unitcell
) :: Int64
# init buffers
current = SVector{4, Int64}[s2.int]
touched = SVector{4, Int64}[s2.int]
metric = 0
not_found = true
# check if sites are identical
if s1.int == s2.int
not_found = false
end
# add sites with bond distance 1 around s2 until s1 is reached
while not_found
# increment metric
metric += 1
# init list for new sites generated in this step
new_ints = SVector{4, Int64}[]
# add sites with bond distance 1 to new sites from last step
for int in current
for i in eachindex(uc.bonds[int[4]])
new_int = int .+ uc.bonds[int[4]][i]
# check if site was touched already
if in(new_int, touched) == false
push!(new_ints, new_int)
end
end
end
# if s1 is reached stop searching, otherwise update lists and continue
if in(s1.int, new_ints)
not_found = false
else
touched = current
current = new_ints
end
end
return metric
end
# check if Float64 item in list within numerical tolerance
function is_in(
e :: Float64,
list :: Vector{Float64}
) :: Bool
in = false
for item in list
if abs(item - e) <= 1e-8
in = true
break
end
end
return in
end
"""
get_nbs(
n :: Int64,
s :: Site,
list :: Vector{Site}
) :: Vector{Int64}
Returns list of n-th nearest neigbors (Euclidean norm) for a given site s, assuming s in list.
"""
function get_nbs(
n :: Int64,
s :: Site,
list :: Vector{Site}
) :: Vector{Int64}
# init buffers
dist = Float64[]
dist_unique = Float64[]
# collect possible distances
for item in list
d = norm(item.vec - s.vec)
if is_in(d, dist_unique) == false
push!(dist_unique, d)
end
push!(dist, d)
end
# determine the n-th nearest neighbor distance
@assert length(dist_unique) >= n + 1 "Could not find neighbors in list."
dn = sort(dist_unique)[n + 1]
# collect all sites with distance dn
nbs = Int64[]
for i in eachindex(dist)
if abs(dn - dist[i]) <= 1e-8
push!(nbs, i)
end
end
return nbs
end
# check if site in list within numerical tolerance
function is_in(
e :: Site,
list :: Vector{Site}
) :: Bool
in = false
for item in list
if norm(item.vec - e.vec) <= 1e-8
in = true
break
end
end
return in
end
# obtain minimal test set to verify symmetry transformations
function get_test_sites(
uc :: Unitcell,
euclidean :: Bool
) :: Tuple{Vector{Site}, Union{Int64, Float64}}
# init buffers
test_sites = Site[]
# add basis sites and connected neighbors to list
for i in eachindex(uc.basis)
b = Site(SVector{4, Int64}(0, 0, 0, i), uc.basis[i])
if is_in(b, test_sites) == false
push!(test_sites, b)
end
for j in eachindex(uc.bonds[i])
int = b.int .+ uc.bonds[i][j]
bp = Site(int, get_vec(int, uc))
if is_in(bp, test_sites) == false
push!(test_sites, bp)
end
end
end
if euclidean
# determine the maximum Euclidean distance
metric = maximum(Float64[norm(s.vec) for s in test_sites])
return test_sites, metric
else
# determine the maximum bond distance
metric = maximum(Int64[get_metric(test_sites[1], s, uc) for s in test_sites])
return test_sites, metric
end
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2277 | """
test_lattice() :: Nothing
Test lattice building for available lattice implementations.
"""
function test_lattice() :: Nothing
lattice_names = ["square",
"honeycomb",
"kagome",
"triangular",
"cubic",
"fcc",
"bcc",
"hyperhoneycomb",
"hyperkagome",
"pyrochlore",
"diamond"]
# for each lattice give bond distance to test, expected number of sites, minimal Euclidean distance for comparison and maximal Euclidean distance for comparison
testsizes = [[8, 145, 2, 4],
[8, 109, 2, 4],
[8, 163, 2, 4],
[8, 217, 2, 4],
[8, 833, 2, 4],
[8, 2057, 2, 4],
[8, 1241, 2, 4],
[8, 319, 3, 4],
[8, 415, 6, 7],
[8, 1029, 2, 4],
[8, 525, 2, 4]]
# run tests for lattice implementations with bond distance metric
@testset "lattices " begin
for i in eachindex(lattice_names)
# generate testdata
current_name = lattice_names[i]
l = get_lattice(current_name, testsizes[i][1], verbose = false)
# check that implementations give right number of sites
@testset "$current_name no. of sites" begin
@test length(l.sites) == testsizes[i][2]
end
# check that Euclidean metric gives same number of sites as sites cut out from larger lattice
@testset "$current_name Euclidean" begin
for j in testsizes[i][3] : testsizes[i][4]
l_bond = get_lattice(current_name, ceil(Int64, 2.5 * j), verbose = false)
l_euclidean = get_lattice(current_name, j, verbose = false, euclidean = true)
nn_distance = norm(l.sites[2].vec)
filtered_sites = filter!(x -> norm(x.vec) <= nn_distance * j, l_bond.sites)
@test length(l_euclidean.sites) == length(filtered_sites)
end
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 997 | """
get_lattice_timers() :: Nothing
Function to test current performance of lattice implementation for L = 6.
"""
function get_lattice_timers() :: Nothing
# init timer
to = TimerOutput()
# init list of lattices
lattices = String["square",
"honeycomb",
"kagome",
"triangular",
"cubic",
"fcc",
"bcc",
"hyperhoneycomb",
"hyperkagome",
"pyrochlore",
"diamond"]
# time lattice building
for name in lattices
@timeit to "=> " * name begin
for reps in 1 : 10
@timeit to "-> build" l = get_lattice(name, 6, verbose = false)
@timeit to "-> reduce" r = get_reduced_lattice("heisenberg", [[0.0]], l, verbose = false)
end
end
end
show(to)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2968 | """
Unitcell
Struct containing the positions of basis sites, primitive translations and bonds for a lattice graph.
* `basis :: Vector{SVector{3, Float64}}` : position of basis sites in unitcell. basis[1] has to be the origin.
* `vectors :: Vector{SVector{3, Float64}}` : primitive translations of the lattice
* `bonds :: Vector{Vector{SVector{4, Int64}}}` : bonds connecting basis sites
Use `get_unitcell` to load the unitcell for a specific lattice and `lattice_avail` to print available lattices.
"""
struct Unitcell
basis :: Vector{SVector{3, Float64}}
vectors :: Vector{SVector{3, Float64}}
bonds :: Vector{Vector{SVector{4, Int64}}}
end
# generate unitcell dummy
function get_unitcell_empty()
basis = Vector{SVector{3, Float64}}(undef, 1)
vectors = Vector{SVector{3, Float64}}(undef, 1)
bonds = Vector{Vector{SVector{4, Int64}}}(undef, 1)
uc = Unitcell(basis, vectors, bonds)
return uc
end
# load custom 2D unitcells
include("unitcell_lib/square.jl")
include("unitcell_lib/honeycomb.jl")
include("unitcell_lib/kagome.jl")
include("unitcell_lib/triangular.jl")
# load custom 3D unitcells
include("unitcell_lib/cubic.jl")
include("unitcell_lib/fcc.jl")
include("unitcell_lib/bcc.jl")
include("unitcell_lib/hyperhoneycomb.jl")
include("unitcell_lib/hyperkagome.jl")
include("unitcell_lib/pyrochlore.jl")
include("unitcell_lib/diamond.jl")
# print available lattices
function lattice_avail() :: Nothing
println("###################### 2D Lattices ######################")
println("square")
println("honeycomb")
println("kagome")
println("triangular")
println()
println("###################### 3D Lattices ######################")
println("cubic")
println("fcc")
println("bcc")
println("hyperhoneycomb")
println("hyperkagome")
println("pyrochlore")
println("diamond")
return nothing
end
"""
get_unitcell(
name :: String
) :: Unitcell
Returns unitcell for lattice name. Use `lattice_avail` to print available lattices.
"""
function get_unitcell(
name :: String
) :: Unitcell
uc = get_unitcell_empty()
if name == "square"
uc = get_unitcell_square()
elseif name == "honeycomb"
uc = get_unitcell_honeycomb()
elseif name == "kagome"
uc = get_unitcell_kagome()
elseif name == "triangular"
uc = get_unitcell_triangular()
elseif name == "cubic"
uc = get_unitcell_cubic()
elseif name == "fcc"
uc = get_unitcell_fcc()
elseif name == "bcc"
uc = get_unitcell_bcc()
elseif name == "hyperhoneycomb"
uc = get_unitcell_hyperhoneycomb()
elseif name == "hyperkagome"
uc = get_unitcell_hyperkagome()
elseif name == "pyrochlore"
uc = get_unitcell_pyrochlore()
elseif name == "diamond"
uc = get_unitcell_diamond()
else
error("Unitcell $(name) unknown.")
end
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 6740 | """
init_model_breathing!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
Init Heisenberg model on a breathing pyrochlore or kagome lattice by overwriting the respective bonds.
Here, J[n] is the coupling to the n-th nearest neighbor (Euclidean norm). J[1] has to be an array of
length 2, specifying the breathing, anisotropic nearest neighbor couplings.
If there are m symmetry inequivalent n-th nearest neighbors (n > 1), these are
* uniformly initialized if J[n] is a single value
* initialized in ascending bond distance from the origin, if J[n] is an array of length m
"""
function init_model_breathing!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
@assert l.name in ["kagome", "pyrochlore"] "Breathing model requires Pyrochlore or Kagome lattice."
@assert length(J[1]) == 2 "Breathing model needs two nearest neighbor couplings."
# iterate over sites and add Heisenberg couplings to lattice bonds
for i in eachindex(l.sites)
for n in eachindex(J)
# find n-th nearest neighbors
nbs = get_nbs(n, l.sites[i], l.sites)
# treat nearest neighbors according to breathing
if n == 1
for j in nbs
# if bond is within unit cell, it belongs to first kind of breathing coupling
if (l.sites[j].int - l.sites[i].int)[1 : 3] == [0, 0, 0]
add_bond!(J[1][1], l.bonds[i, j], 1, 1)
add_bond!(J[1][1], l.bonds[i, j], 2, 2)
add_bond!(J[1][1], l.bonds[i, j], 3, 3)
# if it crosses unit cell boundary, initalizes with second kind
else
add_bond!(J[1][2], l.bonds[i, j], 1, 1)
add_bond!(J[1][2], l.bonds[i, j], 2, 2)
add_bond!(J[1][2], l.bonds[i, j], 3, 3)
end
end
# uniform initialization for n-th nearest neighbor, if no further couplings provided
elseif length(J[n]) == 1
for j in nbs
add_bond!(J[n][1], l.bonds[i, j], 1, 1)
add_bond!(J[n][1], l.bonds[i, j], 2, 2)
add_bond!(J[n][1], l.bonds[i, j], 3, 3)
end
# initialize symmetry non-equivalent bonds interactions in ascending bond-length order
else
# get bond distances of neighbors
dist = Int64[get_metric(l.sites[j], l.sites[i], l.uc) for j in nbs]
# filter out classes of bond distances
nbkinds = sort(unique(dist))
# sanity check
@assert length(J[n]) == length(nbkinds) "$(l.name) has $(length(nbkinds)) inequivalent $(n)-th nearest neighbors, but $(length(J[n])) couplings were supplied."
for nk in eachindex(nbkinds)
# filter out neighbors with dist == nbkinds[nk]
nknbs = nbs[findall(x -> x == nbkinds[nk], dist)]
for j in nknbs
add_bond!(J[n][nk], l.bonds[i, j], 1, 1)
add_bond!(J[n][nk], l.bonds[i, j], 2, 2)
add_bond!(J[n][nk], l.bonds[i, j], 3, 3)
end
end
end
end
end
return nothing
end
"""
init_model_pyrochlore_breathing_c3!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
Init Heisenberg model on a breathing pyrochlore lattice with broken C3 symmetry by overwriting the respective bonds.
Here, J[1] = [J1, J2, δ] specifies the breathing nearest-neighbor couplings J1 (for up tetrahedra),
J2 (for down tetrahedra) and δ, which quantifies the C3 breaking perturbation.
"""
function init_model_pyrochlore_breathing_c3!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
@assert l.name in ["pyrochlore"] "Model requires Pyrochlore lattice."
@assert length(J[1]) == 3 "Model requires two nearest neighbor couplings and C3 breaking perturbation."
@assert length(J) == 1 "Model supports only nearest neighbor couplings."
# iterate over sites and add Heisenberg couplings to lattice bonds
for i in eachindex(l.sites)
# find nearest neighbors
nbs = get_nbs(1, l.sites[i], l.sites)
# treat nearest neighbors according to breathing anisotropy
for j in nbs
# get basis indices
idxs = (l.sites[j].int[4], l.sites[i].int[4])
# set coupling to J1 (± δ) for up tetrahedra
if (l.sites[j].int - l.sites[i].int)[1 : 3] == [0, 0, 0]
# add δ on bonds connecting basis sites 1 and 2
if idxs == (1, 2) || idxs == (2, 1)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 3, 3)
# add δ on bonds connecting basis sites 3 and 4
elseif idxs == (3, 4) || idxs == (4, 3)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][1] + J[1][3], l.bonds[i, j], 3, 3)
# subtract δ for all other bonds
else
add_bond!(J[1][1] - J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][1] - J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][1] - J[1][3], l.bonds[i, j], 3, 3)
end
# set coupling to J2 (± δ) for down tetrahedra
else
# add δ on bonds connecting basis sites 1 and 2
if idxs == (1, 2) || idxs == (2, 1)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 3, 3)
# add δ on bonds connecting basis sites 3 and 4
elseif idxs == (3, 4) || idxs == (4, 3)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][2] + J[1][3], l.bonds[i, j], 3, 3)
# ignore δ for all other bonds
else
add_bond!(J[1][2] - J[1][3], l.bonds[i, j], 1, 1)
add_bond!(J[1][2] - J[1][3], l.bonds[i, j], 2, 2)
add_bond!(J[1][2] - J[1][3], l.bonds[i, j], 3, 3)
end
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2243 | """
init_model_heisenberg!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
Init Heisenberg model on a given lattice by overwriting the respective bonds.
Here, J[n] is the coupling to the n-th nearest neighbor (Euclidean norm).
If there are m symmetry inequivalent n-th nearest neighbors, these are
* uniformly initialized if J[n] is a single value
* initialized in ascending bond distance from the origin, if J[n] is an array of length m
"""
function init_model_heisenberg!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
# iterate over sites and add Heisenberg couplings to lattice bonds
for i in eachindex(l.sites)
for n in eachindex(J)
# find n-th nearest neighbors
nbs = get_nbs(n, l.sites[i], l.sites)
# uniform initialization for n-th nearest neighbor, if no further couplings provided
if length(J[n]) == 1
for j in nbs
add_bond!(J[n][1], l.bonds[i, j], 1, 1)
add_bond!(J[n][1], l.bonds[i, j], 2, 2)
add_bond!(J[n][1], l.bonds[i, j], 3, 3)
end
# initialize symmetry non-equivalent bonds interactions in ascending bond-length order
else
# get bond distances of neighbors
dist = Int64[get_metric(l.sites[j], l.sites[i], l.uc) for j in nbs]
# filter out classes of bond distances
nbkinds = sort(unique(dist))
# sanity check
@assert length(J[n]) == length(nbkinds) "$(l.name) has $(length(nbkinds)) inequivalent $(n)-th nearest neighbors, but $(length(J[n])) couplings were supplied."
for nk in eachindex(nbkinds)
# filter out neighbors with dist == nbkinds[nk]
nknbs = nbs[findall(x -> x == nbkinds[nk], dist)]
for j in nknbs
add_bond!(J[n][nk], l.bonds[i, j], 1, 1)
add_bond!(J[n][nk], l.bonds[i, j], 2, 2)
add_bond!(J[n][nk], l.bonds[i, j], 3, 3)
end
end
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2875 | """
init_model_triangular_dm_c3!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
Init spin model with out-of-plane Dzyaloshinskii-Moriya (DM) interactions on the triangular lattice.
The DM interaction is chosen such that it switches sign between associated neighboring bonds, thus breaking the sixfold rotation symmetry of the triangular lattice down to threefold.
Here, J[n] = [Jxx, Jzz, Jxy] (n <= 3), with
* `Jxx` : n-th nearest neighbor coupling between the xx and yy spin components
* `Jzz` : n-th nearest neighbor coupling between the zz spin components
* `Jxy` : n-th nearest neighbor coupling between the xy spin components (aka DM interaction)
"""
function init_model_triangular_dm_c3!(
J :: Vector{Vector{Float64}},
l :: Lattice
) :: Nothing
# sanity checks
@assert l.name == "triangular" "Model requires triangular lattice."
@assert length(J) <= 3 "Model initialization only works up to third-nearest neighbors."
for n in eachindex(J)
@assert length(J[n]) == 3 "Jxx, Jzz and Jxy all need to be specified for J[$(n)]."
end
# increase test set according to J
max_nbs = get_nbs(length(J), l.sites[1], l.sites)
metric = maximum(Int64[get_metric(l.sites[1], l.sites[i], l.uc) for i in max_nbs])
grow_test_sites!(l, metric)
# save reference vectors to ensure uniform initialization
ref_vecs = Vector{Float64}[]
# iterate over sites and add couplings to lattice bonds
for i in eachindex(l.sites)
for n in eachindex(J)
# find n-th nearest neighbors
nbs = get_nbs(n, l.sites[i], l.sites)
# determine couplings
Jxx, Jzz, Jxy = J[n][1], J[n][2], J[n][3]
# determine (and save) reference vector
if length(ref_vecs) < n
push!(ref_vecs, l.sites[nbs[1]].vec .- l.sites[i].vec)
end
ref_vec = ref_vecs[n]
# iterate over neighbors and overwrite bond matrices
for j in nbs
vec = l.sites[j].vec .- l.sites[i].vec
p = round(dot(ref_vec, vec) / (norm(ref_vec) * norm(vec)), digits = 8)
# disentanle bond dependence of DM coupling, preserving C3 but not C6 symmetry
if acos(p) % (2.0 * pi / 3.0) < 1e-8
add_bond!(+Jxy, l.bonds[i, j], 1, 2)
add_bond!(-Jxy, l.bonds[i, j], 2, 1)
else
add_bond!(-Jxy, l.bonds[i, j], 1, 2)
add_bond!(+Jxy, l.bonds[i, j], 2, 1)
end
# add other couplings to bond
add_bond!(Jxx, l.bonds[i, j], 1, 1)
add_bond!(Jxx, l.bonds[i, j], 2, 2)
add_bond!(Jzz, l.bonds[i, j], 3, 3)
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1111 | function get_unitcell_bcc() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 1)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}( 0.5, 0.5, -0.5)
vectors[2] = SVector{3, Float64}(-0.5, 0.5, 0.5)
vectors[3] = SVector{3, Float64}( 0.5, -0.5, 0.5)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 8)
bonds1[1] = SVector{4, Int64}(-1, 0, 0, 0)
bonds1[2] = SVector{4, Int64}( 1, 0, 0, 0)
bonds1[3] = SVector{4, Int64}( 0, -1, 0, 0)
bonds1[4] = SVector{4, Int64}( 0, 1, 0, 0)
bonds1[5] = SVector{4, Int64}( 0, 0, -1, 0)
bonds1[6] = SVector{4, Int64}( 0, 0, 1, 0)
bonds1[7] = SVector{4, Int64}( 1, 1, 1, 0)
bonds1[8] = SVector{4, Int64}(-1, -1, -1, 0)
bonds[1] = bonds1
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1008 | function get_unitcell_cubic() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 1)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(1.0, 0.0, 0.0)
vectors[2] = SVector{3, Float64}(0.0, 1.0, 0.0)
vectors[3] = SVector{3, Float64}(0.0, 0.0, 1.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 6)
bonds1[1] = SVector{4, Int64}( 1, 0, 0, 0)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 0)
bonds1[3] = SVector{4, Int64}( 0, 1, 0, 0)
bonds1[4] = SVector{4, Int64}( 0, -1, 0, 0)
bonds1[5] = SVector{4, Int64}( 0, 0, 1, 0)
bonds1[6] = SVector{4, Int64}( 0, 0, -1, 0)
bonds[1] = bonds1
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1411 | function get_unitcell_diamond() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 2)
basis[1] = SVector{3, Float64}( 0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}(1.0 / sqrt(3.0), 1.0 / sqrt(3.0), 1.0 / sqrt(3.0))
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}( 0.0, 2.0 / sqrt(3.0), 2.0 / sqrt(3.0))
vectors[2] = SVector{3, Float64}(2.0 / sqrt(3.0), 0.0, 2.0 / sqrt(3.0))
vectors[3] = SVector{3, Float64}(2.0 / sqrt(3.0), 2.0 / sqrt(3.0), 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 4)
bonds1[1] = SVector{4, Int64}( 0, 0, 0, 1)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 1)
bonds1[3] = SVector{4, Int64}( 0, -1, 0, 1)
bonds1[4] = SVector{4, Int64}( 0, 0, -1, 1)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 4)
bonds2[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds2[2] = SVector{4, Int64}( 1, 0, 0, -1)
bonds2[3] = SVector{4, Int64}( 0, 1, 0, -1)
bonds2[4] = SVector{4, Int64}( 0, 0, 1, -1)
bonds[2] = bonds2
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1426 | function get_unitcell_fcc() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 1)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}( 0.0, 1.0 / sqrt(2.0), 1.0 / sqrt(2.0))
vectors[2] = SVector{3, Float64}(1.0 / sqrt(2.0), 0.0, 1.0 / sqrt(2.0))
vectors[3] = SVector{3, Float64}(1.0 / sqrt(2.0), 1.0 / sqrt(2.0), 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 12)
bonds1[1] = SVector{4, Int64}( 1, 0, 0, 0)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 0)
bonds1[3] = SVector{4, Int64}( 0, 1, -1, 0)
bonds1[4] = SVector{4, Int64}( 0, -1, 1, 0)
bonds1[5] = SVector{4, Int64}( 0, 1, 0, 0)
bonds1[6] = SVector{4, Int64}( 0, -1, 0, 0)
bonds1[7] = SVector{4, Int64}( 1, 0, -1, 0)
bonds1[8] = SVector{4, Int64}(-1, 0, 1, 0)
bonds1[9] = SVector{4, Int64}( 0, 0, 1, 0)
bonds1[10] = SVector{4, Int64}( 0, 0, -1, 0)
bonds1[11] = SVector{4, Int64}( 1, -1, 0, 0)
bonds1[12] = SVector{4, Int64}(-1, 1, 0, 0)
bonds[1] = bonds1
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1162 | function get_unitcell_honeycomb() :: Unitcell
# define basis sites
basis = Vector{SVector{3, Float64}}(undef, 2)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}(1.0, 0.0, 0.0)
# define Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(3.0 / 2.0, sqrt(3.0) / 2.0, 0.0)
vectors[2] = SVector{3, Float64}(3.0 / 2.0, -sqrt(3.0) / 2.0, 0.0)
vectors[3] = SVector{3, Float64}( 0.0, 0.0, 0.0)
# define bonds for basis sites
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 3)
bonds1[1] = SVector{4, Int64}( 0, -1, 0, 1)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 1)
bonds1[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 3)
bonds2[1] = SVector{4, Int64}( 0, 1, 0, -1)
bonds2[2] = SVector{4, Int64}( 1, 0, 0, -1)
bonds2[3] = SVector{4, Int64}( 0, 0, 0, -1)
bonds[2] = bonds2
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1698 | function get_unitcell_hyperhoneycomb() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 4)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}(1.0, 1.0, 0.0)
basis[3] = SVector{3, Float64}(1.0, 2.0, 1.0)
basis[4] = SVector{3, Float64}(0.0, -1.0, 1.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(-1.0, 1.0, -2.0)
vectors[2] = SVector{3, Float64}(-1.0, 1.0, 2.0)
vectors[3] = SVector{3, Float64}( 2.0, 4.0, 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 3)
bonds1[1] = SVector{4, Int64}( 0, 0, 0, 1)
bonds1[2] = SVector{4, Int64}( 0, 0, 0, 3)
bonds1[3] = SVector{4, Int64}( 1, 0, 0, 3)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 3)
bonds2[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds2[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds2[3] = SVector{4, Int64}( 0, -1, 0, 1)
bonds[2] = bonds2
bonds3 = Vector{SVector{4, Int64}}(undef, 3)
bonds3[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds3[2] = SVector{4, Int64}( 0, 1, 0, -1)
bonds3[3] = SVector{4, Int64}( 0, 0, 1, 1)
bonds[3] = bonds3
bonds4 = Vector{SVector{4, Int64}}(undef, 3)
bonds4[1] = SVector{4, Int64}( 0, 0, 0, -3)
bonds4[2] = SVector{4, Int64}(-1, 0, 0, -3)
bonds4[3] = SVector{4, Int64}( 0, 0, -1, -1)
bonds[4] = bonds4
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 5104 | function get_unitcell_hyperkagome() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 12)
basis[1] = SVector{3, Float64}( 0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}(-1.0 / sqrt(2.0), 1.0 / sqrt(2.0), 0.0)
basis[3] = SVector{3, Float64}( 0.0, 1.0 / sqrt(2.0), 1.0 / sqrt(2.0))
basis[4] = SVector{3, Float64}( 0.0, 2.0 / sqrt(2.0), 2.0 / sqrt(2.0))
basis[5] = SVector{3, Float64}(-1.0 / sqrt(2.0), 2.0 / sqrt(2.0), 3.0 / sqrt(2.0))
basis[6] = SVector{3, Float64}(-2.0 / sqrt(2.0), 1.0 / sqrt(2.0), 3.0 / sqrt(2.0))
basis[7] = SVector{3, Float64}(-2.0 / sqrt(2.0), 0.0, 2.0 / sqrt(2.0))
basis[8] = SVector{3, Float64}(-3.0 / sqrt(2.0), 0.0, 3.0 / sqrt(2.0))
basis[9] = SVector{3, Float64}(-1.0 / sqrt(2.0), 3.0 / sqrt(2.0), 2.0 / sqrt(2.0))
basis[10] = SVector{3, Float64}(-2.0 / sqrt(2.0), 3.0 / sqrt(2.0), 1.0 / sqrt(2.0))
basis[11] = SVector{3, Float64}(-3.0 / sqrt(2.0), 3.0 / sqrt(2.0), 0.0)
basis[12] = SVector{3, Float64}(-3.0 / sqrt(2.0), 2.0 / sqrt(2.0), 1.0 / sqrt(2.0))
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(2.0 * sqrt(2.0), 0.0, 0.0)
vectors[2] = SVector{3, Float64}(0.0, 2.0 * sqrt(2.0), 0.0)
vectors[3] = SVector{3, Float64}(0.0, 0.0, 2.0 * sqrt(2.0))
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 4)
bonds1[1] = SVector{4, Int64}( 0, 0, 0, 1)
bonds1[2] = SVector{4, Int64}( 0, 0, 0, 2)
bonds1[3] = SVector{4, Int64}( 1, 0, -1, 7)
bonds1[4] = SVector{4, Int64}( 1, -1, 0, 10)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 4)
bonds2[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds2[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds2[3] = SVector{4, Int64}( 0, 0, -1, 3)
bonds2[4] = SVector{4, Int64}( 0, 0, -1, 4)
bonds[2] = bonds2
bonds3 = Vector{SVector{4, Int64}}(undef, 4)
bonds3[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds3[2] = SVector{4, Int64}( 0, 0, 0, -2)
bonds3[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds3[4] = SVector{4, Int64}( 1, 0, 0, 9)
bonds[3] = bonds3
bonds4 = Vector{SVector{4, Int64}}(undef, 4)
bonds4[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds4[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds4[3] = SVector{4, Int64}( 0, 0, 0, 5)
bonds4[4] = SVector{4, Int64}( 1, 0, 0, 8)
bonds[4] = bonds4
bonds5 = Vector{SVector{4, Int64}}(undef, 4)
bonds5[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds5[2] = SVector{4, Int64}( 0, 0, 0, 4)
bonds5[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds5[4] = SVector{4, Int64}( 0, 0, 1, -3)
bonds[5] = bonds5
bonds6 = Vector{SVector{4, Int64}}(undef, 4)
bonds6[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds6[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds6[3] = SVector{4, Int64}( 0, 0, 0, 2)
bonds6[4] = SVector{4, Int64}( 0, 0, 1, -4)
bonds[6] = bonds6
bonds7 = Vector{SVector{4, Int64}}(undef, 4)
bonds7[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds7[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds7[3] = SVector{4, Int64}( 0, -1, 0, 2)
bonds7[4] = SVector{4, Int64}( 0, -1, 0, 3)
bonds[7] = bonds7
bonds8 = Vector{SVector{4, Int64}}(undef, 4)
bonds8[1] = SVector{4, Int64}( 0, 0, 0, -2)
bonds8[2] = SVector{4, Int64}( 0, 0, 0, -1)
bonds8[3] = SVector{4, Int64}(-1, 0, 1, -7)
bonds8[4] = SVector{4, Int64}( 0, -1, 1, 3)
bonds[8] = bonds8
bonds9 = Vector{SVector{4, Int64}}(undef, 4)
bonds9[1] = SVector{4, Int64}( 0, 0, 0, -5)
bonds9[2] = SVector{4, Int64}( 0, 0, 0, -4)
bonds9[3] = SVector{4, Int64}( 0, 1, 0, -2)
bonds9[4] = SVector{4, Int64}( 0, 0, 0, 1)
bonds[9] = bonds9
bonds10 = Vector{SVector{4, Int64}}(undef, 4)
bonds10[1] = SVector{4, Int64}( 0, 1, 0, -3)
bonds10[2] = SVector{4, Int64}( 0, 0, 0, -1)
bonds10[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds10[4] = SVector{4, Int64}( 0, 0, 0, 2)
bonds[10] = bonds10
bonds11 = Vector{SVector{4, Int64}}(undef, 4)
bonds11[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds11[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds11[3] = SVector{4, Int64}(-1, 1, 0, -10)
bonds11[4] = SVector{4, Int64}( 0, 1, -1, -3)
bonds[11] = bonds11
bonds12 = Vector{SVector{4, Int64}}(undef, 4)
bonds12[1] = SVector{4, Int64}( 0, 0, 0, -2)
bonds12[2] = SVector{4, Int64}( 0, 0, 0, -1)
bonds12[3] = SVector{4, Int64}(-1, 0, 0, -9)
bonds12[4] = SVector{4, Int64}(-1, 0, 0, -8)
bonds[12] = bonds12
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1609 | function get_unitcell_kagome() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 3)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}(1.0, 0.0, 0.0)
basis[3] = SVector{3, Float64}(0.5, 0.5 * sqrt(3.0), 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(2.0, 0.0, 0.0)
vectors[2] = SVector{3, Float64}(1.0, sqrt(3.0), 0.0)
vectors[3] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 4)
bonds1[1] = SVector{4, Int64}( 0, 0, 0, 1)
bonds1[2] = SVector{4, Int64}( 0, 0, 0, 2)
bonds1[3] = SVector{4, Int64}(-1, 0, 0, 1)
bonds1[4] = SVector{4, Int64}( 0, -1, 0, 2)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 4)
bonds2[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds2[2] = SVector{4, Int64}( 1, 0, 0, -1)
bonds2[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds2[4] = SVector{4, Int64}( 1, -1, 0, 1)
bonds[2] = bonds2
bonds3 = Vector{SVector{4, Int64}}(undef, 4)
bonds3[1] = SVector{4, Int64}( 0, 0, 0, -2)
bonds3[2] = SVector{4, Int64}( 0, 0, 0, -1)
bonds3[3] = SVector{4, Int64}( 0, 1, 0, -2)
bonds3[4] = SVector{4, Int64}(-1, 1, 0, -1)
bonds[3] = bonds3
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2296 | function get_unitcell_pyrochlore() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 4)
basis[1] = SVector{3, Float64}( 0.0, 0.0, 0.0)
basis[2] = SVector{3, Float64}( 0.0, 0.25, 0.25)
basis[3] = SVector{3, Float64}(0.25, 0.0, 0.25)
basis[4] = SVector{3, Float64}(0.25, 0.25, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(0.0, 0.5, 0.5)
vectors[2] = SVector{3, Float64}(0.5, 0.0, 0.5)
vectors[3] = SVector{3, Float64}(0.5, 0.5, 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 6)
bonds1[1] = SVector{4, Int64}( 0, 0, 0, 1)
bonds1[2] = SVector{4, Int64}( 0, 0, 0, 2)
bonds1[3] = SVector{4, Int64}( 0, 0, 0, 3)
bonds1[4] = SVector{4, Int64}(-1, 0, 0, 1)
bonds1[5] = SVector{4, Int64}( 0, -1, 0, 2)
bonds1[6] = SVector{4, Int64}( 0, 0, -1, 3)
bonds[1] = bonds1
bonds2 = Vector{SVector{4, Int64}}(undef, 6)
bonds2[1] = SVector{4, Int64}( 0, 0, 0, -1)
bonds2[2] = SVector{4, Int64}( 0, 0, 0, 1)
bonds2[3] = SVector{4, Int64}( 0, 0, 0, 2)
bonds2[4] = SVector{4, Int64}( 1, 0, 0, -1)
bonds2[5] = SVector{4, Int64}( 1, -1, 0, 1)
bonds2[6] = SVector{4, Int64}( 1, 0, -1, 2)
bonds[2] = bonds2
bonds3 = Vector{SVector{4, Int64}}(undef, 6)
bonds3[1] = SVector{4, Int64}( 0, 0, 0, -2)
bonds3[2] = SVector{4, Int64}( 0, 0, 0, -1)
bonds3[3] = SVector{4, Int64}( 0, 0, 0, 1)
bonds3[4] = SVector{4, Int64}( 0, 1, 0, -2)
bonds3[5] = SVector{4, Int64}(-1, 1, 0, -1)
bonds3[6] = SVector{4, Int64}( 0, 1, -1, 1)
bonds[3] = bonds3
bonds4 = Vector{SVector{4, Int64}}(undef, 6)
bonds4[1] = SVector{4, Int64}( 0, 0, 0, -3)
bonds4[2] = SVector{4, Int64}( 0, 0, 0, -2)
bonds4[3] = SVector{4, Int64}( 0, 0, 0, -1)
bonds4[4] = SVector{4, Int64}( 0, 0, 1, -3)
bonds4[5] = SVector{4, Int64}(-1, 0, 1, -2)
bonds4[6] = SVector{4, Int64}( 0, -1, 1, -1)
bonds[4] = bonds4
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 905 | function get_unitcell_square() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 1)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(1.0, 0.0, 0.0)
vectors[2] = SVector{3, Float64}(0.0, 1.0, 0.0)
vectors[3] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 4)
bonds1[1] = SVector{4, Int64}( 1, 0, 0, 0)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 0)
bonds1[3] = SVector{4, Int64}( 0, 1, 0, 0)
bonds1[4] = SVector{4, Int64}( 0, -1, 0, 0)
bonds[1] = bonds1
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1048 | function get_unitcell_triangular() :: Unitcell
# define list of basis sites
basis = Vector{SVector{3, Float64}}(undef, 1)
basis[1] = SVector{3, Float64}(0.0, 0.0, 0.0)
# define list of Bravais vectors
vectors = Vector{SVector{3, Float64}}(undef, 3)
vectors[1] = SVector{3, Float64}(sqrt(3.0) / 2.0, -0.5, 0.0)
vectors[2] = SVector{3, Float64}(sqrt(3.0) / 2.0, 0.5, 0.0)
vectors[3] = SVector{3, Float64}( 0.0, 0.0, 0.0)
# define list of bonds for each basis site
bonds = Vector{Vector{SVector{4, Int64}}}(undef, length(basis))
bonds1 = Vector{SVector{4, Int64}}(undef, 6)
bonds1[1] = SVector{4, Int64}( 1, 0, 0, 0)
bonds1[2] = SVector{4, Int64}(-1, 0, 0, 0)
bonds1[3] = SVector{4, Int64}( 0, 1, 0, 0)
bonds1[4] = SVector{4, Int64}( 0, -1, 0, 0)
bonds1[5] = SVector{4, Int64}( 1, -1, 0, 0)
bonds1[6] = SVector{4, Int64}(-1, 1, 0, 0)
bonds[1] = bonds1
# build unitcell
uc = Unitcell(basis, vectors, bonds)
return uc
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 33719 | # function for measurements and checkpointing
function measure(
symmetry :: String,
obs_file :: String,
cp_file :: String,
Λ :: Float64,
dΛ :: Float64,
χ :: Vector{Matrix{Float64}},
χ_tol :: NTuple{2, Float64},
t :: DateTime,
t0 :: DateTime,
r :: Reduced_lattice,
m :: Mesh,
a :: Action,
wt :: Float64,
ct :: Float64
) :: Tuple{DateTime, Bool}
# open files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
# compute correlations
χp = deepcopy(χ)
compute_χ!(Λ, r, m, a, χ, χ_tol)
# save correlations and self energy if respective dataset does not yet exist
if haskey(obs, "χ/$(Λ)") == false
save_self!(obs, Λ, m, a)
save_χ!(obs, Λ, symmetry, m, χ)
end
# check for monotonicity of static part of dominant on-site correlation
idx = argmax(Float64[maximum(abs.(χ[i])) for i in eachindex(χ)])
monotone = χ[idx][1, 1] / χp[idx][1, 1] >= 0.995
# compute current run time (in hours)
h0 = 1e-3 * (Dates.now() - t0).value / 3600.0
# if more than half an hour is left to the wall time limit, use ct as timer heuristic for checkpointing
if wt - h0 > 0.5
# test if time limit for checkpoint (in hours) has been reached
h = 1e-3 * (Dates.now() - t).value / 3600.0
if h >= ct
# generate checkpoint if it does not exist yet
if haskey(cp, "a/$(Λ)") == false
println();
println("Generating checkpoint at cutoff Λ / |J| = $(Λ) ...")
checkpoint!(cp, Λ, dΛ, m, a)
println("Successfully generated checkpoint.")
println();
end
# reset timer
t = Dates.now()
end
# if less than half an hour is left to the wall time, generate checkpoints as if ct = 0. Lower bound to prevent cancellation during checkpoint writing
elseif 0.1 < wt - h0 <= 0.5
# generate checkpoint if it does not exist yet
if haskey(cp, "a/$(Λ)") == false
println(); println()
println("Generating checkpoint at cutoff Λ / |J| = $(Λ) ...")
checkpoint!(cp, Λ, dΛ, m, a)
println("Successfully generated checkpoint.")
println(); println()
end
end
# close files
close(obs)
close(cp)
return t, monotone
end
"""
save_launcher!(
path :: String,
f :: String,
name :: String,
size :: Int64,
model :: String,
symmetry :: String,
J :: Vector{<:Any}
;
A :: Float64 = 0.0,
S :: Float64 = 0.5,
β :: Float64 = 1.0,
euclidean :: Bool = false,
num_σ :: Int64 = 25,
num_Ω :: Int64 = 15,
num_ν :: Int64 = 10,
num_χ :: Int64 = 10,
p_σ :: NTuple{2, Float64} = (0.3, 1.0),
p_Ωs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_νs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_Ωt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.3, 50.0),
p_νt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.5, 50.0),
p_χ :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
lins :: NTuple{5, Float64} = (5.0, 4.0, 8.0, 6.0, 4.0),
bounds :: NTuple{5, Float64} = (0.5, 50.0, 250.0, 150.0, 50.0),
max_iter :: Int64 = 10,
min_eval :: Int64 = 10,
max_eval :: Int64 = 100,
Σ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
Γ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
χ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
parquet_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
ODE_tol :: NTuple{2, Float64} = (1e-8, 1e-2),
loops :: Int64 = 1,
parquet :: Bool = false,
Σ_corr :: Bool = true,
initial :: Float64 = 50.0,
final :: Float64 = 0.05,
bmin :: Float64 = 1e-4,
bmax :: Float64 = 0.2,
overwrite :: Bool = true,
cps :: Vector{Float64} = Float64[],
wt :: Float64 = 23.5,
ct :: Float64 = 4.0
) :: Nothing
Generate executable Julia file `path` which sets up and runs the FRG solver.
For more information on the different solver parameters see documentation of `launch!`.
"""
function save_launcher!(
path :: String,
f :: String,
name :: String,
size :: Int64,
model :: String,
symmetry :: String,
J :: Vector{<:Any}
;
A :: Float64 = 0.0,
S :: Float64 = 0.5,
β :: Float64 = 1.0,
euclidean :: Bool = false,
num_σ :: Int64 = 25,
num_Ω :: Int64 = 15,
num_ν :: Int64 = 10,
num_χ :: Int64 = 10,
p_σ :: NTuple{2, Float64} = (0.3, 1.0),
p_Ωs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_νs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_Ωt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.3, 50.0),
p_νt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.5, 50.0),
p_χ :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
lins :: NTuple{5, Float64} = (5.0, 4.0, 8.0, 6.0, 4.0),
bounds :: NTuple{5, Float64} = (0.5, 50.0, 250.0, 150.0, 50.0),
max_iter :: Int64 = 10,
min_eval :: Int64 = 10,
max_eval :: Int64 = 100,
Σ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
Γ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
χ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
parquet_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
ODE_tol :: NTuple{2, Float64} = (1e-8, 1e-2),
loops :: Int64 = 1,
parquet :: Bool = false,
Σ_corr :: Bool = true,
initial :: Float64 = 50.0,
final :: Float64 = 0.05,
bmin :: Float64 = 1e-4,
bmax :: Float64 = 0.2,
overwrite :: Bool = true,
cps :: Vector{Float64} = Float64[],
wt :: Float64 = 23.5,
ct :: Float64 = 4.0
) :: Nothing
# convert J for type safety
J = Array{Array{Float64,1},1}([[x...] for x in J])
open(path, "w") do file
# load source code
write(file, "using PFFRGSolver \n \n")
# setup for launcher function
write(file, """launch!("$(f)",
"$(name)",
$(size),
"$(model)",
"$(symmetry)",
$(J),
A = $(A),
S = $(S),
β = $(β),
euclidean = $(euclidean),
num_σ = $(num_σ),
num_Ω = $(num_Ω),
num_ν = $(num_ν),
num_χ = $(num_χ),
p_σ = $(p_σ),
p_Ωs = $(p_Ωs),
p_νs = $(p_νs),
p_Ωt = $(p_Ωt),
p_νt = $(p_νt),
p_χ = $(p_χ),
lins = $(lins),
bounds = $(bounds),
max_iter = $(max_iter),
min_eval = $(min_eval),
max_eval = $(max_eval),
Σ_tol = $(Σ_tol),
Γ_tol = $(Γ_tol),
χ_tol = $(χ_tol),
parquet_tol = $(parquet_tol),
ODE_tol = $(ODE_tol),
loops = $(loops),
parquet = $(parquet),
Σ_corr = $(Σ_corr),
initial = $(initial),
final = $(final),
bmin = $(bmin),
bmax = $(bmax),
overwrite = $(overwrite),
cps = $(cps),
wt = $(wt),
ct = $(ct))""")
end
return nothing
end
"""
make_job!(
path :: String,
dir :: String,
input :: String,
exe :: String,
sbatch_args :: Dict{String, String}
) :: Nothing
Generate a SLURM job file `path` to run the FRG solver on a cluster node. `dir` is the job working directory.
`input` is the launcher file generated by `save_launcher!`. `exe` is the path to the Julia executable.
`sbatch_args` is used to set SLURM parameters, e.g. `sbatch_args = Dict(["account" => "my_account", "mem" => "8gb"])`.
"""
function make_job!(
path :: String,
dir :: String,
input :: String,
exe :: String,
sbatch_args :: Dict{String, String}
) :: Nothing
# assert that input is a valid Julia script
@assert endswith(input, ".jl") "Input must be *.jl file."
# make local copy to prevent global modification of sbatch_args
args = copy(sbatch_args)
# set thread affinity, if not done already
if haskey(args, "export")
if occursin("JULIA_EXCLUSIVE", args["export"]) == false
args["export"] *= ",JULIA_EXCLUSIVE=1"
end
else
push!(args, "export" => "ALL,JULIA_EXCLUSIVE=1")
end
# set working directory, if not done already
if haskey(args, "chdir")
@warn "Overwriting working directory passed via SBATCH dict ..."
args["chdir"] = dir
else
push!(args, "chdir" => dir)
end
# set output file, if not done already
if haskey(args, "output") == false
output = split(input, ".jl")[1] * ".out"
push!(args, "output" => output)
end
open(path, "w") do file
# set SLURM parameters
write(file, "#!/bin/bash \n")
for arg in keys(args)
write(file, "#SBATCH --$(arg)=$(args[arg]) \n")
end
write(file, "\n")
# start calculation
write(file, "$(exe) -O3 -t \$SLURM_CPUS_PER_TASK $(input)")
end
return nothing
end
"""
make_repository!(
dir :: String,
exe :: String,
sbatch_args :: Dict{String, String}
) :: Nothing
Generate file structure for several runs of the FRG solver with presumably different parameters.
Assumes that the target folder `dir` contains only launcher files generated by `save_launcher!`.
`exe` is the path to the Julia executable. For each launcher file in `dir` a separate folder and job file are created.
`sbatch_args` is used to set SLURM parameters, e.g. `sbatch_args = Dict(["account" => "my_account", "mem" => "8gb"])`.
"""
function make_repository!(
dir :: String,
exe :: String,
sbatch_args :: Dict{String, String}
) :: Nothing
# init folder for saving finished calculations
fin_dir = joinpath(dir, "finished")
if isdir(fin_dir) == false
mkdir(fin_dir)
end
# for each *.jl file, init a new folder, move the *.jl file into it and create a job file
for file in readdir(dir)
if endswith(file, ".jl")
# buffer paths
subdir = joinpath(dir, split(file, ".jl")[1])
input = joinpath(subdir, file)
path = joinpath(subdir, split(file, ".jl")[1] * ".job")
# create subdir and job file
mkdir(subdir)
mv(joinpath(dir, file), input)
make_job!(path, subdir, file, exe, sbatch_args)
end
end
return nothing
end
"""
collect_repository!(
dir :: String
) :: Nothing
Collect final results in file structure generated by `make_repository!`.
Finished calculations are moved to the finished folder.
"""
function collect_repository!(
dir :: String
) :: Nothing
println("Collecting results from repository ...")
# check that finished folder exists
@assert isdir(joinpath(dir, "finished")) "Folder $(joinpath(dir, "finished")) does not exist."
# for each folder move *_obs, *_cp and *.out, then remove their parent dir. If calculation has not finished set overwrite = false in *.jl file
for file in readdir(dir)
if isdir(joinpath(dir, file)) && file != "finished"
# get file list of subdir
subdir = joinpath(dir, file)
subfiles = readdir(subdir)
# check if output files exist
obs_filter = filter(x -> endswith(x, "_obs"), subfiles)
if length(obs_filter) != 1
@warn "Could not find unique *_obs file in $(subdir), skipping ..."
continue
end
cp_filter = filter(x -> endswith(x, "_cp"), subfiles)
if length(cp_filter) != 1
@warn "Could not find unique *_cp file in $(subdir), skipping ..."
continue
end
out_filter = filter(x -> endswith(x, ".out"), subfiles)
if length(out_filter) != 1
@warn "Could not find unique *.out file in $(subdir), skipping ..."
continue
end
# buffer names of output files
obs_name = obs_filter[1]
cp_name = cp_filter[1]
out_name = out_filter[1]
# buffer paths of output files
obs_file = joinpath(subdir, obs_name)
cp_file = joinpath(subdir, cp_name)
out_file = joinpath(subdir, out_name)
# check if calculation is finished
obs_data = h5open(obs_file, "r")
cp_data = h5open(cp_file, "r")
if haskey(obs_data, "finished") && haskey(cp_data, "finished")
# close files
close(obs_data)
close(cp_data)
# move files to finished folder
mv(obs_file, joinpath(joinpath(dir, "finished"), obs_name))
mv(cp_file, joinpath(joinpath(dir, "finished"), cp_name))
mv(out_file, joinpath(joinpath(dir, "finished"), out_name))
# remove parent dir
rm(subdir, recursive = true)
else
# close files
close(obs_data)
close(cp_data)
# load the launcher
launcher_file = joinpath(subdir, file * ".jl")
stream = open(launcher_file, "r")
launcher = read(stream, String)
if occursin("overwrite = true", launcher)
# replace overwrite flag and overwrite stream
launcher = replace(launcher, "overwrite = true" => "overwrite = false")
stream = open(launcher_file, "w")
write(stream, launcher)
# close the stream
close(stream)
elseif occursin("overwrite = false", launcher)
# close the stream
close(stream)
else
# close the stream
close(stream)
# print error message
println("Parameter file $(launcher_file) seems to be broken.")
end
end
end
end
println("Done. Results collected in $(joinpath(dir, "finished")).")
return nothing
end
# load launchers for parquet equations and FRG
include("parquet.jl")
include("launcher_1l.jl")
include("launcher_2l.jl")
include("launcher_ml.jl")
"""
launch!(
f :: String,
name :: String,
size :: Int64,
model :: String,
symmetry :: String,
J :: Vector{<:Any}
;
A :: Float64 = 0.0,
S :: Float64 = 0.5,
β :: Float64 = 1.0,
euclidean :: Bool = false,
num_σ :: Int64 = 25,
num_Ω :: Int64 = 15,
num_ν :: Int64 = 10,
num_χ :: Int64 = 10,
p_σ :: NTuple{2, Float64} = (0.3, 1.0),
p_Ωs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_νs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_Ωt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.3, 50.0),
p_νt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.5, 50.0),
p_χ :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
lins :: NTuple{5, Float64} = (5.0, 4.0, 8.0, 6.0, 4.0),
bounds :: NTuple{5, Float64} = (0.5, 50.0, 250.0, 150.0, 50.0),
max_iter :: Int64 = 10,
min_eval :: Int64 = 10,
max_eval :: Int64 = 100,
Σ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
Γ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
χ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
parquet_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
ODE_tol :: NTuple{2, Float64} = (1e-8, 1e-2),
loops :: Int64 = 1,
parquet :: Bool = false,
Σ_corr :: Bool = true,
initial :: Float64 = 50.0,
final :: Float64 = 0.05,
bmin :: Float64 = 1e-4,
bmax :: Float64 = 0.2,
overwrite :: Bool = true,
cps :: Vector{Float64} = Float64[],
wt :: Float64 = 23.5,
ct :: Float64 = 4.0
) :: Nothing
Runs the FRG solver. A detailed explanation of the solver parameters is given below:
* `f` : name of the output files. The solver will generate two files (`f * "_obs"` and `f * "_cp"`) containing observables and checkpoints respectively.
* `name` : name of the lattice
* `size` : size of the lattice. Correlations are truncated beyond this range.
* `model` : name of the spin model. Defines coupling structure.
* `symmetry` : symmetry of the spin model. Used to reduce computational complexity.
* `J` : coupling vector of the spin model. J is normalized together with A during initialization of the solver.
* `A` : on-site repulsion term. A is normalized together with J during initialization of the solver.
* `S` : total spin quantum number (only relevant for pure Heisenberg models)
* `β` : damping factor for fixed point iterations of parquet equations
* `euclidean` : flag to build lattice by Euclidean (aka real space) instead of bond distance
* `num_σ` : number of non-zero, positive frequencies for the self energy
* `num_Ω` : number of non-zero, positive frequencies for the bosonic axis of the two-particle irreducible channels
* `num_ν` : number of non-zero, positive frequencies for the fermionic axis of the two-particle irreducible channels
* `num_χ` : number of non-zero, positive frequencies for the correlations
* `p_σ` : parameters for updating self energy mesh between ODE steps \n
p_σ[1] gives the percentage of linearly spaced frequencies
p_σ[2] sets the linear extent relative to the position of the quasi-particle peak
* `p_Ω / p_ν` : parameters for updating bosonic / fermionic s (u) and t channel frequency meshes between ODE steps \n
p_Γ[1] gives the percentage of linearly spaced frequencies
p_Γ[2] (p_Γ[3]) sets the lower (upper) bound for the accepted relative deviation between the values at the origin and the first finite frequency
p_Γ[4] sets the lower bound for the linear spacing in units of the cutoff Λ
p_Γ[5] sets the upper bound for the linear extent in units of the cutoff Λ
* `p_χ` : parameters for updating correlation mesh between ODE steps \n
p_χ[1] gives the percentage of linearly spaced frequencies
p_χ[2] (p_χ[3]) sets the lower (upper) bound for the accepted relative deviation between the values at the origin and the first finite frequency
p_χ[4] sets the lower bound for the linear spacing in units of the cutoff Λ
p_χ[5] sets the upper bound for the linear extent in units of the cutoff Λ
* `lins` : parameters for controlling the scaling of frequency meshes before adaptive scanning is utilized \n
lins[1] gives the scale, in units of |J|, beyond which adaptive meshes are used
lins[2] gives the linear extent, in units of the cutoff Λ, for the self energy
lins[3] gives the linear extent, in units of the cutoff Λ, for the bosonic axis of the two-particle irreducible channels
lins[4] gives the linear extent, in units of the cutoff Λ, for the fermionic axis of the two-particle irreducible channels
lins[5] gives the linear extent, in units of the cutoff Λ, for the correlations
* `bounds` : parameters for controlling the upper mesh bounds \n
bounds[1] gives, in units of |J|, the stopping scale beyond which no further contraction of the meshes is performed
bounds[2] gives, in units of the cutoff Λ, the upper bound for the self energy
bounds[3] gives, in units of the cutoff Λ, the upper bound for the bosonic axis of the two-particle irreducible channels
bounds[4] gives, in units of the cutoff Λ, the upper bound for the fermionic axis of the two-particle irreducible channels
bounds[5] gives, in units of the cutoff Λ, the upper bound for the correlations
* `max_iter` : maximum number of parquet iterations
* `min_eval` : minimum initial number of subdivisions for vertex quadrature. eval is min_eval for parquet iterations.
* `max_eval` : maximum initial number of subdivisions for vertex quadrature. eval is ramped up from min_eval to max_eval as a function of the cutoff Λ (for Λ < |J|).
* `Σ_tol` : absolute and relative error tolerance for self energy quadrature
* `Γ_tol` : absolute and relative error tolerance for vertex quadrature
* `χ_tol` : absolute and relative error tolerance for correlation quadrature
* `parquet_tol` : absolute and relative error tolerance for convergence of parquet iterations
* `ODE_tol` : absolute and relative error tolerance for Bogacki-Shampine solver
* `loops` : number of loops to be calculated
* `parquet` : flag to enable parquet iterations. If `false`, initial condition is chosen as bare vertex.
* `Σ_corr` : flag to enable self energy corrections. Has no effect for 'loops <= 2'.
* `initial` : start value of the cutoff in units of |J|
* `final` : final value of the cutoff in units of |J|. If `final = initial` and `parquet = true` only a solution of the parquet equations is computed.
* `bmin` : minimum step size of the ODE solver in units of |J|
* `bmax` : maximum step size of the ODE solver in units of Λ
* `overwrite` : flag to indicate whether a new calculation should be started. If false, checks if `f * "_obs"` and `f * "_cp"` exist and continues calculation from available checkpoint with lowest cutoff.
* `cps` : list of intermediate cutoffs in units of |J|, where a checkpoint with full vertex data shall be generated
* `wt` : wall time (in hours) for the calculation. Should be set according to cluster configurations. If run remote, set `wt = Inf` to avoid data loss. \n
WARNING: For run times longer than wt, no checkpoints are created.
* `ct` : minimum time (in hours) between subsequent checkpoints
"""
function launch!(
f :: String,
name :: String,
size :: Int64,
model :: String,
symmetry :: String,
J :: Vector{<:Any}
;
A :: Float64 = 0.0,
S :: Float64 = 0.5,
β :: Float64 = 1.0,
euclidean :: Bool = false,
num_σ :: Int64 = 25,
num_Ω :: Int64 = 15,
num_ν :: Int64 = 10,
num_χ :: Int64 = 10,
p_σ :: NTuple{2, Float64} = (0.3, 1.0),
p_Ωs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_νs :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
p_Ωt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.3, 50.0),
p_νt :: NTuple{5, Float64} = (0.3, 0.15, 0.20, 0.5, 50.0),
p_χ :: NTuple{5, Float64} = (0.3, 0.05, 0.10, 0.1, 50.0),
lins :: NTuple{5, Float64} = (5.0, 4.0, 8.0, 6.0, 4.0),
bounds :: NTuple{5, Float64} = (0.5, 50.0, 250.0, 150.0, 50.0),
max_iter :: Int64 = 10,
min_eval :: Int64 = 10,
max_eval :: Int64 = 100,
Σ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
Γ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
χ_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
parquet_tol :: NTuple{2, Float64} = (1e-8, 1e-5),
ODE_tol :: NTuple{2, Float64} = (1e-8, 1e-2),
loops :: Int64 = 1,
parquet :: Bool = false,
Σ_corr :: Bool = true,
initial :: Float64 = 50.0,
final :: Float64 = 0.05,
bmin :: Float64 = 1e-4,
bmax :: Float64 = 0.2,
overwrite :: Bool = true,
cps :: Vector{Float64} = Float64[],
wt :: Float64 = 23.5,
ct :: Float64 = 4.0
) :: Nothing
# init timers for checkpointing
t = Dates.now()
t0 = Dates.now()
println()
println("################################################################################")
println("Initializing solver ...")
println(); println()
# check if symmetry parameter is valid
symmetries = String["su2", "u1-dm"]
@assert in(symmetry, symmetries) "Symmetry $(symmetry) unknown. Valid arguments are su2 and u1-dm."
# init names for observables and checkpoints file
obs_file = f * "_obs"
cp_file = f * "_cp"
# test if a new calculation should be started
if overwrite
println("overwrite = true, starting from scratch ...")
# delete existing observables
if isfile(obs_file)
rm(obs_file)
end
# delete existing checkpoints
if isfile(cp_file)
rm(cp_file)
end
# open new files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
# convert J for type safety
J = Vector{Vector{Float64}}([[x...] for x in J])
# normalize couplings and level repulsion
JAtemp = normalize([J, [[A]]])
J = JAtemp[1]
A = JAtemp[2][1][1]
# build lattice and save to files
println();
l = get_lattice(name, size, euclidean = euclidean)
println();
r = get_reduced_lattice(model, J, l)
save!(obs, r)
save!(cp, r)
# close files
close(obs)
close(cp)
# build meshes
σ = get_mesh(lins[2] * initial, bounds[2] * max(initial, bounds[1]), num_σ, p_σ[1])
Ωs = get_mesh(lins[3] * initial, bounds[3] * max(initial, bounds[1]), num_Ω, p_Ωs[1])
νs = get_mesh(lins[4] * initial, bounds[4] * max(initial, bounds[1]), num_ν, p_νs[1])
Ωt = get_mesh(lins[3] * initial, bounds[3] * max(initial, bounds[1]), num_Ω, p_Ωt[1])
νt = get_mesh(lins[4] * initial, bounds[4] * max(initial, bounds[1]), num_ν, p_νt[1])
χ = get_mesh(lins[5] * initial, bounds[5] * max(initial, bounds[1]), num_χ, p_χ[1])
m = Mesh(num_σ + 1, num_Ω + 1, num_ν + 1, num_χ + 1, σ, Ωs, νs, Ωt, νt, χ)
# build action
a = get_action_empty(symmetry, r, m, S = S)
init_action!(l, r, a)
set_repulsion!(A, a)
# initialize by parquet iterations
if parquet
println(); println()
println("Warming up with some parquet iterations ...")
flush(stdout)
launch_parquet!(obs_file, cp_file, symmetry, l, r, m, a, initial, bmax * initial, β, max_iter, min_eval, Σ_tol, Γ_tol, χ_tol, parquet_tol, S = S)
println("Done. Action is initialized with parquet solution.")
end
println(); println()
println("Solver is ready.")
println("################################################################################")
println()
# start calculation
println("Renormalization group flow with ℓ = $(loops) ...")
flush(stdout)
if loops == 1
launch_1l!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, initial, final, bmax * initial, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
elseif loops == 2
launch_2l!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, initial, final, bmax * initial, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
elseif loops >= 3
launch_ml!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, loops, Σ_corr, initial, final, bmax * initial, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
end
else
println("overwrite = false, trying to load data ...")
if isfile(obs_file) && isfile(cp_file)
println()
println("Found existing output files, checking status ...")
# open files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
if haskey(obs, "finished") && haskey(cp, "finished")
# close files
close(obs)
close(cp)
println(); println()
println("Calculation has finished already.")
println("################################################################################")
flush(stdout)
else
println()
println("Final Λ has not been reached, resuming calculation ...")
# load data
l, r = read_lattice(cp)
Λ, dΛ, m, a_inter = read_checkpoint(cp, 0.0)
χ = read_χ_all(obs, Λ; verbose = false)[2]
# update frequency mesh
a = deepcopy(a_inter)
m = resample_from_to(Λ, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, m, a_inter, a, χ)
# close files
close(obs)
close(cp)
println(); println()
println("Solver is ready.")
println("################################################################################")
println()
# resume calculation
println("Renormalization group flow with ℓ = $(loops) ...")
flush(stdout)
if loops == 1
launch_1l!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, Λ, final, dΛ, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
elseif loops == 2
launch_2l!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, Λ, final, dΛ, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
elseif loops >= 3
launch_ml!(obs_file, cp_file, symmetry, l, r, m, a, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, loops, Σ_corr, Λ, final, dΛ, bmin, bmax, min_eval, max_eval, Σ_tol, Γ_tol, χ_tol, ODE_tol, t, t0, cps, wt, ct, A = A, S = S)
end
end
else
println(); println()
println("Found no existing output files, terminating solver ...")
println("################################################################################")
flush(stdout)
end
end
println()
println("################################################################################")
println("Solver terminated.")
println("################################################################################")
flush(stdout)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 7158 | function launch_1l!(
obs_file :: String,
cp_file :: String,
symmetry :: String,
l :: Lattice,
r :: Reduced_lattice,
m :: Mesh,
a :: Action,
p_σ :: NTuple{2, Float64},
p_Ωs :: NTuple{5, Float64},
p_νs :: NTuple{5, Float64},
p_Ωt :: NTuple{5, Float64},
p_νt :: NTuple{5, Float64},
p_χ :: NTuple{5, Float64},
lins :: NTuple{5, Float64},
bounds :: NTuple{5, Float64},
Λi :: Float64,
Λf :: Float64,
dΛi :: Float64,
bmin :: Float64,
bmax :: Float64,
min_eval :: Int64,
max_eval :: Int64,
Σ_tol :: NTuple{2, Float64},
Γ_tol :: NTuple{2, Float64},
χ_tol :: NTuple{2, Float64},
ODE_tol :: NTuple{2, Float64},
t :: DateTime,
t0 :: DateTime,
cps :: Vector{Float64},
wt :: Float64,
ct :: Float64
;
A :: Float64 = 0.0,
S :: Float64 = 0.5
) :: Nothing
# init ODE solver buffers
da = get_action_empty(symmetry, r, m, S = S)
a_stage = get_action_empty(symmetry, r, m, S = S)
a_inter = get_action_empty(symmetry, r, m, S = S)
a_err = get_action_empty(symmetry, r, m, S = S)
init_action!(l, r, a_inter)
set_repulsion!(A, a_inter)
# init buffers for evaluation of rhs
num_comps = length(a.Γ)
num_sites = length(r.sites)
tbuffs = NTuple{3, Matrix{Float64}}[(zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites)) for i in 1 : Threads.nthreads()]
temps = Array{Float64, 3}[zeros(Float64, num_sites, num_comps, 2) for i in 1 : Threads.nthreads()]
corrs = zeros(Float64, 2, 3, m.num_Ω)
# init cutoff, step size, monotonicity and correlations
Λ = Λi
dΛ = dΛi
monotone = true
χ = get_χ_empty(symmetry, r, m)
# set up required checkpoints
push!(cps, Λi)
push!(cps, Λf)
cps = sort(unique(cps), rev = true)
for i in eachindex(cps)
if cps[i] < Λ
dΛ = min(dΛ, 0.85 * (Λ - cps[i]))
break
end
end
# compute renormalization group flow
while Λ > Λf
println()
println("ODE step at cutoff Λ / |J| = $(Λ) ...")
flush(stdout)
# set eval for integration
eval = min(max(ceil(Int64, min_eval / Λ), min_eval), max_eval)
# prepare da and a_err
replace_with!(da, a)
replace_with!(a_err, a)
# compute k1 and parse to da and a_err
compute_dΣ!(Λ, r, m, a, a_stage, Σ_tol)
compute_dΓ_1l!(Λ, r, m, a, a_stage, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -2.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -7.0 * dΛ / 24.0, a_err)
# compute k2 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.5 * dΛ, a_inter)
compute_dΣ!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_1l!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 4.0, a_err)
# compute k3 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.75 * dΛ, a_inter)
compute_dΣ!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_1l!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -4.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, a_err)
# compute k4 and parse to a_err
replace_with!(a_inter, da)
compute_dΣ!(Λ - dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_1l!(Λ - dΛ, r, m, a_inter, a_stage, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -1.0 * dΛ / 8.0, a_err)
# estimate integration error
subtract_from!(a_inter, a_err)
Δ = get_abs_max(a_err)
scale = ODE_tol[1] + max(get_abs_max(a_inter), get_abs_max(a)) * ODE_tol[2]
err = Δ / scale
println(" Relative integration error err = $(err).")
println(" Current vertex maximum Γmax = $(get_abs_max(a_inter)).")
println(" Performing sanity checks and measurements ...")
if err <= 1.0 || dΛ <= bmin
# update cutoff
Λ -= dΛ
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
# terminate if vertex diverges
if get_abs_max(a_inter) > max(min(50.0 / Λ, 1000), 10.0)
println(" Vertex has diverged, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# do measurements and checkpointing
mk_cp = false
for i in eachindex(cps)
if Λ ≈ cps[i]
mk_cp = true
break
end
end
if mk_cp
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
else
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, ct)
end
# terminate if correlations show non-monotonicity
if monotone == false
println(" Flowing correlations show non-monotonicity, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# update frequency mesh
m = resample_from_to(Λ, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, m, a_inter, a, χ)
if Λ > Λf
println("Done. Proceeding to next ODE step.")
end
else
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
println("Done. Repeating ODE step with smaller dΛ.")
end
end
# open files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
# set finished flags
obs["finished"] = true
cp["finished"] = true
# close files
close(obs)
close(cp)
println("Renormalization group flow finished.")
flush(stdout)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 7285 | function launch_2l!(
obs_file :: String,
cp_file :: String,
symmetry :: String,
l :: Lattice,
r :: Reduced_lattice,
m :: Mesh,
a :: Action,
p_σ :: NTuple{2, Float64},
p_Ωs :: NTuple{5, Float64},
p_νs :: NTuple{5, Float64},
p_Ωt :: NTuple{5, Float64},
p_νt :: NTuple{5, Float64},
p_χ :: NTuple{5, Float64},
lins :: NTuple{5, Float64},
bounds :: NTuple{5, Float64},
Λi :: Float64,
Λf :: Float64,
dΛi :: Float64,
bmin :: Float64,
bmax :: Float64,
min_eval :: Int64,
max_eval :: Int64,
Σ_tol :: NTuple{2, Float64},
Γ_tol :: NTuple{2, Float64},
χ_tol :: NTuple{2, Float64},
ODE_tol :: NTuple{2, Float64},
t :: DateTime,
t0 :: DateTime,
cps :: Vector{Float64},
wt :: Float64,
ct :: Float64
;
A :: Float64 = 0.0,
S :: Float64 = 0.5
) :: Nothing
# init ODE solver buffers
da = get_action_empty(symmetry, r, m, S = S)
a_stage = get_action_empty(symmetry, r, m, S = S)
a_inter = get_action_empty(symmetry, r, m, S = S)
a_err = get_action_empty(symmetry, r, m, S = S)
init_action!(l, r, a_inter)
set_repulsion!(A, a_inter)
# init left part (right part by symmetry)
da_l = get_action_empty(symmetry, r, m, S = S)
# init buffers for evaluation of rhs
num_comps = length(a.Γ)
num_sites = length(r.sites)
tbuffs = NTuple{3, Matrix{Float64}}[(zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites)) for i in 1 : Threads.nthreads()]
temps = Array{Float64, 3}[zeros(Float64, num_sites, num_comps, 4) for i in 1 : Threads.nthreads()]
corrs = zeros(Float64, 2, 3, m.num_Ω)
# init cutoff, step size, monotonicity and correlations
Λ = Λi
dΛ = dΛi
monotone = true
χ = get_χ_empty(symmetry, r, m)
# set up required checkpoints
push!(cps, Λi)
push!(cps, Λf)
cps = sort(unique(cps), rev = true)
for i in eachindex(cps)
if cps[i] < Λ
dΛ = min(dΛ, 0.85 * (Λ - cps[i]))
break
end
end
# compute renormalization group flow
while Λ > Λf
println()
println("ODE step at cutoff Λ / |J| = $(Λ) ...")
flush(stdout)
# set eval for integration
eval = min(max(ceil(Int64, min_eval / Λ), min_eval), max_eval)
# prepare da and a_err
replace_with!(da, a)
replace_with!(a_err, a)
# compute k1 and parse to da and a_err
compute_dΣ!(Λ, r, m, a, a_stage, Σ_tol)
compute_dΓ_2l!(Λ, r, m, a, a_stage, da_l, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -2.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -7.0 * dΛ / 24.0, a_err)
# compute k2 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.5 * dΛ, a_inter)
compute_dΣ!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_2l!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, da_l, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 4.0, a_err)
# compute k3 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.75 * dΛ, a_inter)
compute_dΣ!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_2l!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, da_l, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -4.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, a_err)
# compute k4 and parse to a_err
replace_with!(a_inter, da)
compute_dΣ!(Λ - dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_2l!(Λ - dΛ, r, m, a_inter, a_stage, da_l, tbuffs, temps, corrs, eval, Γ_tol)
mult_with_add_to!(a_stage, -1.0 * dΛ / 8.0, a_err)
# estimate integration error
subtract_from!(a_inter, a_err)
Δ = get_abs_max(a_err)
scale = ODE_tol[1] + max(get_abs_max(a_inter), get_abs_max(a)) * ODE_tol[2]
err = Δ / scale
println(" Relative integration error err = $(err).")
println(" Current vertex maximum Γmax = $(get_abs_max(a_inter)).")
println(" Performing sanity checks and measurements ...")
if err <= 1.0 || dΛ <= bmin
# update cutoff
Λ -= dΛ
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
# terminate if vertex diverges
if get_abs_max(a_inter) > max(min(50.0 / Λ, 1000), 10.0)
println(" Vertex has diverged, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# do measurements and checkpointing
mk_cp = false
for i in eachindex(cps)
if Λ ≈ cps[i]
mk_cp = true
break
end
end
if mk_cp
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
else
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, ct)
end
# terminate if correlations show non-monotonicity
if monotone == false
println(" Flowing correlations show non-monotonicity, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# update frequency mesh
m = resample_from_to(Λ, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, m, a_inter, a, χ)
if Λ > Λf
println("Done. Proceeding to next ODE step.")
end
else
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
println("Done. Repeating ODE step with smaller dΛ.")
end
end
# open files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
# set finished flags
obs["finished"] = true
cp["finished"] = true
# close files
close(obs)
close(cp)
println("Renormalization group flow finished.")
flush(stdout)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 8001 | function launch_ml!(
obs_file :: String,
cp_file :: String,
symmetry :: String,
l :: Lattice,
r :: Reduced_lattice,
m :: Mesh,
a :: Action,
p_σ :: NTuple{2, Float64},
p_Ωs :: NTuple{5, Float64},
p_νs :: NTuple{5, Float64},
p_Ωt :: NTuple{5, Float64},
p_νt :: NTuple{5, Float64},
p_χ :: NTuple{5, Float64},
lins :: NTuple{5, Float64},
bounds :: NTuple{5, Float64},
loops :: Int64,
Σ_corr :: Bool,
Λi :: Float64,
Λf :: Float64,
dΛi :: Float64,
bmin :: Float64,
bmax :: Float64,
min_eval :: Int64,
max_eval :: Int64,
Σ_tol :: NTuple{2, Float64},
Γ_tol :: NTuple{2, Float64},
χ_tol :: NTuple{2, Float64},
ODE_tol :: NTuple{2, Float64},
t :: DateTime,
t0 :: DateTime,
cps :: Vector{Float64},
wt :: Float64,
ct :: Float64
;
A :: Float64 = 0.0,
S :: Float64 = 0.5
) :: Nothing
# init ODE solver buffers
da = get_action_empty(symmetry, r, m, S = S)
a_stage = get_action_empty(symmetry, r, m, S = S)
a_inter = get_action_empty(symmetry, r, m, S = S)
a_err = get_action_empty(symmetry, r, m, S = S)
init_action!(l, r, a_inter)
set_repulsion!(A, a_inter)
# init left (right part by symmetry) and central part, full loop contribution and self energy corrections
da_l = get_action_empty(symmetry, r, m, S = S)
da_c = get_action_empty(symmetry, r, m, S = S)
da_temp = get_action_empty(symmetry, r, m, S = S)
da_Σ = get_action_empty(symmetry, r, m, S = S)
# init buffers for evaluation of rhs
num_comps = length(a.Γ)
num_sites = length(r.sites)
tbuffs = NTuple{3, Matrix{Float64}}[(zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites)) for i in 1 : Threads.nthreads()]
temps = Array{Float64, 3}[zeros(Float64, num_sites, num_comps, 4) for i in 1 : Threads.nthreads()]
corrs = zeros(Float64, 2, 3, m.num_Ω)
# init cutoff, step size, monotonicity and correlations
Λ = Λi
dΛ = dΛi
monotone = true
χ = get_χ_empty(symmetry, r, m)
# set up required checkpoints
push!(cps, Λi)
push!(cps, Λf)
cps = sort(unique(cps), rev = true)
for i in eachindex(cps)
if cps[i] < Λ
dΛ = min(dΛ, 0.85 * (Λ - cps[i]))
break
end
end
# compute renormalization group flow
while Λ > Λf
println()
println("ODE step at cutoff Λ / |J| = $(Λ) ...")
flush(stdout)
# set eval for integration
eval = min(max(ceil(Int64, min_eval / Λ), min_eval), max_eval)
# prepare da and a_err
replace_with!(da, a)
replace_with!(a_err, a)
# compute k1 and parse to da and a_err
compute_dΣ!(Λ, r, m, a, a_stage, Σ_tol)
compute_dΓ_ml!(Λ, r, m, loops, a, a_stage, da_l, da_c, da_temp, da_Σ, tbuffs, temps, corrs, eval, Γ_tol)
if Σ_corr compute_dΣ_corr!(Λ, r, m, a, a_stage, da_Σ, Σ_tol) end
mult_with_add_to!(a_stage, -2.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -7.0 * dΛ / 24.0, a_err)
# compute k2 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.5 * dΛ, a_inter)
compute_dΣ!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_ml!(Λ - 0.5 * dΛ, r, m, loops, a_inter, a_stage, da_l, da_c, da_temp, da_Σ, tbuffs, temps, corrs, eval, Γ_tol)
if Σ_corr compute_dΣ_corr!(Λ - 0.5 * dΛ, r, m, a_inter, a_stage, da_Σ, Σ_tol) end
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 4.0, a_err)
# compute k3 and parse to da and a_err
replace_with!(a_inter, a)
mult_with_add_to!(a_stage, -0.75 * dΛ, a_inter)
compute_dΣ!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_ml!(Λ - 0.75 * dΛ, r, m, loops, a_inter, a_stage, da_l, da_c, da_temp, da_Σ, tbuffs, temps, corrs, eval, Γ_tol)
if Σ_corr compute_dΣ_corr!(Λ - 0.75 * dΛ, r, m, a_inter, a_stage, da_Σ, Σ_tol) end
mult_with_add_to!(a_stage, -4.0 * dΛ / 9.0, da)
mult_with_add_to!(a_stage, -1.0 * dΛ / 3.0, a_err)
# compute k4 and parse to a_err
replace_with!(a_inter, da)
compute_dΣ!(Λ - dΛ, r, m, a_inter, a_stage, Σ_tol)
compute_dΓ_ml!(Λ - dΛ, r, m, loops, a_inter, a_stage, da_l, da_c, da_temp, da_Σ, tbuffs, temps, corrs, eval, Γ_tol)
if Σ_corr compute_dΣ_corr!(Λ - dΛ, r, m, a_inter, a_stage, da_Σ, Σ_tol) end
mult_with_add_to!(a_stage, -1.0 * dΛ / 8.0, a_err)
# estimate integration error
subtract_from!(a_inter, a_err)
Δ = get_abs_max(a_err)
scale = ODE_tol[1] + max(get_abs_max(a_inter), get_abs_max(a)) * ODE_tol[2]
err = Δ / scale
println(" Relative integration error err = $(err).")
println(" Current vertex maximum Γmax = $(get_abs_max(a_inter)).")
println(" Performing sanity checks and measurements ...")
if err <= 1.0 || dΛ <= bmin
# update cutoff
Λ -= dΛ
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
# terminate if vertex diverges
if get_abs_max(a_inter) > max(min(50.0 / Λ, 1000), 10.0)
println(" Vertex has diverged, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# do measurements and checkpointing
mk_cp = false
for i in eachindex(cps)
if Λ ≈ cps[i]
mk_cp = true
break
end
end
if mk_cp
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
else
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, ct)
end
# terminate if correlations show non-monotonicity
if monotone == false
println(" Flowing correlations show non-monotonicity, terminating solver ...")
t, monotone = measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, t, t0, r, m, a_inter, wt, 0.0)
break
end
# update frequency mesh
m = resample_from_to(Λ, p_σ, p_Ωs, p_νs, p_Ωt, p_νt, p_χ, lins, bounds, m, a_inter, a, χ)
if Λ > Λf
println("Done. Proceeding to next ODE step.")
end
else
# update step size
dΛ = max(bmin, min(bmax * Λ, 0.85 * (1.0 / err)^(1.0 / 3.0) * dΛ))
# check if we pass by required checkpoint and adjust step size accordingly
cps_lower = filter(x -> x < 0.0, cps .- Λ)
Λ_cp = 0.0
if length(cps_lower) >= 1
Λ_cp = Λ + first(cps_lower)
end
dΛ = min(dΛ, Λ - Λ_cp)
println("Done. Repeating ODE step with smaller dΛ.")
end
end
# open files
obs = h5open(obs_file, "cw")
cp = h5open(cp_file, "cw")
# set finished flags
obs["finished"] = true
cp["finished"] = true
# close files
close(obs)
close(cp)
println("Renormalization group flow finished.")
flush(stdout)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2650 | function launch_parquet!(
obs_file :: String,
cp_file :: String,
symmetry :: String,
l :: Lattice,
r :: Reduced_lattice,
m :: Mesh,
a :: Action,
Λ :: Float64,
dΛ :: Float64,
β :: Float64,
max_iter :: Int64,
eval :: Int64,
Σ_tol :: NTuple{2, Float64},
Γ_tol :: NTuple{2, Float64},
χ_tol :: NTuple{2, Float64},
parquet_tol :: NTuple{2, Float64}
;
S :: Float64 = 0.5
) :: Nothing
# init output and error buffer
ap = get_action_empty(symmetry, r, m, S = S)
a_err = get_action_empty(symmetry, r, m, S = S)
# init buffers for evaluation of rhs
num_comps = length(a.Γ)
num_sites = length(r.sites)
tbuffs = NTuple{3, Matrix{Float64}}[(zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites), zeros(Float64, num_comps, num_sites)) for i in 1 : Threads.nthreads()]
temps = Array{Float64, 3}[zeros(Float64, num_sites, num_comps, 2) for i in 1 : Threads.nthreads()]
corrs = zeros(Float64, 2, 3, m.num_Ω)
# init errors and iteration count
abs_err = Inf
rel_err = Inf
count = 1
# compute fixed point
while abs_err >= parquet_tol[1] && rel_err >= parquet_tol[2] && count <= max_iter
println();
println("Parquet iteration $count ...")
# compute SDE
println(" Computing SDE ...")
compute_Σ!(Λ, r, m, a, ap, tbuffs, temps, corrs, eval, Γ_tol, Σ_tol)
# compute BSEs
println(" Computing BSEs ...")
compute_Γ!(Λ, r, m, a, ap, tbuffs, temps, corrs, eval, Γ_tol)
# compute the errors
replace_with!(a_err, ap)
mult_with_add_to!(a, -1.0, a_err)
abs_err = get_abs_max(a_err)
rel_err = abs_err / max(get_abs_max(a), get_abs_max(ap))
println("Done. Relative error err = $(rel_err).")
flush(stdout)
# update current solution using damping factor β
mult_with!(a, 1 - β)
mult_with_add_to!(ap, β, a)
# increment iteration count
count += 1
end
if count <= max_iter
println();
println("Converged to fixed point, terminating parquet iterations ...")
else
println();
println("Maximum number of iterations reached, terminating parquet iterations ...")
end
flush(stdout)
# save final result
χ = get_χ_empty(symmetry, r, m)
measure(symmetry, obs_file, cp_file, Λ, dΛ, χ, χ_tol, Dates.now(), Dates.now(), r, m, a, Inf, 0.0)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 291 | # load code
include("momentum.jl")
include("disk.jl")
# load calculation of occupation number fluctuations
include("fluctuations.jl")
# load correlations for different symmetries
include("correlation_lib/correlation_lib.jl")
# load tests and timers
include("test.jl")
include("timers.jl") | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 11215 | # save real space correlations to HDF5 file
function save_χ!(
file :: HDF5.File,
Λ :: Float64,
symmetry :: String,
m :: Mesh,
χ :: Vector{Matrix{Float64}}
) :: Nothing
# save symmetry group
if haskey(file, "symmetry") == false
file["symmetry"] = symmetry
end
# save frequency mesh
file["χ/$(Λ)/mesh"] = m.χ
if symmetry == "su2"
file["χ/$(Λ)/diag"] = χ[1]
elseif symmetry == "u1-dm"
file["χ/$(Λ)/xx"] = χ[1]
file["χ/$(Λ)/zz"] = χ[2]
file["χ/$(Λ)/xy"] = χ[3]
end
return nothing
end
"""
read_χ_labels(
file :: HDF5.File
) :: Vector{String}
Read labels of available real space correlations from HDF5 file (*_obs).
"""
function read_χ_labels(
file :: HDF5.File
) :: Vector{String}
ref = keys(file["χ"])[1]
labels = String[]
for key in keys(file["χ/$(ref)"])
if key != "mesh"
push!(labels, key)
end
end
return labels
end
"""
read_χ(
file :: HDF5.File,
Λ :: Float64,
label :: String
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Matrix{Float64}}
Read real space correlations with name `label` and the associated frequency mesh from HDF5 file (*_obs) at cutoff Λ.
"""
function read_χ(
file :: HDF5.File,
Λ :: Float64,
label :: String
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Matrix{Float64}}
# filter out nearest available cutoff
list = keys(file["χ"])
cutoffs = parse.(Float64, list)
index = argmin(abs.(cutoffs .- Λ))
if verbose
println("Λ was adjusted to $(cutoffs[index]).")
end
# read frequency mesh
m = read(file, "χ/$(cutoffs[index])/mesh")
# read correlations with requested label
χ = read(file, "χ/$(cutoffs[index])/" * label)
return m, χ
end
"""
read_χ_all(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Vector{Matrix{Float64}}}
Read all available real space correlations and the associated frequency mesh from HDF5 file (*_obs) at cutoff Λ.
"""
function read_χ_all(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Vector{Matrix{Float64}}}
# filter out nearest available cutoff
list = keys(file["χ"])
cutoffs = parse.(Float64, list)
index = argmin(abs.(cutoffs .- Λ))
if verbose
println("Λ was adjusted to $(cutoffs[index]).")
end
# read symmetry group
symmetry = read(file, "symmetry")
# read frequency mesh
m = read(file, "χ/$(cutoffs[index])/mesh")
# read correlations
χ = Matrix{Float64}[]
for label in read_χ_labels(file)
push!(χ, read(file, "χ/$(cutoffs[index])/" * label))
end
return m, χ
end
"""
read_χ_flow_at_site(
file :: HDF5.File,
site :: Int64,
label :: String
) :: NTuple{2, Vector{Float64}}
Read flow of static real space correlations with name `label` from HDF5 file (*_obs) at irreducible site.
"""
function read_χ_flow_at_site(
file :: HDF5.File,
site :: Int64,
label :: String
) :: NTuple{2, Vector{Float64}}
# filter out a sorted list of cutoffs
list = keys(file["χ"])
cutoffs = sort(parse.(Float64, list), rev = true)
# allocate array to store values
χ = zeros(Float64, length(cutoffs))
# fill array with values at given site
for i in eachindex(cutoffs)
χ[i] = read(file, "χ/$(cutoffs[i])/" * label)[site, 1]
end
return cutoffs, χ
end
"""
compute_structure_factor_flow!(
file_in :: HDF5.File,
file_out :: HDF5.File,
k :: Matrix{Float64},
label :: String
) :: Nothing
Compute the flow of the structure factor from real space correlations with name `label` in file_in (*_obs) and save the result to file_out.
The momentum space discretization k should be formatted such that k[:, n] is the n-th momentum.
"""
function compute_structure_factor_flow!(
file_in :: HDF5.File,
file_out :: HDF5.File,
k :: Matrix{Float64},
label :: String
) :: Nothing
# filter out a sorted list of cutoffs
list = keys(file_in["χ"])
cutoffs = sort(parse.(Float64, list), rev = true)
# read lattice and reduced lattice
l, r = read_lattice(file_in)
# save momenta
if haskey(file_out, "k") == false
file_out["k"] = k
end
println("Computing structure factor flow ...")
# compute and save structure factors
for Λ in cutoffs
# read correlations
m, χ = read_χ(file_in, Λ, label, verbose = false)
# save frequency mesh
file_out["s/$(Λ)/mesh"] = m
# allocate output matrix
smat = zeros(Float64, size(k, 2), length(m))
# compute structure factors for all Matsubara frequencies
for w in eachindex(m)
smat[:, w] .= compute_structure_factor(χ[:, w], k, l, r)
end
# save structure factors
file_out["s/$(Λ)/" * label] = smat
end
println("Done.")
return nothing
end
"""
compute_structure_factor_flow_all!(
file_in :: HDF5.File,
file_out :: HDF5.File,
k :: Matrix{Float64}
) :: Nothing
Compute the flows of the structure factors for all available real space correlations in file_in (*_obs) and save the result to file_out.
The momentum space discretization k should be formatted such that k[:, n] is the n-th momentum.
"""
function compute_structure_factor_flow_all!(
file_in :: HDF5.File,
file_out :: HDF5.File,
k :: Matrix{Float64}
) :: Nothing
# filter out a sorted list of cutoffs
list = keys(file_in["χ"])
cutoffs = sort(parse.(Float64, list), rev = true)
# read lattice and reduced lattice
l, r = read_lattice(file_in)
# save momenta
if haskey(file_out, "k") == false
file_out["k"] = k
end
println("Computing structure factor flows ...")
# read available labels
for label in read_χ_labels(file_in)
# compute and save structure factors
for Λ in cutoffs
# read correlations
m, χ = read_χ(file_in, Λ, label, verbose = false)
# save frequency mesh
if haskey(file_out, "s/$(Λ)/mesh") == false
file_out["s/$(Λ)/mesh"] = m
end
# allocate output matrix
smat = zeros(Float64, size(k, 2), length(m))
# compute structure factors for all Matsubara frequencies
for w in eachindex(m)
smat[:, w] .= compute_structure_factor(χ[:, w], k, l, r)
end
# save structure factors
file_out["s/$(Λ)/" * label] = smat
end
end
println("Done.")
return nothing
end
"""
read_structure_factor_labels(
file :: HDF5.File
) :: Vector{String}
Read labels of available structure factors from HDF5 file (*_obs).
"""
function read_structure_factor_labels(
file :: HDF5.File
) :: Vector{String}
ref = keys(file["s"])[1]
labels = String[]
for key in keys(file["s/$(ref)"])
if key != "mesh"
push!(labels, key)
end
end
return labels
end
"""
read_structure_factor(
file :: HDF5.File,
Λ :: Float64,
label :: String
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Matrix{Float64}}
Read structure factor with name `label` and the associated frequency mesh from HDF5 file at cutoff Λ.
"""
function read_structure_factor(
file :: HDF5.File,
Λ :: Float64,
label :: String
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Matrix{Float64}}
# filter out nearest available cutoff
list = keys(file["s"])
cutoffs = parse.(Float64, list)
index = argmin(abs.(cutoffs .- Λ))
if verbose
println("Λ was adjusted to $(cutoffs[index]).")
end
# read frequency mesh
m = read(file, "s/$(cutoffs[index])/mesh")
# read structure factor with requested label
s = read(file, "s/$(cutoffs[index])/" * label)
return m, s
end
"""
read_structure_factor_all(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Vector{Matrix{Float64}}}
Read all available structure factors and the associated frequency mesh from HDF5 file at cutoff Λ.
"""
function read_structure_factor_all(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Tuple{Vector{Float64}, Vector{Matrix{Float64}}}
# filter out nearest available cutoff
list = keys(file["s"])
cutoffs = parse.(Float64, list)
index = argmin(abs.(cutoffs .- Λ))
if verbose
println("Λ was adjusted to $(cutoffs[index]).")
end
# read frequency mesh
m = read(file, "s/$(cutoffs[index])/mesh")
# read structure factors
s = Matrix{Float64}[]
for label in read_structure_factor_labels(file)
push!(s, read(file, "s/$(cutoffs[index])/" * label))
end
return m, s
end
"""
read_structure_factor_flow_at_momentum(
file :: HDF5.File,
p :: Vector{Float64},
label :: String
;
verbose :: Bool = true
) :: NTuple{2, Vector{Float64}}
Read flow of static structure factor with name `label` from HDF5 file at momentum p.
"""
function read_structure_factor_flow_at_momentum(
file :: HDF5.File,
p :: Vector{Float64},
label :: String
;
verbose :: Bool = true
) :: NTuple{2, Vector{Float64}}
# filter out a sorted list of cutoffs
list = keys(file["s"])
cutoffs = sort(parse.(Float64, list), rev = true)
# locate closest momentum
k = read(file, "k")
dists = Float64[norm(k[:, i] .- p) for i in 1 : size(k, 2)]
index = argmin(dists)
if verbose
println("Momentum was adjusted to k = $(k[:, index]).")
end
# allocate array to store values
s = zeros(Float64, length(cutoffs))
# fill array with values at given momentum
for i in eachindex(cutoffs)
s[i] = read(file, "s/$(cutoffs[i])/" * label)[index, 1]
end
return cutoffs, s
end
"""
read_reference_momentum(
file :: HDF5.File,
Λ :: Float64,
label :: String
) :: Vector{Float64}
Read the momentum with maximum static structure factor value with name `label` at cutoff Λ from HDF5 file.
"""
function read_reference_momentum(
file :: HDF5.File,
Λ :: Float64,
label :: String
) :: Vector{Float64}
# read struture factor
m, s = read_structure_factor(file, Λ, label)
# determine momentum with maximum amplitude
k = read(file, "k")
p = k[:, argmax(s[:, 1])]
return p
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1301 | # load fluctuation implementations
include("fluctuation_lib/fluctuation_su2.jl")
include("fluctuation_lib/fluctuation_u1_dm.jl")
# auxiliary function to compute occupation number fluctuations
function compute_fluctuations(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Float64
# read symmetry
symmetry = read(file["symmetry"])
# init number fluctuations
eq_corr = 0.0
if symmetry == "su2"
eq_corr = compute_eq_corr_su2(file, Λ, verbose = verbose)
elseif symmetry == "u1-dm"
eq_corr = compute_eq_corr_u1_dm(file, Λ, verbose = verbose)
end
# compute variance of occupation number operator
var = 1.0 - 4.0 * eq_corr / 3.0
return var
end
# auxiliary function to compute flow of occupation number fluctuations
function compute_fluctuations_flow(
file :: HDF5.File,
) :: NTuple{2, Vector{Float64}}
# filter out a sorted list of cutoffs
list = keys(file["χ"])
cutoffs = sort(parse.(Float64, list), rev = true)
# allocate array to store values
vars = zeros(Float64, length(cutoffs))
# fill array with values
for i in eachindex(cutoffs)
vars[i] = compute_fluctuations(file, cutoffs[i], verbose = false)
end
return cutoffs, vars
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 4485 | """
get_momenta(
rx :: NTuple{2, Float64},
ry :: NTuple{2, Float64},
rz :: NTuple{2, Float64},
num :: NTuple{3, Int64}
) :: Matrix{Float64}
Generate a uniform momentum space discretization within a cuboid. rx, ry and rz are the respective cartesian boundaries.
num = (num_x, num_y, num_z) contains the desired number of steps (spacing h = (r[2] - r[1]) / num) along the respective axis.
Returns a matrix k, with k[:, n] being the n-th momentum vector.
"""
function get_momenta(
rx :: NTuple{2, Float64},
ry :: NTuple{2, Float64},
rz :: NTuple{2, Float64},
num :: NTuple{3, Int64}
) :: Matrix{Float64}
# allocate mesh
momenta = zeros(Float64, 3, (num[1] + 1) * (num[2] + 1) * (num[3] + 1))
# fill mesh
for nx in 0 : num[1]
for ny in 0 : num[2]
for nz in 0 : num[3]
# compute linear index
idx = nz + 1 + (num[3] + 1) * ny + (num[3] + 1) * (num[2] + 1) * nx
# compute kx
if num[1] > 0
momenta[1, idx] = rx[1] + nx * (rx[2] - rx[1]) / num[1]
end
# compute ky
if num[2] > 0
momenta[2, idx] = ry[1] + ny * (ry[2] - ry[1]) / num[2]
end
# compute kz
if num[3] > 0
momenta[3, idx] = rz[1] + nz * (rz[2] - rz[1]) / num[3]
end
end
end
end
return momenta
end
"""
get_path(
nodes :: Vector{Vector{Float64}},
nums :: Vector{Int64}
) :: Tuple{Vector{Float64}, Matrix{Float64}}
Generate a discrete path in momentum space linearly connecting the given nodes (passed via their cartesian coordinates [kx, ky, kz]).
nums[i] is the desired number of points between node[i] and node[i + 1], including node[i] and excluding node[i + 1].
Returns a tuple (l, k) where k[:, n] is the n-th momentum vector and l[n] is the distance to node[1] along the generated path.
"""
function get_path(
nodes :: Vector{Vector{Float64}},
nums :: Vector{Int64}
) :: Tuple{Vector{Float64}, Matrix{Float64}}
# sanity check: need some number of points for each path increment between two nodes
@assert length(nums) == length(nodes) - 1 "For N nodes 'nums' must be of length N - 1."
# allocate output arrays
num = sum(nums) + 1
dist = zeros(num)
path = zeros(3, num)
# iterate over path increments between nodes
idx = 0
for i in 1 : length(nums)
dif = nodes[i + 1] .- nodes[i]
step = dif ./ nums[i]
width = norm(step)
# fill path from node i to node i + 1 (excluding node i + 1)
for j in 1 : nums[i]
dist[idx + j + 1] = dist[idx + 1] + width * j
path[:, idx + j] .= nodes[i] .+ step .* (j - 1)
end
idx += nums[i]
end
# set last point in the path to be the last node
path[:, end] = nodes[end]
return dist, path
end
"""
compute_structure_factor(
χ :: Vector{Float64},
k :: Matrix{Float64},
l :: Lattice,
r :: Reduced_lattice
) :: Vector{Float64}
Compute the structure factor for given real space correlations χ on irreducible lattice sites.
k[:, n] is the n-th discrete momentum vector.
Return structure factor s, where s[n] is the value for the n-th momentum.
"""
function compute_structure_factor(
χ :: Vector{Float64},
k :: Matrix{Float64},
l :: Lattice,
r :: Reduced_lattice
) :: Vector{Float64}
# allocate structure factor
s = zeros(Float64, size(k, 2))
# compute all contributions from reference sites in the unitcell
for b in eachindex(l.uc.basis)
vec = l.uc.basis[b]
int = get_site(vec, l)
# compute structure factor for all momenta
Threads.@threads for n in eachindex(s)
@inbounds @fastmath for i in eachindex(l.sites)
# consider only those sites in range of reference site
index = r.project[int, i]
if index > 0
val = k[1, n] * (vec[1] - l.sites[i].vec[1])
val += k[2, n] * (vec[2] - l.sites[i].vec[2])
val += k[3, n] * (vec[3] - l.sites[i].vec[3])
s[n] += cos(val) * χ[index]
end
end
end
end
s ./= length(l.uc.basis)
return s
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1070 | """
test_FM() :: Nothing
Computes structure factors for ferromagnetic correlations on different lattices and checks if the maximum resides at the Γ point.
"""
function test_FM() :: Nothing
# init test dummy
k = get_momenta((0.0, 1.0 * pi), (0.0, 1.0 * pi), (0.0, 1.0 * pi), (10, 10, 10))
# initialize ferromagnetic test correlations
@testset "FM corr" begin
for name in ["square", "cubic", "kagome", "hyperkagome"]
l = get_lattice(name, 6, verbose = false)
r = get_reduced_lattice("heisenberg", [[0.0]], l, verbose = false)
s = compute_structure_factor(Float64[exp(-norm(r.sites[i].vec)) for i in eachindex(r.sites)], k, l, r)
@test norm(k[:, argmax(abs.(s))]) ≈ 0.0
end
end
return nothing
end
"""
test_observable() :: Nothing
Consistency checks for current implementation of observables.
"""
function test_observable() :: Nothing
# test if ferromagnetic correlations are Fourier transformed correctly
test_FM()
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 1787 | """
get_observable_timers() :: Nothing
Test performance of current observable implementation by Fourier transforming test correlations
on a few 2D and 3D lattices with 50 x 50 x 0 (2D) or 50 x 50 x 50 (3D) momenta.
"""
function get_observable_timers() :: Nothing
# init test dummys
l1 = get_lattice("square", 6, verbose = false); r1 = get_reduced_lattice("heisenberg", [[0.0]], l1, verbose = false)
l2 = get_lattice("cubic", 6, verbose = false); r2 = get_reduced_lattice("heisenberg", [[0.0]], l2, verbose = false)
l3 = get_lattice("kagome", 6, verbose = false); r3 = get_reduced_lattice("heisenberg", [[0.0]], l3, verbose = false)
l4 = get_lattice("hyperkagome", 6, verbose = false); r4 = get_reduced_lattice("heisenberg", [[0.0]], l4, verbose = false)
χ1 = Float64[exp(-norm(r1.sites[i].vec)) for i in eachindex(r1.sites)]
χ2 = Float64[exp(-norm(r2.sites[i].vec)) for i in eachindex(r2.sites)]
χ3 = Float64[exp(-norm(r3.sites[i].vec)) for i in eachindex(r3.sites)]
χ4 = Float64[exp(-norm(r4.sites[i].vec)) for i in eachindex(r4.sites)]
k_2D = get_momenta((0.0, 1.0 * pi), (0.0, 1.0 * pi), (0.0, 0.0), (50, 50, 0))
k_3D = get_momenta((0.0, 1.0 * pi), (0.0, 1.0 * pi), (0.0, 1.0 * pi), (50, 50, 50))
# init timer
to = TimerOutput()
@timeit to "=> Fourier transform" begin
for rep in 1 : 10
@timeit to "-> square" compute_structure_factor(χ1, k_2D, l1, r1)
@timeit to "-> cubic" compute_structure_factor(χ2, k_3D, l2, r2)
@timeit to "-> kagome" compute_structure_factor(χ3, k_2D, l3, r3)
@timeit to "-> hyperkagome" compute_structure_factor(χ4, k_3D, l4, r4)
end
end
show(to)
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 2551 | # auxiliary function to compute correlation integrals
function integrate_χ_boxes(
integrand :: Function,
width :: Float64,
χ_tol :: NTuple{2, Float64}
) :: Float64
# map width to interval [0.0, 1.0]
widthp = (width - 2.0 + sqrt(width * width + 4.0)) / (2.0 * width)
# determine box size
size = abs(widthp - 0.5)
# perform integation for top line
I = hcubature_v((vv, buff) -> integrand(vv, buff), Float64[ 0.0, 0.5 + size], Float64[0.5 - size, 1.0], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 - size, 0.5 + size], Float64[0.5 + size, 1.0], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 + size, 0.5 + size], Float64[ 1.0 1.0], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
# perform integation for middle line
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[ 0.0, 0.5 - size], Float64[0.5 - size, 0.5 + size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 - size, 0.5 - size], Float64[0.5 + size, 0.5 + size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 + size, 0.5 - size], Float64[ 1.0, 0.5 + size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
# perform integation for bottom line
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[ 0.0, 0.0], Float64[0.5 - size, 0.5 - size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 - size, 0.0], Float64[0.5 + size, 0.5 - size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
I += hcubature_v((vv, buff) -> integrand(vv, buff), Float64[0.5 + size, 0.0], Float64[ 1.0, 0.5 - size], abstol = χ_tol[1], reltol = χ_tol[2], maxevals = 10^7)[1]
return I
end
# load correlations for different symmetries
include("correlation_su2.jl")
include("correlation_u1_dm.jl")
# generate correlation dummy
function get_χ_empty(
symmetry :: String,
r :: Reduced_lattice,
m :: Mesh
) :: Vector{Matrix{Float64}}
if symmetry == "su2"
return get_χ_su2_empty(r, m)
elseif symmetry == "u1-dm"
return get_χ_u1_dm_empty(r, m)
end
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 3060 | # generate correlation dummy for su2 symmetry
function get_χ_su2_empty(
r :: Reduced_lattice,
m :: Mesh
) :: Vector{Matrix{Float64}}
χs = zeros(Float64, length(r.sites), m.num_χ)
χ = Matrix{Float64}[χs]
return χ
end
# kernel for double integral
function compute_χ_kernel!(
Λ :: Float64,
site :: Int64,
w :: Float64,
vv :: Matrix{Float64},
buff :: Vector{Float64},
r :: Reduced_lattice,
m :: Mesh,
a :: Action_su2
) :: Nothing
for i in eachindex(buff)
# map integration arguments and modify increments
v = (2.0 * vv[1, i] - 1.0) / ((1.0 - vv[1, i]) * vv[1, i])
vp = (2.0 * vv[2, i] - 1.0) / ((1.0 - vv[2, i]) * vv[2, i])
dv = (2.0 * vv[1, i] * vv[1, i] - 2.0 * vv[1, i] + 1) / ((1.0 - vv[1, i]) * (1.0 - vv[1, i]) * vv[1, i] * vv[1, i])
dvp = (2.0 * vv[2, i] * vv[2, i] - 2.0 * vv[2, i] + 1) / ((1.0 - vv[2, i]) * (1.0 - vv[2, i]) * vv[2, i] * vv[2, i])
# get buffers for non-local term
bs1 = get_buffer_s(v + vp, 0.5 * (v - w - vp), 0.5 * (-v - w + vp), m)
bt1 = get_buffer_t(w, v, vp, m)
bu1 = get_buffer_u(v - vp, 0.5 * (v - w + vp), 0.5 * ( v + w + vp), m)
# get buffers for local term
bs2 = get_buffer_s( v + vp, 0.5 * (v - w - vp), 0.5 * (v + w - vp), m)
bt2 = get_buffer_t(-v + vp, 0.5 * (v - w + vp), 0.5 * (v + w + vp), m)
bu2 = get_buffer_u(-w, v, vp, m)
# compute value
buff[i] = -(2.0 * a.S)^2 * get_Γ_comp(1, site, bs1, bt1, bu1, r, a, apply_flags_su2) / (2.0 * pi)^2
if site == 1
vs, vd = get_Γ(site, bs2, bt2, bu2, r, a)
buff[i] -= (2.0 * a.S) * (vs - vd) / (2.0 * (2.0 * pi)^2)
end
buff[i] *= get_G(Λ, v - 0.5 * w, m, a) * get_G(Λ, v + 0.5 * w, m, a) * dv
buff[i] *= get_G(Λ, vp - 0.5 * w, m, a) * get_G(Λ, vp + 0.5 * w, m, a) * dvp
end
return nothing
end
# compute isotropic correlation in real and Matsubara space
function compute_χ!(
Λ :: Float64,
r :: Reduced_lattice,
m :: Mesh,
a :: Action_su2,
χ :: Vector{Matrix{Float64}},
χ_tol :: NTuple{2, Float64}
) :: Nothing
@sync for w in 1 : m.num_χ
for i in eachindex(r.sites)
Threads.@spawn begin
# determine reference scale
ref = Λ + 0.5 * m.χ[w]
# compute vertex contribution
integrand = (vv, buff) -> compute_χ_kernel!(Λ, i, m.χ[w], vv, buff, r, m, a)
χ[1][i, w] = integrate_χ_boxes(integrand, 4.0 * ref, χ_tol)
# compute propagator contribution
if i == 1
integrand = v -> (2.0 * a.S) * get_G(Λ, v - 0.5 * m.χ[w], m, a) * get_G(Λ, v + 0.5 * m.χ[w], m, a) / (4.0 * pi)
χ[1][i, w] += quadgk(integrand, -Inf, -2.0 * ref, 0.0, 2.0 * ref, Inf, atol = χ_tol[1], rtol = χ_tol[2])[1]
end
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 7511 | # generate correlation dummy for u1-dm symmetry
function get_χ_u1_dm_empty(
r :: Reduced_lattice,
m :: Mesh
) :: Vector{Matrix{Float64}}
χxx = zeros(Float64, length(r.sites), m.num_χ)
χzz = zeros(Float64, length(r.sites), m.num_χ)
χxy = zeros(Float64, length(r.sites), m.num_χ)
χ = Matrix{Float64}[χxx, χzz, χxy]
return χ
end
# xx kernel for double integral
function compute_χ_kernel_xx!(
Λ :: Float64,
site :: Int64,
w :: Float64,
vv :: Matrix{Float64},
buff :: Vector{Float64},
r :: Reduced_lattice,
m :: Mesh,
a :: Action_u1_dm
) :: Nothing
for i in eachindex(buff)
# map integration arguments and modify increments
v = (2.0 * vv[1, i] - 1.0) / ((1.0 - vv[1, i]) * vv[1, i])
vp = (2.0 * vv[2, i] - 1.0) / ((1.0 - vv[2, i]) * vv[2, i])
dv = (2.0 * vv[1, i] * vv[1, i] - 2.0 * vv[1, i] + 1) / ((1.0 - vv[1, i]) * (1.0 - vv[1, i]) * vv[1, i] * vv[1, i])
dvp = (2.0 * vv[2, i] * vv[2, i] - 2.0 * vv[2, i] + 1) / ((1.0 - vv[2, i]) * (1.0 - vv[2, i]) * vv[2, i] * vv[2, i])
# get buffers for non-local term
bs1 = get_buffer_s(v + vp, 0.5 * (v - w - vp), 0.5 * (-v - w + vp), m)
bt1 = get_buffer_t(w, v, vp, m)
bu1 = get_buffer_u(v - vp, 0.5 * (v - w + vp), 0.5 * ( v + w + vp), m)
# get buffers for local term
bs2 = get_buffer_s( v + vp, 0.5 * (v - w - vp), 0.5 * (v + w - vp), m)
bt2 = get_buffer_t(-v + vp, 0.5 * (v - w + vp), 0.5 * (v + w + vp), m)
bu2 = get_buffer_u(-w, v, vp, m)
# compute value
buff[i] = -get_Γ_comp(1, site, bs1, bt1, bu1, r, a, apply_flags_u1_dm) / (2.0 * pi)^2
if site == 1
vzz = get_Γ_comp(2, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
vdd = get_Γ_comp(4, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
buff[i] -= (vzz - vdd) / (2.0 * (2.0 * pi)^2)
end
buff[i] *= get_G(Λ, v - 0.5 * w, m, a) * get_G(Λ, v + 0.5 * w, m, a) * dv
buff[i] *= get_G(Λ, vp - 0.5 * w, m, a) * get_G(Λ, vp + 0.5 * w, m, a) * dvp
end
return nothing
end
# zz kernel for double integral
function compute_χ_kernel_zz!(
Λ :: Float64,
site :: Int64,
w :: Float64,
vv :: Matrix{Float64},
buff :: Vector{Float64},
r :: Reduced_lattice,
m :: Mesh,
a :: Action_u1_dm
) :: Nothing
for i in eachindex(buff)
# map integration arguments and modify increments
v = (2.0 * vv[1, i] - 1.0) / ((1.0 - vv[1, i]) * vv[1, i])
vp = (2.0 * vv[2, i] - 1.0) / ((1.0 - vv[2, i]) * vv[2, i])
dv = (2.0 * vv[1, i] * vv[1, i] - 2.0 * vv[1, i] + 1) / ((1.0 - vv[1, i]) * (1.0 - vv[1, i]) * vv[1, i] * vv[1, i])
dvp = (2.0 * vv[2, i] * vv[2, i] - 2.0 * vv[2, i] + 1) / ((1.0 - vv[2, i]) * (1.0 - vv[2, i]) * vv[2, i] * vv[2, i])
# get buffers for non-local term
bs1 = get_buffer_s(v + vp, 0.5 * (v - w - vp), 0.5 * (-v - w + vp), m)
bt1 = get_buffer_t(w, v, vp, m)
bu1 = get_buffer_u(v - vp, 0.5 * (v - w + vp), 0.5 * ( v + w + vp), m)
# get buffers for local term
bs2 = get_buffer_s( v + vp, 0.5 * (v - w - vp), 0.5 * (v + w - vp), m)
bt2 = get_buffer_t(-v + vp, 0.5 * (v - w + vp), 0.5 * (v + w + vp), m)
bu2 = get_buffer_u(-w, v, vp, m)
# compute value
buff[i] = -get_Γ_comp(2, site, bs1, bt1, bu1, r, a, apply_flags_u1_dm) / (2.0 * pi)^2
if site == 1
vxx = get_Γ_comp(1, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
vzz = get_Γ_comp(2, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
vdd = get_Γ_comp(4, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
buff[i] -= (2.0 * vxx - vzz - vdd) / (2.0 * (2.0 * pi)^2)
end
buff[i] *= get_G(Λ, v - 0.5 * w, m, a) * get_G(Λ, v + 0.5 * w, m, a) * dv
buff[i] *= get_G(Λ, vp - 0.5 * w, m, a) * get_G(Λ, vp + 0.5 * w, m, a) * dvp
end
return nothing
end
# xy kernel for double integral
function compute_χ_kernel_xy!(
Λ :: Float64,
site :: Int64,
w :: Float64,
vv :: Matrix{Float64},
buff :: Vector{Float64},
r :: Reduced_lattice,
m :: Mesh,
a :: Action_u1_dm
) :: Nothing
for i in eachindex(buff)
# map integration arguments and modify increments
v = (2.0 * vv[1, i] - 1.0) / ((1.0 - vv[1, i]) * vv[1, i])
vp = (2.0 * vv[2, i] - 1.0) / ((1.0 - vv[2, i]) * vv[2, i])
dv = (2.0 * vv[1, i] * vv[1, i] - 2.0 * vv[1, i] + 1) / ((1.0 - vv[1, i]) * (1.0 - vv[1, i]) * vv[1, i] * vv[1, i])
dvp = (2.0 * vv[2, i] * vv[2, i] - 2.0 * vv[2, i] + 1) / ((1.0 - vv[2, i]) * (1.0 - vv[2, i]) * vv[2, i] * vv[2, i])
# get buffers for non-local term
bs1 = get_buffer_s(v + vp, 0.5 * (v - w - vp), 0.5 * (-v - w + vp), m)
bt1 = get_buffer_t(w, v, vp, m)
bu1 = get_buffer_u(v - vp, 0.5 * (v - w + vp), 0.5 * ( v + w + vp), m)
# get buffers for local term
bs2 = get_buffer_s( v + vp, 0.5 * (v - w - vp), 0.5 * (v + w - vp), m)
bt2 = get_buffer_t(-v + vp, 0.5 * (v - w + vp), 0.5 * (v + w + vp), m)
bu2 = get_buffer_u(-w, v, vp, m)
# compute value
buff[i] = -get_Γ_comp(3, site, bs1, bt1, bu1, r, a, apply_flags_u1_dm) / (2.0 * pi)^2
if site == 1
vzd = get_Γ_comp(5, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
vdz = get_Γ_comp(6, site, bs2, bt2, bu2, r, a, apply_flags_u1_dm)
buff[i] -= (vzd - vdz) / (2.0 * (2.0 * pi)^2)
end
buff[i] *= get_G(Λ, v - 0.5 * w, m, a) * get_G(Λ, v + 0.5 * w, m, a) * dv
buff[i] *= get_G(Λ, vp - 0.5 * w, m, a) * get_G(Λ, vp + 0.5 * w, m, a) * dvp
end
return nothing
end
# compute correlations in real and Matsubara space
function compute_χ!(
Λ :: Float64,
r :: Reduced_lattice,
m :: Mesh,
a :: Action_u1_dm,
χ :: Vector{Matrix{Float64}},
χ_tol :: NTuple{2, Float64}
) :: Nothing
@sync for w in 1 : m.num_χ
for i in eachindex(r.sites)
Threads.@spawn begin
# determine reference scale
ref = Λ + 0.5 * m.χ[w]
# compute xx vertex contribution
integrand = (vv, buff) -> compute_χ_kernel_xx!(Λ, i, m.χ[w], vv, buff, r, m, a)
χ[1][i, w] = integrate_χ_boxes(integrand, 4.0 * ref, χ_tol)
# compute zz vertex contribution
integrand = (vv, buff) -> compute_χ_kernel_zz!(Λ, i, m.χ[w], vv, buff, r, m, a)
χ[2][i, w] = integrate_χ_boxes(integrand, 4.0 * ref, χ_tol)
# compute xy vertex contribution
integrand = (vv, buff) -> compute_χ_kernel_xy!(Λ, i, m.χ[w], vv, buff, r, m, a)
χ[3][i, w] = integrate_χ_boxes(integrand, 4.0 * ref, χ_tol)
# compute propagator contribution
if i == 1
integrand = v -> get_G(Λ, v - 0.5 * m.χ[w], m, a) * get_G(Λ, v + 0.5 * m.χ[w], m, a) / (4.0 * pi)
res = quadgk(integrand, -Inf, -2.0 * ref, 0.0, 2.0 * ref, Inf, atol = χ_tol[1], rtol = χ_tol[2])[1]
χ[1][i, w] += res
χ[2][i, w] += res
end
end
end
end
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 613 | # auxiliary function to compute equal time correlator for su2 symmetry
function compute_eq_corr_su2(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Float64
# load diagonal correlations
m, χ = read_χ(file, Λ, "diag", verbose = verbose)
# compute equal-time on-site correlation
eq_corr = 0.0
for i in 1 : length(m) - 1
eq_corr += (m[i + 1] - m[i]) * (χ[1, i + 1] + χ[1, i])
end
# calculate full correlator
eq_corr *= 3.0
# normalization from Fourier transformation
eq_corr /= 2.0 * pi
return eq_corr
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 703 | # auxiliary function to compute equal time correlator for u1-dm symmetry
function compute_eq_corr_u1_dm(
file :: HDF5.File,
Λ :: Float64
;
verbose :: Bool = true
) :: Float64
# load diagonal correlations
m, χxx = read_χ(file, Λ, "xx", verbose = verbose)
m, χzz = read_χ(file, Λ, "zz", verbose = verbose)
# compute equal-time on-site correlation
eq_corr = 0.0
for i in 1 : length(m) - 1
eq_corr += 2.0 * (m[i + 1] - m[i]) * (χxx[1, i + 1] + χxx[1, i])
eq_corr += 1.0 * (m[i + 1] - m[i]) * (χzz[1, i + 1] + χzz[1, i])
end
# normalization from Fourier transformation
eq_corr /= 2.0 * pi
return eq_corr
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 930 | """
get_PFFRG_timers() :: Nothing
Test current performance of FRG solver.
"""
function get_PFFRG_timers() :: Nothing
println()
println("Testing performance of FRG solver ...")
println()
# time lattice
println("Testing lattice performance ...")
println()
get_lattice_timers()
println()
println()
# time frequencies
println("Testing frequency performance ...")
println()
get_frequency_timers()
println()
println()
# time action
println("Testing action performance ...")
println()
get_action_timers()
println()
println()
# time flow equations
println("Testing flow performance ...")
get_flow_timers()
println()
println()
# time observables
println("Testing observable performance ...")
println()
get_observable_timers()
println()
println()
println("Done.")
return nothing
end | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | code | 502 | using PFFRGSolver
println()
# test frequency implementation
println("Running frequency tests ...")
test_frequencies()
println()
# test action implementation
println("Running lattice tests ...")
test_lattice()
println()
# test action implementation
println("Running action tests ...")
test_action()
println()
# test flow implementation
println("Running flow tests ...")
test_flow()
println()
# test observable implementation
println("Running observable tests ...")
test_observable()
println() | PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.5.0 | 5e2cd6b758e228080cdb43b0e0c469683fcd68b2 | docs | 8766 | # PFFRGSolver.jl <img src=https://github.com/dominikkiese/PFFRGSolver.jl/blob/main/README/logo.png align="right" height="175" width="250">
**P**seudo-**F**ermion **F**unctional **R**enormalization **G**roup **Solver** <br>
(Julia v1.5 and higher)
# Introduction
The package PFFRGSolver.jl aims at providing an efficient, state-of-the-art multiloop solver for functional renormalization group equations of quantum lattice spin models in the pseudo-fermion representation. It is currently applicable to spin models described by Hamiltonians of the form
<p align="center">
<img src=https://github.com/dominikkiese/PFFRGSolver.jl/blob/main/README/hamiltonian.png height="70" width="700">
</p>
which can be defined on a variety of pre-implemented two and three dimensional lattices. Internally, PFFRGSolver.jl first computes a reduced representation of the lattice by employing space group symmetries before initializing the renormalization group flow with the bare couplings or, optionally, a solution of the regularized parquet equations, to which the multiloop truncated FRG converges by construction. The RG equations are integrated using the Bogacki-Shampine method with adaptive step size control. In each stage of the flow, real-space spin-spin correlations are computed from the flowing vertices. For a more detailed discussion of the method and its implementation see https://arxiv.org/abs/2011.01269.
# Installation
The package can be installed with the Julia package manager by switching to package mode in the REPL (with `]`) and using
```julia
pkg> add PFFRGSolver
```
# Citation
If you use PFFRGSolver.jl in your work, please acknowledge the package accordingly and cite our preprint
D. Kiese, T.Müller, Y. Iqbal, R. Thomale and S. Trebst, "Multiloop functional renormalization group approach to quantum spin systems", arXiv:2011.01269 (2020)
A suitable bibtex entry is
```
@misc{kiese2020multiloop,
title={Multiloop functional renormalization group approach to quantum spin systems},
author={Dominik Kiese and Tobias M\"uller and Yasir Iqbal and Ronny Thomale and Simon Trebst},
year={2020},
eprint={2011.01269},
archivePrefix={arXiv},
primaryClass={cond-mat.str-el}
}
```
# Running calculations
In order to simulate e.g. the nearest-neighbor Heisenberg antiferromagnet on the square lattice for a lattice truncation L = 3 simply do
```julia
using PFFRGSolver
launch!("/path/to/output", "square", 3, "heisenberg", "su2", [1.0])
```
The FRG solver allows for more fine grained control over the calculation by various keyword arguments. The full reference can be obtained via `?launch!`. Currently available lattices and models can be obtained in verbose form with `lattice_avail()` and `model_avail()`.
# Post-processing data
Each calculation generates two output files `"/path/to/output_obs"` and `"/path/to/output_cp"` in the HDF5 format, containing observables measured during the RG flow and checkpoints with full vertex data respectively. <br>
The so-obtained real space spin-spin correlations are usually converted to structure factors (or susceptibilities) via a Fourier transform to momentum space, to investigate the ground state predicted by pf-FRG. In the following, example code is provided for computing the momentum (and Matsubara frequency) resolved structure factor for the full FRG flow, as well as a single cutoff, for Heisenberg models on the square lattice.
```julia
using PFFRGSolver
using HDF5
# generate 50 x 50 momentum space discretization within first Brillouin zone of the square lattice
rx = (-1.0 * pi, 1.0 * pi)
ry = (-1.0 * pi, 1.0 * pi)
rz = (0.0, 0.0)
k = get_momenta(rx, ry, rz, (50, 50, 0))
# open observable file and output file to save structure factor
file_in = h5open("/path/to/output_obs", "r")
file_out = h5open("/path/to/output_sf", "cw")
# compute structure factor for the full flow
compute_structure_factor_flow!(file_in, file_out, k, "diag")
# read so-computed structure factor with its frequency mesh at cutoff Λ = 1.0 from file_out
m, s = read_structure_factor(file_out, 1.0, "diag")
# read so-computed static structure factor flow at momentum with largest amplitude with respect to reference scale Λ = 1.0
ref = read_reference_momentum(file_out, 1.0, "diag")
Λ, s = read_structure_factor_flow_at_momentum(file_out, ref, "diag")
# read lattice data and real space correlations with their frequency mesh at cutoff Λ = 1.0 from file_in
l, r = read_lattice(file_in)
m, χ = read_χ(file_in, 1.0, "diag")
# compute static structure factor at cutoff Λ = 1.0
s = compute_structure_factor(χ[:, 1], k, l, r)
# close HDF5 files
close(file_in)
close(file_out)
```
Vertex data can be accessed by reading checkpoints from `"/path/to/output_cp"` like
```julia
using PFFRGSolver
using HDF5
# open checkpoint file of FRG solver
file = h5open("/path/to/output_cp", "r")
# load checkpoint at cutoff Λ = 1.0
Λ, dΛ, m, a = read_checkpoint(file, 1.0)
# close HDF5 file
close(file)
```
The solver generates (if `parquet = true` in the `launch!` command) at least two checkpoints, one with the converged parquet solution used as the initial condition for the FRG and one with the final result at the end of the flow. Additional checkpoints are created according to a timer heuristic, which can be controlled with the `ct` and `wt` keywords in `launch!`.
# Performance notes
The PFFRGSolver.jl package accelerates calculations by making use of Julia's built-in dynamical thread scheduling (`Threads.@spawn`). Even for small systems, the number of flow equations to be integrated is quite tremendous and parallelization is vital to achieve acceptable run times. **We recommend to launch Julia with multiple threads whenever PFFRGSolver.jl is used**, either by setting up the respective enviroment variable `export JULIA_NUM_THREADS=$nthreads` or by adding the `-t` flag when opening the Julia REPL from the terminal i.e. `julia -t $nthreads`. <br>
Note that iterating the parquet equations is quite costly (compared to one loop FRG calculations) and contributes a substantial overhead for computing an initial condition of the flow. It is advisable to turn them on (via the `parquet` keyword in `launch!`) only when accordingly large computing resources are available. <br>
If you are using the package in an HPC environment, make sure that the precompile cache is generated for that CPU architecture on which production runs are performed, as the LoopVectorizations.jl dependency of the solver will unlock compiler optimizations based on the respective hardware.
# SLURM Interface
Calculations with PFFRGSolver.jl on small to medium sized systems can usually be done locally with a low number of threads. However, when the number of loops is increased and high resolution is required, calculations can become quite time consuming and it is advisable to make use of a computing cluster if available. PFFRGSolver.jl exports a few commands, to help people setting up simulations on clusters utilizing the SLURM workload manager (integration for other systems is plannned for future versions). Example code for a rough scan of the phase diagram of the J1-J2 Heisenberg model on the square lattice (with L = 6) is given below.
```julia
using PFFRGSolver
# make new folder and add launcher files for a rough scan of the phase diagram
mkdir("j1j2_square")
for j2 in [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
save_launcher!("j1j2_square/j2$(j2).jl", "j2$(j2)", "square", 6, "heisenberg", "su2", [1.0, j2], num_σ = 50, num_Ω = 30, num_ν = 20, num_χ = 10)
end
# set up SLURM parameters as dictionary
sbatch_args = Dict(["account" => "my_account", "nodes" => "1", "ntasks" => "1", "cpus-per-task" => "8", "time" => "04:00:00", "partition" => "my_partition"])
# generate job files
make_repository!("j1j2_square", "/path/to/julia/exe", sbatch_args)
```
The jobs subsequently can be submitted using
```bash
for FILE in j1j2_square/*/*.job; do sbatch $FILE; done
```
After having submitted and run the jobs, results can be gathered in `"j1j2_square/finished"` with the `collect_repository!` command. Note that simulations, which could not be finished in time, have their `overwrite` flag in the respective launcher file set to `false` by `collect_repository!`. As such they can just be resubmitted and will continue calculations from the last available checkpoint.
# Literature
For further reading on technical aspects of (multiloop) pf-FRG see
* [1] https://journals.aps.org/prb/abstract/10.1103/PhysRevB.81.144410
* [2] https://journals.aps.org/prb/abstract/10.1103/PhysRevB.96.045144
* [3] https://journals.aps.org/prb/abstract/10.1103/PhysRevB.97.064416
* [4] https://journals.aps.org/prb/abstract/10.1103/PhysRevB.97.035162
* [5] https://arxiv.org/abs/2011.01268
| PFFRGSolver | https://github.com/dominikkiese/PFFRGSolver.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 293 | using Documenter, DocumenterMarkdown
using ReactiveDynamics
makedocs(;
format = Documenter.HTML(; prettyurls = false, edit_link = "main"),
sitename = "ReactiveDynamics.jl API Documentation",
pages = ["index.md"],
)
deploydocs(; repo = "github.com/Merck/ReactiveDynamics.jl.git")
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 6665 | module ReactiveDynamics
using Catlab, Catlab.CategoricalAlgebra, Catlab.Present
using Reexport
using MacroTools
using NLopt
using ComponentArrays
@reexport using GeneratedExpressions
const SampleableValues = Union{Expr,Symbol,AbstractString,Float64,Int,Function}
const ActionableValues = Union{Function,Symbol,Float64,Int}
const SampleableRange = Union{
Float64,
Int64,
AbstractString,
Expr,
Symbol,
Tuple{Float64,Union{Float64,Int64,AbstractString,Expr,Symbol}},
}
Base.convert(::Type{SampleableRange}, x::Tuple) = (Float64(x[1]), x[2])
Base.@kwdef mutable struct FoldedObservable
range::Vector{SampleableRange} = SampleableRange[]
every::Float64 = Inf
on::Vector{SampleableValues} = SampleableValues[]
end
@present TheoryReactionNetwork(FreeSchema) begin
(S, T)::Ob # species, transitions
(
SymbolicAttributeT,
DescriptiveAttributeT,
SampleableAttributeT,
ModalityAttributeT,
PcsOptT,
PrmAttributeT,
)::AttrType
specName::Attr(S, SymbolicAttributeT)
specModality::Attr(S, ModalityAttributeT)
specInitVal::Attr(S, SampleableAttributeT)
specInitUncertainty::Attr(S, SampleableAttributeT)
(specCost, specReward, specValuation)::Attr(S, SampleableAttributeT)
trans::Attr(T, SampleableAttributeT)
transPriority::Attr(T, SampleableAttributeT)
transRate::Attr(T, SampleableAttributeT)
transCycleTime::Attr(T, SampleableAttributeT)
transProbOfSuccess::Attr(T, SampleableAttributeT)
transCapacity::Attr(T, SampleableAttributeT)
transMaxLifeTime::Attr(T, SampleableAttributeT)
transPostAction::Attr(T, SampleableAttributeT)
transMultiplier::Attr(T, SampleableAttributeT)
transName::Attr(T, DescriptiveAttributeT)
E::Ob # events
(eventTrigger, eventAction)::Attr(E, SampleableAttributeT)
obs::Ob # processes (observables)
obsName::Attr(obs, SymbolicAttributeT)
obsOpts::Attr(obs, PcsOptT)
(P, M)::Ob # model params, solver args
prmName::Attr(P, SymbolicAttributeT)
prmVal::Attr(P, PrmAttributeT)
metaKeyword::Attr(M, SymbolicAttributeT)
metaVal::Attr(M, SampleableAttributeT)
end
@acset_type FoldedReactionNetworkType(TheoryReactionNetwork)
const ReactionNetwork = FoldedReactionNetworkType{
Symbol,
Union{String,Symbol,Missing},
SampleableValues,
Set{Symbol},
FoldedObservable,
Any,
}
Base.convert(::Type{Symbol}, ex::String) = Symbol(ex)
Base.convert(::Type{Union{String,Symbol,Missing}}, ex::String) =
try
Symbol(ex)
catch
string(ex)
end
Base.convert(::Type{SampleableValues}, ex::String) = MacroTools.striplines(Meta.parse(ex))
Base.convert(::Type{Set{Symbol}}, ex::String) = eval(Meta.parse(ex))
Base.convert(::Type{FoldedObservable}, ex::String) = eval(Meta.parse(ex))
prettynames = Dict(
:transRate => [:rate],
:specInitUncertainty => [:uncertainty, :stoch, :stochasticity],
:transPostAction => [:postAction, :post],
:transName => [:name, :interpretation],
:transPriority => [:priority],
:transProbOfSuccess => [:probability, :prob, :pos],
:transCapacity => [:cap, :capacity],
:transCycleTime => [:ct, :cycletime],
:transMaxLifeTime => [:lifetime, :maxlifetime, :maxtime, :timetolive],
)
defargs = Dict(
:T => Dict{Symbol,Any}(
:transPriority => 1,
:transProbOfSuccess => 1,
:transCapacity => Inf,
:transCycleTime => 0.0,
:transMaxLifeTime => Inf,
:transMultiplier => 1,
:transPostAction => :(),
:transName => missing,
),
:S => Dict{Symbol,Any}(
:specInitUncertainty => 0.0,
:specInitVal => 0.0,
:specCost => 0.0,
:specReward => 0.0,
:specValuation => 0.0,
),
:P => Dict{Symbol,Any}(:prmVal => missing),
:M => Dict{Symbol,Any}(:metaVal => missing),
)
compilable_attrs =
filter(attr -> eltype(attr) == SampleableValues, propertynames(ReactionNetwork()))
species_modalities = [:nonblock, :conserved, :rate]
function assign_defaults!(acs::ReactionNetwork)
for (_, v_) in defargs, (k, v) in v_
for i = 1:length(subpart(acs, k))
isnothing(acs[i, k]) && (subpart(acs, k)[i] = v)
end
end
foreach(
i ->
!isnothing(acs[i, :specModality]) ||
(subpart(acs, :specModality)[i] = Set{Symbol}()),
1:nparts(acs, :S),
)
k = [:specCost, :specReward, :specValuation]
foreach(
k -> foreach(
i -> !isnothing(acs[i, k]) || (subpart(acs, k)[i] = 0.0),
1:nparts(acs, :S),
),
k,
)
return acs
end
function ReactionNetwork(transitions, reactants, obs, events)
return merge_acs!(ReactionNetwork(), transitions, reactants, obs, events)
end
function ReactionNetwork(transitions, reactants, obs)
return merge_acs!(ReactionNetwork(), transitions, reactants, obs, [])
end
function add_obs!(acs, obs)
for p in obs
sym = p.args[3].value
i = incident(acs, sym, :obsName)
i = if isempty(incident(acs, sym, :obsName))
add_part!(acs, :obs; obsName = sym, obsOpts = FoldedObservable())
else
i[1]
end
for opt in p.args[4:end]
if isexpr(opt, :(=)) && (opt.args[1] ∈ fieldnames(FoldedObservable))
opt.args[1] == :every &&
(acs[i, :obsOpts].every = min(acs[i, :obsOpts].every, opt.args[2]))
opt.args[1] == :on && union!(acs[i, :obsOpts].on, [opt.args[2]])
elseif isexpr(opt, :tuple) || opt isa SampleableValues
push!(
acs[i, :obsOpts].range,
isexpr(opt, :tuple) ? tuple(opt.args...) : opt,
)
end
end
end
return acs
end
function merge_acs!(acs::ReactionNetwork, transitions, reactants, obs, events)
foreach(
t -> add_part!(acs, :T; trans = t[1][2], transRate = t[1][1], t[2]...),
transitions,
)
add_obs!(acs, obs)
unique!(reactants)
foreach(
ev -> add_part!(acs, :E; eventTrigger = ev.trigger, eventAction = ev.action),
events,
)
foreach(
r -> isempty(incident(acs, r, :specName)) && add_part!(acs, :S; specName = r),
reactants,
)
return assign_defaults!(acs)
end
include("state.jl")
include("compilers.jl")
include.(readdir(joinpath(@__DIR__, "interface"); join = true))
include.(readdir(joinpath(@__DIR__, "utils"); join = true))
include.(readdir(joinpath(@__DIR__, "operators"); join = true))
include("solvers.jl")
include("optim.jl")
include("loadsave.jl")
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 5831 | using MacroTools: prewalk
"""
Recursively find model variables in expressions.
"""
function recursively_find_vars!(r, exs...)
for ex in exs
if ex isa Symbol
push!(r, ex)
else
(
ex isa Expr &&
recursively_find_vars!(r, ex.args[(!isexpr(ex, :call) ? 1 : 2):end]...)
)
end
end
return r
end
function get_contained_params(ex, prms)
r = []
return recursively_find_vars!(r, ex) ∩ prms
end
"""
Recursively substitute model variables. Subsitution pairs are specified in `varmap`.
"""
function recursively_substitute_vars!(varmap, ex)
ex isa Symbol && return (haskey(varmap, ex) ? varmap[ex] : ex)
ex isa Expr && for i = 1:length(ex.args)
if ex.args[i] isa Expr
recursively_substitute_vars!(varmap, ex.args[i])
else
(
ex.args[i] isa Symbol &&
haskey(varmap, ex.args[i]) &&
(ex.args[i] = varmap[ex.args[i]])
)
end
end
return ex
end
"""
Recursively normalize dotted notation in `ex` to species names whenever a name is contained in `vars`, else left unchanged.
"""
function recursively_expand_dots_in_ex!(ex, vars)
if isexpr(ex, :.)
expanded = recursively_expand_dots(ex)
return if expanded isa Symbol && expanded in vars
expanded
else
recursively_expand_dots_in_ex!.(ex.args, Ref(vars))
ex
end
end
ex isa Expr && for i = 1:length(ex.args)
ex.args[i] isa Union{Expr,Symbol} &&
(ex.args[i] = recursively_expand_dots_in_ex!(ex.args[i], vars))
end
return ex
end
reserved_names =
[:t, :state, :obs, :resample, :solverarg, :take, :log, :periodic, :set_params]
push!(reserved_names, :state)
function escape_ref(ex, species)
return if ex isa Symbol
ex
else
prewalk(
ex ->
isexpr(ex, :ref) && Symbol(string(ex)) ∈ species ? Symbol(string(ex)) : ex,
ex,
)
end
end
function wrap_expr(fex, species_names, prm_names, varmap)
!isa(fex, Union{Expr,Symbol}) && return fex
# escape refs in species names: A[1] -> Symbol("A[1]")
fex = escape_ref(fex, species_names)
# escape dots in species' names: A.B -> Symbol("A.B")
fex = deepcopy(fex)
fex = recursively_expand_dots_in_ex!(fex, species_names)
# prepare the function's body
letex = :(
let
end
)
# expression walking (MacroTools): visit each expression, subsitute with the body's return value
fex = prewalk(fex) do x
# here we convert the query metalanguage: @t() -> time(state) etc.
if isexpr(x, :macrocall) && (macroname(x) ∈ reserved_names)
Expr(:call, macroname(x), :state, x.args[3:end]...)
else
x
end
end
# substitute the species names with "pointers" into the state space: S -> state.u[1]
fex = recursively_substitute_vars!(varmap, fex)
# substitute the params names with "pointers" into the parameter space: β -> state.p[:β]
# params can't be mutated!
foreach(
v -> push!(letex.args[1].args, :($v = state.p[$(QuoteNode(v))])),
get_contained_params(fex, prm_names),
)
push!(letex.args[2].args, fex)
# the function shall be a function of the dynamic ReactiveDynamicsState structure: letex -> :(state -> $letex)
# eval the expression to a Julia function, save that function into the "compiled" acset
return eval(:(state -> $letex))
end
function get_wrap_fun(acs::ReactionNetwork)
species_names = collect(acs[:, :specName])
prm_names = collect(acs[:, :prmName])
varmap = Dict([name => :(state.u[$i]) for (i, name) in enumerate(species_names)])
for name in prm_names
push!(varmap, name => :(state.p[$(QuoteNode(name))]))
end
return ex -> wrap_expr(ex, species_names, prm_names, varmap)
end
function skip_compile(attr)
return any(contains.(Ref(string(attr)), ("Name", "obs", "meta"))) ||
(string(attr) == "trans")
end
function compile_attrs(acs::ReactionNetwork)
species_names = collect(acs[:, :specName])
prm_names = collect(acs[:, :prmName])
varmap = Dict([name => :(state.u[$i]) for (i, name) in enumerate(species_names)])
for name in prm_names
push!(varmap, name => :(state.p[$(QuoteNode(name))]))
end
wrap_fun = ex -> wrap_expr(ex, species_names, prm_names, varmap)
attrs = Dict{Symbol,Vector}()
transitions = Dict{Symbol,Vector}()
for attr in propertynames(acs.subparts)
attrs_ = subpart(acs, attr)
if !contains(string(attr), "trans")
(
attrs[attr] = map(
i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]),
1:length(attrs_),
)
)
else
(
transitions[attr] = map(
i -> skip_compile(attr) ? attrs_[i] : wrap_fun(attrs_[i]),
1:length(attrs_),
)
)
end
end
transitions[:transActivated] = fill(true, nparts(acs, :T))
transitions[:transToSpawn] = zeros(nparts(acs, :T))
transitions[:transHash] =
[coalesce(acs[i, :transName], gensym()) for i = 1:nparts(acs, :T)]
return attrs, transitions, wrap_fun
end
function remove_choose(acs::ReactionNetwork)
acs = deepcopy(acs)
pcs = []
for attr in propertynames(acs.subparts)
attrs_ = subpart(acs, attr)
foreach(
i ->
!isnothing(attrs_[i]) &&
attrs_[i] isa Expr &&
(attrs_[i] = normalize_pcs!(pcs, attrs_[i])),
1:length(attrs_),
)
end
add_obs!(acs, pcs)
return acs
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 6465 | export @import_network, @export_network
export @load_models
export @import_solution, @export_solution
export @export_solution_as_table, @export_solution_as_csv
export @export, @import
using TOML, JLD2, CSV
using DataFrames
const objects_aliases = Dict(
:S => "spec",
:T => "trans",
:P => "prm",
:M => "meta",
:E => "event",
:obs => "obs",
)
const RN_attrs = string.(propertynames(ReactionNetwork().subparts))
function get_attrs(object)
object = object isa Symbol ? objects_aliases[object] : object
return filter(x -> occursin(object, x), RN_attrs)
end
function export_network(acs::ReactionNetwork)
dict = Dict()
for (key, val) in objects_aliases
push!(dict, val => [])
for i = 1:nparts(acs, key)
dict_ = Dict()
for attr in get_attrs(val)
attr_val = acs[i, Symbol(attr)]
ismissing(attr_val) && continue
attr_val = attr_val isa Number ? attr_val : string(attr_val)
push!(dict_, string(attr) => attr_val)
end
push!(dict[val], dict_)
end
end
return dict
end
function load_network(dict::Dict)
acs = ReactionNetwork()
for (key, val) in objects_aliases
val == "prm" && continue
for row in get(dict, val, [])
i = add_part!(acs, key)
for (attr, attrval) in row
set_subpart!(acs, i, Symbol(attr), attrval)
end
end
end
for row in get(dict, "prm", [])
i = add_part!(acs, :P)
for (attr, attrval) in row
if attr == "prmVal"
attrval = attrval isa String ? eval(Meta.parseall(attrval)) : attrval
end
set_subpart!(acs, i, Symbol(attr), attrval)
end
end
for row in get(dict, "registered", [])
eval(Meta.parseall(row["body"]))
end
return assign_defaults!(acs)
end
function import_network_csv(pathmap)
dict = Dict()
for (key, paths) in pathmap
push!(dict, key => [])
for path in paths
data = DataFrame(
CSV.File(
path;
delim = ";;",
types = String,
stripwhitespace = true,
comment = "#",
),
)
for row in eachrow(data)
object = Dict()
for (attr, val) in Iterators.zip(keys(row), values(row))
!ismissing(val) && push!(object, string(attr) => val)
end
push!(dict[key], object)
end
end
end
return load_network(dict)
end
function import_network(path::AbstractString)
if splitext(path)[2] == ".csv"
pathmap =
Dict(val => [] for val in [collect(values(objects_aliases)); "registered"])
for row in CSV.File(path; delim = ";;", stripwhitespace = true, comment = "#")
push!(pathmap[row.type], joinpath(dirname(path), row.path))
end
import_network_csv(pathmap)
else
load_network(TOML.parsefile(path))
end
end
function export_network(acs::ReactionNetwork, path::AbstractString)
if splitext(path)[2] == ".csv"
exported_network = export_network(acs)
paths = DataFrame(; type = [], path = [])
for (key, objs) in exported_network
push!(paths, (key, "export-$key.csv"))
objs_exported = DataFrame(Dict(attr => [] for attr in get_attrs(key)))
for obj in objs
push!(
objs_exported,
[get(obj, key, missing) for key in names(objs_exported)],
)
end
CSV.write(
joinpath(dirname(path), "export-$key.csv"),
objs_exported;
delim = ";;",
)
end
CSV.write(path, paths; delim = ";;")
else
open(io -> TOML.print(io, export_network(acs)), path, "w+")
end
end
"""
Export model to a file: this can be either a single TOML file encoding the entire model,
or a batch of CSV files (a root file and a number of files, each per a class of objects).
See `tutorials/loadsave` for an example.
# Examples
```julia
@export_network acs "acs_data.toml" # as a TOML
@export_network acs "csv/model.csv" # as a CSV
```
"""
macro export_network(acsex, pathex)
return :(export_network($(esc(acsex)), $(string(pathex))))
end
"""
Import a model from a file: this can be either a single TOML file encoding the entire model,
or a batch of CSV files (a root file and a number of files, each per a class of objects).
See `tutorials/loadsave` for an example.
# Examples
```julia
@import_network "model.toml"
@import_network "csv/model.toml"
```
"""
macro import_network(pathex, name = gensym())
return :($(esc(name)) = import_network($(string(pathex))))
end
macro load_models(pathex)
callex = :(
begin end
)
for line in readlines(string(pathex))
name, pathex = split(line, ';')
name = isempty(name) ? gensym() : Symbol(name)
push!(callex.args, :($(esc(name)) = import_network($(string(pathex)))))
end
return callex
end
"""
@import_solution "sol.jld2"
@import_solution "sol.jld2" sol
Import a solution from a file.
# Examples
```julia
@import_solution "sir_acs_sol/serialized/sol.jld2"
```
"""
macro import_solution(pathex, varname = "sol")
return :(JLD2.load($(string(pathex)), $(string(varname))))
end
"""
@export_solution sol
@export_solution sol "sol.jld2"
Export a solution to a file.
# Examples
```julia
@export_solution sol "sol.jdl2"
```
"""
macro export_solution(solex, pathex = "sol.jld2")
return :(JLD2.save($(string(pathex)), $(string(solex)), $(esc(solex))))
end
"""
@export_solution_as_table sol
Export a solution as a `DataFrame`.
# Examples
```julia
@export_solution_as_table sol
```
"""
macro export_solution_as_table(solex, pathex = "sol.jld2")
return :(DataFrame($(esc(solex))))
end
get_DataFrame(sol) = sol isa EnsembleSolution ? DataFrame(sol)[!, [:u, :t]] : DataFrame(sol)
"""
@export_solution_as_csv sol
@export_solution_as_csv sol "sol.csv"
Export a solution to a file.
# Examples
```julia
@export_solution_as_csv sol "sol.csv"
```
"""
macro export_solution_as_csv(solex, pathex = "sol.csv")
return :(CSV.write($(string(pathex)), get_DataFrame($(esc(solex)))))
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 6211 | function build_parametrized_solver(acs, init_vec, u0, params; trajectories = 1)
prob = DiscreteProblem(acs)
vars = prob.p[:__state__][:, :specInitUncertainty]
init_vec = deepcopy(init_vec)
function (vec)
vec = vec isa ComponentVector ? vec : (init_vec .= vec)
data = []
for _ = 1:trajectories
prob.p[:__state__] = deepcopy(prob.p[:__state0__])
for i in eachindex(prob.u0)
rv = randn() * vars[i]
prob.u0[i] = if (sign(rv + prob.u0[i]) == sign(prob.u0[i]))
rv + prob.u0[i]
else
prob.u0[i]
end
end
for (i, k) in enumerate(wkeys(u0))
prob.u0[k] = vec.species[i]
end
for k in wkeys(params)
prob.p[k] = vec[k]
end
sync!(prob.p[:__state__], prob.u0, prob.p)
push!(data, solve(prob))
end
return data
end
end
function build_parametrized_solver_(acs, init_vec, u0, params; trajectories = 1)
prob = DiscreteProblem(acs)
vars = prob.p[:__state__][:, :specInitUncertainty]
init_vec = deepcopy(init_vec)
function (vec)
vec = vec isa ComponentVector ? vec : (init_vec .= vec; init_vec)
data = map(1:trajectories) do _
prob.p[:__state__] = deepcopy(prob.p[:__state0__])
for i in eachindex(prob.u0)
rv = randn() * vars[i]
prob.u0[i] = if (sign(rv + prob.u0[i]) == sign(prob.u0[i]))
rv + prob.u0[i]
else
prob.u0[i]
end
end
for (i, k) in enumerate(wkeys(u0))
prob.u0[k] = vec.species[i]
end
for k in wkeys(params)
prob.p[k] = vec[k]
end
sync!(prob.p[:__state__], prob.u0, prob.p)
return solve(prob)
end
return trajectories == 1 ? data[1] : EnsembleSolution(data, 0.0, true)
end
end
## optimization part
BOUND_DEFAULT = 5000
function optim!(obj, init; nlopt_kwargs...)
nlopt_kwargs = Dict(nlopt_kwargs)
alg = pop!(nlopt_kwargs, :algorithm, :GN_DIRECT)
opt = Opt(alg, length(init))
# match to a ComponentVector
foreach(
o -> setproperty!(opt, o...),
filter(x -> x[1] in propertynames(opt), nlopt_kwargs),
)
if get(nlopt_kwargs, :objective, min) == min
(opt.min_objective = obj)
else
(opt.max_objective = obj)
end
return optimize(opt, deepcopy(init))
end
const n_steps = 100
# loss objective given an objective expression
function build_loss_objective(
acs,
init_vec,
u0,
params,
obex;
loss = identity,
trajectories = 1,
min_t = -Inf,
max_t = Inf,
final_only = false,
)
ob = eval(get_wrap_fun(acs)(obex))
obj_ = build_parametrized_solver(acs, init_vec, u0, params; trajectories)
function (vec, _)
ls = []
for sol in obj_(vec)
t_points = if final_only
[last(sol.t)]
else
min_t = max(min_t, sol.prob.tspan[1])
max_t = min(max_t, sol.prob.tspan[2])
range(min_t, max_t; length = n_steps)
end
push!(
ls,
mean(t -> loss(ob(as_state(sol(t), t, sol.prob.p[:__state__]))), t_points),
)
end
return mean(ls)
end
end
# loss objective given empirical data
function build_loss_objective_datapoints(
acs,
init_vec,
u0,
params,
t,
data,
vars;
loss = abs2,
trajectories = 1,
)
obj_ = build_parametrized_solver(acs, init_vec, u0, params; trajectories)
function (vec, _)
ls = []
for sol in obj_(vec)
push!(
ls,
mean(
t ->
sum(i -> loss(sol(t[2])[i[2]] - data[i[1], t[1]]), enumerate(vars)),
enumerate(t),
),
)
end
return mean(ls)
end
end
# set initial model parameter values in an optimization problem
function prep_params!(params, prob)
for (k, v) in params
(v === NaN) && wset!(params, k, get(prob.p, k, NaN))
end
any(p -> (p[2] === NaN) && @warn("Uninitialized prm: $p"), params)
return params
end
# set initial model variable values in an optimization problem
function prep_u0!(u0, prob)
for (k, v) in u0
(v === NaN) && wset!(u0, k, get(prob.u0, k, NaN))
end
any(u -> (u[2] === NaN) && @warn("Uninitialized prm: $(u[1])"), u0)
return u0
end
"""
Extract symbolic variables referenced in `acs`, `args`.
"""
function get_free_vars(acs, args)
u0_syms = collect(acs[:, :specName])
p_syms = collect(acs[:, :prmName])
u0 = []
p = []
for arg in args
if arg isa Symbol
(k, v) = (arg, NaN)
elseif isexpr(arg, :(=))
(k, v) = (arg.args[1], arg.args[2])
else
continue
end
if ((k in u0_syms || k isa Number) && !in(k, wkeys(u0)))
push!(u0, k => v)
elseif (k in p_syms && !in(k, wkeys(p)))
push!(p, k => v)
end
end
u0_ = []
for (k, v) in u0
if k isa Number
push!(u0_, Int(k) => v)
else
for i = 1:length(subpart(acs, :specName))
(acs[i, :specName] == k) && (push!(u0_, i => v); break)
end
end
end
return u0_, p
end
"""
Resolve symbolic / positional model variable names to positional.
"""
function get_vars(acs, args)
(args == :()) && return args
args_ = []
for arg in (MacroTools.isexpr(args, :vect, :tuple) ? args.args : [args])
arg = recursively_expand_dots(arg)
if arg isa Number
push!(args_, Int(arg))
else
for i = 1:length(subpart(acs, :specName))
!isnothing(acs[i, :specName]) &&
(acs[i, :specName] == arg) &&
(push!(args_, i); break)
end
end
end
return args_
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 13286 | # assortment of SciML-compatible problem solvers
export DiscreteProblem
using DiffEqBase, DifferentialEquations
using Distributions
function get_sampled_transition(state, i)
transition = Dict{Symbol,Any}()
foreach(k -> push!(transition, k => state[i, k]), keys(state.transitions))
return transition
end
"""
Compute resource requirements given transition quantities.
"""
function get_reqs_init!(reqs, qs, state)
reqs .= 0.0
for i = 1:size(reqs, 2)
for tok in state[i, :transLHS]
!any(m -> m in tok.modality, [:rate, :nonblock]) &&
(reqs[tok.index, i] += qs[i] * tok.stoich)
end
end
return reqs
end
"""
Compute resource requirements given transition quantities.
"""
function get_reqs_ongoing!(reqs, qs, state)
reqs .= 0.0
for i = 1:length(state.ongoing_transitions)
for tok in state.ongoing_transitions[i][:transLHS]
in(:rate, tok.modality) &&
(state.ongoing_transitions[i][:transCycleTime] > 0) &&
(reqs[tok.index, i] += qs[i] * tok.stoich * state.solverargs[:tstep])
in(:nonblock, tok.modality) && (reqs[tok.index, i] += qs[i] * tok.stoich)
end
end
return reqs
end
"""
Given requirements, return available allocation.
"""
function get_allocs!(reqs, u, state, priorities, strategy = :weighted)
return if strategy == :weighted
alloc_weighted!(reqs, u, priorities, state)
else
alloc_greedy!(reqs, u, priorities, state)
end
end
function alloc_weighted!(reqs, u, priorities, state)
allocs = zero(reqs)
for i = 1:size(reqs, 1)
s = sum(reqs[i, :])
u[i] >= s && (allocs[i, :] .= reqs[i, :]; continue)
foreach(j -> allocs[i, j] = reqs[i, j] * priorities[j], 1:size(reqs, 2))
s = sum(allocs[i, :])
allocs[i, :] .*= (s == 0) ? 0.0 : (max(0, u[i]) / s)
end
return allocs
end
function alloc_greedy!(reqs, u, priorities, state)
allocs = zero(reqs)
sorted_trans = sort(1:size(reqs, 2); by = i -> -priorities[i])
for i = 1:size(reqs, 1)
s = sum(reqs[i, :])
u[i] >= s && (allocs[i, :] .= reqs[i, :]; continue)
a = u[i]
j = 1
while a > 0 && j <= size(reqs, 2)
allocs[i, sorted_trans[j]] = min(reqs[i, sorted_trans[j]], a)
a -= allocs[i, sorted_trans[j]]
j += 1
end
end
return allocs
end
"""
Given resource requirements and available allocations, output resulting shift size for each transition.
"""
function get_frac_satisfied(allocs, reqs, state)
for i in eachindex(allocs)
allocs[i] = min(1, (reqs[i] == 0.0 ? 1 : (allocs[i] / reqs[i])))
end
qs = vec(minimum(allocs; dims = 1))
foreach(i -> allocs[:, i] .= reqs[:, i] * qs[i], 1:size(reqs, 2))
return qs
end
"""
Given available allocations and qties of transitions requested to spawn, return number of spawned transitions. Update `alloc` to match actual allocation.
"""
function get_init_satisfied(allocs, qs, state)
reqs = zero(allocs)
for i = 1:size(allocs, 2)
all(allocs[:, i] .>= 0) || (allocs[:, i] .= 0.0; qs[i] = 0)
for tok in state[i, :transLHS]
!any(m -> m in tok.modality, [:rate, :nonblock]) &&
(reqs[tok.index, i] += tok.stoich)
end
end
for i in eachindex(allocs)
allocs[i] = reqs[i] == 0.0 ? Inf : floor(allocs[i] / reqs[i])
end
foreach(i -> qs[i] = min(qs[i], minimum(allocs[:, i])), 1:size(reqs, 2))
foreach(i -> allocs[:, i] .= reqs[:, i] * qs[i], 1:size(reqs, 2))
return qs
end
"""
Evolve transitions, spawn new transitions.
"""
function evolve!(u, state)
update_u!(state, u)
actual_allocs = zero(u)
## schedule new transitions
reqs = zeros(nparts(state, :S), nparts(state, :T))
qs = zeros(nparts(state, :T))
foreach(
i -> qs[i] = state[i, :transRate] * state[i, :transMultiplier],
1:nparts(state, :T),
)
qs .= ceil.(Ref(Int), qs)
for i = 1:nparts(state, :T)
new_instances = state.solverargs[:tstep] * qs[i] + state[i, :transToSpawn]
capacity =
state[i, :transCapacity] -
count(t -> t[:transHash] == state[i, :transHash], state.ongoing_transitions)
(capacity < new_instances) &&
add_to_spawn!(state, state[i, :transHash], new_instances - capacity)
qs[i] = min(capacity, new_instances)
end
reqs = get_reqs_init!(reqs, qs, state)
allocs =
get_allocs!(reqs, u, state, state[:, :transPriority], state.solverargs[:strategy])
qs .= get_init_satisfied(allocs, qs, state)
push!(
state.log,
(
:new_transitions,
state.t,
[(hash, q) for (hash, q) in zip(state[:, :transHash], qs)]...,
),
)
u .-= sum(allocs; dims = 2)
actual_allocs .+= sum(allocs; dims = 2)
# add spawned transitions to the heap
for i = 1:nparts(state, :T)
qs[i] != 0 && push!(
state.ongoing_transitions,
Transition(get_sampled_transition(state, i), state.t, qs[i], 0.0),
)
end
update_u!(state, u)
## evolve ongoing transitions
reqs = zeros(nparts(state, :S), length(state.ongoing_transitions))
qs = map(t -> t.q, state.ongoing_transitions)
get_reqs_ongoing!(reqs, qs, state)
allocs = get_allocs!(
reqs,
u,
state,
map(t -> t[:transPriority], state.ongoing_transitions),
state.solverargs[:strategy],
)
qs .= get_frac_satisfied(allocs, reqs, state)
push!(
state.log,
(
:saturation,
state.t,
[
(state.ongoing_transitions[i][:transHash], qs[i]) for
i in eachindex(state.ongoing_transitions)
]...,
),
)
u .-= sum(allocs; dims = 2)
actual_allocs .+= sum(allocs; dims = 2)
foreach(
i -> state.ongoing_transitions[i].state += qs[i] * state.solverargs[:tstep],
eachindex(state.ongoing_transitions),
)
push!(state.log, (:allocation, state.t, actual_allocs))
return push!(
state.log,
(
:valuation_cost,
state.t,
actual_allocs' * [state[i, :specCost] for i = 1:nparts(state, :S)],
),
)
end
# execute callbacks
function event_action!(state)
for i = 1:nparts(state, :E)
!isnothing(state[i, :eventTrigger]) && !isnothing(state[i, :eventAction]) ||
continue
v = state[i, :eventTrigger]
q = v isa Bool ? (v ? 1 : 0) : (v isa Number ? rand(Poisson(v)) : 0)
for _ = 1:q
state[i, :eventAction]
end
end
end
# collect terminated transitions
function finish!(u, state)
update_u!(state, u)
val_reward = 0
terminated_all = Dict{Symbol,Float64}()
terminated_success = Dict{Symbol,Float64}()
ix = 1
while ix <= length(state.ongoing_transitions)
trans_ = state.ongoing_transitions[ix]
((state.t - trans_.t) < trans_.trans[:transMaxLifeTime]) &&
trans_.state < trans_[:transCycleTime] &&
(ix += 1; continue)
toks_rhs = []
for r in extract_reactants(trans_[:transRHS], state)
i = find_index(r.species, state)
push!(
toks_rhs,
UnfoldedReactant(
i,
r.species,
context_eval(state, state.wrap_fun(r.stoich)),
r.modality ∪ state[i, :specModality],
),
)
end
for tok in trans_[:transLHS]
in(:conserved, tok.modality) && (
u[tok.index] +=
trans_.q *
tok.stoich *
(in(:rate, tok.modality) ? trans_[:transCycleTime] : 1)
)
end
q = if trans_.state >= trans_[:transCycleTime]
rand(Distributions.Binomial(Int(trans_.q), trans_[:transProbOfSuccess]))
else
0
end
foreach(
tok -> (u[tok.index] += q * tok.stoich;
val_reward += state[tok.index, :specReward] * q * tok.stoich),
toks_rhs,
)
update_u!(state, u)
context_eval(state, trans_.trans[:transPostAction])
terminated_all[trans_[:transHash]] =
get(terminated_all, trans_[:transHash], 0) + trans_.q
terminated_success[trans_[:transHash]] =
get(terminated_success, trans_[:transHash], 0) + q
ix += 1
end
filter!(s -> s.state < s[:transCycleTime], state.ongoing_transitions)
push!(state.log, (:terminated_all, state.t, terminated_all...))
push!(state.log, (:terminated_success, state.t, terminated_success...))
push!(state.log, (:valuation_reward, state.t, val_reward))
return u
end
function free_blocked_species!(state)
for trans in state.ongoing_transitions, tok in trans[:transLHS]
in(:nonblock, tok.modality) && (state.u[tok.index] += q * tok.stoich)
end
end
"""
Transform an `acs` to a `DiscreteProblem` instance, compatible with standard solvers.
# Examples
```julia
transform(DiscreteProblem, acs; schedule = schedule_weighted!)
```
"""
function transform(
::Type{DiffEqBase.DiscreteProblem},
state::ReactiveDynamicsState;
kwargs...,
)
f = function (du, u, p, t)
state = p[:__state__]
free_blocked_species!(state)
du .= state.u
update_observables(state)
sample_transitions!(state)
evolve!(du, state)
finish!(du, state)
update_u!(state, du)
event_action!(state)
du .= state.u
push!(
state.log,
(:valuation, t, du' * [state[i, :specValuation] for i = 1:nparts(state, :S)]),
)
t = (state.t += state.solverargs[:tstep])
update_u!(state, du)
save!(state)
sync_p!(p, state)
return du
end
return DiffEqBase.DiscreteProblem(
f,
state.u,
(0.0, 2.0),
Dict(state.p..., :__state__ => state, :__state0__ => deepcopy(state));
kwargs...,
)
end
## resolve tspan, tstep
function get_tcontrol(tspan, args)
tspan isa Tuple && (tspan = tspan[2] - tspan[1])
tunit = get(args, :tunit, oneunit(tspan))
tspan = tspan / tunit
tstep = get(args, :tstep, haskey(args, :tstops) ? tspan / args[:tstops] : tunit) / tunit
return ((0.0, tspan), tstep)
end
"""
Transform an `acs` to a `DiscreteProblem` instance, compatible with standard solvers.
Optionally accepts initial values and parameters, which take precedence over specifications in `acs`.
# Examples
```julia
DiscreteProblem(acs, u0, p; tspan = (0.0, 100.0), schedule = schedule_weighted!)
```
"""
function DiffEqBase.DiscreteProblem(
acs::ReactionNetwork,
u0 = Dict(),
p = DiffEqBase.NullParameters();
kwargs...,
)
assign_defaults!(acs)
keywords = Dict{Symbol,Any}([
acs[i, :metaKeyword] => acs[i, :metaVal] for i = 1:nparts(acs, :M) if
!isnothing(acs[i, :metaKeyword]) && !isnothing(acs[i, :metaVal])
])
merge!(keywords, Dict(collect(kwargs)))
merge!(keywords, Dict(:strategy => get(keywords, :alloc_strategy, :weighted)))
keywords[:tspan], keywords[:tstep] = get_tcontrol(keywords[:tspan], keywords)
acs = remove_choose(acs)
attrs, transitions, wrap_fun = compile_attrs(acs)
state = ReactiveDynamicsState(
acs,
attrs,
transitions,
wrap_fun,
keywords[:tspan][1];
keywords...,
)
init_u!(state)
save!(state)
prob = transform(DiffEqBase.DiscreteProblem, state; kwargs...)
u0 isa Dict && foreach(
i ->
prob.u0[i] =
if !isnothing(acs[i, :specName]) && haskey(u0, acs[i, :specName])
u0[acs[i, :specName]]
else
prob.u0[i]
end,
1:nparts(state, :S),
)
p_ = p == DiffEqBase.NullParameters() ? Dict() : Dict(k => v for (k, v) in p)
prob = remake(
prob;
u0 = prob.u0,
tspan = keywords[:tspan],
dt = get(keywords, :tstep, 1),
p = merge(
prob.p,
p_,
Dict(
:tstep => get(keywords, :tstep, 1),
:strategy => get(keywords, :alloc_strategy, :weighted),
),
),
)
return prob
end
function fetch_params(acs::ReactionNetwork)
return Dict{Symbol,Any}((
acs[i, :prmName] => acs[i, :prmVal] for
i in Iterators.filter(i -> !isnothing(acs[i, :prmVal]), 1:nparts(acs, :P))
))
end
# EnsembleProblem's prob_func: sample initial values
function get_prob_func(prob)
vars = prob.p[:__state__][:, :specInitUncertainty]
prob_func = function (prob, _, _)
prob.p[:__state__] = deepcopy(prob.p[:__state0__])
for i in eachindex(prob.u0)
rv = randn() * vars[i]
prob.u0[i] = if (sign(rv + prob.u0[i]) == sign(prob.u0[i]))
rv + prob.u0[i]
else
prob.u0[i]
end
end
sync!(prob.p[:__state__], prob.u0, prob.p)
return prob
end
return prob_func
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 8125 | using DiffEqBase: NullParameters
struct UnfoldedReactant
index::Int
species::Symbol
stoich::ActionableValues
modality::Set{Symbol}
end
"""
Ongoing transition auxiliary structure.
"""
mutable struct Transition
trans::Dict{Symbol,Any}
t::Float64
q::Float64
state::Float64
end
Base.getindex(state::Transition, key) = state.trans[key]
mutable struct Observable
last::Float64 # last sampling time
range::Vector{Union{Tuple{Float64,SampleableValues},SampleableValues}}
every::Float64
on::Vector{ActionableValues}
sampled::Any
end
mutable struct ReactiveDynamicsState
acs::ReactionNetwork
attrs::Dict{Symbol,Vector}
transition_recipes::Dict{Symbol,Vector}
u::Vector{Float64}
p::Any
t::Float64
transitions::Dict{Symbol,Vector}
ongoing_transitions::Vector{Transition}
log::Vector{Tuple}
observables::Dict{Symbol,Observable}
solverargs::Any
wrap_fun::Any
history_u::Vector{Vector{Float64}}
history_t::Vector{Float64}
function ReactiveDynamicsState(
acs::ReactionNetwork,
attrs,
transition_recipes,
wrap_fun,
t0 = 0;
kwargs...,
)
ongoing_transitions = Transition[]
log = NamedTuple[]
observables = compile_observables(acs)
transitions_attrs =
setdiff(
filter(a -> contains(string(a), "trans"), propertynames(acs.subparts)),
(:trans,),
) ∪ [:transLHS, :transRHS, :transToSpawn, :transHash]
transitions = Dict{Symbol,Vector}(a => [] for a in transitions_attrs)
return new(
acs,
attrs,
transition_recipes,
zeros(nparts(acs, :S)),
fetch_params(acs),
t0,
transitions,
ongoing_transitions,
log,
observables,
kwargs,
wrap_fun,
Vector{Float64}[],
Float64[],
)
end
end
# get value of a numeric expression
# evaluate compiled numeric expression in context of (u, p, t)
function context_eval(state::ReactiveDynamicsState, o)
o = o isa Function ? Base.invokelatest(o, state) : o
return o isa Sampleable ? rand(o) : o
end
function Base.getindex(state::ReactiveDynamicsState, keys...)
return context_eval(
state,
(contains(string(keys[2]), "trans") ? state.transitions : state.attrs)[keys[2]][keys[1]],
)
end
function init_u!(state::ReactiveDynamicsState)
return (u = fill(0.0, nparts(state, :S));
foreach(i -> u[i] = state[i, :specInitVal], 1:nparts(state, :S));
state.u = u)
end
function save!(state::ReactiveDynamicsState)
return (push!(state.history_u, state.u); push!(state.history_t, state.t))
end
function compile_observables(acs::ReactionNetwork)
observables = Dict{Symbol,Observable}()
species_names = collect(acs[:, :specName])
prm_names = collect(acs[:, :prmName])
varmap = Dict([name => :(state.u[$i]) for (i, name) in enumerate(species_names)])
for (name, opts) in Iterators.zip(acs[:, :obsName], acs[:, :obsOpts])
on = map(on -> wrap_expr(on, species_names, prm_names, varmap), opts.on)
range = map(
r -> begin
r = r isa Tuple ? r : (1.0, r)
(r[1], wrap_expr(r[2], species_names, prm_names, varmap))
end,
opts.range,
)
push!(observables, name => Observable(-Inf, range, opts.every, on, missing))
end
return observables
end
compileval(ex, state) = !isa(ex, Expr) ? ex : eval(state.wrap_fun(ex))
function sample_range(rng, state)
isempty(rng) && return missing
r = rand() * sum(r -> r isa Tuple ? eval(r[1]) : 1, rng)
ix = 0
s = 0
while s <= r && (ix < length(rng))
ix += 1
s += rng[ix] isa Tuple ? compileval(rng[ix][1], state) : 1
end
r = rng[ix] isa Tuple ? rng[ix][2] : rng[ix]
return r isa Sampleable ? rand(r) : r
end
function resample!(state::ReactiveDynamicsState, o::Observable)
o.last = state.t
isempty(o.range) && (return o.val = missing)
return o.sampled = context_eval(state, sample_range(o.range, state))
end
resample(state::ReactiveDynamicsState, o::Symbol) = resample!(state, state.observables[o])
function update_observables(state::ReactiveDynamicsState)
return foreach(
o -> (state.t - o.last) >= o.every && resample!(state, o),
values(state.observables),
)
end
function prune_r_line(r_line)
return if r_line isa Expr && r_line.args[1] ∈ fwd_arrows
r_line.args[2:3]
elseif r_line isa Expr && r_line.args[1] ∈ bwd_arrows
r_line.args[[3, 2]]
elseif isexpr(r_line, :macrocall) && (macroname(r_line) == :choose)
sample_range(
[(
if isexpr(r, :tuple)
(r.args[1], prune_r_line(r.args[2]))
else
prune_r_line(r)
end
) for r in r_line.args[3:end]],
state,
)
end
end
function find_index(species::Symbol, state::ReactiveDynamicsState)
return findfirst(i -> state[i, :specName] == species, 1:nparts(state, :S))
end
function sample_transitions!(state::ReactiveDynamicsState)
for (_, v) in state.transitions
empty!(v)
end
for i = 1:length(state.transition_recipes[:trans])
!(state.transition_recipes[:transActivated][i]) && continue
l_line, r_line = prune_r_line(state.transition_recipes[:trans][i])
for attr in keys(state.transition_recipes)
attr ∈ [:trans, :transPostAction, :transActivated, :transHash] && continue
push!(
state.transitions[attr],
context_eval(state, state.transition_recipes[attr][i]),
)
end
reactants = []
for r in extract_reactants(l_line, state)
j = find_index(r.species, state)
push!(
reactants,
UnfoldedReactant(
j,
r.species,
context_eval(state, state.wrap_fun(r.stoich)),
r.modality ∪ state[j, :specModality],
),
)
end
push!(state.transitions[:transLHS], reactants)
push!(state.transitions[:transRHS], r_line)
foreach(
k -> push!(state.transitions[k], state.transition_recipes[k][i]),
[:transPostAction, :transToSpawn, :transHash],
)
state.transition_recipes[:transToSpawn] .= 0
end
end
## sync
update_u!(state::ReactiveDynamicsState, u) = (state.u .= u)
update_t!(state::ReactiveDynamicsState, t) = (state.t = t)
sync_p!(p, state::ReactiveDynamicsState) = merge!(p, state.p)
function sync!(state::ReactiveDynamicsState, u, p)
state.u .= u
for k in keys(state.p)
haskey(p, k) && (state.p[k] = p[k])
end
end
function as_state(u, t, state::ReactiveDynamicsState)
return (state = deepcopy(state); state.u .= u; state.t = t; state)
end
function Catlab.CategoricalAlgebra.nparts(state::ReactiveDynamicsState, obj::Symbol)
return obj == :T ? length(state.transitions[:transLHS]) : nparts(state.acs, obj)
end
## query the state
t(state::ReactiveDynamicsState) = state.t
solverarg(state::ReactiveDynamicsState, arg) = state.solverargs[arg]
take(state::ReactiveDynamicsState, pcs::Symbol) = state.observables[pcs].sampled
log(state::ReactiveDynamicsState, msg) = (println(msg); push!(state.log, (:log, msg)))
state(state::ReactiveDynamicsState) = state
function periodic(state::ReactiveDynamicsState, period)
return period == 0.0 || (
length(state.history_t) > 1 &&
(fld(state.t, period) - fld(state.history_t[end-1], period) > 0)
)
end
set_params(state::ReactiveDynamicsState, vals...) =
for (p, v) in vals
state.p[p] = v
end
function add_to_spawn!(state::ReactiveDynamicsState, hash, n)
ix = findfirst(ix -> state.transition_recipes[:transHash][ix] == hash)
return !isnothing(ix) && (state.transition_recipes[:transHash][ix] += n)
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 9044 | # reaction network DSL: CREATE part; reaction line and event parsing
export @ReactionNetwork
using MacroTools: prewalk, postwalk, striplines, isexpr
using Symbolics: build_function, get_variables
empty_set = Set{Symbol}([:∅])
fwd_arrows = Set{Symbol}([:>, :→, :↣, :↦, :⇾, :⟶, :⟼, :⥟, :⥟, :⇀, :⇁, :⇒, :⟾])
bwd_arrows =
Set{Symbol}([:<, :←, :↢, :↤, :⇽, :⟵, :⟻, :⥚, :⥞, :↼, :↽, :⇐, :⟽, Symbol("<--")])
double_arrows = Set{Symbol}([:↔, :⟷, :⇄, :⇆, :⇌, :⇋, :⇔, :⟺, Symbol("<-->")])
arrows = fwd_arrows ∪ bwd_arrows ∪ double_arrows ∪ [:-->]
ifs = [:&&, :if]
reserved_sampling_macros = [:register, :sample, :take]
struct Reactant
species::Symbol
stoich::SampleableValues
modality::Set{Symbol}
end
struct FoldedReactionStruct
rate::SampleableValues
reaction::SampleableValues
end
struct Event
trigger::SampleableValues
action::SampleableValues
end
# Declares symbols which may neither be used as parameters not varriables.
forbidden_symbols = [:t, :π, :pi, :ℯ, :im, :nothing, :∅]
"""
Macro that takes an expression corresponding to a reaction network and outputs an instance of `TheoryReactionNetwork` that can be converted to a `DiscreteProblem` or solved directly.
Most arrows accepted (both right, left, and bi-drectional arrows). Use 0 or ∅ for annihilation/creation to/from nothing.
Custom functions and sampleable objects can be used as numeric parameters. Note that these have to be accessible from ReactiveDynamics's source code.
# Examples
```julia
acs = @ReactionNetwork begin
1.0, X ⟶ Y
1.0, X ⟶ Y, priority => 6.0, prob => 0.7, capacity => 3.0
1.0, ∅ --> (Poisson(0.3γ)X, Poisson(0.5)Y)
(XY > 100) && (XY -= 1)
end
@push acs 1.0 X ⟶ Y
@prob_init acs X = 1 Y = 2 XY = α
@prob_params acs γ = 1 α = 4
@solve_and_plot acs
```
"""
macro ReactionNetwork end
macro ReactionNetwork()
return make_ReactionNetwork(:())
end
macro ReactionNetwork(ex)
return make_ReactionNetwork(ex; eval_module = __module__)
end
macro ReactionNetwork(ex, args...)
return make_ReactionNetwork(
generate(Expr(:braces, ex, args...); eval_module = __module__);
eval_module = __module__,
)
end
function make_ReactionNetwork(ex::Expr; eval_module = @__MODULE__)
blockex = generate(ex; eval_module)
blockex = unblock_shallow!(blockex)
return :(ReactionNetwork(get_data($(QuoteNode(blockex)))...))
end
### Functions that process the input and rephrase it as a reaction system ###
function esc_dollars!(ex)
if ex isa Expr
if ex.head == :$
return esc(:($(ex.args[1])))
else
for i = 1:length(ex.args)
ex.args[i] = esc_dollars!(ex.args[i])
end
end
end
return ex
end
symbolize(pairex) = pairex isa Number ? pairex : (pairex.args[2] => pairex.args[3])
function get_data(ex)
trans = []
evs = []
reactants = []
pcs = []
if isexpr(ex, :block)
ex = striplines(ex)
esc_dollars!(ex)
foreach(
l -> get_data!(trans, reactants, pcs, evs, isexpr(l, :tuple) ? l.args : [l]),
ex.args,
)
elseif ex != :()
get_data!(trans, reactants, pcs, evs, ex)
end
return trans, reactants, pcs, evs
end
function get_data!(trans, reactants, pcs, evs, exs)
length(exs) == 0 && return
if exs[1] isa Expr && (exs[1].head ∈ ifs)
get_events!(evs, normalize_pcs!(pcs, exs[1]))
else
get_transitions!(trans, reactants, pcs, exs)
end
end
get_events!(evs, ex) =
if ex.head == :&&
push!(evs, Event(ex.args...))
else
recursively_expand_actions!(evs, Expr(:call, :&), ex)
end
function recursively_expand_actions!(evs, condex, event)
if isexpr(event, :if)
condex_ = deepcopy(condex)
push!(condex_.args, event.args[1])
push!(evs, Event(condex_, event.args[2]))
push!(condex.args, Expr(:call, :!, event.args[1]))
length(event.args) >= 3 && recursively_expand_actions!(evs, condex, event.args[3])
else
push!(evs, Event(condex, event))
end
end
function expand_rate(rate)
rate = if !(isexpr(rate, :macrocall) && (macroname(rate) == :per_step))
:(rand(Poisson(max($rate, 0))))
else
rate.args[3]
end
postwalk(rate) do ex
if (isexpr(ex, :macrocall) && (macroname(ex) ∈ prettynames[:transCycleTime]))
:(1 / $(ex.args[3]))
else
ex
end
end
end
function get_transitions!(trans, reactants, pcs, exs)
args = empty(defargs[:T])
(rate, r_line) = exs[1:2]
rxs = prune_reaction_line!(pcs, reactants, r_line)
rate = expand_rate(rate)
rxs = rxs isa Tuple ? tuple.(fill(rate, length(rxs)), rxs) : ((rate, rxs),)
exs = exs[3:end]
empty!(args)
ix = 1
while ix <= length(exs)
(!isa(exs[ix], Expr) || (exs[ix].head != :call)) && (ix += 1; continue)
karg = (xi = findfirst(k -> exs[ix].args[2] ∈ k, prettynames);
isnothing(xi) && (ix += 1; continue);
xi)
push!(args, karg => normalize_pcs!(pcs, exs[ix].args[3]))
deleteat!(exs, ix)
end
args = merge(defargs[:T], args)
append!(trans, tuple.(rxs, Ref(args)))
return trans
end
function replace_in_expr(expr, pairs...)
dict = Dict(pairs...)
return prewalk(ex -> haskey(dict, ex) ? dict[ex] : ex, expr)
end
function normalize_pcs!(pcs, expr)
postwalk(expr) do ex
isexpr(ex, :macrocall) &&
macroname(ex) == :register &&
(push!(pcs, deepcopy(ex));
ex.args[1] = Symbol("@", :take);
ex.args = ex.args[1:3])
if isexpr(ex, :macrocall) && macroname(ex) == :register
r_sym = gensym()
(push!(pcs, (ex_ = deepcopy(ex); insert!(ex_.args, 3, r_sym); ex_));
ex.args[1] = Symbol("@", :take);
ex.args = [
r_sym
ex.args[1:2]
])
end
return ex
end
end
function get_reaction_line(expr)
biarrow = nothing
prewalk(ex --> (ex ∈ double_arrows && (biarrow = ex); ex), expr)
return if !isnothing(biarrow)
[expr]
else
[replace_in_expr(expr, biarrow => :⟶), replace_in_expr(expr, biarrow => :⟵)]
end
end
function prune_reaction_line!(pcs, reactants, line)
line isa Expr &&
(line.head == :-->) &&
(line = Expr(:call, :→, line.args[1], line.args[2]))
if isexpr(line, :macrocall)
lines = copy(line.args[3:end])
line.args = line.args[1:2]
for l in lines
biarrow = nothing
prewalk(ex -> (ex ∈ double_arrows && (biarrow = ex); ex), l)
append!(
line.args,
if isnothing(biarrow)
[l]
else
[replace_in_expr(l, biarrow => :⟶), replace_in_expr(l, biarrow => :⟵)]
end,
)
end
for i = 3:length(line.args)
line.args[i] = if isexpr(line.args[i], :tuple)
Expr(
:tuple,
line.args[i].args[1],
prune_reaction_line!(pcs, reactants, line.args[i].args[2]),
)
else
prune_reaction_line!(pcs, reactants, line.args[i])
end
end
elseif line isa Expr && line.args[1] ∈ union(fwd_arrows, bwd_arrows)
line.args[2:3] =
recursively_find_reactants!.(Ref(reactants), Ref(pcs), line.args[2:3])
elseif line isa Expr && line.args[1] ∈ double_arrows
biarrow = nothing
prewalk(ex -> (ex ∈ double_arrows && (biarrow = ex); ex), line)
line =
prune_reaction_line!.(
Ref(pcs),
Ref(reactants),
(
replace_in_expr(line, biarrow => :⟶),
replace_in_expr(line, biarrow => :⟵),
),
)
end
return line
end
function recursively_find_reactants!(reactants, pcs, ex::SampleableValues)
if typeof(ex) != Expr || isexpr(ex, :.) || (ex.head == :escape)
if (ex == 0 || in(ex, empty_set))
return :∅
else
push!(reactants, recursively_expand_dots(ex))
end
elseif ex.args[1] == :*
recursively_find_reactants!(reactants, pcs, ex.args[end])
foreach(i -> ex.args[i] = normalize_pcs!(pcs, ex.args[i]), 2:(length(ex.args)-1))
elseif ex.args[1] == :+
for i = 2:length(ex.args)
recursively_find_reactants!(reactants, pcs, ex.args[i])
end
elseif isexpr(ex, :macrocall) && macroname(ex) == :choose
for i = 3:length(ex.args)
recursively_find_reactants!(
reactants,
pcs,
isexpr(ex.args[i], :tuple) ? ex.args[i].args[2] : ex.args[i],
)
end
elseif isexpr(ex, :macrocall)
recursively_find_reactants!(reactants, pcs, ex.args[3])
else
push!(reactants, underscorize(ex))
end
return ex
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 1490 | # parts of the code were taken from Catalyst.jl and adapted
recursively_expand_dots(ex) = underscorize(ex)
# Returns the length of a expression tuple, or 1 if it is not an expression tuple (probably a Symbol/Numerical).
function tup_leng(ex::SampleableValues)
(typeof(ex) == Expr && ex.head == :tuple) && (return length(ex.args))
return 1
end
#Gets the ith element in a expression tuple, or returns the input itself if it is not an expression tuple (probably a Symbol/Numerical).
function get_tup_arg(ex::SampleableValues, i::Int)
(tup_leng(ex) == 1) && (return ex)
return ex.args[i]
end
function multiplex(mult, mults...)
all(m -> isa(m, Number), [mult] ∪ mults) && return mult * prod(mults; init = 1.0)
multarray = SampleableValues[]
recursively_find_mults!(multarray, mults...)
mults_numeric =
prod(filter(m -> isa(m, Number), multarray); init = 1.0) *
(mult isa Number ? mult : 1.0)
mults_expr = filter(m -> !isa(m, Number), multarray)
mult = mult isa Expr ? deepcopy(mult) : :(*())
mults_numeric == 1 && length(mults_expr) == 1 && return mults_expr[1]
mults_numeric != 1.0 && push!(mult.args, mults_numeric)
append!(mult.args, mults_expr)
return mult
end
function recursively_find_mults!(multarray, mults...)
for m in mults
if isa(m, Expr) && m.args[1] == :*
recursively_find_mults!(multarray, m.args[2:end]...)
else
push!(multarray, m)
end
end
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2240 | # parts of the code were taken from Catalyst.jl and adapted
using MacroTools: postwalk
struct FoldedReactant
species::Symbol
stoich::SampleableValues
modality::Set{Symbol}
end
function recursively_choose(r_line, state)
postwalk(r_line) do ex
if isexpr(ex, :macrocall) && (macroname(ex) == :choose)
sample_range(
[
(
if isexpr(r, :tuple)
(r.args[1], recursively_choose(r.args[2], state))
else
recursively_choose(r, state)
end
) for r in ex.args[3:end]
],
state,
)
else
ex
end
end
end
function extract_reactants(r_line, state::ReactiveDynamicsState)
r_line = recursively_choose(r_line, state)
return recursive_find_reactants!(
escape_ref(r_line, state[:, :specName]),
1.0,
Set{Symbol}(),
Vector{FoldedReactant}(undef, 0),
)
end
function recursive_find_reactants!(
ex::SampleableValues,
mult::SampleableValues,
mods::Set{Symbol},
reactants::Vector{FoldedReactant},
)
if typeof(ex) != Expr || isexpr(ex, :.) || (ex.head == :escape)
if (ex == 0 || in(ex, empty_set))
return reactants
else
push!(reactants, FoldedReactant(recursively_expand_dots(ex), mult, mods))
end
elseif ex.args[1] == :*
recursive_find_reactants!(
ex.args[end],
multiplex(mult, ex.args[2:(end-1)]...),
mods,
reactants,
)
elseif ex.args[1] == :+
for i = 2:length(ex.args)
recursive_find_reactants!(ex.args[i], mult, mods, reactants)
end
elseif ex.head == :macrocall
mods = copy(mods)
macroname(ex) in species_modalities && push!(mods, macroname(ex))
foreach(
i -> push!(mods, ex.args[i] isa Symbol ? ex.args[i] : ex.args[i].value),
4:length(ex.args),
)
recursive_find_reactants!(ex.args[3], mult, mods, reactants)
else
@error("malformed reaction")
end
return reactants
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 14890 | export @problematize, @solve, @plot
export @optimize, @fit, @fit_and_plot, @build_solver
using DifferentialEquations: DiscreteProblem, EnsembleProblem, FunctionMap, EnsembleSolution
import MacroTools
import Plots
"""
Convert a model to a `DiscreteProblem`. If passed a problem instance, return the instance.
# Examples
```julia
@problematize acs tspan = 1:100
```
"""
macro problematize(acsex, args...)
args, kwargs = args_kwargs(args)
quote
if $(esc(acsex)) isa DiscreteProblem
$(esc(acsex))
else
DiscreteProblem($(esc(acsex)), $(args...); $(kwargs...))
end
end
end
"""
Solve the problem. Solverargs passed at the calltime take precedence.
# Examples
```julia
@solve prob
@solve prob tspan = 1:100
@solve prob tspan = 100 trajectories = 20
```
"""
macro solve(probex, args...)
args, kwargs = args_kwargs(args)
mode = find_kwargex_delete!(kwargs, :mode, nothing)
!isnothing(findfirst(el -> el.args[1] == :trajectories, kwargs)) && (mode = :ensemble)
quote
prob = if $(esc(probex)) isa DiscreteProblem
$(esc(probex))
else
DiscreteProblem($(esc(probex)), $(args...); $(kwargs...))
end
if $(preserve_sym(mode)) == :ensemble
solve(
EnsembleProblem(prob; prob_func = get_prob_func(prob)),
FunctionMap(),
$(kwargs...),
)
else
solve(prob)
end
end
end
# auxiliary plotting functions
function plot_summary(s, labels, ixs; kwargs...)
isempty(ixs) && return @warn "Set of species to plot must be non-empty!"
s = EnsembleSummary(s)
f_ix = first(ixs)
p = Plots.plot(
s.t,
s.u[f_ix, :];
ribbon = (-s.qlow[f_ix, :] + s.u[f_ix, :], s.qhigh[f_ix, :] - s.u[f_ix, :]),
label = labels[f_ix],
fillalpha = 0.2,
w = 2.0,
kwargs...,
)
foreach(
i -> Plots.plot!(
p,
s.t,
s.u[i, :];
ribbon = (-s.qlow[i, :] + s.u[i, :], s.qhigh[i, :] - s.u[i, :]),
label = labels[i],
fillalpha = 0.2,
w = 2.0,
kwargs...,
),
ixs[2:end],
)
return p
end
function plot_ensemble_sol(sol, label, ixs; kwargs...)
return if !(sol isa EnsembleSolution)
Plots.plot(sol; idxs = ixs, label = reshape(label[ixs], 1, :), kwargs...)
else
Plots.plot(sol; idxs = ixs, alpha = 0.7, kwargs...)
end
end
first_sol(sol) = sol isa EnsembleSolution ? first(sol) : sol
function match_names(selector, names)
if isnothing(selector)
1:length(names)
else
selector = selector isa Union{AbstractString,Regex,Symbol} ? [selector] : selector
ixs = Int[]
for s in selector
s isa Symbol && (s = string(s))
append!(
ixs,
findall(
name -> s isa Regex ? occursin(s, name) : (string(s) == string(name)),
names,
),
)
end
unique!(ixs)
end
end
"""
Plot the solution (summary).
# Examples
```julia
@plot sol plot_type = summary
@plot sol plot_type = allocation # not supported for ensemble solutions!
@plot sol plot_type = valuations # not supported for ensemble solutions!
@plot sol plot_type = new_transitions # not supported for ensemble solutions!
```
"""
macro plot(solex, args...)
_, kwargs = args_kwargs(args)
plot = find_kwargex_delete!(kwargs, :plot_type, nothing)
selector = find_kwargex_delete!(kwargs, :show, nothing)
quote
plot_type = $(preserve_sym(plot))
sol = $(esc(solex))
if plot_type ∈ [nothing, :ensemble]
names = string.(first_sol(sol).prob.p[:__state__][:, :specName])
plot_ensemble_sol(sol, names, match_names($selector, names); $(kwargs...))
elseif plot_type == :summary
names = string.(first_sol(sol).prob.p[:__state__][:, :specName])[:]
plot_summary(sol, names, match_names($selector, names); $(kwargs...))
else
names = string.(sol.prob.p[:__state__][:, :specName])
plot_from_log(
sol.prob.p[:__state__],
plot_type,
match_names($selector, names);
$(kwargs...),
)
end
end
end
function get_transitions(log)
transitions = Symbol[]
for r in log
r[1] ∈ [:new_transitions, :saturation] &&
union!(transitions, map(r -> r[1], r[3:end]))
end
return transitions
end
function complete_log_transitions(log, hashes, record_type)
pos = Dict(hashes[ix] => ix for ix in eachindex(hashes))
steps = unique(map(r -> r[2], log))
vals = zeros(length(steps), length(hashes))
ix = 1
for r in log
if r[1] == record_type
for (hash, val) in r[3:end]
vals[ix, pos[hash]] = val
end
ix += 1
end
end
return vals, steps
end
function complete_log_species(log, n_species, record_type)
steps = unique(map(r -> r[2], log))
vals = zeros(length(steps), n_species)
ix = 1
for r in log
if r[1] == record_type
vals[ix, :] .= r[3]
ix += 1
end
end
return vals, steps
end
function complete_log_valuations(log)
steps = unique(map(r -> r[2], log))
vals = zeros(length(steps), 4)
ix = 0
time_last = -Inf
for r in log
r[2] > time_last && (time_last = r[2]; ix += 1)
if r[1] == :valuation
vals[ix, 1] = r[3]
elseif r[1] == :valuation_cost
vals[ix, 2] = r[3]
elseif r[1] == :valuation_reward
vals[ix, 3] = r[3]
end
end
return vals, steps
end
function get_names(state, hashes)
names = String[]
for hash in hashes
ix = findfirst(==(hash), state[:, :transHash])
push!(names, if assigned(state.transition_recipes[:transName], ix)
string(state[ix, :transName])
else
"transition $ix"
end)
end
return names
end
function plot_from_log(state, record_type, ixs; kwargs...)
if record_type ∈ [:new_transitions, :terminated_transitions, :saturation]
hashes = get_transitions(state.log)
label = get_names(state, hashes)
vals, steps = complete_log_transitions(state.log, hashes, record_type)
elseif record_type ∈ [:allocation]
label = string.(state[:, :specName])
vals, steps = complete_log_species(state.log, length(label), record_type)
vals = vals[:, ixs]
label = label[ixs]
elseif record_type ∈ [:valuations]
label = ["portfolio valuation", "costs", "rewards", "total balance"]
vals, steps = complete_log_valuations(state.log)
end
return Plots.plot(
steps,
vals;
title = string(record_type),
label = reshape(label, 1, :),
kwargs...,
)
end
"""
@optimize acset objective <free_var=[init_val]>... <free_prm=[init_val]>... opts...
Take an acset and optimize given functional.
Objective is an expression which may reference the model's variables and parameters, i.e., `A+β`.
The values to optimized are listed using their symbolic names; unless specified, the initial value is inferred from the model.
The vector of free variables passed to the `NLopt` solver has the form `[free_vars; free_params]`; order of vars and params, respectively, is preserved.
By default, the functional is minimized. Specify `objective=max` to perform maximization.
Propagates `NLopt` solver arguments; see [NLopt documentation](https://github.com/JuliaOpt/NLopt.jl).
# Examples
```julia
@optimize acs abs(A - B) A B = 20.0 α = 2.0 lower_bounds = 0 upper_bounds = 100
@optimize acss abs(A - B) A B = 20.0 α = 2.0 upper_bounds = [200, 300, 400] maxeval = 200 objective =
min
```
"""
macro optimize(acsex, obex, args...)
args_all = args
args, kwargs = args_kwargs(args)
min_t = find_kwargex_delete!(kwargs, :min_t, -Inf)
max_t = find_kwargex_delete!(kwargs, :max_t, Inf)
final_only = find_kwargex_delete!(kwargs, :final_only, false)
okwargs = filter(ex -> ex.args[1] in [:loss, :trajectories], kwargs)
quote
u0, p = get_free_vars($(esc(acsex)), $(QuoteNode(args_all)))
prob_ = DiscreteProblem($(esc(acsex)))
prep_u0!(u0, prob_)
prep_params!(p, prob_)
init_p = [k => v for (k, v) in p]
init_vec = if length(u0) > 0
ComponentVector{Float64}(; species = collect(wvalues(u0)), init_p...)
else
ComponentVector{Float64}(; init_p...)
end
o = build_loss_objective(
$(esc(acsex)),
init_vec,
u0,
p,
$(QuoteNode(obex));
min_t = $min_t,
max_t = $max_t,
final_only = $final_only,
$(okwargs...),
)
optim!(o, init_vec; $(kwargs...))
end
end
"""
@fit acset data_points time_steps empiric_variables <free_var=[init_val]>... <free_prm=[init_val]>... opts...
Take an acset and fit initial values and parameters to empirical data.
The values to optimized are listed using their symbolic names; unless specified, the initial value is inferred from the model.
The vector of free variables passed to the `NLopt` solver has the form `[free_vars; free_params]`; order of vars and params, respectively, is preserved.
Propagates `NLopt` solver arguments; see [NLopt documentation](https://github.com/JuliaOpt/NLopt.jl).
# Examples
```julia
t = [1, 50, 100]
data = [80 30 20]
@fit acs data t vars = A B = 20 A α # fit B, A, α; empirical data is for variable A
```
"""
macro fit(acsex, data, t, args...)
args_all = args
args, kwargs = args_kwargs(args)
okwargs = filter(ex -> ex.args[1] in [:loss, :trajectories], kwargs)
vars = (ix = findfirst(ex -> ex.args[1] == :vars, kwargs);
!isnothing(ix) ? (v = kwargs[ix].args[2];
deleteat!(kwargs, ix);
v) : :())
quote
u0, p = get_free_vars($(esc(acsex)), $(QuoteNode(args_all)))
vars = get_vars($(esc(acsex)), $(QuoteNode(vars)))
prob_ = DiscreteProblem($(esc(acsex)))
prep_u0!(u0, prob_)
prep_params!(p, prob_)
init_p = [k => v for (k, v) in p]
init_vec = if length(u0) > 0
ComponentVector{Float64}(; species = collect(wvalues(u0)), init_p...)
else
ComponentVector{Float64}(; init_p...)
end
o = build_loss_objective_datapoints(
$(esc(acsex)),
init_vec,
u0,
p,
$(esc(t)),
$(esc(data)),
vars;
$(okwargs...),
)
optim!(o, init_vec; $(kwargs...))
end
end
"""
@fit acset data_points time_steps empiric_variables <free_var=[init_val]>... <free_prm=[init_val]>... opts...
Take an acset, fit initial values and parameters to empirical data, and plot the result.
The values to optimized are listed using their symbolic names; unless specified, the initial value is inferred from the model.
The vector of free variables passed to the `NLopt` solver has the form `[free_vars; free_params]`; order of vars and params, respectively, is preserved.
Propagates `NLopt` solver arguments; see [NLopt documentation](https://github.com/JuliaOpt/NLopt.jl).
# Examples
```julia
t = [1, 50, 100]
data = [80 30 20]
@fit acs data t vars = A B = 20 A α # fit B, A, α; empirical data is for variable A
```
"""
macro fit_and_plot(acsex, data, t, args...)
args_all = args
trajectories = get_kwarg(args, :trajectories, 1)
args, kwargs = args_kwargs(args)
okwargs = filter(ex -> ex.args[1] in [:loss, :trajectories], kwargs)
vars = (ix = findfirst(ex -> ex.args[1] == :vars, kwargs);
!isnothing(ix) ? (v = kwargs[ix].args[2];
deleteat!(kwargs, ix);
v) : :())
quote
u0, p = get_free_vars($(esc(acsex)), $(QuoteNode(args_all)))
vars = get_vars($(esc(acsex)), $(QuoteNode(vars)))
prob_ = DiscreteProblem($(esc(acsex)); suppress_warning = true)
prep_u0!(u0, prob_)
prep_params!(p, prob_)
init_p = [k => v for (k, v) in p]
init_vec = if length(u0) > 0
ComponentVector{Float64}(; species = collect(wvalues(u0)), init_p...)
else
ComponentVector{Float64}(; init_p...)
end
o = build_loss_objective_datapoints(
$(esc(acsex)),
init_vec,
u0,
p,
$(esc(t)),
$(esc(data)),
vars;
$(okwargs...),
)
r = optim!(o, init_vec; $(kwargs...))
if r[3] != :FORCED_STOP
s_ = build_parametrized_solver(
$(esc(acsex)),
init_vec,
u0,
p;
trajectories = $trajectories,
)
sol = first(s_(init_vec))
sol_ = first(s_(r[2]))
p = Plots.plot(
sol;
idxs = vars,
label = "(initial) " .*
reshape(String.($(esc(acsex))[:, :specName])[vars], 1, :),
)
Plots.plot!(
p,
$(esc(t)),
transpose($(esc(data)));
label = "(empirical) " .*
reshape(String.($(esc(acsex))[:, :specName])[vars], 1, :),
)
Plots.plot!(
p,
sol_;
idxs = vars,
label = "(fitted) " .*
reshape(String.($(esc(acsex))[:, :specName])[vars], 1, :),
)
p
else
:FORCED_STOP
end
end
end
"""
@build_solver acset <free_var=[init_val]>... <free_prm=[init_val]>... opts...
Take an acset and export a solution as a function of free vars and free parameters.
# Examples
```julia
solver = @build_solver acs S α β # function of variable S and parameters α, β
solver([S, α, β])
```
"""
macro build_solver(acsex, args...)
args_all = args#; args, kwargs = args_kwargs(args)
trajectories = get_kwarg(args, :trajectories, 1)
quote
u0, p = get_free_vars($(esc(acsex)), $(QuoteNode(args_all)))
prob_ = DiscreteProblem($(esc(acsex)))
prep_u0!(u0, prob_)
prep_params!(p, prob_)
init_p = [k => v for (k, v) in p]
init_vec = if length(u0) > 0
ComponentVector{Float64}(; species = collect(wvalues(u0)), init_p...)
else
ComponentVector{Float64}(; init_p...)
end
build_parametrized_solver_(
$(esc(acsex)),
init_vec,
u0,
p;
trajectories = $trajectories,
)
end
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 12353 | # reaction network DSL: UPDATE part; add species, name, add modalities, set model variables, set solver arguments
export @push, @name_transition, @mode, @add_species
export @periodic, @jump
export @prob_init, @prob_uncertainty, @prob_params, @prob_meta
export @prob_role, @list_by_role, @list_roles
export @prob_check_verbose
export @aka
export @register
using DataFrames
using MacroTools: striplines
function push_to_acs!(acsex, exs...)
if isexpr(exs[1], :block)
ex = striplines(exs[1])
else
args = Any[]
map(el -> if isexpr(el, :(=))
push!(args, :($(el.args[1]) => $(el.args[2])))
else
push!(args, el)
end, exs)
ex = Expr(:tuple, args...)
end
quote
ex = blockize($(QuoteNode(ex)))
merge_acs!($(esc(acsex)), get_data(ex)...)
end
end
"""
Add reactions to an acset.
# Examples
```julia
@push sir_acs β * S * I * tdecay(@time()) S + I --> 2I name => SI2I
@push sir_acs begin
ν * I, I --> R, name => I2R
γ, R --> S, name => R2S
end
```
"""
macro push(acsex, exs...)
return push_to_acs!(acsex, exs...)
end
"""
Set name of a transition in the model.
# Examples
```julia
@name_transition acs 1 = "name"
@name_transition acs name = "transition_name"
@name_transition acs "name" = "transition_name"
```
"""
macro name_transition(acsex, exs...)
call = :(
begin end
)
for ex in exs
call_ = if ex.args[1] isa Number
:($(esc(acsex))[$(ex.args[1]), :transName] = $(QuoteNode(ex.args[2])))
else
quote
acs = $(esc(acsex))
ixs = findall(
i -> string(acs[i, :transName]) == $(string(ex.args[1])),
1:nparts(acs, :T),
)
foreach(i -> acs[i, :transName] = $(string(ex.args[2])), ixs)
end
end
push!(call.args, call_)
end
return call
end
function incident_pattern(pattern, attr)
ix = []
for i = 1:length(attr)
!isnothing(attr[i]) &&
(m = match(pattern, string(attr[i]));
!isnothing(m) && (string(attr[i]) == m.match)) &&
push!(ix, i)
end
return ix
end
function mode!(acs, dict)
for (spex, mods) in dict
i = if spex isa Regex
incident_pattern(spex, acs[:, :specName])
else
incident(acs, Symbol(spex), :specName)
end
for ix in i
isnothing(acs[ix, specModality]) && (acs[ix, specModality] = Set{Symbol}())
union!(acs[ix, :specModality], mods)
end
end
end
"""
Set species modality.
# Supported modalities
- nonblock
- conserved
- rate
# Examples
```julia
@mode acs (r"proj\\w+", r"experimental\\w+") conserved
@mode acs (S, I) conserved
@mode acs S conserved
```
"""
macro mode(acsex, spexs, mexs)
mods = !isa(mexs, Expr) ? [mexs] : collect(mexs.args)
spexs = isexpr(spexs, :tuple) ? spexs.args : [spexs]
exs = map(ex -> striplines(ex), spexs)
quote
dictcall = Dict()
exs_ = []
foreach(s -> push!(exs_, striplines(blockize(s))), $(QuoteNode(exs)))
exs__ = []
foreach(s -> foreach(s -> push!(exs__, s), s.args), exs_)
foreach(
ex -> push!(dictcall, get_pattern(recursively_expand_dots(ex)) => $mods),
exs__,
)
mode!($(esc(acsex)), dictcall)
end
end
function set_valuation!(acs, dict, valuation_type)
for (spex, val) in dict
i = if spex isa Regex
incident_pattern(spex, subpart(acs, :specName))
else
incident(acs, Symbol(spex), :specName)
end
foreach(
ix ->
acs[ix, Symbol(:spec, Symbol(uppercasefirst(string(valuation_type))))] =
eval(val),
i,
)
end
end
export @cost, @reward, @valuation
for valuation_type in (:cost, :reward, :valuation)
eval(
quote
export $(Symbol(Symbol("@"), valuation_type))
@doc """
Set $($(string(valuation_type))).
# Examples
```julia
@$($(string(valuation_type))) model experimental1=2 experimental2=3
```
"""
macro $valuation_type(acsex, exs...)
dictcall = Dict()
exs_ = []
foreach(s -> push!(exs_, striplines(blockize(s))), exs)
exs__ = []
foreach(s -> foreach(s -> push!(exs__, s), s.args), exs_)
foreach(
ex -> push!(
dictcall,
get_pattern(recursively_expand_dots(ex.args[1])) => ex.args[2],
),
exs__,
)
return :(set_valuation!(
$(esc(acsex)),
$dictcall,
$(QuoteNode($(QuoteNode(valuation_type)))),
))
end
end,
)
end
"""
Add new species to a model.
# Examples
```julia
@add_species acs S I R
```
"""
macro add_species(acsex, exs...)
call = :(
begin end
)
spexs_ = []
foreach(s -> push!(spexs_, s), exs)
for ex in recursively_expand_dots.(spexs_)
push!(call.args, :(add_part!($(esc(acsex)), :S; specName = $(QuoteNode(ex)))))
end
push!(call.args, :(assign_defaults!($(esc(acsex)))))
return call
end
get_pattern(ex) = ex isa Expr && (macroname(ex) == :r_str) ? eval(ex) : ex
"""
Set initial values of species in an acset.
# Examples
```julia
@prob_init acs X = 1 Y = 2 Z = h(α)
@prob_init acs [1.0, 2.0, 3.0]
```
"""
macro prob_init(acsex, exs...)
exs = map(ex -> striplines(ex), exs)
return if length(exs) == 1 && (isexpr(exs[1], :vect) || (exs[1] isa Symbol))
:(init!($(esc(acsex)), $(esc(exs[1]))))
else
quote
dictcall = Dict()
exs_ = []
foreach(s -> push!(exs_, striplines(blockize(s))), $(QuoteNode(exs)))
exs__ = []
foreach(s -> foreach(s -> push!(exs__, s), s.args), exs_)
foreach(
ex -> push!(
dictcall,
get_pattern(recursively_expand_dots(ex.args[1])) => ex.args[2],
),
exs__,
)
init!($(esc(acsex)), dictcall)
end
end
end
# deprecate
macro prob_init_from_vec(acsex, vecex)
return :(init!($(esc(acsex)), $(esc(vecex))))
end
function init!(acs, inits)
inits isa AbstractVector &&
length(inits) == nparts(acs, :S) &&
(subpart(acs, :specInitVal) .= inits; return)
inits isa AbstractDict && for (k, init_val) in inits
if k isa Number
acs[k, :specInitVal] = init_val
else
begin
i = if k isa Regex
incident_pattern(k, subpart(acs, :specName))
else
incident(acs, k, :specName)
end
foreach(ix -> (acs[ix, :specInitVal] = init_val), i)
end
end
end
return acs
end
"""
Set uncertainty in initial values of species in an acset (stderr).
# Examples
```julia
@prob_uncertainty acs X = 0.1 Y = 0.2
@prob_uncertainty acs [0.1, 0.2]
```
"""
macro prob_uncertainty(acsex, exs...)
exs = map(ex -> striplines(ex), exs)
return if length(exs) == 1 && (isexpr(exs[1], :vect) || (exs[1] isa Symbol))
:(uncinit!($(esc(acsex)), $(esc(exs[1]))))
else
quote
dictcall = Dict()
exs_ = []
foreach(s -> push!(exs_, striplines(blockize(s))), $(QuoteNode(exs)))
exs__ = []
foreach(s -> foreach(s -> push!(exs__, s), s.args), exs_)
foreach(
ex -> push!(
dictcall,
get_pattern(recursively_expand_dots(ex.args[1])) => ex.args[2],
),
exs__,
)
uncinit!($(esc(acsex)), dictcall)
end
end
end
function uncinit!(acs, inits)
inits isa AbstractVector &&
length(inits) == nparts(acs, :S) &&
(subpart(acs, :specInitUncertainty) .= inits; return)
inits isa AbstractDict && for (k, init_val) in inits
if k isa Number
acs[k, :specInitUncertainty] = init_val
else
begin
i = if k isa Regex
incident_pattern(k, subpart(acs, :specName))
else
incident(acs, k, :specName)
end
foreach(ix -> (acs[ix, :specInitUncertainty] = init_val), i)
end
end
end
return acs
end
function set_params!(acs, params)
return params isa AbstractDict && for (k, init_val) in params
k = get_pattern(k)
if k isa Regex
i = incident_pattern(k, subpart(acs, :prmName))
else
i = incident(acs, k, :prmName)
isempty(i) && (i = add_part!(acs, :P; prmName = k))
end
foreach(ix -> acs[ix, :prmVal] = eval(init_val), i)
end
end
"""
Set parameter values in an acset.
# Examples
```julia
@prob_params acs α = 1.0 β = 2.0
```
"""
macro prob_params(acsex, exs...)
exs = map(ex -> striplines(ex), exs)
quote
dictcall = Dict()
exs_ = []
foreach(s -> push!(exs_, striplines(blockize(s))), $(QuoteNode(exs)))
exs__ = []
foreach(s -> foreach(s -> push!(exs__, s), s.args), exs_)
foreach(
ex -> push!(
dictcall,
get_pattern(recursively_expand_dots(ex.args[1])) => ex.args[2],
),
exs__,
)
set_params!($(esc(acsex)), dictcall)
end
end
meta!(acs, metas) =
for (k, metaval) in metas
i = incident(acs, k, :metaKeyword)
isempty(i) && (i = add_part!(acs, :M; metaKeyword = k))
set_subpart!(acs, first(i), :metaVal, metaval)
end
"""
Set model metadata (e.g. solver arguments)
# Examples
```julia
@prob_meta acs tspan = (0, 100.0) schedule = schedule_weighted!
@prob_meta sir_acs tspan = 250 tstep = 1
```
"""
macro prob_meta(acsex, exs...)
dictcall = :(Dict([]))
foreach(ex -> push!(dictcall.args[2].args, (ex.args[1] => eval(ex.args[2]))), exs)
return :(meta!($(esc(acsex)), $dictcall))
end
"""
Alias object name in an acs.
# Default names
| name | short name |
|:---------- |:---------- |
| species | S |
| transition | T |
| action | A |
| event | E |
| param | P |
| meta | M |
# Examples
```julia
@aka acs species = resource transition = reaction
```
"""
macro aka(acsex, exs...)
dictcall = :(Dict([]))
foreach(
ex -> push!(
dictcall.args[2].args,
Symbol("alias_", findfirst(==(ex.args[1]), alias_default)) => ex.args[2],
),
exs,
)
return :(meta!($(esc(acsex)), $dictcall))
end
alias_default = Dict(
:S => :species,
:T => :transition,
:A => :action,
:E => :event,
:P => :param,
:M => :meta,
)
get_alias(acs, ob) = (i = incident(acs, Symbol(:alias_, ob), :metaKeyword);
!isempty(i) ? acs[first(i), :metaVal] : alias_default[ob])
"""
Check model parameters have been set. # msg as return value
"""
macro prob_check_verbose(acsex) # msg as return value
return :(missing_params = check_params($(esc(acsex)));
isempty(missing_params) ? "Params OK." : "Missing params: $missing_params")
end
"""
Add a periodic callback to a model.
# Examples
```julia
@periodic acs 1.0 X += 1
```
"""
macro periodic(acsex, pex, acex)
return push_to_acs!(acsex, Expr(:&&, :(@periodic($pex)), acex))
end
"""
Add a jump process (with specified Poisson intensity per unit time step) to a model.
# Examples
```julia
@jump acs λ Z += rand(Poisson(1.0))
```
"""
macro jump(acsex, inex, acex)
return push_to_acs!(
acsex,
Expr(:&&, Expr(:call, :rand, :(Poisson(max(@solverarg(:tstep) * $inex, 0)))), acex),
)
end
"""
Evaluate expression in ReactiveDynamics scope.
# Examples
```julia
@register bool_cond(t) = (100 < t < 200) || (400 < t < 500)
@register tdecay(t) = exp(-t / 10^3)
```
"""
macro register(ex)
return :(@eval ReactiveDynamics $ex)
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2325 | export @equalize
expand_name_ff(ex) =
if ex isa Expr && isexpr(ex, :macrocall)
(macroname(ex), underscorize(ex.args[end]))
else
(nothing, underscorize(ex))
end
"""
Parse species equation blocks.
"""
function get_eqs_ff(eq)
if eq isa Expr && isexpr(eq, :(=))
[
expand_name_ff(eq.args[1])
isexpr(eq.args[2], :(=)) ? get_eqs_ff(eq.args[2]) : expand_name_ff(eq.args[2])
]
else
[expand_name_ff(eq)]
end
end
function equalize!(acs::ReactionNetwork, eqs = [])
specmap = Dict()
for block in eqs
block_alias = findfirst(e -> e[1] == :alias, block)
block_alias = !isnothing(block_alias) ? block[block_alias][2] : first(block)[2]
species_ixs = Int64[]
for e in block, i = 1:nparts(acs, :S)
(
(i == e[2]) ||
(
e[1] == :catchall &&
occursin(Regex("(__$(e[2])|$(e[2]))\$"), string(acs[i, :specName]))
) ||
(e[2] == acs[i, :specName])
) && (push!(species_ixs, i);
push!(specmap, acs[i, :specName] => (acs[i, :specName] = block_alias)))
end
isempty(species_ixs) && continue
species_ixs = sort(unique!(species_ixs))
lix = first(species_ixs)
for attr in propertynames(acs.subparts)
!occursin("spec", string(attr)) && continue
for i in species_ixs
ismissing(acs[lix, attr]) && (acs[lix, attr] = acs[i, attr])
end
end
rem_parts!(acs, :S, species_ixs[2:end])
end
for attr in propertynames(acs.subparts)
attr == :specName && continue
attr_ = acs[:, attr]
for i = 1:length(attr_)
attr_[i] = escape_ref(attr_[i], collect(keys(specmap)))
attr_[i] = recursively_substitute_vars!(specmap, attr_[i])
end
end
return acs
end
"""
Identify (collapse) a set of species in a model.
# Examples
```julia
@join acs acs1.A = acs2.A B = C
```
"""
macro equalize(acsex, exs...)
exs = collect(exs)
foreach(i -> (exs[i] = MacroTools.striplines(exs[i])), 1:length(exs))
eqs = []
foreach(ex -> ex isa Expr && merge_eqs!(eqs, get_eqs_ff(ex)), exs)
return :(equalize!($(esc(acsex)), $eqs))
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 6865 | # model joins
export @join
using MacroTools
using MacroTools: prewalk
"""
Merge `acs2` onto `acs1`, the attributes in `acs2` taking precedence. Identify respective species given `eqs`, renaming species in `acs2`.
"""
function union_acs!(acs1, acs2, name = gensym("acs_"), eqs = [])
acs2 = deepcopy(acs2)
prepend!(acs2, name, eqs)
for i = 1:nparts(acs2, :S)
inc = incident(acs1, acs2[i, :specName], :specName)
isempty(inc) && (inc = add_part!(acs1, :S; specName = acs2[i, :specName]);
assign_defaults!(acs1))
return (acs1, acs2)
println(first(inc))
println(acs1[first(inc), :specModality])
println()
println(acs2[:, :specModality])
union!(acs1[first(inc), :specModality], acs2[i, :specModality])
for attr in propertynames(acs1.subparts)
!occursin("spec", string(attr)) && continue
!ismissing(acs2[i, attr]) && (acs1[first(inc), attr] = acs2[i, attr])
end
end
new_trans_ix = add_parts!(acs1, :T, nparts(acs2, :T))
for attr in propertynames(acs2.subparts)
!occursin("trans", string(attr)) && continue
acs1[new_trans_ix, attr] .= acs2[:, attr]
end
foreach(
i -> (
acs1[i, :transName] =
normalize_name(Symbol(coalesce(acs1[i, :transName], i)), name)
),
new_trans_ix,
)
for i = 1:nparts(acs2, :P)
inc = incident(acs1, acs2[i, :prmName], :prmName)
isempty(inc) && (inc = add_part!(acs1, :P; prmName = acs2[i, :prmName]))
!ismissing(acs2[i, :prmVal]) && (acs1[first(inc), :prmVal] = acs2[i, :prmVal])
end
for i = 1:nparts(acs2, :M)
inc = incident(acs1, acs2[i, :metaKeyword], :metaKeyword)
isempty(inc) && (inc = add_part!(acs1, :M; metaKeyword = acs2[i, :metaKeyword]))
!ismissing(acs2[i, :metaVal]) && (acs1[first(inc), :metaVal] = acs2[i, :metaVal])
end
return acs1
end
"""
Prepend species names with a model identifier (unless a global species name).
"""
function prepend!(acs::ReactionNetwork, name = gensym("acs"), eqs = [])
specmap = Dict()
for i = 1:nparts(acs, :S)
new_name = normalize_name(name, i, acs[i, :specName], eqs)
push!(specmap, acs[i, :specName] => (acs[i, :specName] = new_name))
end
for attr in propertynames(acs.subparts)
attr == :specName && continue
attr_ = acs[:, attr]
for i = 1:length(attr_)
attr_[i] = escape_ref(attr_[i], collect(keys(specmap)))
attr_[i] = recursively_substitute_vars!(specmap, attr_[i])
attr_[i] isa Expr && (attr_[i] = prepend_obs(attr_[i], name))
end
end
return acs
end
"""
Prepend identifier of an observable with a model identifier.
"""
function prepend_obs end
function prepend_obs(ex::Expr, name)
return prewalk(ex -> if (isexpr(ex, :macrocall) && (macroname(ex) == :obs))
(ex.args[end] = Symbol(name, "__", ex.args[end]); ex)
else
ex
end, ex)
end
prepend_obs(ex, _) = ex
## species name normalization
normalize_name(name::Symbol, parent_name) = Symbol("$(parent_name)__$name")
normalize_name(name::String, parent_name) = "$(parent_name)__$name"
normalize_name(name, parent_name) = Symbol(parent_name, "__", name)
function normalize_name(acs_name, i::Int, name::Symbol, eqs = [])
for (block_ix, block) in enumerate(eqs)
block_alias = findfirst(e -> e[1] == :alias, block)
block_alias = if !isnothing(block_alias)
block[block_alias][2]
else
Symbol(:shared_species_, block_ix)
end
for e in block
(
(i == e[2]) ||
(
e[1] == :catchall &&
(normalize_name(e[2], acs_name) == normalize_name(name, acs_name))
) ||
(
e[1] == acs_name &&
(normalize_name(e[2], acs_name) == normalize_name(name, acs_name))
)
) && return block_alias
end
end
return normalize_name(name, acs_name)
end
matching_name(name::Symbol, parent_name) = [name, Symbol("$(parent_name)__$name")]
expand_name(ex) =
if isexpr(ex, :.)
reconstruct(ex)
elseif isexpr(ex, :macrocall)
(
if macroname(ex) == :alias
[(:alias, ex.args[3])]
else
[(:catchall, ex.args[3]), (:alias, ex.args[3])]
end
)
else
(:catchall, ex)
end
function recursively_get_syms(ex)
return isexpr(ex, :.) ? [recursively_get_syms(ex.args[1]); ex.args[2].value] : ex
end
function reconstruct(ex)
return if ex isa Symbol
(ex,)
else
(syms = recursively_get_syms(ex); (syms[1], Symbol(join(syms[2:end], "__"))))
end
end
"""
Parse species equation blocks.
"""
function get_eqs(eq)
if isexpr(eq, :macrocall)
expand_name(eq)
elseif eq isa Expr
[
expand_name(eq.args[1])
isexpr(eq.args[2], :(=)) ? get_eqs(eq.args[2]) : expand_name(eq.args[2])
]
else
[eq]
end
end
function merge_eqs!(eqs, eqblock)
eqs_ = []
for s in eqblock
ix = findfirst(e -> s in e, eqs)
!isnothing(ix) && push!(eqs_, ix)
end
foreach(i -> append!(eqblock, eqs[i]), eqs_)
foreach(i -> deleteat!(eqs, i), Iterators.reverse(sort!(eqs_)))
push!(eqs, eqblock)
return eqs_
end
"""
@join models... [equalize...]
Performs join of models and identifies model variables, as specified.
Model variables / parameter values and metadata are propagated; the last model takes precedence.
# Examples
```julia
@join acs1 acs2 @catchall(A) = acs2.Z @catchall(XY) @catchall(B)
```
"""
macro join(exs...)
callex = :(
begin
acs_new = ReactionNetwork()
end
)
exs = collect(exs)
foreach(i -> (exs[i] = MacroTools.striplines(exs[i])), 1:length(exs))
eqs = []
ix = 1
while ix <= length(exs)
if exs[ix] isa Expr && MacroTools.isexpr(exs[ix], :macrocall, :(=))
merge_eqs!(eqs, get_eqs(exs[ix]))
deleteat!(exs, ix)
continue
end
ix += 1
end
for acsex in exs
(acsex, symex) = if isexpr(acsex, :macrocall)
str_inc = string(
isexpr(acsex.args[3], :(=)) ? acsex.args[3].args[2] : acsex.args[3],
)
if isexpr(acsex.args[3], :(=))
(:(include_model($str_inc)), acsex.args[3].args[1])
else
(:(include_model($str_inc)), gensym(:acs))
end
else
(acsex, acsex)
end
push!(callex.args, :(union_acs!(acs_new, $(esc(acsex)), $(QuoteNode(symex)), $eqs)))
end
push!(callex.args, :(acs_new))
return callex
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 383 | using Test
export @safeinclude
macro safeinclude(args...)
length(args) != 2 && error("invalid arguments to `@safeinclude`")
name, ex = args
quote
path = pwd()
td = mktempdir()
cp(dirname($ex), td; force = true)
cd(td)
@testset $name begin
include(joinpath(td, basename($ex)))
end
cd(path)
end
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2529 | # Assortment of expression handling utilities
using MacroTools: striplines
"""
Return array of keyword expressions in `args`.
"""
function kwargize(args)
kwargs = Any[]
map(el -> isexpr(el, :(=)) && push!(kwargs, Expr(:kw, el.args[1], el.args[2])), args)
return kwargs
end
"""
Split an array of expressions into arrays of "argument" expressions and keyword expressions.
"""
function args_kwargs(args)
args_ = Any[]
kwargs = Any[]
map(el -> if isexpr(el, :(=))
push!(kwargs, Expr(:kw, el.args[1], el.args[2]))
else
push!(args_, esc(el))
end, args)
return args_, kwargs
end
"""
Return the (expression) value stored for the given key in a collection of keyword expression, or the given default value if no mapping for the key is present.
"""
function find_kwargex_delete!(collection, key, default = :())
ix = findfirst(ex -> ex.args[1] == key, collection)
return if !isnothing(ix)
(v = collection[ix].args[2]; deleteat!(collection, ix); v)
else
default
end
end
macroname(ex) =
if isexpr(ex, :macrocall)
(str = string(ex.args[1]); Symbol(strip(str, '@')))
else
error("expr $ex is not a macrocall")
end
strip_sym(sym) = (str = string(sym); Symbol(strip(str, '@')))
blockize(ex) = striplines(isexpr(ex, :block) ? ex : Expr(:block, ex))
preserve_sym(el) = el isa Symbol ? QuoteNode(el) : el
assigned(collection, ix) = isassigned(collection, ix) && !ismissing(collection[ix])
function unblock_shallow!(ex)
isexpr(ex, :block) || return ex
args = []
for ex in ex.args
isexpr(ex, :block) ? append!(args, ex.args) : push!(args, ex)
end
ex.args = args
return ex
end
function underscorize(ex)
return if ex isa Number
ex
else
(str = string(ex); replace(str, '.' => "__", '(' => "", ')' => "") |> Symbol)
end
end
wkeys(itr) = map(x -> x isa Pair ? x[1] : x, itr)
wvalues(itr) = map(x -> x isa Pair ? x[2] : x, itr)
function wset!(col, key, val)
ix = findfirst(==(key), wkeys(col))
!isnothing(ix) && (col[ix] = (key => val))
return col
end
"""
Return the (expression) value stored for the given key in a collection of keyword expression, or the given default value if no mapping for the key is present.
"""
function get_kwarg(collection, key, default = :())
ix = findfirst(
ex -> ex isa Expr && hasproperty(ex, :args) && (ex.args[1] == key),
collection,
)
return !isnothing(ix) ? collection[ix].args[2] : default
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 143 | using SafeTestsets, BenchmarkTools
@time begin
@time @safetestset "Tutorial tests" begin
include("tutorial_tests.jl")
end
end
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 377 | using ReactiveDynamics
@safeinclude "example" "../tutorial/example.jl"
@safeinclude "joins" "../tutorial/joins/joins.jl"
@safeinclude "loadsave" "../tutorial/loadsave/loadsave.jl"
@safeinclude "optimize" "../tutorial/optimize/optimize.jl"
@safeinclude "solution wrap" "../tutorial/optimize/optimize_custom.jl"
@safeinclude "toy pharma model" "../tutorial/toy_pharma_model.jl"
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 378 | using ReactiveDynamics
# acs = @ReactionNetwork begin
# 1.0, X ⟺ Y
# end
acs = @ReactionNetwork begin
1.0, X ⟺ Y, name => "transition1"
end
@prob_init acs X = 10 Y = 20
@prob_params acs
@prob_meta acs tspan = 250 dt = 0.1
prob = @problematize acs
# sol = ReactiveDynamics.solve(prob)
sol = @solve prob trajectories = 20
using Plots
@plot sol plot_type = summary
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2946 | using ReactiveDynamics
# acs as a model : incomplete dynamics
sir_acs = @ReactionNetwork
# set up ontology: try ?@aka
@aka sir_acs transition = reaction species = population_group
# add single reaction
@push sir_acs β * S * I * tdecay(@t()) S + I --> @choose(
(1.5, 2 * @choose(1, 2) * I),
(1.6, @register(:RATE, 1, every = 2) * I)
) name => SI2I
# additional dynamics
@push sir_acs begin
ν * I, I --> R, name => I2R
γ, R --> S, name => R2S
end
# register custom function
@register bool_cond(t) = (100 < t < 200) || (400 < t < 500)
@register tdecay(t) = exp(-t / 10^3)
@valuation sir_acs I = 0.1 # for testing purpose only
# atomic data: initial values, parameter values
@prob_init sir_acs S = 999 I = 100 R = 100
u0 = [999, 10, 0] # alternative specification
@prob_init sir_acs u0
@prob_params sir_acs β = 0.0001 ν = 0.01 γ = 5
@prob_meta sir_acs tspan = 100
#prob = @problematize sir_acs
prob = @problematize sir_acs tspan = 200
sol = @solve prob trajectories = 20
@plot sol plot_type = summary
sol = @solve prob
@plot sol plot_type = allocation
@plot sol plot_type = valuations
@plot sol plot_type = new_transitions
# acs as a model : incomplete dynamics
sir_acs = @ReactionNetwork
# set up ontology: try ?@aka
@aka sir_acs transition = reaction species = population_group
# add single reaction
# additional dynamics
@push sir_acs begin
ν * I * tdecay(@t()), I --> @choose(E, R, S), name => I2R
γ, R --> S, name => R2S
end
@jump sir_acs 3 (S > 0 && bool_cond(@t()) && (I += 1; S -= 1)) # drift term, support for event conditioning
@periodic sir_acs 5.0 (β += 1; println(β))
# register custom function
@register bool_cond(t) = (100 < t < 200) || (400 < t < 500)
@register tdecay(t) = exp(-t / 10^3)
# atomic data: initial values, parameter values
@prob_init sir_acs S = 999 I = 10 R = 0
u0 = [999, 10, 0] # alternative specification
@prob_init sir_acs u0
@prob_params sir_acs β = 0.0001 ν = 0.01 γ = 5
# model dynamics
sir_acs = @ReactionNetwork begin
α * S * I, S + I --> 2I, cycle_time => 0, name => I2R
β * I, I --> R, cycle_time => 0, name => R2S
end
# simulation parameters
@prob_init sir_acs S = 999 I = 10 R = 0
@prob_uncertainty sir_acs S = 10.0 I = 5.0
@prob_params sir_acs α = 0.0001 β = 0.01
@prob_meta sir_acs tspan = 250 dt = 0.1
# batch simulation
prob = @problematize sir_acs
sol = @solve prob trajectories = 20
@plot sol plot_type = summary
@plot sol plot_type = summary show = :S
@plot sol plot_type = summary c = :green xlimits = (0.0, 100.0)
acs_1 = @ReactionNetwork begin
1.0, A --> B + C
end
acs_2 = @ReactionNetwork begin
1.0, A --> B + C
end
acs_union = @join acs_1 acs_2 acs_1.A = acs_2.A = @alias(A) @catchall(B) # @catchall: equalize species "B" from the joined submodels
@equalize acs_union acs_1.C = acs_2.C = @alias(C) # the species can be set equal either within the call to @join the acsets, but you may always equalize a set of species of any given acset
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 1696 | using ReactiveDynamics
rd_model = @ReactionNetwork
# need to bring data into ReactiveDynamics's (solver) scope
@register begin
# number of phases
n_phase = 2
n_workforce = 5
n_equipment = 4
# transition matrix: ones at the upper diagonal + rand noise
prob_success = [i / (i + 1) for i = 1:n_phase]
transitions = zeros(n_phase, n_phase)
foreach(i -> transitions[i, i+1] = 1, 1:(n_phase-1))
transitions .+= 0.1 * rand(n_phase, n_phase)
end
rd_model = @ReactionNetwork begin
$i, phase[$i] --> phase[$j], cycle_time => $i * $j
end i = 1:3 j = 1:($i)
using ReactiveDynamics: nparts
u0 = rand(1:1000, nparts(rd_model, :S))
@prob_init rd_model u0
@prob_meta rd_model tspan = 100
prob = @problematize rd_model
sol = @solve prob trajectories = 20
@plot sol plot_type
# need to bring data into ReactiveDynamics's (solver) scope
@register begin
k = 5
r = 3
M = zeros(k, k)
for i = 1:k
for conn_in in rand(1:k, rand(1:4))
M[conn_in, i] += 0.1 * rand(1:10)
end
for conn_out in rand(1:k, rand(1:4))
M[i, conn_out] += 0.1 * rand(1:10)
end
end
cycle_times = rand(1:5, k, k)
resource = rand(1:10, k, k, r)
end
rd_model = @ReactionNetwork begin
M[$i, $j],
mod[$i] +
{resource[$i, $j, $k] * resource[$k], k = rand(1:(ReactiveDynamics.r)), dlm = +} -->
mod[$j],
cycle_time => cycle_times[$i, $j]
end i = 1:(ReactiveDynamics.k) j = 1:(ReactiveDynamics.k)
using ReactiveDynamics: nparts
u0 = rand(1:1000, nparts(rd_model, :S))
@prob_init rd_model u0
@prob_meta rd_model tspan = 100
prob = @problematize rd_model
sol = @solve prob
@plot sol plot_type = allocation
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2856 | using ReactiveDynamics
# model dynamics
toy_pharma_model = @ReactionNetwork begin
α(candidate_compound, marketed_drug, κ),
3 * @conserved(scientist) + @rate(budget) --> candidate_compound,
name => discovery,
probability => 0.3,
cycletime => 10.0,
priority => 0.5
β(candidate_compound, marketed_drug),
candidate_compound + 5 * @conserved(scientist) + 2 * @rate(budget) -->
marketed_drug + 5 * budget,
name => dx2market,
probability => 0.5 + 0.001 * @t(),
cycletime => 4
γ * marketed_drug, marketed_drug --> ∅, name => drug_killed
end
@periodic toy_pharma_model 1.0 budget += 11 * marketed_drug
@register function α(number_candidate_compounds, number_marketed_drugs, κ)
return κ + exp(-number_candidate_compounds) + exp(-number_marketed_drugs)
end
@register function β(number_candidate_compounds, number_marketed_drugs)
return number_candidate_compounds + exp(-number_marketed_drugs)
end
# simulation parameters
## initial values
@prob_init toy_pharma_model candidate_compound = 5 marketed_drug = 6 scientist = 20 budget =
100
## parameters
@prob_params toy_pharma_model κ = 4 γ = 0.1
## other arguments passed to the solver
@prob_meta toy_pharma_model tspan = 250 dt = 0.1
prob = @problematize toy_pharma_model
sol = @solve prob trajectories = 20
using Plots
@plot sol plot_type = summary
@plot sol plot_type = summary show = :marketed_drug
## for deterministic rates
# model dynamics
toy_pharma_model = @ReactionNetwork begin
@per_step(α(candidate_compound, marketed_drug, κ)),
3 * @conserved(scientist) + @rate(budget) --> candidate_compound,
name => discovery,
probability => 0.3,
cycletime => 10.0,
priority => 0.5
@per_step(β(candidate_compound, marketed_drug)),
candidate_compound + 5 * @conserved(scientist) + 2 * @rate(budget) -->
marketed_drug + 5 * budget,
name => dx2market,
probability => 0.5 + 0.001 * @t(),
cycletime => 4
@per_step(γ * marketed_drug), marketed_drug --> ∅, name => drug_killed
end
@periodic toy_pharma_model 0.0 budget += 11 * marketed_drug
@register function α(number_candidate_compounds, number_marketed_drugs, κ)
return κ + exp(-number_candidate_compounds) + exp(-number_marketed_drugs)
end
@register function β(number_candidate_compounds, number_marketed_drugs)
return number_candidate_compounds + exp(-number_marketed_drugs)
end
# simulation parameters
## initial values
@prob_init toy_pharma_model candidate_compound = 5 marketed_drug = 6 scientist = 20 budget =
100
## parameters
@prob_params toy_pharma_model κ = 4 γ = 0.1
## other arguments passed to the solver
@prob_meta toy_pharma_model tspan = 250
prob = @problematize toy_pharma_model
sol = @solve prob trajectories = 20
using Plots
@plot sol plot_type = summary
@plot sol plot_type = summary show = :marketed_drug
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 1820 | using ReactiveDynamics
## setup the environment
n_models = 5;
r = 2; # number of submodels, resources
rd_models = ReactiveDynamics.ReactionNetwork[] # submodels
@register begin
ns = Int[] # size of submodels
M = Array[] # transition intensities of submodels
cycle_times = Array[] # cycle times of transitions in submodels
demand = Array[]
production = Array[] # resource production / generation for transitions in submodels
end
# submodels: dense interactions
@generate {@fileval(submodel.jl, i = $i, r = r), i = 1:n_models}
# batch join over the submodels
rd_model = @generate "@join {rd_models[\$i], i=1:n_models, dlm=' '}"
# identify resources
@generate {
@equalize(
rd_model,
@alias(resource[$j]) = {rd_models[$i].resource[$j], i = 1:n_models, dlm = :(=)}
),
j = 1:r,
}
# sparse off-diagonal interactions, sparse declaration
sparse_off_diagonal = zeros(sum(ReactiveDynamics.ns), sum(ReactiveDynamics.ns))
for i = 1:n_models
j = rand(setdiff(1:n_models, (i,)))
i_ix = rand(1:ReactiveDynamics.ns[i])
j_ix = rand(1:ReactiveDynamics.ns[j])
sparse_off_diagonal[
i_ix+sum(ReactiveDynamics.ns[1:(i-1)]),
j_ix+sum(ReactiveDynamics.ns[1:(j-1)]),
] += 1
interaction_ex = """@push rd_model begin 1., var"rd_models[$i].state[$i_ix]" --> var"rd_models[$j]__state[$j_ix]" end"""
eval(Meta.parseall(interaction_ex))
end
sparse_off_diagonal += cat(ReactiveDynamics.M...; dims = (1, 2))
using Plots;
heatmap(1 .- sparse_off_diagonal; color = :greys, legend = false);
using ReactiveDynamics: nparts
u0 = rand(1:1000, nparts(rd_model, :S))
@prob_init rd_model u0
@prob_meta rd_model tspan = 10
prob = @problematize rd_model
sol = @solve prob trajectories = 2
# plot "state" species only
@plot sol plot_type = summary show = r"state"
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 878 | # substitute $r as the global number of resources, $i as the submodel identifier
@register begin
push!(ns, rand(1:5))
ϵ = 10e-2
push!(M, rand(ns[$i], ns[$i]))
foreach(i -> M[$i][i, i] += ϵ, 1:ns[$i])
foreach(i -> M[$i][i, :] /= sum(M[$i][i, :]), 1:ns[$i])
push!(cycle_times, rand(1:5, ns[$i], ns[$i]))
push!(demand, rand(1:10, ns[$i], ns[$i], $r))
push!(production, rand(1:10, ns[$i], ns[$i], $r))
end
# generate submodel dynamics
push!(
rd_models,
@ReactionNetwork begin
M[$i][$m, $n],
state[$m] + {demand[$i][$m, $n, $l] * resource[$l], l = 1:($r), dlm = +} -->
state[$n] + {production[$i][$m, $n, $l] * resource[$l], l = 1:($r), dlm = +},
cycle_time => cycle_times[$i][$m, $n],
probability_of_success => $m * $n / (n[$i])^2
end m = 1:ReactiveDynamics.ns[$i] n = 1:ReactiveDynamics.ns[$i]
)
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 847 | using ReactiveDynamics
# import a model, solve the problem
@import_network model.toml sir_acs
@assert @isdefined sir_acs
@assert isdefined(ReactiveDynamics, :tdecay)
prob = @problematize sir_acs
sol = @solve prob trajectories = 20
@import_network "csv/model.csv" sir_acs_
@assert @isdefined sir_acs_
@assert isdefined(ReactiveDynamics, :foo)
prob_ = @problematize sir_acs_
sol_ = @solve prob_ trajectories = 20
# export, import the solution
@export_solution sol
@import_solution sol.jld2
# export the same model (w/o registered functions)
@export_network sir_acs modell.toml
mkpath("csv_");
@export_network sir_acs "csv_/model.csv";
# load multiple models
@load_models models.txt
# export solution as a DataFrame, .csv
@export_solution_as_table sol
@export_solution_as_csv sol sol.csv
# another test
@import_network model2.toml sir_acs_2
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 919 | using ReactiveDynamics
# solve for steady state
acss = @ReactionNetwork begin
3.0, A --> A, priority => 0.6, name => aa
1.0, B + 0.2 * A --> 2 * α * B, prob => 0.7, priority => 0.6, name => bb
3.0, A + 2 * B --> 2 * C, prob => 0.7, priority => 0.7, name => cc
end
# initial values, check params
@prob_init acss A = 100.0 B = 200 C = 150.0
@prob_params acss α = 10
@prob_meta acss tspan = 100.0
prob = @problematize acss
sol = @solve prob trajectories = 10
# check https://github.com/JuliaOpt/NLopt.jl for solver opts
@optimize acss abs(A - B) A B = 20.0 α = 2.0 lower_bounds = 0 upper_bounds = 200 min_t = 50 max_t =
100 maxeval = 20 final_only = true
t_ = [1, 50, 100]
data = [70 50 50]
@fit acss data t_ vars = [A] B = 20 A α lower_bounds = 0 upper_bounds = 200 maxeval = 20
@fit_and_plot acss data t_ vars = [A] B = 20 A α lower_bounds = 0 upper_bounds = 200 maxeval =
2 trajectories = 10
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | code | 2226 | using ReactiveDynamics
# fit unknown dynamics to empirical data
## some embedded neural network, etc.
@register begin
function function_to_learn(A, B, C, params)
return [A, B, C]' * params # params: 3-element vector
end
end
acs = @ReactionNetwork begin
function_to_learn(A, B, C, params), A --> B + C
1.0, B --> C
2.0, C --> B
end
# initial values, check params
@prob_init acs A = 60.0 B = 10.0 C = 150.0
@prob_params acs params = [0.01, 0.01, 0.01]
@prob_meta acs tspan = 100.0
prob = @problematize acs
sol = @solve prob
time_points = [1, 50, 100]
data = [60 30 5]
@fit_and_plot acs data time_points vars = [A] params α maxeval = 200 lower_bounds = 0 upper_bounds =
0.01
# a slightly more extended example: export solver as a function of given params
## some embedded neural network, etc.
@register begin
function learnt_function(A, B, C, params, α)
return [A, B, C]' * params + α # params: 3-element vector
end
end
acs = @ReactionNetwork begin
learnt_function(A, B, C, params, α), A --> B + C, priority => 0.6
1.0, B --> C
2.0, C --> B
end
# initial values, check params
@prob_init acs A = 60.0 B = 10.0 C = 150.0
@prob_params acs params = [1, 2, 3] α = 1
@prob_meta acs tspan = 100.0
prob = @problematize acs
sol = @solve prob
@optimize acs abs(C) params α maxeval = 200 lower_bounds = 0 upper_bounds = 200 final_only =
true
## export solution as a function of params
parametrized_solver = @build_solver acs A params α trajectories = 10
parametrized_solver = @build_solver acs A params α
parametrized_solver([1.0, 0.0, 0.0, 0.0, 1.0])
using Statistics # for mean
my_little_objective(params) =
mean(1:10) do _ # take avg over 10 samples
sol = parametrized_solver(params) # compute solution
return sol[3, end] # some objective
end
## now some optimizer...
using NLopt # https://github.com/JuliaOpt/NLopt.jl
obj_for_nlopt = (vec, _) -> my_little_objective(vec) # the second term corresponds to a gradient - won't be used, but is a part of the NLopt interface
opt = Opt(:GN_DIRECT, 5)
opt.lower_bounds = 0
opt.upper_bounds = 100
opt.max_objective = obj_for_nlopt
opt.maxeval = 100
(minf, minx, ret) = optimize(opt, rand(5))
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | docs | 15897 | # ReactiveDynamics.jl <br>
<p align="center">
<img src="docs/src/assets/diagram1.png" alt="wiring diagram"> <br>
<a href="#about">About</a> |
<a href="#context-dynamics-of-value-evolution-dyve">Context</a> |
<a href="#four-sketches">Four Sketches</a> |
<a href="https://merck.github.io/ReactiveDynamics.jl/stable">Documentation</a>
</p>
## About
The package provides a category of reaction (transportation) network-type problems formalized on top of the **[generalized algebraic theory](https://ncatlab.org/nlab/show/generalized+algebraic+theory)**, and is compatible with the **[SciML](https://sciml.ai/)** ecosystem.
Our motivation stems from the area of **[system dynamics](https://www.youtube.com/watch?v=o-Yp8A7BPE8)**, which is a mathematical modeling approach to frame, analyze, and optimize complex (nonlinear) dynamical systems, to augment the strategy and policy design.
<img src="docs/src/assets/diagram2.png" align="right" alt="wiring diagram"></a>
<p>The central concept is of a <b>transition</b> (transport, flow, rule, reaction - a subcategory of general algebraic action). Generally, a transition prescribes a stochastic rule which repeatedly transforms the modeled system's <b>resources</b>. An elementary instance of such an ontology is provided by chemical reaction networks.
A <b>reaction network</b> (system modeled) is then a tuple $(T, R)$, where $T$ is a set of the transitions and $R$ is a set of the network's resource classes (aka species). The simultaneous action of transitions on the resources evolves the dynamical system.
The transitions are generally **stateful** (i.e., act over a period of time). Moreover, at each time step a quantum of the a transition's instances is brought into the scope, where the size of the batch is drived by a Poisson counting process. A transition takes the from `rate, a*A + b*B + ... --> c*C + ...`, where `rate` gives the expected batch size per time unit. `A`, `B`, etc., are the resources, and `a`, `b`, etc., are the generalized stoichiometry coefficients. Note that both `rate` and the "coefficients" can in fact be given by a function which depends on the system's instantaneous state (stochastic, in general). In particular, even the structural form of a transition can be stochastic, as will be demonstrated shortly.
</p>
An instance of a stateful transition evolves gradually from its genesis up to the terminal point, where the products on the instance's right hand-side are put into the system. An instance advances proportionally to the quantity of resources allocated. To understand this behavior, we note that the system's resource classes (or occurences of a resource class in a transition) may be assigned a **modality**; a modality governs the interaction between the resource and the transition, as well as the interpretation of the generalized stoichiometry coefficient.
In particular, a resource can be allocated to an instance either for the instance's lifetime or a single time step of the model's evolution (after each time step, the resource may be reallocated based on the global demand). Moreover, the coefficient of a resource on the left hand-side can either be interpreted as a total amount of the resource required or as an amount required per time unit. Similarly, it is possible to declare a resource **conserved**, in which case it is returned into the scope once the instance terminates.
<img src="docs/src/assets/diagram3.png" align="left" alt="attributes diagram"></a>
The transitions are <b>parametric</b>. That is, it is possible to set the period over which an instance of a transition acts in the system (as well as the maximal period of this action), the total number of transition's instances allowed to exist in the system, etc. An annotated transition takes the form `rate, a*A + b*B + ... --> c*C + ..., prm => val, ...`, where the numerical values can be given by a function which depends on the system's state. Internally, the reaction network is represented as an <a href=https://algebraicjulia.github.io/Catlab.jl/dev/generated/wiring_diagrams/wd_cset/><b>attributed C-set</b></a>.
For an overview of accepted attributes for both transitions and species classes, read the [docs](https://merck.github.io/ReactiveDynamics.jl/#Update-model-objects)
A network's dynamics is specified using a compact **modeling metalanguage**. Moreover, we have integrated another expression comprehension metalanguage which makes it easy to generate arbitrarily complex dynamics from a single template transition!
Taking **unions** of reaction networks is fully supported, and it is possible to identify the resource classes as appropriate.
Moreover, it is possible to **export and import** reaction network dynamics using the [TOML](https://toml.io/) format.
Once a network's dynamics is specified, it can be converted to a problem and simulated. The exported problem is a **`DiscreteProblem`** compatible with **[DifferentialEquations.jl](https://diffeq.sciml.ai/stable/)** ecosystem, and hence the latter package's all powerful capabilities are available. For better user experience, we have tailored and exported many of the functionalities within the modeling metalanguage, including ensemble analysis, parameter optimization, parameter inference, etc. Would you guess that **[universal differential equations](https://arxiv.org/abs/2001.04385)** are supported? If even the dynamics is unknown, you may just infer it!
## Context: Dynamics of Value Evolution (DyVE)
The package is an integral part of the **Dynamics of Value Evolution (DyVE)** computational framework for learning, designing, integrating, simulating, and optimizing R&D process models, to better inform strategic decisions in science and business.
As the framework evolves, multiple functionalities have matured enough to become standalone packages.
This includes **[GeneratedExpressions.jl](https://github.com/Merck/GeneratedExpressions.jl)**, a metalanguage to support code-less expression comprehensions. In the present context, expression comprehensions are used to generate complex dynamics from user-specified template transitions.
Another package is **[AlgebraicAgents.jl](https://github.com/Merck/AlgebraicAgents.jl)**, a lightweight package to enable hierarchical, heterogeneous dynamical systems co-integration. It implements a highly scalable, fully customizable interface featuring sums and compositions of dynamical systems. In present context, we note it can be used to co-integrate a reaction network problem with, e.g., a stochastic ordinary differential problem!
## Four Sketches
For other examples, see the **[tutorials](tutorial)**.
### SIR Model
The acronym SIR stands for susceptible, infected, and recovered, and as such the SIR model attempts to capture the dynamics of disease spread. We express the SIR dynamics as a reaction network using the compact modeling metalanguage.
Follow the SIR model's reactions:
<p align="center">
<img src="docs/src/assets/sir_reactions.png" alt="SIR reactions"> <br>
</p>
```julia
using ReactiveDynamics
# model dynamics
sir_acs = @ReactionNetwork begin
α*S*I, S+I --> 2I, name=>I2R
β*I, I --> R, name=>R2S
end
# simulation parameters
## initial values
@prob_init sir_acs S=999 I=10 R=0
## uncertainty in initial values (Gaussian)
@prob_uncertainty sir_acs S=10. I=5.
## parameters
@prob_params sir_acs α=0.0001 β=0.01
## other arguments passed to the solver
@prob_meta sir_acs tspan=250 dt=.1
```
The resulting reaction network is represented as an attributed C-set:

Next we solve the problem.
```
# turn model into a problem
prob = @problematize sir_acs
# solve the problem over multiple trajectories
sol = @solve prob trajectories=20
# plot the solution
@plot sol plot_type=summary
## show only species S
@plot sol plot_type=summary show=:S
## plot evolution over (0., 100.) in green (propagates to Plots.jl)
@plot sol plot_type=summary c=:green xlimits=(.0, 100.)
```

### A Primer on Attributed Transitions
Before we move on to more intricate examples demonstrating generative capabilities of the package, let's sketch a toy pharma model with as little as three transitions.
```julia
toy_pharma_model = @ReactionNetwork
```
First, a **"discovery" transition** will take a team of scientist and a portion of a company's budget at the input (say, for experimental resources), and it will **output candidate compounds**.
```julia
@push toy_pharma_model α(candidate_compound, marketed_drug, κ) 3*@conserved(scientist) + @rate(budget) --> candidate_compound name=>discovery probability=>.3 cycletime=>6 priority=>.5
```
Note that per a time unit, `α(candidate_compound, marketed_drug, κ)` "discovery" projects will be started. We provide a name of the class of transitions (`name=>discovery`), set up a probability of the transition terminating successfully (`probability=>.3`), a cycle time (`cycletime=>6`), and we provide a weight of the transitions' class for use in resource allocation (`priority=>.5`).
Moreover, we annotate "scientists" as a conserved resource (no matter how the project terminates, the workforce isn't consumed), i.e., `@conserved(scientist)`, and we state that a unit "budget" is consumed per a time unit, i.e., `@rate(budget)`.
Next, **candidate compounds will undergo clinical trials**. If successful, a compound transforms into a marketed drug, and the company receives a premium.
```julia
@push toy_pharma_model β(candidate_compound, marketed_drug) candidate_compound + 5*@conserved(scientist) + 2*@rate(budget) --> marketed_drug + 5*budget name=>dx2market probability=>.5+.001*@t() cycletime=>4
```
Note that as time evolves, the probability of technical success increases, i.e., `probability=>.5+.001*@t()`.
In addition, **marketed drugs bring profit to the company** - which will fuel invention of new drugs.
We model the situation as a periodic callback.
```julia
@periodic toy_pharma_model 1. budget += 11*marketed_drug
```
A **marketed drug may eventually be withdrawn** from the market. To account for such scenario, we add the following transition:
```julia
@push toy_pharma_model γ*marketed_drug marketed_drug --> ∅ name=>drug_withdrawn
```
Next we provide the functions `α` and `β`.
```julia
@register α(number_candidate_compounds, number_marketed_drugs, κ) = κ + exp(-number_candidate_compounds) + exp(-number_marketed_drugs)
@register β(number_candidate_compounds, number_marketed_drugs) = numbercandidate_compounds + exp(-number_marketed_drugs)
```
Likewise, we set the remaining parameters, initial values, and model metadata:
```julia
# simulation parameters
## initial values
@prob_init toy_pharma_model candidate_compound=5 marketed_drug=6 scientist=20 budget=100
## parameters
@prob_params toy_pharma_model κ=4 γ=.1
## other arguments passed to the solver
@prob_meta toy_pharma_model tspan=250 dt=.1
```
And we problematize the model, solve the problem, and plot the solution:
```julia
prob = @problematize toy_pharma_model
sol = @solve prob trajectories=20
@plot sol plot_type=summary show=[:candidate_compound, :marketed_drug]
```

### Sparse Interactions
We introduce a complex reaction network as a union of $n_{\text{models}}$ reaction networks, where the off-diagonal interactions are sparse.
To harness the capabilities of **GeneratedExpressions.jl**, let us first declare a template atomic model.
```julia
# submodel.jl
# substitute $r as the global number of resources, $i as the submodel identifier
@register begin
push!(ns, rand(1:5)); ϵ = 10e-2
push!(M, rand(ns[$i], ns[$i])); foreach(i -> M[$i][i, i] += ϵ, 1:ns[$i])
foreach(i -> M[$i][i, :] /= sum(M[$i][i, :]), 1:ns[$i])
push!(cycle_times, rand(1:5, ns[$i], ns[$i]))
push!(demand, rand(1:10, ns[$i], ns[$i], $r)); push!(production, rand(1:10, ns[$i], ns[$i], $r))
end
# generate submodel dynamics
push!(rd_models, @ReactionNetwork begin
M[$i][$m, $n], state[$m] + {demand[$i][$m, $n, $l]*resource[$l], l=1:$r, dlm=+} --> state[$n] +
{production[$i][$m, $n, $l]*resource[$l], l=1:$r, dlm=+}, cycle_time=>cycle_times[$i][$m, $n], probability_of_success=>$m*$n/(n[$i])^2
end m=1:ReactiveDynamics.ns[$i] n=1:ReactiveDynamics.ns[$i]
)
```
The next step is to instantiate the atomic models (submodels).
```julia
using ReactiveDynamics
## setup the environment
rd_models = ReactiveDynamics.ReactionNetwork[] # submodels
# needs to live within ReactiveDynamics's scope
# the arrays will contain the submodel
@register begin
ns = Int[] # size of submodels
M = Array[] # transition intensities of submodels
cycle_times = Array[] # cycle times of transitions in submodels
demand = Array[]; production = Array[] # resource production / generation for transitions in submodels
end
```
Load $n_{\text{models}}$ the atomic models (substituting into `submodel.jl`):
```julia
n_models = 5; r = 2 # number of submodels, resources
# submodels: dense interactions
@generate {@fileval(submodel.jl, i=$i, r=r), i=1:n_models}
```
We take union of the atomic models, and we identify common resources.
```julia
# batch join over the submodels
rd_model = @generate "@join {rd_models[\$i], i=1:n_models, dlm=' '}"
# identify resources
@generate {@equalize(rd_model, @alias(resource[$j])={rd_models[$i].resource[$j], i=1:n_models, dlm=:(=)}), j=1:r}
```
Next step is to add some off-diagonal interactions.
```julia
# sparse off-diagonal interactions, sparse declaration
# again, we use GeneratedExpressions.jl
sparse_off_diagonal = zeros(sum(ReactiveDynamics.ns), sum(ReactiveDynamics.ns))
for i in 1:n_models
j = rand(setdiff(1:n_models, (i, )))
i_ix = rand(1:ReactiveDynamics.ns[i]); j_ix = rand(1:ReactiveDynamics.ns[j])
sparse_off_diagonal[i_ix+sum(ReactiveDynamics.ns[1:i-1]), j_ix+sum(ReactiveDynamics.ns[1:j-1])] += 1
interaction_ex = """@push rd_model begin 1., var"rd_models[$i].state[$i_ix]" --> var"rd_models[$j]__state[$j_ix]" end"""
eval(Meta.parseall(interaction_ex))
end
```
Let's plot the interactions:

The resulting model can then be conveniently simulated using the modeling metalanguage.
```julia
using ReactiveDynamics: nparts
u0 = rand(1:1000, nparts(rd_model, :S))
@prob_init rd_model u0
@prob_meta rd_model tspan=10
prob = @problematize rd_model
sol = @solve prob trajectories=2
# plot "state" species only
@plot sol plot_type=summary show=r"state"
```
### Universal Differential Equations: Fitting Unknown Dynamics
We demonstrate how to fit unknown part of dynamics to empirical data.
We use `@register` to define a simple linear function within the scope of module `ReactiveDynamics`; parameters of the function will be then optimized for. Note that `function_to_learn` can be generally replaced with a neural network (Flux chain), etc.
```julia
## some embedded function (neural network, etc.)
@register begin
function function_to_learn(A, B, C, params)
[A, B, C]' * params # params: 3-element vector
end
end
```
Next we set up a simple dynamics and supply initial parameters.
```julia
acs = @ReactionNetwork begin
function_to_learn(A, B, C, params), A --> B+C
1., B --> C
2., C --> B
end
# initial values, check params
@prob_init acs A=60. B=10. C=150.
@prob_params acs params=[.01, .01, .01]
@prob_meta acs tspan=100.
```
Let's next see the numerical results for the initial guess.
```julia
sol = @solve acs
@plot sol
```

Next we supply empirical data and fit `params`.
```julia
time_points = [1, 50, 100]
data = [60 30 5]
@fit_and_plot acs data time_points vars=[A] params α maxeval=200 lower_bounds=0 upper_bounds=.01
```

| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | docs | 2708 | # API Documentation
## Create a model
```@docs
@ReactionNetwork
```
## Modify a model
We list common transition attributes. When being specified using the `@ReactionNetwork` macro they can be conveniently referred to using their shorthand description.
| attribute | shorthand | interpretation |
| :----- | :----- | :----- |
| `transPriority` | `priority` | priority of a transition (influences resource allocation) |
| `transProbOfSuccess` | `probability` `prob` `pos` | probability that a transition terminates successfully |
| `transCapacity` | `cap` `capacity` | maximum number of concurrent instances of the transition |
| `transCycleTime` | `ct` `cycletime` | duration of a transition's instance (adjusted by resource allocation) |
| `transMaxLifeTime` | `lifetime` `maxlifetime` `maxtime` `timetolive` | maximal duration of a transition's instance |
| `transPostAction` | `postAction` `post` | action to be executed once a transition's instance terminates |
| `transName` | `name` `interpretation` | name of a transition, either a string or unquoted text |
We list common species attributes:
| attribute | shorthand | interpretation |
| :----- | :----- | :----- |
| `specInitUncertainty` | `uncertainty` `stoch` `stochasticity` | uncertainty about variable's initial state (modelled as Gaussian standard deviation) |
| `specInitVal` | | initial value of a variable |
Moreover, it is possible to specify the semantics of the "rate" term. By default, at each time step `n ~ Poisson(rate * dt)` instances of a given transition will be spawned. If you want to specify the rate in terms of a cycle time, you may want to use `@ct(cycle_time)`, e.g., `@ct(ex), A --> B, ...`. This is a shorthand for `1/ex, A --> B, ...`.
For deterministic "rates", use `@per_step(ex)`. Here, `ex` evaluates to a deterministic number (ceiled to the nearest integer) of a transition's instances to spawn per a single integrator's step. However, note that in this case, the number doesn't scale with the step length! Moreover
```@docs
@add_species
@aka
@mode
@name_transition
```
## Resource costs
```@docs
@cost
@valuation
@reward
```
## Add reactions
```@docs
@push
@jump
@periodic
```
## Set initial values, uncertainty, and solver arguments
```@docs
@prob_init
@prob_uncertainty
@prob_params
@prob_meta
```
## Model unions
```@docs
@join
@equalize
```
## Model import and export
```@docs
@import_network
@export_network
```
## Solution import and export
```@docs
@import_solution
@export_solution_as_table
@export_solution_as_csv
@export_solution
```
## Problematize,sSolve, and plot
```@docs
@problematize
@solve
@plot
```
## Optimization and fitting
```@docs
@optimize
@fit
@fit_and_plot
@build_solver
``` | ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 0.2.7 | ddc8a249e7e2a5634deeea47b4cf894209270402 | docs | 1814 | flowchart TD
o["∅"] -->|"@ReactionNetwork"| acs["ReactiveDynamics.ReactionNetwork (aka ACS)"]
acs --> |"@add_species, @aka, @cost, @equalize, @jump, @mode,
@name_transition, @optimize, @periodic, @prob_check_verbose,
@prob_init, @prob_meta, @prob_params, @prob_uncertainty,
@push, @reward, @valuation"| acs
sol --> |"@export_solution_as_table"| table["table"]
sol --> |"@export_solution_as_csv"| csvsol["sol.csv"]
acs --> |"@import_network"| mod["model.toml"]
sol--> |"@export_solution"| solex["sol.jld2"]
joinsol --> |"@fit_and_plot"| plot
mod --> |"@export_network"| acs
solex --> |"@import_solution"| sol["solution"]
acs1["ACS1\n~ReactiveDynamics.ReactionNetwork"] --- join[ ]
acs2["ACS2\n~ReactiveDynamics.ReactionNetwork"] --- join[ ]
join --> |"@join"| acs
sol --> |"@plot,
@plot_new_transitions,
@plot_terminated_transitions,
@plot_valuations"| plot["plot"]
acs --> |"@problematize"| DP["DiscreteProblem"]
acs --> |"@solve"| sol
DP --> |"@solve"| sol
sol2["model"] --- joinsol
data["empirical data"] --- joinsol[ ]
joinsol --> |"@fit"| sol
subgraph Legend
acsClass["ReactiveDynamics objects"]
csvClass["csv files"]
DPcl["DiscreteProblem"]
plotClass["Plots objects"]
other["others"]
end
classDef ReactiveDynamics fill:#B0F5F4,stroke:#3585CC;
class acs,acs1,acs2,mod,join,solex,joinsol,acsClass,sol,sol2,table ReactiveDynamics;
classDef DPcl fill:#F0BC93,stroke:#F0453D;
class DP,DPcl DPcl;
classDef csvfile fill:#c0f8be,stroke:#127f0e;
class csvsol,csvClass csvfile;
classDef plots fill:#fbffa7,stroke:#a6ae00;
class plot,plotClass plots;
| ReactiveDynamics | https://github.com/Merck/ReactiveDynamics.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 325 | using Documenter
using EarthAlbedo
makedocs(
sitename = "EarthAlbedo.jl",
format = Documenter.HTML(prettyurls = false),
pages = [
"Introduction" => "index.md",
"API" => "api.md"
]
)
deploydocs(
repo = "github.com/RoboticExplorationLab/EarthAlbedo.jl.git",
devbranch = "main"
) | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 5947 | # [src/EarthAlbedo.jl]
module EarthAlbedo
using LinearAlgebra
# using SatelliteDynamics # For GEOD/ECEF Conversions (may not work on Windows?)
using CoordinateTransformations # For spherical <-> Cartesian transformations
using StaticArrays
using JLD2
include("rad2idx.jl")
include("idx2rad.jl")
include("gridangle.jl")
include("earthfov.jl")
include("cellarea.jl")
export REFL, earth_albedo, load_refl
""" REFL Structure for holding reflectivity data"""
struct REFL
data
type
start_time
stop_time
end
"""
Determines the Earth's albedo at a satellite for a given set of reflectivity data.
First divides the Earth's surface into a set of cells (determined by the size of the refl data),
and then determines which cells are visible by both the satellite and the Sun. This is
then used to determine how much sunlight is reflected by the Earth towards the satellite.
Arguments:
- sat: Vector from center of Earth to satellite | SVector{3, Float64}
- sun: Vector from center of Earth to Sun | SVector{3, Flaot64}
- refl_data: Matrix containing the averaged reflectivity data for each cell | Array{Float64, 2}
- Rₑ: (Optional) Average radius of the Earth (default is 6371010 m) | Scalar
- AM₀: (Optional) Solar irradiance (default is 1366.9) | Scalar
Returns:
- cell_albedos: Matrix with each element corresponding to the albedo coming from
the corresponding cell on the surface of the earth | [num_lat x num_lon]
"""
function earth_albedo(sat::SVector{3, Float64}, sun::SVector{3, Float64}, refl_data::Array{Float64, 2}; Rₑ = 6371.01e3, AM₀ = 1366.9)
num_lat, num_lon = size(refl_data);
# Verify no satellite collision has occured
if norm(sat) < Rₑ
error("albedo.m: The satellite has crashed into Earth!");
end
# # Convert from Cartesian -> Spherical (r θ ϕ)
sat_sph_t = SphericalFromCartesian()(sat);
sun_sph_t = SphericalFromCartesian()(sun);
# Adjust order to match template code to (θ ϵ r), with ϵ = (π/2) - ϕ
sat_sph = SVector{3, Float64}(sat_sph_t.θ, (pi/2) - sat_sph_t.ϕ, sat_sph_t.r);
sun_sph = SVector{3, Float64}(sun_sph_t.θ, (pi/2) - sun_sph_t.ϕ, sun_sph_t.r);
# # REFL Indices
sat_i, sat_j = rad2idx(sat_sph[1], sat_sph[2], num_lat, num_lon);
sun_i, sun_j = rad2idx(sun_sph[1], sun_sph[2], num_lat, num_lon);
# # SKIP GENERATING PLOTS FOR NOW
cells = fill!(BitArray(undef, num_lat, num_lon), 1)
earthfov!(cells, sat_sph, num_lat, num_lon)
earthfov!(cells, sun_sph, num_lat, num_lon)
cell_albedos = zeros(Float64, num_lat, num_lon)
for i = 1:num_lat
for j = 1:num_lon
if cells[i, j]
cell_albedos[i, j] = albedo_per_cell(sat, refl_data[i, j], i, j, sun_i, sun_j, num_lat, num_lon; Rₑ = Rₑ, AM₀ = AM₀)
end
end
end
return cell_albedos
end
"""
Internal function that evaluates the albedo reflected by every cell.
Arguments:
- sat: Vector from center of Earth to satellite | SVector{3, Float64}
- refl_data: Matrix containing the averaged reflectivity data for current cell | Array{Float64, 2}
- cell_i: Latitude index of cell
- cell_j: Longitude index of cell
- sun_i: Latitude index of sun
- sun_j: Longitude index of sun
- num_lat: Number of latitude cells Earth's surface is divided into | Int
- num_lon: Number of longitude cells Earth's surface is divided into | Int
- Rₑ: (Optional) Average radius of the Earth (default is 6371010 m) | Scalar
- AM₀: (Optional) Solar irradiance (default is 1366.9) | Scalar
Returns:
- P_out: Cell albedo generated by current cell towards the satellite | Float64
"""
function albedo_per_cell(sat::SVector{3, Float64}, refl_cell_data::Float64, cell_i::Int, cell_j::Int, sun_i::Int, sun_j::Int, num_lat::Int, num_lon::Int; Rₑ = 6371.01e3, AM₀ = 1366.9)::Float64
ϕ_in = gridangle(cell_i, cell_j, sun_i, sun_j, num_lat, num_lon);
ϕ_in = (ϕ_in > pi/2) ? pi/2 : ϕ_in
E_inc = AM₀ * cellarea(cell_i, cell_j, num_lat, num_lon) * cos(ϕ_in)
grid_theta, grid_phi = idx2rad(cell_i, cell_j, num_lat, num_lon)
grid_spherical = Spherical(Rₑ, grid_theta, (pi/2) - grid_phi)
grid = CartesianFromSpherical()(grid_spherical);
sat_dist = norm(sat - grid); # Unit vector pointing from grid center to satellite
ϕ_out = acos( ((sat - grid)/sat_dist)' * grid / norm(grid) ); # Angle to sat from grid
P_out = E_inc * refl_cell_data * cos(ϕ_out) / (pi * sat_dist^2);
return P_out
end
"""
Loads in reflectivity data and stores it in a REFL struct
"""
function load_refl(path = "data/refl.jld2")
temp = load(path)
refl = REFL( temp["data"], temp["type"], temp["start_time"], temp["stop_time"])
return refl
end
end # module
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 1069 | # [src/cellarea.jl]
"""
Calculate the area of a TOMS REFL Matrix cell for use in calculating Earth albedo.
Arguments:
- i: TOMS REFL Matrix latitude index of desired cell (0 < i ≤ sy) | Int
- j: TOMS REFL Matrix longitude index of desired cell (0 < j ≤ sx) | Int
- sy: Number of latitude cells in grid | Int
- sx: Number of longitude cells in grid | Int
- Rₑ: (Optional) Average radius of the Earth, defaults to meters | Scalar
Returns:
- A: Area of desired cell | Scalar
"""
function cellarea(i::Int, j::Int, sy::Int, sx::Int, Rₑ = 6371.01e3) # Average radius of the Earth, m
_d2r = pi / 180.0; # Standard degrees to radians conversion
θ, ϕ = idx2rad(i, j, sy, sx) # Convert to angles (radians)
dϕ = (180.0 / sy) * _d2r;
dθ = (360.0 / sx) * _d2r;
# Get diagonal points
ϕ_max = ϕ + dϕ/2;
ϕ_min = ϕ - dϕ/2;
A = (Rₑ^2) * dθ * (cos(ϕ_min) - cos(ϕ_max));
return A
end | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 3322 | # [src/earthfov.jl]
"""
Determines which cells on the Earth's surface are in the field of view
of an object in space (e.g., satellite, sun) using spherical coordinates.
Arguments:
- pos_sph: Vector from Earth to the object in question (e.g., satellite, sun)
in ECEF frame using spherical coordinates [θ, ϵ, r] | [3,]
- sy: Number of latitude cells Earth's surface is divided into | Int
- sx: Number of longitude cells Earth's surface is divided into | Int
- Rₑ: (Optional) Average radius of the Earth (m) | Float
Returns:
- fov: Cells on Earth's surface that are in the field of view of the given object | BitMatrix [sy, sx]
"""
function earthfov(pos_sph::Vector{Float64}, sy::Int, sx::Int, Rₑ = 6371.01e3)::BitMatrix # Matrix{Int8}
if pos_sph[3] < Rₑ # LEO shortcut (?) -
pos_sph[3] = pos_sph[3] + Rₑ
@warn "Warning: radial distance is less than radius of the Earth. Adding in Earth's radius..."
end
# Small circle center
θ₀, ϕ₀ = pos_sph[1], pos_sph[2]
sϕ₀, cϕ₀ = sincos(ϕ₀) # Precompute to use in the for loop
ρ = acos(Rₑ / pos_sph[3]) # FOV on Earth
fov = BitArray(undef, sy, sx) # zeros(Int8, sy, sx)
for i = 1:sy
for j = 1:sx
θ, ϕ = idx2rad(i, j, sy, sx)
rd = acos( sϕ₀ * sin(ϕ) * cos(θ₀ - θ) + cϕ₀ * cos(ϕ) ); # Radial Distance
fov[i, j] = (rd ≤ ρ) ? 1 : 0 # 1 if in FOV, 0 otherwise
end
end
return fov
end
"""
Determines which cells on the Earth's surface are in the field of view
of an object in space (e.g., satellite, sun) using spherical coordinates.
This version takes in and updates a field-of-view (FOV) matrix in place.
Arguments:
- fov: Cells on Earth's surface (updated in place with cells that are in field | Bitmatrix [sy, sx]
of view of provided object)
- pos_sph: Vector from Earth to the object in question (e.g., satellite, sun) | [3,]
in ECEF frame using spherical coordinates [θ, ϵ, r]
- sy: Number of latitude cells Earth's surface is divided into | Int
- sx: Number of longitude cells Earth's surface is divided into | Int
- Rₑ: (Optional) Average radius of the Earth (m) | Float
"""
function earthfov!(fov::BitMatrix, pos_sph::SVector{3, Float64}, sy::Int, sx::Int, Rₑ = 6371.01e3)::BitMatrix # Matrix{Int8}
if pos_sph[3] < Rₑ # LEO shortcut
pos_sph[3] = pos_sph[3] + Rₑ
@info "Warning: radial distance is less than radius of the Earth. Adding in Earth's radius..."
end
# Small circle center
θ₀, ϕ₀ = pos_sph[1], pos_sph[2]
sϕ₀, cϕ₀ = sincos(ϕ₀) # Precompute to use in the for loop
ρ = acos(Rₑ / pos_sph[3]) # FOV on Earth
# fov = BitArray(undef, sy, sx) # zeros(Int8, sy, sx)
for i = 1:sy
for j = 1:sx
if fov[i, j]
θ, ϕ = idx2rad(i, j, sy, sx)
rd = acos( sϕ₀ * sin(ϕ) * cos(θ₀ - θ) + cϕ₀ * cos(ϕ) ); # Radial Distance
fov[i, j] = (rd ≤ ρ) ? 1 : 0 # 1 if in FOV, 0 otherwise
end
end
end
return fov
end
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 998 | # [src/gridangle.jl]
"""
Determines the angle between two cells given their indices
Arguments:
- i₁: Latitude index of first cell in grid | Int
- j₁: Longitude index of first cell in grid | Int
- i₂: Latitude index of second cell in grid | Int
- j₂: Longitude index of second cell in grid | Int
- sy: Number of latitude cells in grid | Int
- sx: Number of longitude cells in grid | Int
Outputs:
- ρ: Angle between the two grid index pairs (rad) | Float
"""
function gridangle(i₁, j₁, i₂, j₂, sy, sx)
# Convert from index to angles
θ₁, ϕ₁ = idx2rad(i₁, j₁, sy, sx);
θ₂, ϕ₂ = idx2rad(i₂, j₂, sy, sx);
# Determine the angular distance
angle = sin(ϕ₁) * sin(ϕ₂) * cos(θ₁ - θ₂) + cos(ϕ₁) * cos(ϕ₂)
# Correct numerical precision errors
if (angle > 1.0) && (angle ≈ 1.0)
angle = 1.0
elseif (angle < -1.0) && (angle ≈ -1.0)
angle = -1.0
end
return acos( angle )
end | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 751 | # [scr/idx2rad.jl]
"""
Transforms from TOMS REFL Matrix indices to spherical coordinates (radians)
Arguments:
- i: TOMS REFL Matrix latitude index of desired cell | Int
- j: TOMS REFL Matrix longitude index of desired cell | Int
- sy: Number of latitude cells in grid | Int
- sx: Number of longitude cells in grid | Int
Returns: (Tuple)
- (θ, ϵ): Tuple of (Polar, Elevation) angle corresponding
to center of desired cell (rad) | Tuple{Float, Float}
"""
function idx2rad(i::Int, j::Int, sy::Int, sx::Int)::Tuple{Float64, Float64}
dx = 2 * pi / sx;
dy = pi / sy;
ϵ = pi - dy/2 - (i-1)*dy;
θ = (j-1) * dx - pi + dx/2;
return θ, ϵ
end | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 1057 | # [scr/rad2idx.jl]
"""
Transforms location of a cell center in spherical coordinates (radians) to TOMS REFL Matrix indices.
(NOTE that we are forcing a specific rounding style to match MATLAB's)
Arguments:
- θ: Polar angle corresponding to center of desired cell (rad) | Scalar
- ϵ: Elevation angle corresponding to center of desired cell (rad) | Scalar
- sy: Number of latitude cells in grid | Int
- sx: Number of longitude cells in grid | Int
Returns:
- (i, j): TOMS REFL Matrix (latitude, longitude) index of desired cell | Tuple{Int, Int}
"""
function rad2idx(θ, ϵ, sy::Int, sx::Int)::Tuple{Int, Int}
dx = 2.0 * pi / sx; # 360* / number of longitude cells
dy = pi / sy; # 180* / number of latitude cells
# Always round up to match MATLAB (vs default Bankers rounding)
i = Int(round( (pi - dy/2.0 - ϵ)/dy , RoundNearestTiesAway) + 1);
j = Int(round( (θ + pi - dx/2.0 )/dx , RoundNearestTiesAway) + 1);
return i, j
end | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 1009 | # [test/cellarea_tests.jl]
using Test
@testset "Cell Area" begin
import EarthAlbedo.cellarea
using JLD2
@testset "Default Dimensions" begin
sy, sx = 288, 180
N = 50
is = Int.(round.(range(1, sy, length = N)))
js = Int.(round.(range(1, sx, length = N)))
@load "test_files/cellarea_default_dim.jld2" cellarea_default_dim
for k = 1:length(is)
i, j = is[k], js[k]
a_jl = cellarea(i, j, sy, sx)
@test cellarea_default_dim[k] ≈ a_jl
end
end;
@testset "Changing a few things" begin
sy, sx = 50, 300
N = 50
is = Int.(round.(range(1, sy, length = N)))
js = Int.(round.(range(1, sx, length = N)))
@load "test_files/cellarea_changes.jld2" cellarea_changes
for k = 1:length(is)
i, j = is[k], js[k]
a_jl = cellarea(i, j, sy, sx)
@test cellarea_changes[k] ≈ a_jl
end
end;
end;
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 1643 | # [test/earth_albedo_tests.jl]
using Test
using StaticArrays
@testset "Earth Albedo Tests" begin
import EarthAlbedo.earth_albedo
import EarthAlbedo.load_refl
import EarthAlbedo.REFL
using JLD2, StaticArrays
refl = load_refl("../data/refl.jld2");
refl_data = refl.data;
@testset "Standard" begin
sat = SVector{3, Float64}(0, 0, 8e6)
sun = SVector{3, Float64}(0, 1e9, 0)
sat_mat = [0, 0, 8e6]
sun_mat = [0, 1e9, 0]
@load "test_files/earth_alb_std.jld2" cell_albs_mat
cell_albs_jl = earth_albedo(sat, sun, refl_data);
@test cell_albs_jl ≈ cell_albs_mat atol=1e-12
end
@testset "Additional Positions" begin
# different sat, sun positions
sats = [ 0 0 1e7;
0 1e8 0;
5e7 0 0;
-1e6 1e7 1e8;
-1e7 -1e7 -1e7;
0 1e9 0;
0 1e9 0 ]
suns = [ 0 0 1e9;
0 0 1e9;
0 0 1e9;
1e10 1e5 0;
-2e8 3300 9e9;
0 1e9 0;
0 -1e9 0 ]
N = size(sats, 1)
@load "test_files/earth_alb_extra.jld2" cell_albs_mats
for i = 1:N
sat_mat, sun_mat = sats[i, :], suns[i, :]
sat = SVector{3, Float64}(sat_mat)
sun = SVector{3, Float64}(sun_mat)
cell_albs_jl = earth_albedo(sat, sun, refl_data);
@test cell_albs_jl ≈ cell_albs_mats[i] atol=1e-12
end
end
end
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 2964 | # [test/earthfov.jl]
using Test
@testset "Earth FOV" begin
import EarthAlbedo.earthfov
using CoordinateTransformations
using Random
using JLD2
@testset "Defaults" begin
sy, sx = 288, 180
# Run through some preset
positions = [6.5e6 6.5e6 6.5e6; # Near the surface
1.0e9 1.0e9 1.0e9; # Far away
1.0e3 2.0e3 -1.0e3; # Too close (inside Earth) -> Should warn and then add in Re
0 0 8e7; # +Z
0 0 -8e7; # -Z
0 9e7 0; # +Y
0 -7e8 0; # -Y
7.5e6 0 0; # +X
-8.2e6 0 0 # -X
]
N = size(positions, 1)
@load "test_files/earthfov_test.jld2" earthfov_test
for i = 1:N
sat_sph_t = SphericalFromCartesian()(positions[i, :])
sat_sph = [sat_sph_t.θ; (pi/2) - sat_sph_t.ϕ; sat_sph_t.r]; # Adjust order to match template code to (θ ϵ r), with ϵ = (π/2) - ϕ
fov_jl = earthfov(sat_sph, sy, sx)
@test earthfov_test[i] == fov_jl
end
end
@testset "More tests" begin
sy, sx = 288, 180
# # Throw in some more tests
N = 50
Random.seed!(5)
positions = ones(N, 3) * 6.5e6 + 3e6 * rand(N, 3) # Make at least Earth's radius away
signs = randn(N, 3)
signs[signs .> 0] .= 1
signs[signs .<= 0] .= -1
positions = positions .* signs
@load "test_files/earthfov_more_tests.jld2" earthfov_more_tests
for i = 1:N
sat_sph_t = SphericalFromCartesian()(positions[i, :])
sat_sph = [sat_sph_t.θ; (pi/2) - sat_sph_t.ϕ; sat_sph_t.r]; # Adjust order to match template code to (θ ϵ r), with ϵ = (π/2) - ϕ
fov_jl = earthfov(sat_sph, sy, sx)
@test earthfov_more_tests[i] == fov_jl
end
end
@testset "Modified Units" begin
sy, sx = 20, 32
N = 50
Random.seed!(5)
positions = ones(N, 3) * 6.5e6 + 3e6 * rand(N, 3) # Make at least Earth's radius away
signs = randn(N, 3)
signs[signs .> 0] .= 1
signs[signs .<= 0] .= -1
positions = positions .* signs ./ 1000 # Convert to kilometers
Rₑ = 6371.01 # make km
@load "test_files/earthfov_mod_units.jld2" earthfov_mod_units
for i = 1:N
sat_sph_t = SphericalFromCartesian()(positions[i, :])
sat_sph = [sat_sph_t.θ; (pi/2) - sat_sph_t.ϕ; sat_sph_t.r]; # Adjust order to match template code to (θ ϵ r), with ϵ = (π/2) - ϕ
sat_sph_unconverted = [sat_sph[1], sat_sph[2], 1000 * sat_sph[3]]
fov_jl = earthfov(sat_sph, sy, sx, Rₑ)
@test earthfov_mod_units[i] == fov_jl
end
end
end;
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 509 | # [test/gridangle.jl]
using Test
@testset "Gridangle" begin
import EarthAlbedo.gridangle
using Random
sy, sx = 288, 180
N = 150
Random.seed!(10)
i1s, j1s = rand(1:sy, N), rand(1:sx, N)
i2s, j2s = rand(1:sy, N), rand(1:sx, N)
@load "test_files/gridangle_test.jld2" gridangle_test
for k = 1:N
i1, j1 = i1s[k], j1s[k]
i2, j2 = i2s[k], j2s[k]
ρ_jl = gridangle(i1, j1, i2, j2, sy, sx)
@test ρ_jl ≈ gridangle_test[k]
end
end
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 571 | # [test/idx2rad.jl]
using Test
@testset "Idx2Rad" begin
import EarthAlbedo.idx2rad
using JLD2
sy, sx = 288, 180
N = 20
is = range(0, sy, length = N)
js = range(0, sx, length = N)
@load "test_files/idx2rad_test.jld2" idx2rad_test
for iIdx = 1:N
for jIdx = 1:N
i, j = Int(round(is[iIdx])), Int(round(js[jIdx]))
theta_jl, eps_jl = idx2rad(i, j, sy, sx)
@test idx2rad_test[iIdx, jIdx, 1] == theta_jl
@test idx2rad_test[iIdx, jIdx, 2] == eps_jl
end
end
end
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 1202 | # [test/rad2idx.jl]
using Test
@testset "Rad2Idx" begin
import EarthAlbedo.rad2idx
using JLD2
@testset "Test 1" begin
sy, sx = 288, 180
N = 15
θs = range(0, pi, length = N) # Cell center in spherical coordinates (radians)
ϵs = range(0, 2 * pi, length = N)
@load "test_files/rad2idx_test1.jld2" rad2idx_test1
for i = 1:N
for j = 1:N
θ, ϵ = θs[i], ϵs[j]
i_jl, j_jl = rad2idx(θ, ϵ, sy, sx)
@test rad2idx_test1[i, j, 1] == i_jl
@test rad2idx_test1[i, j, 2] == j_jl
end
end
end;
@testset "Test 2" begin
sy, sx = 150, 3
N = 15
θs = range(0, pi, length = N) # Cell center in spherical coordinates (radians)
ϵs = range(0, 2 * pi, length = N)
@load "test_files/rad2idx_Test2.jld2" rad2idx_test2
for i = 1:N
for j = 1:N
θ, ϵ = θs[i], ϵs[j]
i_jl, j_jl = rad2idx(θ, ϵ, sy, sx)
@test rad2idx_test2[i, j, 1] == i_jl
@test rad2idx_test2[i, j, 2] == j_jl
end
end
end
end
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | code | 400 | # [test/runtests.jl]
# Note that the comparison files for these tests were generated by
# running the MATLAB code on the same variables and storing the results
using EarthAlbedo
using Test
using JLD2
# Test scripts
include("rad2idx_tests.jl")
include("idx2rad_tests.jl")
include("gridangle_tests.jl")
include("earthfov_tests.jl")
include("cellarea_tests.jl")
include("earth_albedo_tests.jl") | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | docs | 1937 | [](https://github.com/RoboticExplorationLab/EarthAlbedo.jl/actions/workflows/CI.yml)
[](https://codecov.io/gh/RoboticExplorationLab/EarthAlbedo.jl)
[](http://roboticexplorationlab.org/EarthAlbedo.jl/dev/)
# EarthAlbedo.jl
This package holds code used for the calculation of Earth's albedo for a given satellite, sun location, and set of reflectivity data. Note that this has been ported over from MATLAB's 'Earth Albedo Toolbox', and uses reflectivity data downloaded from https://bhanderi.dk/downloads/ .
## Downloading reflectivity data
The reflectivity data is based off of a set measured reflectivity data known as the TOMS dataset. The surface of the Earth is divided into cells and the TOMS data corresponding to each cell are averaged and used to estimate the reflectivity of a given area of the Earth's surface.
A version of this data has been processed and saved in the 'data/' folder. The source data can be downloaded by selecting the MATLAB converted TOMS data corresponding to the desired year from https://bhanderi.dk/downloads/ (e.g., refl = matread("tomsdata2005/2005/ga050101-051231.mat"), and then creating a struct.
Note that the 'Earth Albedo Toolbox' does not need to be downloaded for this to work.
## Use
The primary function is 'albedo(sat, sun, refl_data)' which takes in a vector containing the satellite and sun positions in the inertial frame (centered on Earth), as well as a set of reflectivity data. The provided data from the above link is from the TOMS dataset and is the average measured reflectivity for each section of Earth over a specified time period.
## Other
Note that SatelliteDynamics.jl is used to convert between | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | docs | 233 | ```@meta
CurrentModule = EarthAlbedo
```
```@contents
Pages = ["api.md"]
```
# API
This page is a dump of all the docstrings found in the code.
```@autodocs
Modules = [EarthAlbedo]
Order = [:module, :type, :function, :macro]
``` | EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 1.0.0 | 70342f0016548d36de354c1529064b194beeae95 | docs | 31 | # EarthAlbedo.jl
## Overview
| EarthAlbedo | https://github.com/RoboticExplorationLab/EarthAlbedo.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1270 | pushfirst!(LOAD_PATH, joinpath(@__DIR__, "..")) # add CubedSphere.jl to environment stack
using
Documenter,
DocumenterCitations,
Literate,
GLMakie,
CubedSphere
#####
##### Build and deploy docs
#####
format = Documenter.HTML(
collapselevel = 2,
prettyurls = get(ENV, "CI", nothing) == "true",
canonical = "https://clima.github.io/CubedSphere.jl/stable/",
)
pages = [
"Home" => "index.md",
"Conformal Cubed Sphere" => "conformal_cubed_sphere.md",
"References" => "references.md",
"Library" => [
"Contents" => "library/outline.md",
"Public" => "library/public.md",
"Private" => "library/internals.md",
"Function index" => "library/function_index.md",
],
]
bib = CitationBibliography(joinpath(@__DIR__, "src", "references.bib"))
makedocs(
sitename = "CubedSphere.jl",
modules = [CubedSphere],
plugins = [bib],
format = format,
pages = pages,
doctest = true,
clean = true,
checkdocs = :exports
)
deploydocs( repo = "github.com/CliMA/CubedSphere.jl.git",
versions = ["stable" => "v^", "v#.#.#", "dev" => "dev"],
forcepush = true,
devbranch = "main",
push_preview = true
)
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1911 | import Elliptic.Jacobi: sn, cn, dn
"""
sn(z::Complex, m::Real)
Compute the Jacobi elliptic function `sn(z | m)` following [AbramowitzStegun1964](@citet), Eq. 16.21.2.
# References
* [AbramowitzStegun1964](@cite) Abramowitz, M., & Stegun, I. A. (Eds.). (1964). Handbook of mathematical functions with formulas, graphs, and mathematical tables (Vol. 55). US Government Printing Office
"""
@inline function sn(z::Complex, m::Real)
s = sn(real(z), m)
s₁ = sn(imag(z), 1-m)
c = cn(real(z), m)
c₁ = cn(imag(z), 1-m)
d = dn(real(z), m)
d₁ = dn(imag(z), 1-m)
return (s * d₁ + im * c * d * s₁ * c₁) / (c₁^2 + m * s^2 * s₁^2)
end
"""
cn(z::Complex, m::Real)
Compute the Jacobi elliptic function `cn(z | m)` following [AbramowitzStegun1964](@citet), Eq. 16.21.3.
# References
* [AbramowitzStegun1964](@cite) Abramowitz, M., & Stegun, I. A. (Eds.). (1964). Handbook of mathematical functions with formulas, graphs, and mathematical tables (Vol. 55). US Government Printing Office
"""
@inline function cn(z::Complex, m::Real)
s = sn(real(z), m)
s₁ = sn(imag(z), 1-m)
c = cn(real(z), m)
c₁ = cn(imag(z), 1-m)
d = dn(real(z), m)
d₁ = dn(imag(z), 1-m)
return (c * c₁ - im * s * d * s₁ * d₁) / (c₁^2 + m * s^2 * s₁^2)
end
"""
dn(z::Complex, m::Real)
Compute the Jacobi elliptic function `dn(z | m)` following [AbramowitzStegun1964](@citet), Eq. 16.21.4.
# References
* [AbramowitzStegun1964](@cite) Abramowitz, M., & Stegun, I. A. (Eds.). (1964). Handbook of mathematical functions with formulas, graphs, and mathematical tables (Vol. 55). US Government Printing Office
"""
@inline function dn(z::Complex, m::Real)
s = sn(real(z), m)
s₁ = sn(imag(z), 1-m)
c = cn(real(z), m)
c₁ = cn(imag(z), 1-m)
d = dn(real(z), m)
d₁ = dn(imag(z), 1-m)
return (d * c₁ * d₁ - im * m * s * c * s₁) / (c₁^2 + m * s^2 * s₁^2)
end
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 6527 | using FFTW, SpecialFunctions, TaylorSeries, ProgressBars
function find_angles(φ)
φ⁻ = -φ
φ⁺ = +φ
w⁻ = cis(φ⁻)
w⁺ = cis(φ⁺)
w′⁻ = (1 - w⁻) / (1 + w⁻/2)
w′⁺ = (1 - w⁺) / (1 + w⁺/2)
φ′⁻ = angle(w′⁻)
φ′⁺ = angle(w′⁺)
return φ′⁻, φ′⁺
end
# cbrt goes from W to w
# cbrt′ goes from W′ to w′
function Base.cbrt(z::Complex)
r = abs(z)
φ = angle(z) # ∈ [-π, +π]
θ = φ / 3
return cbrt(r) * cis(θ)
end
function cbrt′(z::Complex)
φ′⁻, φ′⁺ = find_angles(π/3)
r = abs(z)
φ = angle(z) # ∈ [-π, +π]
θ = φ / 3
if 0 < θ ≤ φ′⁻
θ -= 2π/3
elseif φ′⁺ ≤ θ < 0
θ += 2π/3
end
return r^(1/3) * cis(θ)
end
"""
find_N(r; decimals=15)
Return the required number of points we need to consider around the circle of
radius `r` to compute the conformal map series coefficients up to `decimals`
points. The number of points is computed based on the estimate of eq. (B9) in
the paper by [Rancic-etal-1996](@citet). That is, is the smallest integer ``N`` (which
is chosen to be a power of 2 so that the FFTs are efficient) for which
```math
N - \\frac{7}{12} \\frac{\\mathrm{log}_{10}(N)}{\\mathrm{log}_{10}(r)} - \\frac{r + \\mathrm{log}_{10}(A₁ / C)}{-4 \\mathrm{log}_{10}(r)} > 0
```
where ``r`` is the number of `decimals` we are aiming for and
```math
C = \\frac{\\sqrt{3} \\Gamma(1/3) A₁^{1/3}}{256^{1/3} π}
```
with ``A₁`` an estimate of the ``Z^1`` Taylor series coefficient of ``W(Z)``.
For ``A₁ ≈ 1.4771`` we get ``C ≈ 0.265``.
# References
* [Rancic-etal-1996](@cite) Rančić et al., *Q. J. R. Meteorol.*, (1996).
"""
function find_N(r; decimals=15)
A₁ = 1.4771 # an approximation of the first coefficient
C = sqrt(3) * gamma(1/3) * A₁^(1/3) / ((256)^(1/3) * π)
N = 2
while N + 7/12 * log10(N) / (-log10(r)) - (decimals + log10(A₁ / C)) / (-4 * log10(r)) < 0
N *= 2
end
return N
end
function _update_coefficients!(A, r, Nφ)
Ncoefficients = length(A)
Lφ = π/2
dφ = Lφ / Nφ
φ = range(-Lφ/2 + dφ/2, stop=Lφ/2 - dφ/2, length=Nφ)
z = @. r * cis(φ)
W̃′ = 0z
for k = Ncoefficients:-1:1
@. W̃′ += A[k] * (1 - z)^(4k)
end
w̃′ = @. cbrt′(W̃′)
w̃ = @. (1 - w̃′) / (1 + w̃′/2)
W̃ = @. w̃^3
k = collect(fftfreq(Nφ, Nφ))
g̃ = fft(W̃) ./ (Nφ * cis.(k * 4φ[1])) # divide with Nϕ * exp(-ikπ) to account for FFT's normalization
g̃ = g̃[2:Ncoefficients+1] # drop coefficient for 0-th power
A .= [real(g̃[k] / r^(4k)) for k in 1:Ncoefficients]
return nothing
end
"""
find_taylor_coefficients(r = 1 - 1e-7;
Niterations = 30,
maximum_coefficients = 256,
Nevaluations = find_N(r; decimals=15))
Return the Taylor coefficients for the conformal map ``Z \\to W`` and also of the
inverse map, ``W \\to Z``, where ``Z = z^4`` and ``W = w^3``. In particular, it returns the
coefficients ``A_k`` of the Taylor series
```math
W(Z) = \\sum_{k=1}^\\infty A_k Z^k
```
and also coefficients ``B_k`` the inverse Taylor series
```math
Z(W) = \\sum_{k=1}^\\infty B_k Z^k
```
The algorithm to obtain the coefficients follows the procedure described in the
Appendix of the paper by [Rancic-etal-1996](@citet)
Arguments
=========
* `r` (positional): the radius about the center and the edge of the cube used in the
algorithm described by [Rancic-etal-1996](@citet). `r` must be less than 1; default: 1 - 10``^{-7}``.
* `maximum_coefficients` (keyword): the truncation for the Taylor series; default: 256.
* `Niterations` (keyword): the number of update iterations we perform on the
Taylor coefficients ``A_k``; default: 30.
* `Nevaluations` (keyword): the number of function evaluations in over the circle of radius `r`;
default `find_N(r; decimals=15)`; see [`find_N`](@ref).
Example
```@example
julia> using CubedSphere
julia> using CubedSphere: find_taylor_coefficients
julia> A, B = find_taylor_coefficients(1 - 1e-4);
[ Info: Computing the first 256 coefficients of the Taylor serieses
[ Info: using 32768 function evaluations on a circle with radius 0.9999.
100.0%┣████████████████████████████████████████████┫ 30/30 [00:02<00:00, 12it/s]
julia> A[1:10]
10-element Vector{Float64}:
1.4771306289227293
-0.3818351018795475
-0.05573057838030261
-0.008958833150428962
-0.007913155711663374
-0.004866251689037038
-0.003292515242976284
-0.0023548122712604494
-0.0017587029515141275
-0.0013568087584722149
```
!!! info "Reproducing coefficient table by Rančić et al. (1996)"
To reproduce the coefficients tabulated by [Rancic-etal-1996](@citet) use
the default values, i.e., ``r = 1 - 10^{-7}``.
# References
* [Rancic-etal-1996](@cite) Rančić et al., *Q. J. R. Meteorol.*, (1996).
"""
function find_taylor_coefficients(r = 1 - 1e-7;
Niterations = 30,
maximum_coefficients = 256,
Nevaluations = find_N(r; decimals=15))
(r < 0 || r ≥ 1) && error("r needs to be within 0 < r < 1")
Ncoefficients = Int(Nevaluations/2) - 2 > maximum_coefficients ? maximum_coefficients : Int(Nevaluations/2) - 2
@info "Computing the first $Ncoefficients coefficients of the Taylor serieses"
@info "using $Nevaluations function evaluations on a circle with radius $r."
# initialize coefficients
A_coefficients = rand(Ncoefficients)
A_coefficients[1:min(maximum_coefficients, 30)] = CubedSphere.A_Rancic[2:min(maximum_coefficients, 30)+1]
A_coefficients_old = deepcopy(A_coefficients)
for iteration in ProgressBar(1:Niterations)
_update_coefficients!(A_coefficients, r, Nevaluations)
rel_error = (abs.(A_coefficients - A_coefficients_old) ./ abs.(A_coefficients))[1:maximum_coefficients]
A_coefficients_old .= A_coefficients
if all(rel_error .< 1e-15)
iteration_str = iteration == 1 ? "iteration" : "iterations"
@info "Algorithm converged after $iteration $iteration_str"
break
end
end
# convert to Taylor series; add coefficient for 0-th power
A_series = Taylor1([0; A_coefficients])
B_series = inverse(A_series) # This is the inverse Taylor series
B_series.coeffs[1] !== 0.0 && error("coefficient that corresponds to W^0 is non-zero; something went wrong")
B_coefficients = B_series.coeffs[2:end] # don't return coefficient for 0-th power
return A_coefficients, B_coefficients
end
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1604 | using GLMakie
using Elliptic
using CubedSphere
"""
visualize_conformal_mapping(w; x_min, y_min, x_max, y_max, n_lines, n_samples, filepath="mapping.png")
Visualize a complex mapping ``w(z)`` from the rectangle `x ∈ [x_min, x_max]`, `y ∈ [y_min, y_max]` using `n_lines`
equally spaced lines in ``x`` and ``y`` each evaluated at `n_samples` sample points.
"""
function visualize_conformal_mapping(w; x_min, y_min, x_max, y_max, n_lines, n_samples, filepath="mapping.png")
z₁ = [[x + im * y for x in range(x_min, x_max, length=n_samples)] for y in range(y_min, y_max, length=n_lines)]
z₂ = [[x + im * y for y in range(y_min, y_max, length=n_samples)] for x in range(x_min, x_max, length=n_lines)]
zs = cat(z₁, z₂, dims=1)
ws = [w.(z) for z in zs]
fig = Figure(size=(1200, 1200), fontsize=30)
ax = Axis(fig[1, 1];
xlabel = "Re(w)",
ylabel = "Im(w)",
aspect = DataAspect())
[lines!(ax, real(z), imag(z), color = :grey) for z in zs]
[lines!(ax, real(w), imag(w), color = :blue) for w in ws]
save(filepath, fig)
display(fig)
end
# maps square (±Ke, ±Ke) to circle of unit radius
w(z) = (1 - cn(z, 1/2)) / sn(z, 1/2)
Ke = Elliptic.F(π/2, 1/2) # ≈ 1.854
visualize_conformal_mapping(w;
x_min = -Ke,
y_min = -Ke,
x_max = Ke,
y_max = Ke,
n_lines = 21,
n_samples = 1000,
filepath = "square_to_disk_conformal_mapping.png")
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 2714 | # Compute Rančić coefficients with the method described in
# [Rancic-etal-1996](@citet)
using GLMakie
using Printf
include("compute_taylor_coefficients.jl")
function plot_transformation(A, r, Nφ; Lφ=π/2)
dφ = Lφ / Nφ
φ = range(-Lφ/2 + dφ/2, stop=Lφ/2 - dφ/2, length=Nφ)
z = @. r * cis(φ)
Z = @. z^4
W = zeros(eltype(z), size(z))
W̃′ = zeros(eltype(z), size(z))
for k = length(A):-1:1
@. W += A[k] * z^(4k)
@. W̃′ += A[k] * (1 - z)^(4k)
end
w = @. cbrt(W)
w′ = @. (1 - w) / (1 + w/2)
W′ = @. w′^3
w̃′ = @. cbrt′(W̃′)
w̃ = @. (1 - w̃′) / (1 + w̃′/2)
W̃ = @. w̃^3
fig = Figure(size=(1200, 1800), fontsize=30)
axz = Axis(fig[1, 1], title="z")
axZ = Axis(fig[1, 2], title="Z")
axw = Axis(fig[2, 1], title="w")
axW = Axis(fig[2, 2], title="W")
axwp = Axis(fig[3, 1], title="w′")
axWp = Axis(fig[3, 2], title="W′")
lim = 2
for ax in (axw, axW)
xlims!(ax, -lim, lim)
ylims!(ax, -lim, lim)
end
lim = 1
for ax in (axwp, axWp)
xlims!(ax, -lim, lim)
ylims!(ax, -lim, lim)
end
lim = 1.5
for ax in (axz, axZ)
xlims!(ax, -lim, lim)
ylims!(ax, -lim, lim)
end
scatter!(axz, real.(z), imag.(z), linewidth=4)
scatter!(axZ, real.(Z), imag.(Z))
scatter!(axw, real.(w), imag.(w), color=(:black, 0.5), linewidth=8, label=L"w")
scatter!(axw, real.(w̃), imag.(w̃), color=(:orange, 0.8), linewidth=4, label=L"w̃")
scatter!(axW, real.(W), imag.(W), color=(:black, 0.5), linewidth=8, label=L"W")
scatter!(axW, real.(W̃), imag.(W̃), color=(:orange, 0.8), linewidth=4, label=L"W̃")
scatter!(axwp, real.(w′), imag.(w′), color=(:black, 0.5), linewidth=8, label=L"w′")
scatter!(axwp, real.(w̃′), imag.(w̃′), color=(:orange, 0.8), linewidth=4, label=L"w̃′")
scatter!(axWp, real.(W′), imag.(W′), color=(:black, 0.5), linewidth=8, label=L"W′")
scatter!(axWp, real.(W̃′), imag.(W̃′), color=(:orange, 0.8), linewidth=4, label=L"W̃′")
for ax in [axw, axW, axwp, axWp]
axislegend(ax)
end
save("consistency.png", fig)
return fig
end
r = 1 - 1e-6
Nφ = find_N(r; decimals=10)
maximum_coefficients = 128
Ncoefficients = Int(Nφ/2) - 2 > maximum_coefficients ? maximum_coefficients : Int(Nφ/2) - 2
Niterations = 30
A, B = find_taylor_coefficients(r; maximum_coefficients, Niterations)
@info "After $Niterations iterations we have:"
for (k, Aₖ) in enumerate(A[1:30])
@printf("k = %2i, A ≈ %+.14f, A_Rancic = %+.14f, |A - A_Rancic| = %.2e \n", k, real(Aₖ), CubedSphere.A_Rancic[k+1], abs(CubedSphere.A_Rancic[k+1] - real(Aₖ)))
end
fig = plot_transformation(A, r, Nφ)
fig
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 268 | module CubedSphere
export conformal_cubed_sphere_mapping, conformal_cubed_sphere_inverse_mapping, cartesian_to_lat_lon
using TaylorSeries
include("rancic_taylor_coefficients.jl")
include("conformal_cubed_sphere.jl")
include("cartesian_to_lat_lon.jl")
end # module
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1073 | """
cartesian_to_lat_lon(x, y, z)
Convert 3D cartesian coordinates `(x, y, z)` on the sphere to latitude-longitude. Returns a tuple
`(latitude, longitude)` in degrees.
The equatorial plane falls at ``z = 0``, latitude is the angle measured from the equatorial plane,
and longitude is measured anti-clockwise (eastward) from ``x``-axis (``y = 0``) about the ``z``-axis.
Examples
========
Find latitude-longitude of the North Pole
```jldoctest 1
julia> using CubedSphere
julia> x, y, z = (0, 0, 6.4e6); # cartesian coordinates of North Pole [in meters]
julia> cartesian_to_lat_lon(x, y, z)
(90.0, 0.0)
```
Let's confirm that for few points on the unit sphere we get the answers we expect.
```jldoctest 1
julia> cartesian_to_lat_lon(√2/4, -√2/4, √3/2)
(59.99999999999999, -45.0)
julia> cartesian_to_lat_lon(-√6/4, √2/4, -√2/2)
(-45.00000000000001, 150.0)
```
"""
cartesian_to_lat_lon(x, y, z) = cartesian_to_latitude(x, y, z), cartesian_to_longitude(x, y, z)
cartesian_to_latitude(x, y, z) = atand(z, hypot(x, y))
cartesian_to_longitude(x, y, z) = atand(y, x)
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 4112 |
W_Rancic(Z) = sum(A_Rancic[k] * Z^(k-1) for k in length(A_Rancic):-1:1)
Z_Rancic(W) = sum(B_Rancic[k] * W^(k-1) for k in length(B_Rancic):-1:1)
"""
conformal_cubed_sphere_mapping(x, y; W_map=W_Rancic)
Conformal mapping from a face of a cube onto the equivalent sector of a sphere with unit radius.
Map the north-pole face of a cube with coordinates ``(x, y)`` onto the equivalent sector of the
sphere with coordinates ``(X, Y, Z)``.
The cube's face oriented normal to ``z``-axis and its coordinates must lie within the
range ``-1 ≤ x ≤ 1``, ``-1 ≤ y ≤ 1`` with its center at ``(x, y) = (0, 0)``. The coordinates
``X, Y`` increase in the same direction as ``x, y``.
The numerical conformal mapping used here is described by [Rancic-etal-1996](@citet).
This is a Julia translation of [MATLAB code from MITgcm](http://wwwcvs.mitgcm.org/viewvc/MITgcm/MITgcm_contrib/high_res_cube/matlab-grid-generator/map_xy2xyz.m?view=markup) that is based on
Fortran 77 code from Jim Purser & Misha Rančić.
Examples
========
The center of the cube's face ``(x, y) = (0, 0)`` is mapped onto ``(X, Y, Z) = (0, 0, 1)``
```jldoctest
julia> using CubedSphere
julia> conformal_cubed_sphere_mapping(0, 0)
(0, 0, 1.0)
```
and the edge of the cube's face at ``(x, y) = (1, 1)`` is mapped onto ``(X, Y, Z) = (√3/3, √3/3, √3/3)``
```jldoctest
julia> using CubedSphere
julia> conformal_cubed_sphere_mapping(1, 1)
(0.5773502691896256, 0.5773502691896256, 0.5773502691896257)
```
# References
* [Rancic-etal-1996](@cite) Rančić et al., *Q. J. R. Meteorol.*, (1996).
"""
function conformal_cubed_sphere_mapping(x, y; W_map=W_Rancic)
(abs(x) > 1 || abs(y) > 1) && throw(ArgumentError("(x, y) must lie within [-1, 1] x [-1, 1]"))
X = xᶜ = abs(x)
Y = yᶜ = abs(y)
kxy = yᶜ > xᶜ
xᶜ = 1 - xᶜ
yᶜ = 1 - yᶜ
kxy && (xᶜ = 1 - Y)
kxy && (yᶜ = 1 - X)
Z = ((xᶜ + im * yᶜ) / 2)^4
W = W_map(Z)
im³ = im^(1/3)
ra = √3 - 1
cb = -1 + im
cc = ra * cb / 2
W = im³ * (W * im)^(1/3)
W = (W - ra) / (cb + cc * W)
X, Y = reim(W)
H = 2 / (1 + X^2 + Y^2)
X = X * H
Y = Y * H
Z = H - 1
if kxy
X, Y = Y, X
end
y < 0 && (Y = -Y)
x < 0 && (X = -X)
# Fix truncation for x = 0 or y = 0.
x == 0 && (X = 0)
y == 0 && (Y = 0)
return X, Y, Z
end
"""
conformal_cubed_sphere_inverse_mapping(X, Y, Z; Z_map=Z_Rancic)
Inverse mapping for conformal cube sphere for quadrant of North-pole face in which `X` and `Y` are both
positive. All other mappings to other cube face coordinates can be recovered from rotations of this map.
There a 3 other quadrants for the north-pole face and five other faces for a total of twenty-four quadrants.
Because of symmetry only the reverse for a single quadrant is needed. Because of branch cuts and the complex
transform the inverse mappings are multi-valued in general, using a single quadrant case allows a simple
set of rules to be applied.
The mapping is valid for the cube face quadrant defined by ``0 < x < 1`` and ``0 < y < 1``, where a full cube
face has extent ``-1 < x < 1`` and ``-1 < y < 1``. The quadrant for the mapping is from a cube face that has
"north-pole" at its center ``(x=0, y=0)``. i.e., has `X, Y, Z = (0, 0, 1)` at its center. The valid ranges of `X`
and `Y` for this mapping and convention are a quadrant defined be geodesics that connect the points A, B, C and D,
on the shell of a sphere of radius ``R`` with `X`, `Y` coordinates as follows
```
A = (0, 0)
B = (√2, 0)
C = (√3/3, √3/3)
D = (0, √2)
```
"""
function conformal_cubed_sphere_inverse_mapping(X, Y, Z; Z_map=Z_Rancic)
H = Z + 1
Xˢ = X / H
Yˢ = Y / H
ω = Xˢ + im * Yˢ
ra = √3 - 1
cb = -1 + im
cc = ra * cb / 2
ω⁰ = (ω * cb + ra) / (1 - ω * cc)
W⁰ = im * ω⁰^3 * im
Z = Z_map(W⁰)
z = 2 * Z^(1/4)
x, y = reim(z)
kxy = abs(y) > abs(x)
xx = x
yy = y
!kxy && ( x = 1 - abs(yy) )
!kxy && ( y = 1 - abs(xx) )
xf = x
yf = y
( X < Y ) && ( xf = y )
( X < Y ) && ( yf = x )
x = xf
y = yf
return x, y
end
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 6527 | using FFTW, SpecialFunctions, TaylorSeries, ProgressBars
function find_angles(φ)
φ⁻ = -φ
φ⁺ = +φ
w⁻ = cis(φ⁻)
w⁺ = cis(φ⁺)
w′⁻ = (1 - w⁻) / (1 + w⁻/2)
w′⁺ = (1 - w⁺) / (1 + w⁺/2)
φ′⁻ = angle(w′⁻)
φ′⁺ = angle(w′⁺)
return φ′⁻, φ′⁺
end
# cbrt goes from W to w
# cbrt′ goes from W′ to w′
function Base.cbrt(z::Complex)
r = abs(z)
φ = angle(z) # ∈ [-π, +π]
θ = φ / 3
return cbrt(r) * cis(θ)
end
function cbrt′(z::Complex)
φ′⁻, φ′⁺ = find_angles(π/3)
r = abs(z)
φ = angle(z) # ∈ [-π, +π]
θ = φ / 3
if 0 < θ ≤ φ′⁻
θ -= 2π/3
elseif φ′⁺ ≤ θ < 0
θ += 2π/3
end
return r^(1/3) * cis(θ)
end
"""
find_N(r; decimals=15)
Return the required number of points we need to consider around the circle of
radius `r` to compute the conformal map series coefficients up to `decimals`
points. The number of points is computed based on the estimate of eq. (B9) in
the paper by [Rancic-etal-1996](@citet). That is, is the smallest integer ``N`` (which
is chosen to be a power of 2 so that the FFTs are efficient) for which
```math
N - \\frac{7}{12} \\frac{\\mathrm{log}_{10}(N)}{\\mathrm{log}_{10}(r)} - \\frac{r + \\mathrm{log}_{10}(A₁ / C)}{-4 \\mathrm{log}_{10}(r)} > 0
```
where ``r`` is the number of `decimals` we are aiming for and
```math
C = \\frac{\\sqrt{3} \\Gamma(1/3) A₁^{1/3}}{256^{1/3} π}
```
with ``A₁`` an estimate of the ``Z^1`` Taylor series coefficient of ``W(Z)``.
For ``A₁ ≈ 1.4771`` we get ``C ≈ 0.265``.
# References
* [Rancic-etal-1996](@cite) Rančić et al., *Q. J. R. Meteorol.*, (1996).
"""
function find_N(r; decimals=15)
A₁ = 1.4771 # an approximation of the first coefficient
C = sqrt(3) * gamma(1/3) * A₁^(1/3) / ((256)^(1/3) * π)
N = 2
while N + 7/12 * log10(N) / (-log10(r)) - (decimals + log10(A₁ / C)) / (-4 * log10(r)) < 0
N *= 2
end
return N
end
function _update_coefficients!(A, r, Nφ)
Ncoefficients = length(A)
Lφ = π/2
dφ = Lφ / Nφ
φ = range(-Lφ/2 + dφ/2, stop=Lφ/2 - dφ/2, length=Nφ)
z = @. r * cis(φ)
W̃′ = 0z
for k = Ncoefficients:-1:1
@. W̃′ += A[k] * (1 - z)^(4k)
end
w̃′ = @. cbrt′(W̃′)
w̃ = @. (1 - w̃′) / (1 + w̃′/2)
W̃ = @. w̃^3
k = collect(fftfreq(Nφ, Nφ))
g̃ = fft(W̃) ./ (Nφ * cis.(k * 4φ[1])) # divide with Nϕ * exp(-ikπ) to account for FFT's normalization
g̃ = g̃[2:Ncoefficients+1] # drop coefficient for 0-th power
A .= [real(g̃[k] / r^(4k)) for k in 1:Ncoefficients]
return nothing
end
"""
find_taylor_coefficients(r = 1 - 1e-7;
Niterations = 30,
maximum_coefficients = 256,
Nevaluations = find_N(r; decimals=15))
Return the Taylor coefficients for the conformal map ``Z \\to W`` and also of the
inverse map, ``W \\to Z``, where ``Z = z^4`` and ``W = w^3``. In particular, it returns the
coefficients ``A_k`` of the Taylor series
```math
W(Z) = \\sum_{k=1}^\\infty A_k Z^k
```
and also coefficients ``B_k`` the inverse Taylor series
```math
Z(W) = \\sum_{k=1}^\\infty B_k Z^k
```
The algorithm to obtain the coefficients follows the procedure described in the
Appendix of the paper by [Rancic-etal-1996](@citet)
Arguments
=========
* `r` (positional): the radius about the center and the edge of the cube used in the
algorithm described by [Rancic-etal-1996](@citet). `r` must be less than 1; default: 1 - 10``^{-7}``.
* `maximum_coefficients` (keyword): the truncation for the Taylor series; default: 256.
* `Niterations` (keyword): the number of update iterations we perform on the
Taylor coefficients ``A_k``; default: 30.
* `Nevaluations` (keyword): the number of function evaluations in over the circle of radius `r`;
default `find_N(r; decimals=15)`; see [`find_N`](@ref).
Example
```@example
julia> using CubedSphere
julia> using CubedSphere: find_taylor_coefficients
julia> A, B = find_taylor_coefficients(1 - 1e-4);
[ Info: Computing the first 256 coefficients of the Taylor serieses
[ Info: using 32768 function evaluations on a circle with radius 0.9999.
100.0%┣████████████████████████████████████████████┫ 30/30 [00:02<00:00, 12it/s]
julia> A[1:10]
10-element Vector{Float64}:
1.4771306289227293
-0.3818351018795475
-0.05573057838030261
-0.008958833150428962
-0.007913155711663374
-0.004866251689037038
-0.003292515242976284
-0.0023548122712604494
-0.0017587029515141275
-0.0013568087584722149
```
!!! info "Reproducing coefficient table by Rančić et al. (1996)"
To reproduce the coefficients tabulated by [Rancic-etal-1996](@citet) use
the default values, i.e., ``r = 1 - 10^{-7}``.
# References
* [Rancic-etal-1996](@cite) Rančić et al., *Q. J. R. Meteorol.*, (1996).
"""
function find_taylor_coefficients(r = 1 - 1e-7;
Niterations = 30,
maximum_coefficients = 256,
Nevaluations = find_N(r; decimals=15))
(r < 0 || r ≥ 1) && error("r needs to be within 0 < r < 1")
Ncoefficients = Int(Nevaluations/2) - 2 > maximum_coefficients ? maximum_coefficients : Int(Nevaluations/2) - 2
@info "Computing the first $Ncoefficients coefficients of the Taylor serieses"
@info "using $Nevaluations function evaluations on a circle with radius $r."
# initialize coefficients
A_coefficients = rand(Ncoefficients)
A_coefficients[1:min(maximum_coefficients, 30)] = CubedSphere.A_Rancic[2:min(maximum_coefficients, 30)+1]
A_coefficients_old = deepcopy(A_coefficients)
for iteration in ProgressBar(1:Niterations)
_update_coefficients!(A_coefficients, r, Nevaluations)
rel_error = (abs.(A_coefficients - A_coefficients_old) ./ abs.(A_coefficients))[1:maximum_coefficients]
A_coefficients_old .= A_coefficients
if all(rel_error .< 1e-15)
iteration_str = iteration == 1 ? "iteration" : "iterations"
@info "Algorithm converged after $iteration $iteration_str"
break
end
end
# convert to Taylor series; add coefficient for 0-th power
A_series = Taylor1([0; A_coefficients])
B_series = inverse(A_series) # This is the inverse Taylor series
B_series.coeffs[1] !== 0.0 && error("coefficient that corresponds to W^0 is non-zero; something went wrong")
B_coefficients = B_series.coeffs[2:end] # don't return coefficient for 0-th power
return A_coefficients, B_coefficients
end
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1073 | # Coefficients taken from Table B1 of Rančić et al., (1996): Quarterly Journal of the Royal Meteorological Society,
# A global shallow-water model using an expanded spherical cube - Gnomonic versus conformal coordinates
A_Rancic = [
+0.00000000000000,
+1.47713062600964,
-0.38183510510174,
-0.05573058001191,
-0.00895883606818,
-0.00791315785221,
-0.00486625437708,
-0.00329251751279,
-0.00235481488325,
-0.00175870527475,
-0.00135681133278,
-0.00107459847699,
-0.00086944475948,
-0.00071607115121,
-0.00059867100093,
-0.00050699063239,
-0.00043415191279,
-0.00037541003286,
-0.00032741060100,
-0.00028773091482,
-0.00025458777519,
-0.00022664642371,
-0.00020289261022,
-0.00018254510830,
-0.00016499474461,
-0.00014976117168,
-0.00013646173946,
-0.00012478875823,
-0.00011449267279,
-0.00010536946150,
-0.00009725109376
]
A_series = Taylor1(A_Rancic)
B_series = inverse(A_series) # This is the inverse Taylor series.
B_Rancic = B_series.coeffs
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | code | 1593 | using Test
using CubedSphere
using Documenter
B_Rancic_correct = [
0.00000000000000,
0.67698819751739,
0.11847293456554,
0.05317178134668,
0.02965810434052,
0.01912447304028,
0.01342565621117,
0.00998873323180,
0.00774868996406,
0.00620346979888,
0.00509010874883,
0.00425981184328,
0.00362308956077,
0.00312341468940,
0.00272360948942,
0.00239838086555,
0.00213001905118,
0.00190581316131,
0.00171644156404,
0.00155493768255,
0.00141600715207,
0.00129556597754,
0.00119042140226,
0.00109804711790,
0.00101642216628,
0.00094391366522,
0.00087919021224,
0.00082115710311,
0.00076890728775,
0.00072168382969,
0.00067885087750
]
@testset "CubedSphere" begin
@testset "Rančić et al. (1996) Taylor coefficients" begin
for k in eachindex(B_Rancic_correct)
@test CubedSphere.B_Rancic[k] ≈ B_Rancic_correct[k]
end
end
@testset "Rančić et al. (1996) inverse mapping" begin
ξ = collect(0:0.1:1)
η = collect(0:0.1:1)
ξ′ = 0ξ
η′ = 0η
# transform from cube -> sphere -> cube
for j in eachindex(η), i in eachindex(ξ)
ξ′[i], η′[j] = conformal_cubed_sphere_inverse_mapping(conformal_cubed_sphere_mapping(ξ[i], η[j])...)
end
@test ξ ≈ ξ′ && η ≈ η′
end
@test_throws ArgumentError conformal_cubed_sphere_mapping(2, 0.5)
@test_throws ArgumentError conformal_cubed_sphere_mapping(0.5, -2)
end
@time @testset "Doctests" begin
doctest(CubedSphere)
end
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | docs | 361 | CubedSphere.jl Release Notes
===============================
v0.3.0
------
We moved `conformal_map_tylor_coefficients.jl` and `complex_jacobi_ellptic.jl`
from main package to `sandbox`. This allowed us to remove most dependencies of
`CubedSphere.jl`. `sandbox` now contains a Julia environment with the packages
needed to execute the scripts in that folder.
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
|
[
"MIT"
] | 0.3.0 | 51bb25de518b4c62b7cdf26e5fbb84601bb27a60 | docs | 732 | # CubedSphere.jl
<p align="center">
<a href="https://clima.github.io/CubedSphere.jl/stable">
<img alt="Stable documentation" src="https://img.shields.io/badge/documentation-stable%20release-blue?style=flat-square">
</a>
<a href="https://clima.github.io/CubedSphere.jl/dev">
<img alt="Development documentation" src="https://img.shields.io/badge/documentation-in%20development-orange?style=flat-square">
</a>
</p>
Tools for generating cubed sphere grids and solving partial differential equations on the sphere.

(A visualization of the conformal transform that maps the faces of a cube onto the sphere.)
| CubedSphere | https://github.com/CliMA/CubedSphere.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.