licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
26283
# * N-body term factors """ NBodyTermFactor Abstract type for a factor in a term in a N-body matrix element expansion """ abstract type NBodyTermFactor end # ** Orbital overlaps """ OrbitalOverlap(a,b) Represents the overlap between the orbitals `a` and `b` in a N-body matrix element expansion. # Examples ```jldoctest julia> EnergyExpressions.OrbitalOverlap(:a,:b) ⟨a|b⟩ ``` """ struct OrbitalOverlap{A,B} <: NBodyTermFactor a::A b::B end # By default, we assume that all orbital overlaps are non-zero, # i.e. the orbitals are non-orthogonal, since we specify # non-orthogonality precisely by providing OrbitalOverlaps. Base.iszero(::OrbitalOverlap) = false Base.:(==)(a::OrbitalOverlap, b::OrbitalOverlap) = a.a == b.a && a.b == b.b Base.hash(o::OrbitalOverlap, h::UInt) = hash(hash(hash(o.a), hash(o.b)), h) Base.adjoint(o::OrbitalOverlap{A,B}) where {A,B} = OrbitalOverlap{B,A}(o.b, o.a) """ numbodies(::OrbitalOverlap) Returns the number of bodies coupled by the zero-body operator in the orbital overlap, i.e. `0`. """ numbodies(::OrbitalOverlap) = 0 """ isdependent(o::OrbitalOverlap, orbital) Returns `true` if the [`OrbitalOverlap`](@ref) `o` depends on `orbital`. # Examples ```jldoctest julia> isdependent(OrbitalOverlap(:a,:b), :a) false julia> isdependent(OrbitalOverlap(:a,:b), Conjugate(:a)) true julia> isdependent(OrbitalOverlap(:a,:b), :b) true ``` """ isdependent(o::OrbitalOverlap, corb::Conjugate{O}) where O = o.a == corb.orbital isdependent(o::OrbitalOverlap, orb::O) where O = o.b == orb Base.show(io::IO, o::OrbitalOverlap) = write(io, "⟨$(o.a)|$(o.b)⟩") # ** Orbital matrix elements """ OrbitalMatrixElement(a,o,b) Represents the N-body matrix element between the sets of orbitals `a` and `b`. # Examples ```jldoctest julia> struct MyTwoBodyOperator <: TwoBodyOperator end julia> EnergyExpressions.OrbitalMatrixElement((:a,:b), MyTwoBodyOperator(), (:c,:d)) ⟨a b|MyTwoBodyOperator()|c d⟩ ``` """ struct OrbitalMatrixElement{N,A,O<:NBodyOperator{N},B} <: NBodyTermFactor a::Vector{A} o::O b::Vector{B} function OrbitalMatrixElement(a::Vector{A}, o::O, b::Vector{B}) where {N,A,O<:NBodyOperator{N},B} la = length(a) lb = length(b) la == lb == N || throw(ArgumentError("Number of orbitals $(la) and $(lb) do not agree with N = $N")) new{N,A,O,B}(a, o, b) end end Base.iszero(::OrbitalMatrixElement) = false Base.:(==)(a::OrbitalMatrixElement, b::OrbitalMatrixElement) = a.a == b.a && a.o == b.o && a.b == b.b Base.hash(ome::OrbitalMatrixElement, h::UInt) = hash(hash(hash(hash(ome.a), hash(ome.o)), hash(ome.b)), h) Base.adjoint(ome::OrbitalMatrixElement) = OrbitalMatrixElement(ome.b, adjoint(ome.o), ome.a) """ numbodies(::OrbitalMatrixElement{N}) Returns the number of bodies coupled by the operator, i.e. `N`. """ numbodies(::OrbitalMatrixElement{N}) where N = N """ contract(ome::OrbitalMatrixElement{N}, i...) Contract `ome` over all coordinates `i...`. `length(i)` cannot be larger than `N`. """ function contract(ome::OrbitalMatrixElement{N,A,O,B}, i::Integer...) where {N,A,O,B} Q = length(i) Q ≤ N || throw(ArgumentError("Cannot contract $(N)-body orbital matrix element over $(length(i)) coordinates")) iszero(Q) && return ome.o ContractedOperator(NTuple{Q,A}(ome.a[ii] for ii in i), ome.o, NTuple{Q,B}(ome.b[ii] for ii in i)) end """ isdependent(o::OrbitalMatrixElement, orbital) Returns `true` if the [`OrbitalMatrixElement`](@ref) `o` depends on `orbital`. # Examples ```jldoctest julia> isdependent(EnergyExpressions.OrbitalMatrixElement((:a,), OneBodyHamiltonian(), (:b,)), :a) false julia> isdependent(EnergyExpressions.OrbitalMatrixElement((:a,), OneBodyHamiltonian(), (:b,)), Conjugate(:a)) true julia> isdependent(EnergyExpressions.OrbitalMatrixElement((:a,), OneBodyHamiltonian(), (:b,)), :b) true julia> isdependent(EnergyExpressions.OrbitalMatrixElement((:a,:b,), CoulombInteraction(), (:c,:d)), :c) true ``` """ isdependent(o::OrbitalMatrixElement, corb::Conjugate{O}) where O = corb.orbital ∈ o.a isdependent(o::OrbitalMatrixElement, orb::O) where O = orb ∈ o.b function Base.show(io::IO, ome::OrbitalMatrixElement{N}) where N write(io, "⟨", join(string.(ome.a), " ")) N > 0 && write(io, "|") show(io, ome.o) N > 0 && write(io, "|") write(io, join(string.(ome.b), " "), "⟩") end # * N-body terms """ NBodyTerm(factors, coeff) Structure representing one term in the expansion of a N-body matrix element. """ struct NBodyTerm factors::Vector{NBodyTermFactor} coeff end Base.:(==)(a::NBodyTerm, b::NBodyTerm) = compare_vectors(a.factors, b.factors) && a.coeff == b.coeff Base.hash(nbt::NBodyTerm, h::UInt) = hash(hash(hash(nbt.factors), hash(nbt.coeff)), h) Base.one(::Type{NBodyTerm}) = NBodyTerm(NBodyTermFactor[], 1) Base.one(::NBodyTerm) = one(NBodyTerm) Base.isone(term::NBodyTerm) = isempty(term.factors) && isone(term.coeff) isminusone(term::NBodyTerm) = isempty(term.factors) && isone(-term.coeff) Base.zero(::Type{NBodyTerm}) = NBodyTerm(NBodyTermFactor[], 0) Base.zero(::NBodyTerm) = zero(NBodyTerm) Base.iszero(term::NBodyTerm) = iszero(term.coeff) || any(iszero.(term.factors)) LinearAlgebra.adjoint(nbt::NBodyTerm) = NBodyMatrixElement(conj(nbt.coeff)*prod(adjoint.(nbt.factors))) Base.convert(::Type{NBodyTerm}, f::NBodyTermFactor) = NBodyTerm([f], 1) Base.convert(::Type{T}, nbt::NBodyTerm) where {T<:Number} = convert(T, nbt.coeff)*prod(f -> convert(T, f), nbt.factors) Base.:(*)(a::NBodyTerm, b::NBodyTerm) = NBodyTerm(vcat(a.factors, b.factors), a.coeff*b.coeff) Base.:(*)(a::NBodyTerm, b::Number) = NBodyTerm(a.factors, a.coeff*b) Base.:(*)(a::Number, b::NBodyTerm) = NBodyTerm(b.factors, a*b.coeff) Base.:(-)(f::NBodyTerm) = (-1)*f Base.:(*)(a::NBodyTerm, b::NBodyTermFactor) = NBodyTerm(vcat(a.factors, b), a.coeff) Base.:(*)(a::NBodyTermFactor, b::NBodyTerm) = NBodyTerm(vcat(a, b.factors), b.coeff) Base.:(*)(a::NBodyTermFactor, b::NBodyTermFactor) = NBodyTerm([a, b], 1) Base.:(+)(a::NBodyTermFactor, b::NBodyTermFactor) = convert(NBodyTerm, a) + convert(NBodyTerm, b) Base.:(+)(a::NBodyTerm, b::NBodyTermFactor) = a + convert(NBodyTerm, b) Base.:(+)(a::NBodyTermFactor, b::NBodyTerm) = convert(NBodyTerm, a) + b Base.:(*)(a::NBodyTermFactor, b::Number) = NBodyTerm([a], b) Base.:(*)(a::Number, b::NBodyTermFactor) = NBodyTerm([b], a) Base.:(-)(f::NBodyTermFactor) = (-1)*f """ isdependent(nbt::NBodyTerm, o) Returns `true` if any of the factors comprising `nbt` is dependent on the orbital `o`. Not that the result is dependent on whether `o` is conjugated or not. """ isdependent(nbt::NBodyTerm, o) = any(isdependent.(nbt.factors, Ref(o))) """ transform(f::Function, nbt::NBodyTerm) Transform integrals of the the N-body matrix element expansion term `nbt` according to the function `f`, which should accept a single [`NBodyTermFactor`](@ref) as its argument. """ function transform(f::Function, nbt::NBodyTerm) isempty(nbt.factors) && return NBodyMatrixElement([nbt]) # Generate the starting N-body matrix element by applying the # transform function `f` on the first factor of the NBodyTerm nbt. nbme = [nbt.coeff*f(first(nbt.factors))] # Then generate successively larger expansion by multiplying all # previous terms by the transformation of the current factor. for fac in nbt.factors[2:end] nbme[1] = sum([term*f(fac) for term in nbme[1].terms]) end nbme[1] end function Base.show(io::IO, term::NBodyTerm; show_sign=false) showcoeff(io, term.coeff, show_sign, isempty(term.factors)) (iszero(term) || isempty(term.factors)) && return noprintfactors = 2 factors = if get(io, :limit, false) && length(term.factors) > 2noprintfactors vcat(term.factors[1:noprintfactors], "…", term.factors[end-(noprintfactors-1):end]) else term.factors end write(io, join(string.(factors), "")) end # * N-body matrix elements """ NBodyMatrixElement(terms) Structure representing the expansion of a N-body matrix element. """ struct NBodyMatrixElement terms::Vector{NBodyTerm} end NBodyMatrixElement(term::NBodyTerm) = NBodyMatrixElement([term]) Base.zero(::Type{NBodyMatrixElement}) = NBodyMatrixElement(NBodyTerm[]) Base.zero(::NBodyMatrixElement) = zero(NBodyMatrixElement) Base.one(::Type{NBodyMatrixElement}) = NBodyMatrixElement([one(NBodyTerm)]) Base.one(::NBodyMatrixElement) = one(NBodyMatrixElement) Base.iszero(nbme::NBodyMatrixElement) = isempty(nbme.terms) || all(iszero, nbme.terms) Base.isone(nbme::NBodyMatrixElement) = nbme.terms == [one(NBodyTerm)] Base.convert(::Type{NBodyMatrixElement}, nbt::NBodyTerm) = NBodyMatrixElement([nbt]) Base.convert(::Type{NBodyMatrixElement}, n::Number) = n*one(NBodyMatrixElement) Base.:(+)(a::NBodyMatrixElement, b::NBodyMatrixElement) = NBodyMatrixElement(vcat(a.terms, b.terms)) Base.:(+)(a::NBodyMatrixElement, b::NBodyTerm) = NBodyMatrixElement(vcat(a.terms, b)) Base.:(+)(a::NBodyTerm, b::NBodyMatrixElement) = NBodyMatrixElement(vcat(a, b.terms)) Base.:(+)(a::NBodyMatrixElement, b::NBodyTermFactor) = a + convert(NBodyTerm, b) Base.:(+)(a::NBodyTermFactor, b::NBodyMatrixElement) = convert(NBodyTerm, a) + b function Base.:(+)(a::NBodyTerm, b::NBodyTerm) if a.factors == b.factors NBodyTerm(a.factors, a.coeff+b.coeff) else NBodyMatrixElement([a, b]) end end Base.:(-)(a::NBodyTerm, b::NBodyTerm) = a + (-b) Base.:(*)(a::NBodyMatrixElement, b::Union{Number,NBodyTerm,NBodyTermFactor}) = NBodyMatrixElement([b*t for t in a.terms]) Base.:(*)(a::Union{Number,NBodyTerm,NBodyTermFactor}, b::NBodyMatrixElement) = NBodyMatrixElement([a*t for t in b.terms]) Base.:(-)(f::NBodyMatrixElement) = (-1)*f Base.:(-)(a::Union{NBodyTerm,NBodyTermFactor,NBodyMatrixElement}, b::Union{NBodyTerm,NBodyTermFactor,NBodyMatrixElement}) = a + (-b) Base.convert(::Type{T}, nbme::NBodyMatrixElement) where {T<:Number} = sum(t -> convert(T, t), nbme.terms) function Base.show(io::IO, nbme::NBodyMatrixElement) if iszero(nbme) write(io, "0") return end noprintterms = 6 nterms = length(nbme.terms) for (i,term) in enumerate(nbme.terms) if get(io, :limit, false) && i > noprintterms && i ≤ nterms-noprintterms i == noprintterms+1 && write(io, " + …") else i > 1 && write(io, " ") show(io, term, show_sign=(i > 1)) end end end # ** Comparison of NBodyMatrixElements """ compare(a::NBodyMatrixElement, op, b::NBodyMatrixElement; kwargs...) Compare the [`NBodyMatrixElement`](@ref)s `a` and `b` for similarity; all the terms of `a` need to be present in `b`, and vice versa, and their expansion coefficients have to agree when compared using `op`. This function is mainly designed for testing purposes, i.e. to compare an expression with a reference, generated otherwise. It may not be performant. It may also fail on edge cases. """ function compare(a::NBodyMatrixElement, op, b::NBodyMatrixElement; kwargs...) iszero(a) && iszero(b) && return op(0, 0) ad,bd = map((a,b)) do o od = Dict{Vector{NBodyTermFactor},Number}() for term in o.terms c = get(od, term.factors, 0.0) od[term.factors] = c + term.coeff end od end length(keys(ad)) == length(keys(bd)) || return false isempty(setdiff(keys(ad), keys(bd))) || return false for (ak,ac) in pairs(ad) op(ac, bd[ak]; kwargs...) || return false end true end """ Base.:(==)(a::NBodyMatrixElement, b::NBodyMatrixElement; kwargs...) Test if `a` and `b` are exactly equal to each other, i.e. their terms all agree exactly, as well as the expansion coefficients. The actual comparison is performed by [`compare`](@ref). """ Base.:(==)(a::NBodyMatrixElement, b::NBodyMatrixElement) = compare(a, ==, b) Base.:(==)(a::NBodyMatrixElement, b::NBodyTerm) = a == convert(NBodyMatrixElement, b) Base.:(==)(a::NBodyTerm, b::NBodyMatrixElement) = convert(NBodyMatrixElement, a) == b """ Base.isapprox(a::NBodyMatrixElement, b::NBodyMatrixElement; kwargs...) Test if `a` and `b` are approximately equal to each other, i.e. their terms all agree exactly, and the expansion coefficients are approximately equal. The actual comparison is performed by [`compare`](@ref). """ Base.isapprox(a::NBodyMatrixElement, b::NBodyMatrixElement; kwargs...) = compare(a, ≈, b; kwargs...) Base.hash(nbme::NBodyMatrixElement, h::UInt) = hash(nbme.terms, h) # ** Determinant utilities """ detaxis(i::CartesianIndex{N}) Generate the axis index vector for the determinant minor, whose rows or columns represented by the `CartesianIndex` `i` should be omitted. Implemented via [`complement`](@ref). """ detaxis(i::AbstractVector, n) = complement(n, i) detaxis(i::Tuple, n) = complement(n, i...) detaxis(i::CartesianIndex, n) = complement(n, Tuple(i)...) detaxis(i::Integer, n) = complement(n, i) """ detminor(k, l, A) Calculate the [determinant minor](https://en.wikipedia.org/wiki/Minor_(linear_algebra)) of `A`, where the rows `k` and the columns `l` have been stricken out. """ function detminor(k, l, A) n = size(A,1) n == 1 && isempty(k) && return A[1] det(A[detaxis(k,n),detaxis(l,n)]) end indexsum(k::Integer,l::Integer) = k+l indexsum(k::Tuple,l::Tuple) = sum(k) + sum(l) indexsum(k::AbstractVector,l::AbstractVector) = sum(k) + sum(l) indexsum(k::CartesianIndex,l::CartesianIndex) = indexsum(Tuple(k), Tuple(l)) """ powneg1(k) = (-)ᵏ Calculates powers of negative unity for integer `k`. """ powneg1(k::Integer) = isodd(k) ? -1 : 1 """ cofactor(k, l, A) Calculate the [cofactor](https://en.wikipedia.org/wiki/Minor_(linear_algebra)) of `A`, where the rows `k` and the columns `l` have been stricken out. The cofactor is calculated recursively, by expanding the minor determinants in cofactors, so this function should only be used in case it is known that the cofactor is non-zero. """ cofactor(k, l, A) = powneg1(indexsum(k,l))*detminor(k, l, A) function merge_overlapping_blocks(blocks::Vector{UnitRange{Int}}) blocks = sort(blocks, by=first) new_blocks = [first(blocks)] for b in blocks cur_block = new_blocks[end] if isempty(cur_block ∩ b) push!(new_blocks, b) else new_blocks[end] = min(cur_block[1],b[1]):max(cur_block[end],b[end]) end end new_blocks end function find_diagonal_blocks(A::AbstractSparseMatrix) m,n = size(A) m == n || throw(ArgumentError("Matrix must be square")) rows = rowvals(A) # Find the row extent of each column, including the diagonal; each # column is tentatively its own diagonal block. blocks = map(1:n) do j j_rows = rows[nzrange(A,j)] min(j,minimum(j_rows)):max(j,maximum(j_rows)) end merge_overlapping_blocks(blocks) end function block_det(A::AbstractSparseMatrix{T}, blocks::Vector{UnitRange{Int}}) where T D = one(T) for b in blocks if length(b) > 1 D *= det(A[b,b]) else i = b[1] D *= A[i,i] end end D end """ det(A) Calculate the determinant of the matrix `A` whose elements are of the [`NBodyTerm`](@ref) type, by expanding the determinant along the first column. This is an expensive operation, and should only be done with relatively sparse matrices. """ function LinearAlgebra.det(A::AbstractSparseMatrix{<:NBodyTerm}) m,n = size(A) # Some trivial special cases (m,n) == (0,0) && return 1 (m,n) == (1,1) && return A[1,1] iszero(A) && return zero(NBodyMatrixElement) # If the matrix is too large, we try to break it up in smaller # diagonal blocks; however, if we only get one block back, we have # to apply the general case. if m > 5 blocks = find_diagonal_blocks(A) length(blocks) > 1 && return block_det(A, blocks) end # The general case, Laplace expansion. D = zero(NBodyMatrixElement) j = 1 # Expand along first column for i = 1:m iszero(A[i,j]) && continue Cᵢⱼ = cofactor(i,j,A) iszero(Cᵢⱼ) && continue D += A[i,j]*Cᵢⱼ end D end """ permutation_sign(p) Calculate the sign of the permutation `p`, 1 if `iseven(p)`, -1 otherwise. """ permutation_sign(p) = iseven(Combinatorics.parity(p)) ? 1 : -1 # ** N-body matrix construction """ distinct_permutations(fun::Function, ::NBodyOperator{N}, b) Generate all distinct permutations `p` of `b` (which is expected to be of length `N`), and call `fun(σ, b[p])` where `σ=(-1)^p` is the sign of the permutation `p`. """ @generated function distinct_permutations(fun::Function, ::NBodyOperator{N}, b) where N quote jN = zeros(Int, $N) @anti_diagonal_loop $N j N begin Base.Cartesian.@nexprs $N d -> jN[d] = j_d fun(permutation_sign(jN), b[[jN...]]) end end end """ NBodyMatrixElement(a, op, b, nzcofactors) Generate the matrix element of the N-body operator `op`, between the orbital sets `a` and `b`, where `nzcofactors` list all N-tuples for which the determinantal cofactor of the orbital overlap matrix is non-vanishing. """ function NBodyMatrixElement(a, op::NBodyOperator{N}, b, nzcofactors) where N length(a) == length(b) || throw(DimensionMismatch("Different number of orbitals")) terms = NBodyTerm[] for (k,l,Dkl) in nzcofactors iszero(Dkl) && continue ak = a[k] distinct_permutations(op, b[l]) do σ, bl me = OrbitalMatrixElement(ak, op, bl) iszero(me) && return nbme = convert(NBodyMatrixElement, σ*Dkl*me) append!(terms, nbme.terms) end end NBodyMatrixElement(terms) end """ NBodyMatrixElement(a, op, b, overlap) Generate the matrix element of the N-body operator `op`, between the Slater determinants `a` and `b`, according to the Löwdin rules. The matrix `overlap` contains the mutual overlaps between all single-particle orbitals in the Slater determinants. If the orbitals are all orthogonal, the Löwdin rules collapse to the Slater–Condon rules. """ function NBodyMatrixElement(a::SlaterDeterminant, op::NBodyOperator{N}, b::SlaterDeterminant, overlap::AbstractMatrix) where N ks,ls = nonzero_minors(N, overlap) nzcofactors = zip(ks, ls, (cofactor(k, l, overlap) for (k,l) in zip(ks,ls))) NBodyMatrixElement(a.orbitals, op, b.orbitals, nzcofactors) end """ NBodyMatrixElement(a, op, b, overlap) Generate the matrix element of `op`, a linear combination of [`NBodyOperator`](@ref), between the configurations (e.g. Slater determinants) `a` and `b`, according to the Löwdin rules. The matrix `overlap` contains the mutual overlaps between all single-particle orbitals in the Slater determinants. If the orbitals are all orthogonal, the Löwdin rules collapse to the Slater–Condon rules. """ function NBodyMatrixElement(a::Cfg, op::LinearCombinationOperator, b::Cfg, overlap) where Cfg terms = NBodyTerm[] for (o,coeff) in op.operators iszero(coeff) && continue nbme = coeff*NBodyMatrixElement(a, o, b, overlap) !iszero(nbme) && append!(terms, nbme.terms) end NBodyMatrixElement(terms) end """ transform(f::Function, nbme::NBodyMatrixElement) Transform integrals of the the N-body matrix element `nbme` according to the function `f`, which should accept a single [`NBodyTermFactor`](@ref) as its argument, and return a [`NBodyMatrixElement`](@ref). This is useful for adapting energy expressions to specific symmetries of the system under consideration. """ function transform(f::Function, nbme::NBodyMatrixElement) iszero(nbme) && return nbme sum(map(t -> transform(f, t), nbme.terms)) end LinearAlgebra.adjoint(nbme::NBodyMatrixElement) = sum(adjoint.(nbme.terms)) # * Overlap matrices function overlap_matrix!(S::AbstractSparseMatrix{<:NBodyTerm}, a::Cfg, b::Cfg) where Cfg num_electrons(a) == num_electrons(b) || throw(ArgumentError("Configurations not of same length: $a & $b")) for (i,ao) in enumerate(orbitals(a)) for (j,bo) in enumerate(orbitals(b)) if ao == bo S[i,j] = one(NBodyTerm) end end end S end """ overlap_matrix(a::Cfg, b::Cfg[, overlaps=[]]) where Cfg Generate the single-particle orbital overlap matrix, between the orbitals in the configurations (e.g. Slater determinants) `a` and `b`. All orbitals are assumed to be orthogonal, except for those which are given in `overlaps`. # Examples First we define two Slater determinants that have some orbitals in common: ```jldoctest overlap_matrix julia> sa = SlaterDeterminant([:i, :j, :l,:k̃]) i(1)j(2)l(3)k̃(4) - i(1)j(2)l(4)k̃(3) - i(1)j(3)l(2)k̃(4) + i(1)j(3)l(4)k̃(2) + … + i(4)j(1)l(3)k̃(2) + i(4)j(2)l(1)k̃(3) - i(4)j(2)l(3)k̃(1) - i(4)j(3)l(1)k̃(2) + i(4)j(3)l(2)k̃(1) julia> sb = SlaterDeterminant([:i, :j, :k, :l̃]) i(1)j(2)k(3)l̃(4) - i(1)j(2)k(4)l̃(3) - i(1)j(3)k(2)l̃(4) + i(1)j(3)k(4)l̃(2) + … + i(4)j(1)k(3)l̃(2) + i(4)j(2)k(1)l̃(3) - i(4)j(2)k(3)l̃(1) - i(4)j(3)k(1)l̃(2) + i(4)j(3)k(2)l̃(1) ``` The orbital overlap matrix by default is ```jldoctest overlap_matrix julia> overlap_matrix(sa, sb) 4×4 SparseArrays.SparseMatrixCSC{EnergyExpressions.NBodyTerm,Int64} with 2 stored entries: [1, 1] = 1 [2, 2] = 1 ``` which has only two non-zero entries, since only two of the orbitals are common between the Slater determinants `sa` and `sb`. We can then define that the orbitals `k̃` and `l̃` are non-orthogonal: ```jldoctest overlap_matrix julia> overlap_matrix(sa, sb, [OrbitalOverlap(:k̃,:l̃)]) 4×4 SparseArrays.SparseMatrixCSC{EnergyExpressions.NBodyTerm,Int64} with 3 stored entries: [1, 1] = 1 [2, 2] = 1 [4, 4] = ⟨k̃|l̃⟩ ``` We can even specify that the orbital `k̃` is non-orthogonal to _itself_ (this can be useful when the `k̃` is a linear combination of orthogonal orbitals): ```jldoctest overlap_matrix julia> overlap_matrix(sa, sa, [OrbitalOverlap(:k̃,:k̃)]) 4×4 SparseArrays.SparseMatrixCSC{EnergyExpressions.NBodyTerm,Int64} with 4 stored entries: [1, 1] = 1 [2, 2] = 1 [3, 3] = 1 [4, 4] = ⟨k̃|k̃⟩ ``` Notice that this overlap matrix was calculated between the Slater determinant `sa` and itself. """ function overlap_matrix(a::Cfg, b::Cfg, overlaps::Vector{<:OrbitalOverlap}=OrbitalOverlap[]) where Cfg m = length(orbitals(a)) n = length(orbitals(b)) S = spzeros(NBodyTerm, m, n) overlap_matrix!(S, a, b) add_overlap! = (oa, ob) -> begin i = findfirst(isequal(oa), orbitals(a)) isnothing(i) && return j = findfirst(isequal(ob), orbitals(b)) isnothing(j) && return S[i,j] = OrbitalOverlap(oa,ob) end for overlap in overlaps add_overlap!(overlap.a,overlap.b) add_overlap!(overlap.b,overlap.a) end S end # * Energy expression matrix """ EnergyExpression An energy expression is given by an energy matrix, or interaction matrix, sandwiched between a vector of mixing coefficients: `E = c'H*c`, where `c` are the mixing coefficients and `H` the energy matrix. """ const EnergyExpression = SparseMatrixCSC{NBodyMatrixElement} """ Matrix(a, op::QuantumOperator, b[, overlaps]) Generate the matrix corresponding to the quantum operator `op`, between the configurations (e.g. [`SlaterDeterminant`](@ref)s) `a` and `b`, i.e `⟨a|op|b⟩`. It is possible to specify non-orthogonalities between single-particle orbitals in `overlaps`. """ function Base.Matrix(as::CFGs, op::QuantumOperator, bs::CFGs, overlaps::Vector{<:OrbitalOverlap}=OrbitalOverlap[]; verbosity=0) where {CFGs<:AbstractVector} m,n = length(as),length(bs) I = [Int[] for i in 1:Threads.nthreads()] J = [Int[] for i in 1:Threads.nthreads()] V = [NBodyMatrixElement[] for i in 1:Threads.nthreads()] p = if verbosity > 0 @info "Generating energy expression" Progress(m*n) end Threads.@threads for i in eachindex(as) tid = Threads.threadid() a = as[i] aoverlaps = filter(o -> o.a ∈ a.orbitals || o.b ∈ a.orbitals, overlaps) for (j,b) in enumerate(bs) aboverlaps = filter(o -> o.a ∈ b.orbitals || o.b ∈ b.orbitals, aoverlaps) S = overlap_matrix(a, b, aboverlaps) me = NBodyMatrixElement(a,op,b, S) !isnothing(p) && ProgressMeter.next!(p) iszero(me) && continue push!(I[tid], i) push!(J[tid], j) push!(V[tid], me) end end sparse(reduce(vcat, I), reduce(vcat, J), reduce(vcat, V), m, n) end """ Matrix(op::QuantumOperator, slater_determinants[, overlaps]) Generate the matrix corresponding to the quantum operator `op`, between the different `slater_determinants`. It is possible to specify non-orthogonalities between single-particle orbitals in `overlaps`. """ Base.Matrix(op::QuantumOperator, cfgs::CFGs, overlaps::Vector{<:OrbitalOverlap}=OrbitalOverlap[]; kwargs...) where {CFGs<:AbstractVector} = Matrix(cfgs, op, cfgs, overlaps; kwargs...) function transform(fun::Function, E::EnergyExpression; verbosity=0, kwargs...) m,n = size(E) I = Int[] J = Int[] V = NBodyMatrixElement[] rows = rowvals(E) vals = nonzeros(E) p = if verbosity > 0 @info "Transforming energy expression" Progress(nnz(E)) end for j = 1:n for ind in nzrange(E, j) i = rows[ind] me = transform(fun, vals[ind]) !isnothing(p) && ProgressMeter.next!(p) iszero(me) && continue push!(I, i) push!(J, j) push!(V, me) end end sparse(I, J, V, m, n) end export OrbitalOverlap, numbodies, overlap_matrix, transform, EnergyExpression, isdependent
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
7251
# * N-body operators abstract type QuantumOperator end """ ishermitian(op::QuantumOperator) By default, all `QuantumOperator`s are Hermitian; this can be overridden for subtypes to explicitly declare an operator non-Hermitian. """ LinearAlgebra.ishermitian(::QuantumOperator) = true """ NBodyOperator{N} Abstract N-body operator coupling `N` bodies each between two Slater determinants """ abstract type NBodyOperator{N} <: QuantumOperator end """ numbodies(::NBodyOperator{N}) Returns the number of bodies coupled by the N-body operator, i.e. `N`. """ numbodies(::NBodyOperator{N}) where N = N # # Examples # ```jldoctest # julia> ZeroBodyOperator # Ω₀ # julia> OneBodyOperator # Ω₁ # julia> TwoBodyOperator # Ω₂ # julia> NBodyOperator{6} # Ω₆ # ``` # Base.show(io::IO, ::Type{NBodyOperator{N}}) where N = # write(io, "Ω", to_subscript(N)) const ZeroBodyOperator = NBodyOperator{0} const OneBodyOperator = NBodyOperator{1} const TwoBodyOperator = NBodyOperator{2} """ IdentityOperator{N} The N-body identity operator. Leaves the orbital(s) acted upon unchanged. """ struct IdentityOperator{N} <: NBodyOperator{N} end Base.show(io::IO, ::IdentityOperator{N}) where N = write(io, to_boldface("I"), to_subscript(N)) LinearAlgebra.adjoint(I::IdentityOperator) = I # * Adjoint operator struct AdjointOperator{N,O<:NBodyOperator{N}} <: NBodyOperator{N} o::O end Base.parent(ao::AdjointOperator) = ao.o Base.hash(ao::AdjointOperator, h::UInt) = hash(parent(ao), hash(0x123, h)) numbodies(ao::AdjointOperator) = numbodies(parent(ao)) LinearAlgebra.adjoint(o::QuantumOperator) = AdjointOperator(o) LinearAlgebra.adjoint(ao::AdjointOperator) = parent(ao) function Base.show(io::IO, ao::AdjointOperator) show(io, parent(ao)) write(io, "†") end # * Linear combination """ LinearCombinationOperator(operators) Represents a linear combination of [`NBodyOperator`](@ref)s. """ struct LinearCombinationOperator <: QuantumOperator operators::Vector{<:Pair{<:NBodyOperator,<:Number}} end Base.zero(::LinearCombinationOperator) = LinearCombinationOperator(Pair{<:NBodyOperator,<:Number}[]) Base.zero(::Type{LinearCombinationOperator}) = LinearCombinationOperator(Pair{<:NBodyOperator,<:Number}[]) Base.iszero(op::LinearCombinationOperator) = isempty(op.operators) LinearAlgebra.adjoint(op::LinearCombinationOperator) = sum(adjoint(o)*conj(c) for (o,c) in op.operators) Base.:(==)(a::LinearCombinationOperator,b::LinearCombinationOperator) = a.operators == b.operators function Base.hash(lco::LinearCombinationOperator, h::UInt) for (op,coeff) in lco.operators h = hash(op, hash(coeff, h)) end h end """ numbodies(lco::LinearCombinationOperator) Returns the maximum number of bodies coupled by any of the N-body operators in the [`LinearCombinationOperator`](@ref). """ numbodies(lco::LinearCombinationOperator) = iszero(lco) ? 0 : maximum(numbodies.(first.(lco.operators))) function Base.show(io::IO, op::LinearCombinationOperator) if iszero(op) write(io, "0") return end for (i,(o,n)) in enumerate(op.operators) i > 1 && write(io, " ") showcoeff(io, n, i > 1) write(io, string(o)) end end Base.:(+)(a::NBodyOperator, b::NBodyOperator) = LinearCombinationOperator([a=>1,b=>1]) Base.:(-)(a::NBodyOperator, b::NBodyOperator) = LinearCombinationOperator([a=>1,b=>-1]) Base.:(+)(a::LinearCombinationOperator, b::NBodyOperator) = LinearCombinationOperator(vcat(a.operators, b=>1)) Base.:(-)(a::LinearCombinationOperator, b::NBodyOperator) = LinearCombinationOperator(vcat(a.operators, b=>-1)) Base.:(+)(a::NBodyOperator, b::LinearCombinationOperator) = LinearCombinationOperator(vcat(a=>1, b.operators)) Base.:(-)(a::NBodyOperator, b::LinearCombinationOperator) = LinearCombinationOperator(vcat(a=>1, Pair{<:NBodyOperator,<:Number}[o[1]=>-o[2] for o in b.operators])) Base.:(+)(a::LinearCombinationOperator, b::LinearCombinationOperator) = LinearCombinationOperator(vcat(a.operators, b.operators)) Base.:(-)(a::LinearCombinationOperator, b::LinearCombinationOperator) = LinearCombinationOperator(vcat(a.operators, Pair{<:NBodyOperator,<:Number}[o[1]=>-o[2] for o in b.operators])) Base.:(*)(a::Number, b::NBodyOperator) = LinearCombinationOperator([b=>a]) Base.:(*)(a::NBodyOperator, b::Number) = LinearCombinationOperator([a=>b]) Base.:(-)(op::QuantumOperator) = -1op Base.:(*)(a::Number, b::LinearCombinationOperator) = LinearCombinationOperator(Pair{<:NBodyOperator,<:Number}[op=>a*c for (op,c) in b.operators]) Base.:(*)(a::LinearCombinationOperator, b::Number) = LinearCombinationOperator(Pair{<:NBodyOperator,<:Number}[op=>b*c for (op,c) in a.operators]) Base.filter(fun::Function, op::LinearCombinationOperator) = LinearCombinationOperator(filter(oc -> fun(oc[1]), op.operators)) # * Contracted operators """ ContractedOperator(a, o, b) An [`NBodyOperator`](@ref) representing the contraction of the operator `o` over the orbital sets `a` and `b`. The lengths of `a` and `b` have to equal, and they cannot exceed the dimension of `o`. """ struct ContractedOperator{N,P,Q,A,O<:NBodyOperator{P},B} <: NBodyOperator{N} a::NTuple{Q,A} o::O b::NTuple{Q,B} function ContractedOperator(a::NTuple{Q,A}, o::O, b::NTuple{Q,B}) where {P,Q,A,O<:NBodyOperator{P},B} P ≥ Q || throw(ArgumentError("Cannot contract $(P)-body operator over $(Q) coordinates")) N = P - Q new{N,P,Q,A,O,B}(a, o, b) end end Base.:(==)(a::ContractedOperator, b::ContractedOperator) = a.a == b.a && a.o == b.o && a.b == b.b """ in(orbital, co::ContractedOperator) Test if `orbital` is among the right set of orbitals of the [`ContractedOperator`](@ref) `co`. Useful to test if `co` is an integral operator with respect to `orbital`. """ Base.in(orbital::O, co::ContractedOperator) where O = orbital ∈ co.b """ in(corbital::Conjugate, co::ContractedOperator) Test if `corbital` is among the left set of orbitals of the [`ContractedOperator`](@ref) `co`. Useful to test if `co` is an integral operator with respect to `corbital`. """ Base.in(corbital::Conjugate{O}, co::ContractedOperator) where O = corbital.orbital ∈ co.a """ contract(orbital_matrix_element, i...) Contract the `orbital_matrix_element` over all coordinates `i...`. """ function contract end """ complement(N, i...) Generate the complement to `i...` in the set `1:N`. Useful for contracting [`OrbitalMatrixElement`](@ref)s over all coordinates _except_ `i...`. """ complement(N::Integer, i::Integer...) = setdiff(1:N, i) complement(N::Integer, i::AbstractVector{<:Integer}) = setdiff(1:N, i) function Base.show(io::IO, o::ContractedOperator{N}) where N write(io, "⟨", join(string.(o.a), " ")) write(io, "|") show(io, o.o) write(io, "|") write(io, join(string.(o.b), " "), "⟩") end export QuantumOperator, NBodyOperator, AdjointOperator, numbodies, ZeroBodyOperator, OneBodyOperator, TwoBodyOperator, IdentityOperator, ContractedOperator
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
834
function showcoeff(io::IO, n::Number, show_sign::Bool, show_one::Bool=false) isimag(n) = !iszero(n) && isreal(im*n) isneg(n) = n < 0 if isreal(n) && isneg(real(n)) || isimag(n) && isneg(imag(n)) write(io, "- ") else show_sign && write(io, "+ ") end n = round(n, digits=6) if !(isone(n) || isone(-n)) if !(isreal(n) || isimag(n)) write(io, "($n)") elseif isimag(n) ii = imag(n) if !(isone(ii) || isone(-ii)) write(io, "$(abs(ii))im") else write(io, "im") end else write(io, string(abs(n))) end elseif show_one write(io, "1") end end function showcoeff(io::IO, n, show_sign::Bool, _) show_sign && write(io, "+ ") print(io, n) end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
2604
# * Slater determinants """ SlaterDeterminant(orbitals::Vector{O}) Constructs a Slater determinant from a set of spin-orbitals. # Examples ```jldoctest julia> SlaterDeterminant([:a, :b]) a(1)b(2) - a(2)b(1) julia> SlaterDeterminant([:a, :b, :c]) a(1)b(2)c(3) - a(1)b(3)c(2) - a(2)b(1)c(3) + a(2)b(3)c(1) + a(3)b(1)c(2) - a(3)b(2)c(1) ``` """ struct SlaterDeterminant{O} orbitals::Vector{O} end """ SlaterDeterminant(configuration::Configuration{<:SpinOrbital}) Constructs a Slater determinant from the spin-orbitals of the spin-configuration `configuration`. # Examples ```jldoctest julia> SlaterDeterminant(spin_configurations(c"1s2")[1]) 1s₀α(1)1s₀β(2) - 1s₀α(2)1s₀β(1) ``` """ SlaterDeterminant(c::Configuration{<:SpinOrbital}) = SlaterDeterminant(c.orbitals) """ length(slater_determinant) Return the number of spin-orbitals in the Slater determinant. """ Base.length(sd::SlaterDeterminant) = length(sd.orbitals) AtomicLevels.num_electrons(sd::SlaterDeterminant) = length(sd) AtomicLevels.orbitals(sd::SlaterDeterminant) = sd.orbitals Base.show(io::IO, sd::SlaterDeterminant) = write(io, "|",join(sd.orbitals, " "), "|") function Base.show(io::IO, ::MIME"text/plain", sd::SlaterDeterminant) noprintterms = 5 n = length(sd) if n > 3 show(io, sd) return end numperm = factorial(n) for (j,p) in enumerate(permutations(1:n)) if j < noprintterms || j > numperm-noprintterms s = Combinatorics.parity(p) (j > 1 || s == 1) && write(io, " ", s == 0 ? "+" : "-", " ") for (i,c) in enumerate(p) write(io, "$(sd.orbitals[i])($(c))") end elseif j == noprintterms write(io, " + … ") end end end """ AdjointSlaterDeterminant(slater_determinant) Representation of the Hermitian conjugate (dual vector) of a Slater determinant. Constructed via the usual [`adjoint`](@ref) operator. """ struct AdjointSlaterDeterminant{O} sd::SlaterDeterminant{O} end """ adjoint(slater_determinant) Construct the adjoint of `slater_determinant` # Examples ```jldoctest julia> SlaterDeterminant([:a, :b])' [a(1)b(2) - a(2)b(1)]† ``` """ Base.adjoint(sd::SlaterDeterminant) = AdjointSlaterDeterminant(sd) """ length(adjoint_slater_determinant) Return the number of spin-orbitals in the adjoint Slater determinant. """ Base.length(asd::AdjointSlaterDeterminant) = length(asd.sd) function Base.show(io::IO, asd::AdjointSlaterDeterminant) write(io, "[") show(io, asd.sd) write(io, "]†") end export SlaterDeterminant
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
3195
# * Variation of orbital overlaps """ diff(ab::OrbitalOverlap, o::O) Vary the orbital overlap ⟨a|b⟩ with respect to |o⟩. """ Base.diff(ab::OrbitalOverlap, o::O) where O = o == ab.b ? NBodyEquation(Conjugate(ab.a), IdentityOperator{1}()) : 0 """ diff(ab::OrbitalOverlap, o::Conjugate{O}) Vary the orbital overlap ⟨a|b⟩ with respect to ⟨o|. """ Base.diff(ab::OrbitalOverlap, o::Conjugate{O}) where O = conj(o) == ab.a ? NBodyEquation(ab.b, IdentityOperator{1}()) : 0 # * Variation of orbital matrix elements """ diff(ome::OrbitalMatrixElement, o::O) Vary the orbital matrix element ⟨abc...|Ω|xyz...⟩ with respect to |o⟩. """ function Base.diff(ome::OrbitalMatrixElement{N}, o::O) where {N,O} is = findall(isequal(o), ome.b) (isempty(is) || iszero(ome)) && return 0 sum(NBodyEquation(Conjugate(ome.a[i]), contract(ome, complement(N, i)...)) for i in is) end """ diff(ome::OrbitalMatrixElement, o::Conjugate{O}) Vary the orbital matrix element ⟨abc...|Ω|xyz...⟩ with respect to ⟨o|. """ function Base.diff(ome::OrbitalMatrixElement{N}, o::Conjugate{O}) where {N,O} is = findall(isequal(conj(o)), ome.a) (isempty(is) || iszero(ome)) && return 0 sum(NBodyEquation(ome.b[i], contract(ome, complement(N, i)...)) for i in is) end # * Variation of NBodyMatrixElements """ diff(me::NBodyMatrixElement, o::O) Vary the [`NBodyMatrixElement`](@ref) `me` with respect to the orbital `o`. """ function Base.diff(me::NBodyMatrixElement, o::O) where O equations = Vector{NBodyEquation}() for t in me.terms for (i,f) in enumerate(t.factors) v = diff(f, o) iszero(v) && continue v = v * NBodyTerm(vcat(t.factors[1:(i-1)]..., t.factors[(i+1):end]...), t.coeff) add_equations!(equations, v) end end LinearCombinationEquation(equations) end # * Variation of energy expression matrices """ diff(E::Matrix{NBodyMatrixElement}, o::O) Vary the matrix of [`NBodyMatrixElement`](@ref)s with respect to the orbital `o`. # Examples ```jldoctest julia> E = Matrix(OneBodyHamiltonian()+CoulombInteraction(), SlaterDeterminant.([[:a, :b], [:c, :d]])) 2×2 Array{EnergyExpressions.NBodyMatrixElement,2}: (a|a) + (b|b) - G(a,b) + F(a,b) - [a b|d c] + [a b|c d] - [c d|b a] + [c d|a b] (c|c) + (d|d) - G(c,d) + F(c,d) julia> diff(E, :a) 2×2 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 2 stored entries: [1, 1] = ⟨a|ĥ + -⟨b|[a|b] + ⟨a|[b|b] [2, 1] = -⟨d|[c|b] + ⟨c|[d|b] julia> diff(E, Conjugate(:b)) 2×2 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 2 stored entries: [1, 1] = ĥ|b⟩ + -[a|b]|a⟩ + [a|a]|b⟩ [1, 2] = -[a|d]|c⟩ + [a|c]|d⟩ ``` """ function Base.diff(E::EM, o::O) where {EM<:EnergyExpression,O} m,n = size(E) eqm = spzeros(LinearCombinationEquation, m, n) for i = 1:m for j = 1:n eq = diff(E[i,j], o) iszero(eq) && continue eqm[i,j] = eq end end eqm end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
18047
@testset "Show binary values" begin @test string(BitPattern(1)) == "1" @test string(BitPattern(2)) == ".1" @test string(BitPattern(3)) == "11" @test string(BitPattern(5)) == "1.1" @test string(BitPattern(16)) == ".... 1" @test "...1 1111 1" == @capture_out begin bv = BitVector(digits(504, base=2)) showbin(bv) end end @testset "Bit configurations" begin @testset "Orbitals" begin @testset "Orthogonal orbitals" begin o = Orbitals(collect(1:10)) @test o.overlaps == I @test size(o.has_overlap) == (10,10) @test o.has_overlap == I @test isnothing(o.non_orthogonalities) @test length(o) == 10 @test eachindex(o) == 1:10 @test o[4] == 4 end @testset "Non-orthogonal orbitals" begin o = Orbitals(collect(1:10), [ov(3,8)]) @test o.overlaps isa SparseMatrixCSC @test size(o.overlaps) == (10,10) @test o.overlaps[3,8].factors[1] == ov(3,8) @test o.overlaps[8,3].factors[1] == ov(8,3) @test size(o.has_overlap) == (10,10) @test o.has_overlap[3,8] @test o.has_overlap[8,3] @test sum(o.has_overlap - I) == 2 @test o.non_orthogonalities == [0,0,1,0,0,0,0,1,0,0] @test length(o) == 10 @test eachindex(o) == 1:10 @test o[4] == 4 end end @testset "BitConfiguration" begin orbitals = ["a", "b", "c", "d", "e", "f"] a = BitConfiguration(orbitals, BitVector([1,0,1])) b = BitConfiguration(orbitals, BitVector([1,1,0,0,1])) c = BitConfiguration(orbitals, BitVector([1,1,0,0,1,0])) d = BitConfiguration(orbitals, BitVector([1,0,1,0,1])) e = BitConfiguration(orbitals, BitVector([0,1,1,0,1])) @test b == BitConfiguration(orbitals, BitVector([1,1,0,0,1])) @test b ≠ c @test string(a) == "a c" @test string(b) == "a b e" let io = IOBuffer() showbin(io, a) @test String(take!(io)) == "1.1" showbin(io, b) @test String(take!(io)) == "11.. 1" end @test "1.1" == @capture_out begin showbin(a) end @test num_particles(a) == 2 @test num_particles(b) == 3 @test orbital_numbers(a) == [1,3] @test orbital_numbers(b) == [1,2,5] @test get_orbitals(a) == ["a", "c"] @test get_orbitals(b) == ["a", "b", "e"] @test get_orbitals(["a", "c"]) == ["a", "c"] @test get_orbitals(c"1s 2p") == [o"1s", o"2p"] @test b & d == BitVector([1,0,0,0,1]) @test b & d.occupations == BitVector([1,0,0,0,1]) @test b.occupations & d == BitVector([1,0,0,0,1]) @test b | d == BitVector([1,1,1,0,1]) @test b | d.occupations == BitVector([1,1,1,0,1]) @test b.occupations | d == BitVector([1,1,1,0,1]) @test b ⊻ d == BitVector([0,1,1,0,0]) @test b ⊻ d.occupations == BitVector([0,1,1,0,0]) @test b.occupations ⊻ d == BitVector([0,1,1,0,0]) @test num_excitations(b,b) == 0 @test num_excitations(b,d) == 2 @test holes_mask(b, d) == BitVector([0,1,0,0,0]) @test holes(b, d) == [2] @test particles_mask(b, d) == BitVector([0,0,1,0,0]) @test particles(b, d) == [3] @test holes_particles_mask(b, d) == (BitVector([0,1,1,0,0]),BitVector([0,1,0,0,0]),BitVector([0,0,1,0,0])) @test holes_particles(b, d) == ([2], [3]) test_value_and_output(1, """ a = 11.. 1 b = 1.1. 1 (h, p, lo, hi) = (2, 3, 2, 3) av = 11.. 1 mask = .... . ma = .... . """) do relative_sign(b,d,holes_particles(b,d)...,verbosity=Inf) end test_value_and_output(-1, """ a = 11.. 1 b = .11. 1 (h, p, lo, hi) = (1, 3, 1, 3) av = 11.. 1 mask = .1.. . ma = .1.. . """) do relative_sign(b,e,holes_particles(b,e)...,verbosity=Inf) end end @testset "BitConfigurations" begin @testset "Empty" begin bcs = BitConfigurations([]) @test length(bcs) == 0 @test isempty(bcs) end @testset "Orthogonal orbitals" begin bcs = BitConfigurations([[:a, :b, :c], [:a, :d, :e]]) @test orbitals(bcs) == [:a, :b, :c, :d, :e] @test length(bcs) == 2 @test !isempty(bcs) os = bcs.orbitals @test length(os) == 5 @test os.orbitals == [:a, :b, :c, :d, :e] @test os.overlaps == I @test size(os.overlaps) == (5,5) @test os.has_overlap == I @test size(os.has_overlap) == (5,5) @test all(iszero, os.non_orthogonalities) @test bcs[1].occupations == BitVector([1,1,1,0,0]) @test bcs[2].occupations == BitVector([1,0,0,1,1]) @test bcs[1:2] == bcs @test core(bcs) == 1:1 @test string(bcs) == "5-orbital 2-configuration BitConfigurations" o = one(NBodyTerm) z = zero(NBodyTerm) @test orbital_overlap_matrix(bcs, 1, 1) == [o z z z o z z z o] @test orbital_overlap_matrix(bcs, 1, 2) == [o z z z z z z z z] end @testset "Non-orthogonal orbitals" begin bd = ov(:b, :d) bcs = BitConfigurations([[:a, :b, :c], [:a, :d, :e]], [bd]) @test length(bcs) == 2 @test !isempty(bcs) o = one(NBodyTerm) z = zero(NBodyTerm) os = bcs.orbitals @test length(os) == 5 @test os.orbitals == [:a, :b, :c, :d, :e] @test os.overlaps == NBodyTerm[o z z z z z o z bd z z z o z z z bd' z o z z z z z o] @test os.has_overlap == [1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1] @test os.non_orthogonalities == BitVector([0,1,0,1,0]) @test bcs[1].occupations == BitVector([1,1,1,0,0]) @test bcs[2].occupations == BitVector([1,0,0,1,1]) @test bcs[1:2] == bcs @test core(bcs) == 1:1 @test string(bcs) == "5-orbital 2-configuration BitConfigurations" @test orbital_overlap_matrix(bcs, 1, 1) == NBodyTerm[o z z z o z z z o] @test orbital_overlap_matrix(bcs, 1, 2) == NBodyTerm[o z z z bd z z z z] end @testset "Pretty-printing" begin @test strdisplay(BitConfigurations([[:a, :b, :c], [:a, :d, :e]])) == """ 5-orbital 2-configuration BitConfigurations Common core: 1:1 1: b c 2: b c -> d e""" @test strdisplay(BitConfigurations([[:a, :b, :c]])) == """ 3-orbital 1-configuration BitConfigurations Common core: 1:3 1: a b c""" @test strdisplay(BitConfigurations([[:a, :b, :c], [:d, :e]])) == """ 5-orbital 2-configuration BitConfigurations 1: a b c 2: a b c -> d e""" @test strdisplay(BitConfigurations([])) == """ 0-orbital 0-configuration BitConfigurations """ @test strdisplay(BitConfigurations([[0,i] for i = 1:100])) == """ 101-orbital 100-configuration BitConfigurations Common core: 1:1 1: 1 2: 1 -> 2 3: 1 -> 3 4: 1 -> 4 5: 1 -> 5 6: 1 -> 6 7: 1 -> 7 8: 1 -> 8 9: 1 -> 9 ⋮ 91: 1 -> 91 92: 1 -> 92 93: 1 -> 93 94: 1 -> 94 95: 1 -> 95 96: 1 -> 96 97: 1 -> 97 98: 1 -> 98 99: 1 -> 99 100: 1 -> 100""" end end @testset "Non-zero cofactors" begin o = one(NBodyMatrixElement) z = zero(NBodyMatrixElement) @testset "N-body interaction, N > n" begin bcs = BitConfigurations([[1],[2]]) ks, ls, Ds = non_zero_cofactors(bcs, 2, 1, 2) @test isempty(ks) @test isempty(ls) @test isempty(Ds) end @testset "N-body interaction, N == n" begin bcs = BitConfigurations([[1],[2]]) ks, ls, Ds = non_zero_cofactors(bcs, 1, 1, 2) @test ks == [[1]] @test ls == [[2]] @test Ds == [o] end @testset "Pure Slater–Condon not yet implemented" begin os = Orbitals([1,2,3,4]) bcs = BitConfigurations(os, [[1,2],[3,4]]) @test_throws ErrorException non_zero_cofactors(bcs, 1, 1, 2) end @testset "Orthogonal orbitals" begin bcs = BitConfigurations([[1,2,3],[1,3,4],[1,2,5],[1,5,6]]) @testset "Zero-body operators" begin test_value_and_output(([[]], [[]], [o]), """ N = 0 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 3 stored entries: 1 ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ 1 det(S) = 1 canonical_orbitals = [1, 2, 3] 0×0 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries 0×0 SparseMatrixCSC{Bool, Int64} with 0 stored entries We're essentially in Slater–Condon land We need to strike out 0..0 rows/columns from S2 rs = 1 """) do non_zero_cofactors(bcs, 0, 1, 1, verbosity=Inf) end end @testset "One-body operators" begin test_value_and_output(([[1], [2], [3]], [[1], [2], [3]], [o, o, o]), """ N = 1 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 3 stored entries: 1 ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ 1 det(S) = 1 canonical_orbitals = [1, 2, 3] 0×0 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries 0×0 SparseMatrixCSC{Bool, Int64} with 0 stored entries We're essentially in Slater–Condon land We need to strike out 0..0 rows/columns from S2 rs = 1 (n, m) = (0, 1) (k, l) = (Int64[], Int64[]) Dkl = 1 """) do non_zero_cofactors(bcs, 1, 1, 1, verbosity=Inf) end test_value_and_output(([[2]], [[4]], [-o]), """ N = 1 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 2 stored entries: 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ canonical_orbitals = [1, 3] 1×1 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries: ⋅ 1×1 SparseMatrixCSC{Bool, Int64} with 0 stored entries: ⋅ We need to strike out 1..1 rows/columns from S2 a = 111. .. b = 1.11 .. (h, p, lo, hi) = (2, 4, 2, 4) av = 111. .. mask = ..1. .. ma = ..1. .. rs = -1 (n, m) = (1, 0) (k, l) = ([1], [1]) Dkl = 1 """) do non_zero_cofactors(bcs, 1, 1, 2, verbosity=Inf) end test_value_and_output(([], [], []), """ N = 1 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 1 stored entry: 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ canonical_orbitals = [1] 2×2 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries: ⋅ ⋅ ⋅ ⋅ 2×2 SparseMatrixCSC{Bool, Int64} with 0 stored entries: ⋅ ⋅ ⋅ ⋅ Too many vanishing rows/columns """) do non_zero_cofactors(bcs, 1, 1, 4, verbosity=Inf) end end @testset "Two-body operators" begin test_value_and_output(([[2, 3]], [[5, 6]], [o]), """ N = 2 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 1 stored entry: 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ canonical_orbitals = [1] 2×2 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries: ⋅ ⋅ ⋅ ⋅ 2×2 SparseMatrixCSC{Bool, Int64} with 0 stored entries: ⋅ ⋅ ⋅ ⋅ We need to strike out 2..2 rows/columns from S2 a = 111. .. b = 1... 11 (h, p, lo, hi) = (2, 5, 2, 5) av = 111. .. mask = ..11 .. ma = ..1. .. (h, p, lo, hi) = (3, 6, 3, 6) av = 1.1. 1. mask = ...1 1. ma = .... 1. rs = 1 (n, m) = (2, 0) (k, l) = ([1, 2], [1, 2]) Dkl = 1 """) do non_zero_cofactors(bcs, 2, 1, 4, verbosity=Inf) end test_value_and_output(([[1, 2], [1, 3], [2, 3]], [[1, 2], [1, 3], [2, 3]], [o, o, o]), """ N = 2 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 3 stored entries: 1 ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ 1 det(S) = 1 canonical_orbitals = [1, 2, 3] 0×0 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries 0×0 SparseMatrixCSC{Bool, Int64} with 0 stored entries We're essentially in Slater–Condon land We need to strike out 0..0 rows/columns from S2 rs = 1 (n, m) = (0, 2) (k, l) = (Int64[], Int64[]) Dkl = 1 """) do non_zero_cofactors(bcs, 2, 1, 1, verbosity=Inf) end test_value_and_output(([[2, 1], [2, 3]], [[4, 1], [4, 3]], [-o, -o]), """ N = 2 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 2 stored entries: 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ canonical_orbitals = [1, 3] 1×1 SparseMatrixCSC{NBodyTerm, Int64} with 0 stored entries: ⋅ 1×1 SparseMatrixCSC{Bool, Int64} with 0 stored entries: ⋅ We need to strike out 1..1 rows/columns from S2 a = 111. .. b = 1.11 .. (h, p, lo, hi) = (2, 4, 2, 4) av = 111. .. mask = ..1. .. ma = ..1. .. rs = -1 (n, m) = (1, 1) (k, l) = ([1], [1]) Dkl = 1 """) do non_zero_cofactors(bcs, 2, 1, 2, verbosity=Inf) end end end @testset "Non-orthogonal orbitals" begin s = ov(2,5) bcs = BitConfigurations([[1,2,3],[1,3,4],[1,2,5],[1,5,6]], [s]) test_value_and_output(([[3]], [[6]], NBodyMatrixElement[1s]), """ N = 1 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 2 stored entries: 1 ⋅ ⋅ ⋅ ⟨2|5⟩ ⋅ ⋅ ⋅ ⋅ canonical_orbitals = [1] 2×2 SparseMatrixCSC{NBodyTerm, Int64} with 1 stored entry: ⟨2|5⟩ ⋅ ⋅ ⋅ 2×2 SparseMatrixCSC{Bool, Int64} with 1 stored entry: 1 ⋅ ⋅ ⋅ We need to strike out 1..1 rows/columns from S2 a = 111. .. b = 1... 11 (h, p, lo, hi) = (2, 5, 2, 5) av = 111. .. mask = ..11 .. ma = ..1. .. (h, p, lo, hi) = (3, 6, 3, 6) av = 1.1. 1. mask = ...1 1. ma = .... 1. rs = 1 (n, m) = (1, 0) (k, l) = ([2], [2]) Dkl = ⟨2|5⟩ """) do non_zero_cofactors(bcs, 1, 1, 4, verbosity=Inf) end test_value_and_output(([[3, 1], [2, 3]], [[6, 1], [5, 6]], NBodyMatrixElement[1s, o]), """ N = 2 Overlap matrix: 3×3 SparseMatrixCSC{NBodyTerm, Int64} with 2 stored entries: 1 ⋅ ⋅ ⋅ ⟨2|5⟩ ⋅ ⋅ ⋅ ⋅ canonical_orbitals = [1] 2×2 SparseMatrixCSC{NBodyTerm, Int64} with 1 stored entry: ⟨2|5⟩ ⋅ ⋅ ⋅ 2×2 SparseMatrixCSC{Bool, Int64} with 1 stored entry: 1 ⋅ ⋅ ⋅ We need to strike out 1..2 rows/columns from S2 a = 111. .. b = 1... 11 (h, p, lo, hi) = (2, 5, 2, 5) av = 111. .. mask = ..11 .. ma = ..1. .. (h, p, lo, hi) = (3, 6, 3, 6) av = 1.1. 1. mask = ...1 1. ma = .... 1. rs = 1 (n, m) = (1, 1) (k, l) = ([2], [2]) Dkl = ⟨2|5⟩ (n, m) = (2, 0) (k, l) = ([1, 2], [1, 2]) Dkl = 1 """) do non_zero_cofactors(bcs, 2, 1, 4, verbosity=Inf) end end end @testset "NBodyMatrixElement" begin s = ov(2,5) bcs = BitConfigurations([[1,2,3],[1,3,4],[1,2,5],[1,5,6],[1,3,5]], [s]) I₀ = IdentityOperator{0}() h = FieldFreeOneBodyHamiltonian() g = CoulombInteraction() H = h + g @test NBodyMatrixElement(bcs, I₀, 1, 5) == -ome([], I₀, [])*s @test NBodyMatrixElement(bcs, h, 1, 1) == ome(1, h, 1) + ome(2, h, 2) + ome(3, h, 3) @test NBodyMatrixElement(bcs, h, 1, 3) == -ome(3, h, 2)*s + ome(3, h, 5) @test NBodyMatrixElement(bcs, h, 1, 4) == ome(3, h, 6)*s @test NBodyMatrixElement(bcs, g, 1, 1) == ( (ome([2,3], g, [2,3]) + ome([1,3], g, [1,3]) + ome([2,1], g, [2,1])) - (ome([2,3], g, [3,2]) + ome([1,3], g, [3,1]) + ome([2,1], g, [1,2]))) @test NBodyMatrixElement(bcs, g, 1, 4) == ( (ome([3,1], g, [6,1])*s + ome([2,3], g, [5,6])) - (ome([3,1], g, [1,6])*s + ome([2,3], g, [6,5]))) @test NBodyMatrixElement(bcs, H, 1, 1) == ome(1, h, 1) + ome(2, h, 2) + ome(3, h, 3) + ((ome([2,3], g, [2,3]) + ome([1,3], g, [1,3]) + ome([2,1], g, [2,1])) - (ome([2,3], g, [3,2]) + ome([1,3], g, [3,1]) + ome([2,1], g, [1,2]))) end @testset "Multi-configurational" begin s = ov(2,5) bcs = BitConfigurations([[1,2,3],[1,5,6]], [s]) h = FieldFreeOneBodyHamiltonian() val = nothing err = @capture_err begin val = Matrix(bcs, h, verbosity=Inf) end @test val == [ome(1, h, 1) + ome(2, h, 2) + ome(3, h, 3) ome(3, h, 6)*s ome(6, h, 3)*s' ome(1, h, 1) + ome(5, h, 5) + ome(6, h, 6)] @test occursin("[ Info: Generating energy expression\n", err) @test Matrix(bcs, h, left=1, right=2) == reshape([ome(3, h, 6)*s],1,1) @test Matrix(bcs, h, left=1, right=1:2) == reshape([ome(1, h, 1) + ome(2, h, 2) + ome(3, h, 3),ome(3, h, 6)*s],1,2) @test Matrix(bcs, h, left=1, right=2, my_kwarg=1) == reshape([ome(3, h, 6)*s],1,1) end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
2107
import EnergyExpressions: OrbitalMatrixElement @testset "Common operators" begin @testset "OneBodyHamiltonian" begin h = OneBodyHamiltonian() @test string(h) == "ĥ" ahb = OrbitalMatrixElement(["a"],h,["b"]) @test string(ahb) == "(a|b)" @test !iszero(ahb) @test !iszero(OrbitalMatrixElement([so"1s₀α"], h, [so"2s₀α"])) @test !iszero(OrbitalMatrixElement([so"1s₀α"], h, [so"2p₀α"])) @test iszero(OrbitalMatrixElement([so"1s₀α"], h, [so"2p₀β"])) end @testset "FieldFreeOneBodyHamiltonian" begin h₀ = FieldFreeOneBodyHamiltonian() @test string(h₀) == "ĥ₀" ah₀b = OrbitalMatrixElement(["a"],h₀,["b"]) @test string(ah₀b) == "(a|b)" @test !iszero(ah₀b) @test !iszero(OrbitalMatrixElement([so"1s₀α"], h₀, [so"2s₀α"])) @test iszero(OrbitalMatrixElement([so"1s₀α"], h₀, [so"2p₀α"])) @test iszero(OrbitalMatrixElement([so"1s₀α"], h₀, [so"2p₀β"])) end @testset "CoulombInteraction" begin g = CoulombInteraction() @test hash(g) == hash(nothing) @test string(g) == "ĝ" abcd = OrbitalMatrixElement(["a","b"],g,["c","d"]) @test string(abcd) == "[a b|c d]" abab = OrbitalMatrixElement(["a","b"],g,["a","b"]) @test string(abab) == "F(a,b)" abba = OrbitalMatrixElement(["a","b"],g,["b","a"]) @test string(abba) == "G(a,b)" @test !iszero(OrbitalMatrixElement([so"1s₀α",so"2p₁β"],g,[so"1s₀α",so"2p₁β"])) @test iszero(OrbitalMatrixElement([so"1s₀α",so"2p₁β"],g,[so"2p₁β",so"1s₀α"])) bd = ContractedOperator(NTuple{1,String}(("b",)),g,NTuple{1,String}(("d",))) @test bd isa CoulombPotential @test string(bd) == "[b|d]" g = CoulombInteraction() @test ome([1,2], g, [1,2]) == ome([2,1], g, [2,1]) @test ome([1,2], g, [2,1]) == ome([2,1], g, [1,2]) e1 = ome([1,2], g, [1,2]) + ome([1,2], g, [2,1]) e2 = ome([2,1], g, [2,1]) + ome([2,1], g, [1,2]) @test e1 == e2 @test hash(e1) == hash(e2) end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
301
@testset "Conjugated orbitals" begin for (o,label) in ((o"1s", "1s†"), (so"1s(0,α)", "1s₀α†"), (rso"3d-(-1/2)", "3d-(-1/2)†")) co = conj(o) @test co == Conjugate(o) @test conj(co) == o @test symmetry(co) == symmetry(o) @test string(co) == label end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
1925
@testset "Equations" begin h = FieldFreeOneBodyHamiltonian() g = CoulombInteraction() z = zero(NBodyEquation) @test iszero(z) e = eq(:a, c(:a, g, :b)) e2 = 2e @test !iszero(e) @test !iszero(e2) @test e2.factor.coeff == 2 @test iszero(0e) @test -e == (-1)*e @test (-e).factor.coeff == -1 @test string(e) == "+ 1[a|b]|a⟩" @test string(ceq(:a, c(:a, g, :b))) == "+ 1⟨a|[a|b]" ee = eq(:a, c(:a, g, :b)) + eq(:a, h) + eq(:b, c(:a, g, :a)) @test -ee == -eq(:a, c(:a, g, :b)) - eq(:a, h) - eq(:b, c(:a, g, :a)) @test iszero(zero(LinearCombinationEquation)) @test iszero(zero(ee)) @test iszero(ee + (-1)*ee) @test 0ee - ee == -ee @test ee - 0ee == ee @test ee - 2eq(:b, h) == eq(:a, c(:a, g, :b)) + eq(:a, h) + eq(:b, c(:a, g, :a)) - 2eq(:b, h) @test 2eq(:b, h) - ee == 2eq(:b, h) - eq(:a, c(:a, g, :b)) - eq(:a, h) - eq(:b, c(:a, g, :a)) @test (eq(:a, c(:a, g, :b)) + eq(:a, h)) - eq(:a, c(:a, g, :b)) == eq(:a, h) @test (eq(:a, c(:a, g, :b)) + eq(:a, h)) - 2eq(:a, c(:a, g, :b)) == (-eq(:a, c(:a, g, :b)) + eq(:a, h)) @test (eq(:a, c(:a, g, :b)) + eq(:a, h)) - eq(:b, h) == (eq(:a, c(:a, g, :b)) + eq(:a, h)) + (-1)*eq(:b, h) @test string(ee) == "+ 1[a|b]|a⟩ + 1ĥ₀|a⟩ + 1[a|a]|b⟩" @test strdisplay(eq(:a, c(:a, g, :b)) + eq(:a, h) + eq(:b, c(:a, g, :a)) + eq(:a, c(:b, g, :a)) + eq(:b, h) + eq(:b, c(:a, g, :b)), limit=true) == "+ 1[a|b]|a⟩ + 1ĥ₀|a⟩ … + 1ĥ₀|b⟩ + 1[a|b]|b⟩" @test string(0ee) == "0" @testset "Comparison of equations" begin test_equations_equal(eq(:a, c(:a, g, :b)) + eq(:a, h) + eq(:b, c(:a, g, :a)), eq(:a, h) + eq(:a, c(:a, g, :b)) + eq(:b, c(:a, g, :a))) test_equations_equal(eq(:a, h) + eq(:b, c(:a, g, :a)) + eq(:a, h), 2eq(:a, h) + eq(:b, c(:a, g, :a))) end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
302
@testset "Invariant sets" begin @test invariant_sets(sparse(Matrix(I, 3,3))) == [[1], [2], [3]] @test invariant_sets(sparse([1 1 0; 1 1 0; 0 0 1])) == [[1, 2], [3]] # Unsure if we do not want state 3 to be its own set @test invariant_sets(sparse([0 1 0; 1 0 0; 0 0 0])) == [[1, 2]] end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
184
@testset "KeyTracker" begin kt = EnergyExpressions.KeyTracker{Int}() for (i,j) in enumerate(10:-1:1) @test get!(kt, j) == i end @test keys(kt) == 10:-1:1 end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
343
@testset "LockedDict" begin ld = EnergyExpressions.LockedDict{Int,Int}() @test isempty(ld) Threads.@threads for i = 1:1_000 n = mod(i, 10) @test get!(ld, n, n) == n end for (k,v) in ld @test k == v end @test length(ld) == 10 @test sort(collect(pairs(ld))) == [i => i for i = 0:9] end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
748
@testset "Loop macros" begin @testset "@above_diagonal_loop" begin v = Vector{NTuple{3,Int}}() EnergyExpressions.@above_diagonal_loop 3 i 5 begin @test i_1 > i_2 > i_3 push!(v, (i_1, i_2, i_3)) end @test length(v) == 10 @test v[1] == (3,2,1) @test v[end] == (5,4,3) end @testset "@anti_diagonal_loop" begin v = Vector{NTuple{4,Int}}() EnergyExpressions.@anti_diagonal_loop 4 i 10 begin push!(v, Base.Cartesian.@ntuple(4, i)) end @test length(v) == 5040 @test allunique(v) @test all(e -> length(e) == 4, v) @test all(allunique, v) @test all(e -> all(in(1:10), extrema(e)), v) end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
7786
# Used to generate reference data to test the linear complexity # algorithm against; the naïve algorithm is correct, but is of # factorial complexity and cannot be used for more than ~20 orbitals. @generated function naive_nonzero_minors(op::NBodyOperator{N}, overlap, numorbitals) where N quote ks = Vector{Vector{Int}}() ls = Vector{Vector{Int}}() @above_diagonal_loop $N k numorbitals begin kN = zeros(Int, $N) Base.Cartesian.@nexprs $N d -> kN[d] = k_d @above_diagonal_loop $N l numorbitals begin lN = zeros(Int, $N) Base.Cartesian.@nexprs $N d -> lN[d] = l_d Dkl = cofactor(kN, lN, overlap) # Determinantal overlap of all other orbitals iszero(Dkl) && continue push!(ks, kN) push!(ls, lN) end end ks, ls end end struct ConcreteNBodyOperator{N} <: NBodyOperator{N} end function test_find_minors(cfga, cfgb, overlaps=OrbitalOverlap[]) a = SlaterDeterminant(cfga) b = SlaterDeterminant(cfgb) S = overlap_matrix(a, b, overlaps) h = ConcreteNBodyOperator{1}() g = ConcreteNBodyOperator{2}() errors = 0 for (op,label) in [(h,"γ"), (g,"Γ")] ks,ls = naive_nonzero_minors(op, S, length(a)) N = numbodies(op) ks′,ls′ = nonzero_minors(N, S) kls′ = collect(zip(sort.(ks′),sort.(ls′))) for (k,l) in zip(sort.(ks),sort.(ls)) if (k,l) ∉ kls′ errors += 1 kl = nice_string(k) ll = nice_string(l) println("$label($kl|$ll) missing from new algorithm") end end end @test errors == 0 end function find_diagonal_blocks_test_case(A, blocks) @test find_diagonal_blocks(A) == blocks @test find_diagonal_blocks(SparseMatrixCSC(A')) == blocks end function test_cofactors(N, ii, jj) orbitals = 1:N excite = i -> i+100 virtuals = map(excite, orbitals) configurations = [SlaterDeterminant(vcat(1:i-1,excite(i),i+1:N)) for i=1:N] overlaps = map(((a,b),) -> OrbitalOverlap(a,b), reduce(vcat, [collect(combinations(virtuals,2)), [[a,a] for a in virtuals]])) results = Vector{EnergyExpressions.NBodyMatrixElement}() for (i,j) = [(ii,jj),(jj,ii)] a = configurations[i] b = configurations[j] S = overlap_matrix(a, b, overlaps) ks,ls = nonzero_minors(1, S) for (k,l) in zip(ks,ls) push!(results, cofactor(k, l, S)) end end results end @testset "Minor determinants" begin @testset "Minor axes" begin @test detaxis([1], 5) == 2:5 @test detaxis([2,4], 5) == [1,3,5] @test detaxis((1,), 5) == 2:5 @test detaxis((2,4), 5) == [1,3,5] @test detaxis(CartesianIndex(1,), 5) == 2:5 @test detaxis(CartesianIndex(2,4), 5) == [1,3,5] @test detaxis(1, 5) == 2:5 end @testset "Signatures" begin for i = 0:2:10 @test powneg1(i) == 1 @test powneg1(i+1) == -1 end @test permutation_sign(1:10) == 1 @test permutation_sign([2,1,3,4]) == -1 @test permutation_sign([2,1,4,3]) == 1 @test indexsum(1, 1) == 2 @test indexsum((1,), (1,)) == 2 @test indexsum((1,2), (1,2)) == 6 @test indexsum((1,2), (1,3)) == 7 @test indexsum([1,2], [1,3]) == 7 @test indexsum(CartesianIndex(1,2), CartesianIndex(1,3)) == 7 end @testset "Find diagonal blocks" begin find_diagonal_blocks_test_case((sparse([3,1,2], 1:3, ones(Int, 3))), [1:3]) find_diagonal_blocks_test_case((sparse([1,4,2,3], 1:4, ones(Int, 4))), [1:1, 2:4]) find_diagonal_blocks_test_case((sparse([1,2,5,3,4], 1:5, ones(Int, 5))), [1:1, 2:2, 3:5]) find_diagonal_blocks_test_case((sparse([1,2,3,6,4,5], 1:6, ones(Int, 6))), [1:1, 2:2, 3:3, 4:6]) end @testset "Cofactors" begin @test test_cofactors(7,4,7) == [NBodyMatrixElement([-OrbitalOverlap(104,107)]), NBodyMatrixElement([-OrbitalOverlap(107,104)])] @test test_cofactors(8,5,8) == [NBodyMatrixElement([-OrbitalOverlap(105,108)]), NBodyMatrixElement([-OrbitalOverlap(108,105)])] @test test_cofactors(9,6,9) == [NBodyMatrixElement([-OrbitalOverlap(106,109)]), NBodyMatrixElement([-OrbitalOverlap(109,106)])] @test test_cofactors(9,7,9) == [NBodyMatrixElement([-OrbitalOverlap(107,109)]), NBodyMatrixElement([-OrbitalOverlap(109,107)])] @test test_cofactors(54,45,54) == [NBodyMatrixElement([-OrbitalOverlap(145,154)]), NBodyMatrixElement([-OrbitalOverlap(154,145)])] end @testset "Base cases" begin test_find_minors([:a], [:a]) test_find_minors([:a,:b], [:a,:b]) test_find_minors([:a,:b], [:b,:a]) test_find_minors([:a,:b], [:a,:c]) test_find_minors([:a,:b], [:c,:a]) test_find_minors([:a,:b,:c], [:a,:b,:c]) test_find_minors([:a,:b,:c], [:a,:b,:d]) test_find_minors([:a,:b,:c], [:a,:b,:d], [OrbitalOverlap(:a,:b)]) test_find_minors([:a,:b,:c], [:a,:b,:d], [OrbitalOverlap(:a,:c)]) test_find_minors([:a,:b,:c], [:a,:b,:d], [OrbitalOverlap(:b,:d),OrbitalOverlap(:c,:d)]) test_find_minors([:a,:b,:c], [:a,:b,:d], [OrbitalOverlap(:a,:c),OrbitalOverlap(:c,:d)]) test_find_minors([:a,:b,:c], [:a,:b,:d], [OrbitalOverlap(:a,:d),OrbitalOverlap(:c,:d)]) test_find_minors([:a,:b,:c], [:b,:c,:a]) test_find_minors([:a,:b,:c], [:c,:b,:a]) test_find_minors([:a,:b,:c], [:b,:c,:a], [OrbitalOverlap(:a,:c)]) test_find_minors([:a,:b,:c], [:a,:d,:e]) test_find_minors([:a,:b,:c,:d], [:a,:b,:c,:d]) test_find_minors([:a,:b,:c,:d], [:a,:b,:c,:d], [OrbitalOverlap(:c,:d)]) test_find_minors([:a,:b,:c,:d], [:a,:b,:c,:e], [OrbitalOverlap(:c,:d)]) test_find_minors([:a,:b,:c,:d], [:a,:b,:c,:e], [OrbitalOverlap(:c,:e)]) test_find_minors([:a,:b,:c,:d], [:a,:b,:e,:f], [OrbitalOverlap(:c,:b),OrbitalOverlap(:d,:b)]) test_find_minors([:a,:b,:c,:d], [:a,:b,:e,:f], [OrbitalOverlap(:a,:e),OrbitalOverlap(:c,:f),OrbitalOverlap(:d,:b)]) test_find_minors([:b,:c,:d,:k_a], [:a,:c,:d,:k_b], [OrbitalOverlap(:k_a,:k_b)]) test_find_minors([:k_a,:b,:c,:d], [:a,:k_b,:c,:d], [OrbitalOverlap(:k_a,:k_b)]) test_find_minors([:a, :b, :c, :d], [:a, :e, :f, :g]) test_find_minors([:a,:b,:c,:d], [:d,:c,:b,:a]) end @testset "Atomic cases" begin h = ConcreteNBodyOperator{1}() g = ConcreteNBodyOperator{2}() for (cfga,cfgb,exp1,exp2) in [ (c"1s2",c"1s2",2,1), (c"1s2",c"1s 2p",1,1), (c"1s2 2s2",c"1s2 2s2",4,binomial(4,2)), (c"1s2 2s2 2p6",c"1s2 2s2 2p6",10,binomial(10,2)), (c"1s2 2s2 2p6 3s2",c"1s2 2s2 2p6 3s2",12,binomial(12,2)), (c"1s2 2s2 2p6 3s2 3p6",c"1s2 2s2 2p6 3s2 3p6",18,binomial(18,2)), (c"[Ar]",c"[Ar]",18,binomial(18,2)), (c"[Kr]",c"[Kr]",36,binomial(36,2)), (c"[Xe]",c"[Xe]",54,binomial(54,2)) ] a = SlaterDeterminant(spin_configurations(cfga)[1]) b = SlaterDeterminant(spin_configurations(cfgb)[1]) S = overlap_matrix(a, b) for (op,ex) in [(h,exp1),(g,exp2)] ks,ls = nonzero_minors(numbodies(op), S) @test length(ks) == length(ls) == ex end end end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
6097
@testset "Multi-configurational equations" begin @testset "pushifmissing!" begin v = [1,2,3,4] @test pushifmissing!(v, 3) == 3 @test length(v) == 4 @test pushifmissing!(v, 5) == 5 @test length(v) == 5 end @testset "One-body operator" begin gst = collect(1:3) cfgs = [vcat(gst[1:i-1],100+i,gst[i+1:end]) for i in eachindex(gst)] bcs = BitConfigurations(vcat([gst], cfgs)) h = FieldFreeOneBodyHamiltonian() E = Matrix(bcs, h) os = orbitals(bcs) norb = length(os) eqs = nothing err = @capture_err begin eqs = diff(E, Conjugate.(os), verbosity=Inf) end @test length(eqs.equations) == norb @test isempty(eqs.integrals) @test occursin("OrbitalEquation(1): ", string(eqs.equations[1])) term_refs = [[(1,1,1,1), (1,2,1,101), (3,3,1,1), (4,4,1,1)], [(1,1,1,2), (2,2,1,2), (1,3,-1,102), (4,4,1,2)], [(1,1,1,3), (2,2,1,3), (3,3,1,3), (1,4,1,103)], [(2,1,1,1), (2,2,1,101)], [(3,1,-1,2), (3,3,1,102)], [(4,1,1,3), (4,4,1,103)]] for (i,e) in enumerate(eqs.equations) @test e.orbital == os[i] @test length(e.terms) == 1 integral,ts = first(e.terms) @test integral == 0 term_ref = [EnergyExpressions.MCTerm(i,j,coeff,h,so,Int[]) for (i,j,coeff,so) in term_refs[i]] @test ts == term_ref end @test occursin("[ Info: Deriving equations for $(norb) orbitals\n", err) end @testset "Two-body operator" begin cfgs = [[1,2],[1,3]] bcs = BitConfigurations(cfgs) g = CoulombInteraction() E = Matrix(bcs, g) os = [2,3] norb = length(os) eqs = diff(E, Conjugate.(os)) @test length(eqs.equations) == norb @test length(eqs.integrals) == 3 @test c(1, g, 1) ∈ eqs.integrals i11 = findfirst(isequal(c(1, g, 1)), eqs.integrals) @test c(1, g, 2) ∈ eqs.integrals i12 = findfirst(isequal(c(1, g, 2)), eqs.integrals) @test c(1, g, 3) ∈ eqs.integrals i13 = findfirst(isequal(c(1, g, 3)), eqs.integrals) e1 = eqs.equations[1] e2 = eqs.equations[2] @test e1.orbital == 2 @test e2.orbital == 3 @test occursin("OrbitalEquation(2): ", string(e1)) @test occursin("OrbitalEquation(3): ", string(e2)) z = zero(LinearCombinationEquation) @test e1.equation == [-eq(1, c(1,g,2)) + eq(2, c(1,g,1)) -eq(1, c(1, g, 3)) + eq(3, c(1, g, 1)); z z] @test e2.equation == [z z; -eq(1, c(1,g,2)) + eq(2, c(1,g,1)) -eq(1, c(1, g, 3)) + eq(3, c(1, g, 1))] @test (0 => [EnergyExpressions.MCTerm(1,1,-1,c(1,g,2),1,Int[])]) ∈ e1.terms @test (i11 => [EnergyExpressions.MCTerm(1,1,1,c(1,g,1),2,Int[]), EnergyExpressions.MCTerm(1,2,1,c(1,g,1),3,Int[])]) ∈ e1.terms @test (i13 => [EnergyExpressions.MCTerm(1,2,-1,c(1,g,3),1,Int[])]) ∈ e1.terms @test (0 => [EnergyExpressions.MCTerm(2,2,-1,c(1,g,3),1,Int[])]) ∈ e2.terms @test (i11 => [EnergyExpressions.MCTerm(2,1,1,c(1,g,1),2,Int[]), EnergyExpressions.MCTerm(2,2,1,c(1,g,1),3,Int[])]) ∈ e2.terms @test (i12 => [EnergyExpressions.MCTerm(2,1,-1,c(1,g,2),1,Int[])]) ∈ e2.terms end @testset "Modify energy expression as-you-go" begin g = CoulombInteraction() E = sparse(reshape(NBodyMatrixElement[1ome([1,2],g,[3,4])],1,1)) ref1 = reshape(LinearCombinationEquation[eq(3, c(2, g, 4))],1,1) ref2 = reshape(LinearCombinationEquation[eq(4, c(1, g, 3))],1,1) os = 1:2 norb = length(os) eqs = diff(E, Conjugate.(os)) @test eqs.integrals == [c(2, g, 4), c(1, g, 3)] @test length(eqs.equations) == 2 @test eqs.equations[1].orbital == 1 @test eqs.equations[2].orbital == 2 @test eqs.equations[1].equation == ref1 @test eqs.equations[2].equation == ref2 @test eqs.equations[1].terms == [1 => [EnergyExpressions.MCTerm(1, 1, 1, c(2, g, 4), 3, Int[])]] @test eqs.equations[2].terms == [2 => [EnergyExpressions.MCTerm(1, 1, 1, c(1, g, 3), 4, Int[])]] # Now we instead modify the energy expression during the # calculus of variations, to avoid double-counting the # contribution of the two-electron integral, if we use the # orbital equations to compute the total energy. eqs2 = nothing err = @capture_err begin eqs2 = diff(E, Conjugate.(os), verbosity=Inf) do E,corb rows = rowvals(E) vals = nonzeros(E) m,n = size(E) for j = 1:n for k in nzrange(E, j) i = rows[k] v = vals[k] vals[k] = NBodyMatrixElement(filter(t -> !isdependent(t, corb), v.terms)) end end end end @test eqs2.integrals == [c(2, g, 4)] @test length(eqs2.equations) == 2 @test eqs2.equations[1] == eqs.equations[1] @test iszero(eqs2.equations[2].equation) @test isempty(eqs2.equations[2].terms) @test occursin("[ Info: Deriving equations for $(norb) orbitals\n", err) end @testset "Pretty-printing" begin cfgs = spin_configurations(c"1s 2p") bcs = BitConfigurations(cfgs) h = FieldFreeOneBodyHamiltonian() E = Matrix(bcs, h) a,b = so"1s₀α",so"2p₀β" mceqs = diff(E, conj([a,b])) @test string(mceqs) == "2-equation MCEquationSystem, 2 non-zero equations, 0 common integrals" test_value_and_output(nothing, "2-equation MCEquationSystem, 2 non-zero equations, 0 common integrals - 1: $(mceqs.equations[1])- 2: $(mceqs.equations[2])") do show(stdout, "text/plain", mceqs) end end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
7780
@testset "NBodyMatrixElements" begin @testset "NBodyTermFactor" begin @testset "OrbitalOverlap" begin s = ov(1,2) @test !iszero(s) @test s == ov(1,2) @test hash(s) == hash(ov(1,2)) @test s' == ov(2,1) @test numbodies(s) == 0 @test isdependent(s, 2) @test !isdependent(s, 1) @test !isdependent(s, Conjugate(2)) @test isdependent(s, Conjugate(1)) @test string(s) == "⟨1|2⟩" end @testset "OrbitalMatrixElement" begin Z = IdentityOperator{0}() A = IdentityOperator{1}() B = IdentityOperator{2}() @test_throws ArgumentError ome([1], A, [2, 3]) @test_throws ArgumentError ome(1, B, 2) l = ome([], Z, []) m = ome(1, A, 2) n = ome([1,2], B, [2,3]) @test !iszero(l) @test !iszero(m) @test !iszero(n) @test l == ome([], Z, []) @test m == ome(1, A, 2) @test n == ome([1,2], B, [2,3]) @test hash(l) == hash(ome([], Z, [])) @test hash(m) == hash(ome(1, A, 2)) @test hash(n) == hash(ome([1,2], B, [2,3])) @test numbodies(l) == 0 @test numbodies(m) == 1 @test numbodies(n) == 2 @test !isdependent(l, 1) @test isdependent(m, 2) @test !isdependent(m, 1) @test !isdependent(m, Conjugate(2)) @test isdependent(m, Conjugate(1)) @test string(l) == "⟨𝐈₀⟩" @test string(m) == "⟨1|𝐈₁|2⟩" @test string(n) == "⟨1 2|𝐈₂|2 3⟩" @test contract(n) == B @test contract(n, 1) == c(1, B, 2) @test contract(n, 2) == c(2, B, 3) @test contract(n, 1, 2) == c([1,2], B, [2,3]) end end @testset "NBodyTerm" begin o = one(NBodyTerm) z = zero(NBodyTerm) @test o == one(o) @test isone(o) @test EnergyExpressions.isminusone(-o) @test z == zero(o) @test iszero(z) h = FieldFreeOneBodyHamiltonian() s = ov(1,2) m = ome(3,h,4) n = nbt(m, s) @test n == nbt(m, s) @test n == convert(NBodyTerm, m)*convert(NBodyTerm, s) @test m' == ome(4,h',3) @test string(m') == "⟨4|ĥ₀†|3⟩" # This is rather contrived, but just to make sure the printing # does not crash if NBodyTerm::coeff is not a number. @test string(NBodyTerm(Vector{EnergyExpressions.NBodyTermFactor}(),OrbitalOverlap(:a,:b))) == "⟨a|b⟩" end @testset "NBodyMatrixElement" begin o = one(NBodyMatrixElement) z = zero(NBodyMatrixElement) az = convert(NBodyMatrixElement, 0) bz = 0convert(NBodyMatrixElement, 1) @test o == one(z) @test isone(o) @test o == NBodyMatrixElement(one(NBodyTerm)) @test z == zero(o) @test iszero(z) @test z == az @test z == bz @test z ≈ az @test z ≈ bz h = FieldFreeOneBodyHamiltonian() s = ov(1,2) m = ome(3,h,4) n = nbt(m, s) @test convert(NBodyMatrixElement, n) == nbme(n) @test convert(NBodyMatrixElement, 3) == nbme(3one(NBodyTerm)) @test nbme(n) == n @test n == nbme(n) me = nbme(n) @test me ≈ (1+1e-9)*me @test me ≈ 1.001me atol=1e-3 @test string(zero(NBodyMatrixElement)) == "0" @test string(0*(m+s)) == "0" @test string(2*(m+s)) == "2.0(3|4) + 2.0⟨1|2⟩" me = m + n + s me += me me += me me += me @test strdisplay(me, limit=true) == "(3|4) + (3|4)⟨1|2⟩ + ⟨1|2⟩ + (3|4) + (3|4)⟨1|2⟩ + ⟨1|2⟩ + … + (3|4) + (3|4)⟨1|2⟩ + ⟨1|2⟩ + (3|4) + (3|4)⟨1|2⟩ + ⟨1|2⟩" @test m' == ome(4,h',3) @test (4im*m)' == -4im*(m') @test n' == nbt(m', s') @test nbme(m)' == nbme(m') @test nbme(n)' == nbme(nbt(m', s')) @test (m + n + s)' == m' + n' + s' end @testset "Arithmetic" begin h = FieldFreeOneBodyHamiltonian() s = ov(1,2) @test 2s == nbt(s,f=2) @test s*2 == 2s @test -s == nbt(s,f=-1) @test -s == (-1)*s m = ome(3,h,4) n = nbt(m, s) @test 2n == nbt(m,s, f=2) @test n*2 == 2n @test n*(2n) == nbt(m,s,m,s, f=2) == nbt(s,m,s,m, f=2) @test -n == (-1)*n @test n*s == nbt(m,s,s, f=1) @test s*n == nbt(m,s,s, f=1) @test s*s == nbt(s,s, f=1) @test s + s == 2s @test s + m == nbme(s, m) @test 2s + m == nbme(2s, m) @test s + 2m == nbme(s, 2m) @test isdependent(n, 2) @test isdependent(n, 4) @test !isdependent(n, 3) @test !isdependent(n, 1) @test !isdependent(n, Conjugate(2)) @test !isdependent(n, Conjugate(4)) @test isdependent(n, Conjugate(3)) @test isdependent(n, Conjugate(1)) @test string(n) == "(3|4)⟨1|2⟩" @test string(-n) == "- (3|4)⟨1|2⟩" @test string(2n) == "2.0(3|4)⟨1|2⟩" @test string(-2n) == "- 2.0(3|4)⟨1|2⟩" @test strdisplay(n*n*n, limit=true) == "(3|4)⟨1|2⟩…(3|4)⟨1|2⟩" @test (m+s) + (m+s) == 2m + 2s @test (m+s) + s == m + 2s @test s + (m+s) == m + 2s @test (m+s) + 2s == m + 3s @test 2s + (m+s) == m + 3s @test m - s == nbme(m, -s) @test 2m - 2s == 2nbme(m, -s) @test 2*(m+s) == 2m + 2s @test (m+s)*2 == 2m + 2s @test_broken (m+s)*s == m*s + s*s @test (m+s)*s == s*m + s*s @test -(m+s) == -m - s end @testset "Matrix elements" begin # We test the implementation based on SlaterDeterminant:s # using the other implementation based on BitConfigurations. a = [1,2,6] b = [3,4,7] s = ov(6,7) bcs = BitConfigurations([a,b],[s]) sa = SlaterDeterminant(a) sb = SlaterDeterminant(b) cfgs = [sa, sb] h = FieldFreeOneBodyHamiltonian() g = CoulombInteraction() H = h + g E1 = Matrix(bcs, H) E2 = nothing err = @capture_err begin E2 = Matrix(H, cfgs, [s], verbosity=Inf) end # The old implementation generates the opposite order of all # factors, and we do not yet know how to compare matrix # elements with flipped factor order, therefore we flip them # manually. for nv in E2.nzval for t in nv.terms reverse!(t.factors) end end @test E1 == E2 @test occursin("[ Info: Generating energy expression\n", err) @test (E1')' == E1'' == E1 end @testset "Transformations" begin n = zero(NBodyTerm) zme = transform(identity, n) @test zme isa NBodyMatrixElement @test iszero(zme) g = CoulombInteraction() F12 = ome([1,2],g,[1,2]) F34 = ome([3,4],g,[3,4]) G12 = ome([1,2],g,[2,1]) G34 = ome([3,4],g,[4,3]) ab = 2F12*F34 ab2 = ab + F12 ref = 2*(F12*(F34-G34)-G12*(F34-G34)) ref2 = ref + (F12-G12) E = sparse(NBodyMatrixElement[ab 0; 0 ab2]) Eref = sparse(NBodyMatrixElement[ref 0; 0 ref2]) trf = n -> n - ome(n.a, g, reverse(n.b)) @test transform(trf, ab) == ref @test transform(trf, ab2) == ref2 val = nothing err = @capture_err begin val = transform(trf, E, verbosity=Inf) end @test val == Eref @test occursin("[ Info: Transforming energy expression\n", err) end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
2160
@testset "N-body operators" begin I₁ = IdentityOperator{1}() @test ishermitian(I₁) @test I₁ isa OneBodyOperator @test string(I₁) == "𝐈₁" I₂ = IdentityOperator{2}() @test I₂ isa TwoBodyOperator @test adjoint(I₁) == I₁ h = FieldFreeOneBodyHamiltonian() @test h' == AdjointOperator(h) @test (h')' == h'' == h @test string(h') == "ĥ₀†" @test hash(h') == hash(AdjointOperator(h)) @test numbodies(h') == 1 @testset "LinearCombinationOperator" begin L = I₁ + I₂ @test !iszero(L) @test iszero(zero(L)) @test iszero(zero(typeof(L))) @test L.operators == [I₁ => 1, I₂ => 1] @test (I₁ - I₂).operators == [I₁ => 1, I₂ => -1] @test (2I₁ + I₂).operators == [I₁ => 2, I₂ => 1] @test (2I₁ - I₂).operators == [I₁ => 2, I₂ => -1] @test (I₁ + 2I₂).operators == [I₁ => 1, I₂ => 2] @test (I₁ - im*I₂).operators == [I₁ => 1, I₂ => -im] @test (2I₁ + 2I₂).operators == [I₁ => 2, I₂ => 2] @test (2I₁ - 2I₂).operators == [I₁ => 2, I₂ => -2] @test (I₁*2).operators == [I₁ => 2] @test (2*(2I₁)).operators == [I₁ => 4] @test ((2I₁)*2).operators == [I₁ => 4] @test L == I₁ + I₂ @test hash(L) == hash(I₁ + I₂) @test numbodies(L) == 2 @test string(L) == "𝐈₁ + 𝐈₂" @test string(I₁ + 2I₂) == "𝐈₁ + 2.0𝐈₂" @test string(I₁ - im*I₂) == "𝐈₁ - im𝐈₂" @test string(zero(L)) == "0" @test filter(Base.Fix2(isa, OneBodyOperator), L).operators == [I₁ => 1] @test -I₁ == (-1)*I₁ @test -I₂ == (-1)*I₂ @test -L == -I₁ - I₂ @test adjoint(L) == L end @testset "ContractedOperator" begin co = ContractedOperator((:a,), I₁, (:b,)) @test co == ContractedOperator((:a,), I₁, (:b,)) @test :b ∈ co @test :a ∉ co @test Conjugate(:b) ∉ co @test Conjugate(:a) ∈ co @test_throws ArgumentError ContractedOperator((:a,:c), I₁, (:b,:d)) @test string(co) == "⟨a|𝐈₁|b⟩" @test string(ContractedOperator((:a,:c), I₂, (:b,:d))) == "⟨a c|𝐈₂|b d⟩" end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
2859
using EnergyExpressions import EnergyExpressions: @above_diagonal_loop, cofactor, nonzero_minors, find_diagonal_blocks, detaxis, powneg1, permutation_sign, indexsum, NBodyTerm, NBodyMatrixElement, OrbitalMatrixElement, contract, BitPattern, Orbitals, BitConfiguration, showbin, num_particles, orbital_numbers, get_orbitals, num_excitations, holes_mask, holes, particles_mask, particles, holes_particles_mask, holes_particles, relative_sign, orbital_overlap_matrix, non_zero_cofactors, pushifmissing! using SparseArrays using Combinatorics using AtomicLevels using LinearAlgebra using Test using DeepDiffs using Suppressor function strdisplay(o; kwargs...) buf = IOBuffer() io = IOContext(buf, kwargs...) show(io, MIME"text/plain"(), o) String(take!(buf)) end rstripeachline(s) = join([rstrip(l) for l in split(s, '\n')], '\n') function test_value_and_output(fun::Function, expected_value, expected_output) value = nothing out = @capture_out begin value = fun() end @test value == expected_value out = rstripeachline(out) expected_output = rstripeachline(expected_output) if out ≠ expected_output @error "Output does not match expected" println(deepdiff(expected_output, out)) end @test out == expected_output end ome(a, op, b) = OrbitalMatrixElement(a, op, b) ome(a::T, op, b::T) where {T<:Union{Symbol,<:Integer}} = ome([a], op, [b]) c(a, op, b) = ContractedOperator(Tuple(e for e in a), op, Tuple(e for e in b)) c(a::T, op, b::T) where {T<:Union{Symbol,<:Integer}} = c([a], op, [b]) eq(orb, op, args...) = NBodyEquation(orb, op, args...) ceq(orb, op, args...) = eq(Conjugate(orb), op, args...) ov(a,b) = OrbitalOverlap(a,b) nbt(args...;f=1) = NBodyTerm([args...], f) nbme(args...) = NBodyMatrixElement(NBodyTerm[args...]) function test_variations_equal(E, orbital, b) a = diff(E, orbital) a == b || @error "When varying, expected equality between" E a b a-b @test a == b b == a || @error "When varying, expected equality between" E b a b-a @test b == a end function test_equations_equal(a, b) a == b || @error "Expected equality between" a b a-b @test a == b b == a || @error "Expected equality between" b a b-a @test b == a end @testset "EnergyExpressions" verbose=true begin include("key_tracker.jl") include("locked_dict.jl") include("invariant_sets.jl") include("conjugate_orbitals.jl") include("nbody_matrix_elements.jl") include("bit_configurations.jl") include("loop_macros.jl") include("minors.jl") include("slater_determinants.jl") include("show_coefficients.jl") include("nbody_operators.jl") include("common_operators.jl") include("equations.jl") include("variations.jl") include("multi_configurational_equations.jl") end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
1202
function strcoeff(args...) buf = IOBuffer() EnergyExpressions.showcoeff(buf, args...) String(take!(buf)) end @testset "Pretty-print coefficients" begin @test strcoeff(1, false) == "" @test strcoeff(1, true) == "+ " @test strcoeff(-1, false) == "- " @test strcoeff(-1, true) == "- " @test strcoeff(2, false) == "2.0" @test strcoeff(2, true) == "+ 2.0" @test strcoeff(-2, false) == "- 2.0" @test strcoeff(-2, true) == "- 2.0" @test strcoeff(1, false, true) == "1" @test strcoeff(1, true, true) == "+ 1" @test strcoeff(-1, false, true) == "- 1" @test strcoeff(-1, true, true) == "- 1" @test strcoeff(im, false) == "im" @test strcoeff(im, true) == "+ im" @test strcoeff(-im, false) == "- im" @test strcoeff(-im, true) == "- im" @test strcoeff(2im, false) == "2.0im" @test strcoeff(2im, true) == "+ 2.0im" @test strcoeff(-2im, false) == "- 2.0im" @test strcoeff(-2im, true) == "- 2.0im" @test strcoeff((1+im), false) == "(1.0 + 1.0im)" @test strcoeff((1+im), true) == "+ (1.0 + 1.0im)" @test strcoeff(-(1+im), false) == "(-1.0 - 1.0im)" @test strcoeff(-(1+im), true) == "+ (-1.0 - 1.0im)" end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
796
@testset "Slater determinants" begin c = sc"1s₀α 2s₀α 2p₋₁β" os = orbitals(c) s = SlaterDeterminant(c) @test length(s) == 3 @test num_electrons(s) == 3 @test orbitals(s) == os @test string(s) == "|1s₀α 2s₀α 2p₋₁β|" @test strdisplay(s) == "1s₀α(1)2s₀α(2)2p₋₁β(3) - 1s₀α(1)2s₀α(3)2p₋₁β(2) - 1s₀α(2)2s₀α(1)2p₋₁β(3) + 1s₀α(2)2s₀α(3)2p₋₁β(1) + 1s₀α(3)2s₀α(1)2p₋₁β(2) - 1s₀α(3)2s₀α(2)2p₋₁β(1)" @test strdisplay(SlaterDeterminant(collect(1:3))) == "1(1)2(2)3(3) - 1(1)2(3)3(2) - 1(2)2(1)3(3) + 1(2)2(3)3(1) + 1(3)2(1)3(2) - 1(3)2(2)3(1)" @test strdisplay(SlaterDeterminant(collect(1:4))) == "|1 2 3 4|" as = s' @test as isa EnergyExpressions.AdjointSlaterDeterminant @test length(as) == 3 @test string(as) == "[|1s₀α 2s₀α 2p₋₁β|]†" end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
code
6311
@testset "Calculus-of-variations" begin h = FieldFreeOneBodyHamiltonian() g = CoulombInteraction() I₁ = IdentityOperator{1}() I₃ = IdentityOperator{3}() I₄ = IdentityOperator{4}() @testset "Various variations" begin extra = EnergyExpressions.OrbitalMatrixElement([:a,:a], g, [:a,:b]) ex_extra = eq(:a, c(:a, g, :b)) + eq(:b, c(:a, g, :a)) cex_extra = ceq(:a, c(:a, g, :b)) for (a,op,b,ovs,ex,cex) in [ ([:a], h, [:a], (), eq(:a, h), ceq(:a, h)), ([:a], h, [:b], (), eq(:b, h), 0), ([:b], h, [:a], (), 0, ceq(:b, h)), ([:a], h, [:a], ((:a,:a),), eq(:a, h, nbt(ov(:a, :a))) + eq(:a, I₁, nbt(ome(:a, h, :a))), ceq(:a, h, nbt(ov(:a, :a))) + ceq(:a, I₁, nbt(ome(:a, h, :a)))), ([:a], h, [:b], ((:a,:a),), eq(:b, h, nbt(ov(:a, :a))) + eq(:a, I₁, nbt(ome(:a, h, :b))), ceq(:a, I₁, nbt(ome(:a, h, :b)))), ([:b], h, [:a], ((:a,:a),), eq(:a, I₁, nbt(ome(:b, h, :a))), ceq(:b, h, nbt(ov(:a, :a))) + ceq(:a, I₁, nbt(ome(:b, h, :a)))), ([:a], h, [:a], ((:a,:b),), eq(:a, h, nbt(ov(:a, :b))) + eq(:b, I₁, nbt(ome(:a, h, :a))), ceq(:a, h, nbt(ov(:a, :b)))), ([:a], h, [:b], ((:a,:b),), eq(:b, h, nbt(ov(:a, :b))) + eq(:b, I₁, nbt(ome(:a, h, :b))), 0), ([:b], h, [:a], ((:a,:b),), eq(:b, I₁, nbt(ome(:b, h, :a))), ceq(:b, h, nbt(ov(:a, :b)))), ([:a], h, [:a], ((:c,:d),), eq(:a, h, nbt(ov(:c, :d))), ceq(:a, h, nbt(ov(:c, :d)))), ([:a], h, [:b], ((:c,:d),), eq(:b, h, nbt(ov(:c, :d))), 0), ([:b], h, [:a], ((:c,:d),), 0, ceq(:b, h, nbt(ov(:c, :d)))), ([:a,:a], g, [:a,:a], (), 2eq(:a, c(:a, g, :a)), 2ceq(:a, c(:a, g, :a))), ([:a,:b], g, [:a,:b], (), eq(:a, c(:b, g, :b)), ceq(:a, c(:b, g, :b))), ([:a,:b], g, [:b,:a], (), eq(:b, c(:b, g, :a)), ceq(:b, c(:a, g, :b))), ([:a,:a], g, [:a,:b], (), eq(:a, c(:a, g, :b)) + eq(:b, c(:a, g, :a)), ceq(:a, c(:a, g, :b))), ([:a,:a], g, [:a,:b], ((:a,:a),), (eq(:a, c(:a, g, :b), nbt(ov(:a, :a))) + eq(:b, c(:a, g, :a), nbt(ov(:a, :a))) + eq(:a, I₁, nbt(ome([:a,:a], g, [:a,:b])))), (ceq(:a, c(:a, g, :b), nbt(ov(:a, :a))) + ceq(:a, I₁, nbt(ome([:a,:a], g, [:a,:b]))))), ([:a,:a], g, [:a,:b], ((:c,:d),), (eq(:a, c(:a, g, :b), nbt(ov(:c, :d))) + eq(:b, c(:a, g, :a), nbt(ov(:c, :d)))), (ceq(:a, c(:a, g, :b), nbt(ov(:c, :d))))), ([:a,:a,:a], I₃, [:a,:a,:a], (), 3eq(:a, c([:a,:a], I₃, [:a,:a])), 3ceq(:a, c([:a,:a], I₃, [:a,:a]))), ([:a,:a,:a], I₃, [:a,:b,:a], (), eq(:a, c([:a,:a], I₃, [:b,:a])) + eq(:b, c([:a,:a], I₃, [:a,:a])) + eq(:a, c([:a,:a], I₃, [:a,:b])), ceq(:a, c([:a,:a], I₃, [:b,:a])) + ceq(:a, c([:a,:a], I₃, [:a,:b]))), ([:a,:a,:a], I₃, [:a,:b,:c], (), eq(:a, c([:a,:a], I₃, [:b,:c])) + eq(:b, c([:a,:a], I₃, [:a,:c])) + eq(:c, c([:a,:a], I₃, [:a,:b])), ceq(:a, c([:a,:a], I₃, [:b,:c]))), ([:a,:a,:a], I₃, [:a,:a,:a], ((:a,:a),), 3eq(:a, c([:a,:a], I₃, [:a,:a]), nbt(ov(:a, :a))) + eq(:a, I₁, nbt(ome([:a, :a, :a], I₃, [:a, :a, :a]))), 3ceq(:a, c([:a,:a], I₃, [:a,:a]), nbt(ov(:a, :a))) + ceq(:a, I₁, nbt(ome([:a, :a, :a], I₃, [:a, :a, :a])))), ([:a, :a, :a, :a], I₄, [:a, :a, :b, :a], (), 2eq(:a, c([:a, :a, :a], I₄, [:a, :b, :a])) + eq(:b, c([:a, :a, :a], I₄, [:a, :a, :a])) + eq(:a, c([:a, :a, :a], I₄, [:a, :a, :b])), 2ceq(:a, c([:a, :a, :a], I₄, [:a, :b, :a])) + ceq(:a, c([:a, :a, :a], I₄, [:a, :a, :b]))), ([:a, :a, :a, :a], I₄, [:a, :b, :a, :a], (), eq(:a, c([:a, :a, :a], I₄, [:b, :a, :a])) + eq(:b, c([:a, :a, :a], I₄, [:a, :a, :a])) + 2eq(:a, c([:a, :a, :a], I₄, [:a, :b, :a])), ceq(:a, c([:a, :a, :a], I₄, [:b, :a, :a])) + 2ceq(:a, c([:a, :a, :a], I₄, [:a, :b, :a]))) ] local ome = EnergyExpressions.OrbitalMatrixElement(a, op, b) local nbt = isempty(ovs) ? ome : EnergyExpressions.NBodyTerm(vcat(ome, [OrbitalOverlap(ov...) for ov in ovs]), 1) nbme1 = EnergyExpressions.NBodyMatrixElement([nbt]) nbme2 = EnergyExpressions.NBodyMatrixElement([nbt, extra]) ex = iszero(ex) ? zero(NBodyEquation) : ex cex = iszero(cex) ? zero(NBodyEquation) : cex test_variations_equal(nbme1, Conjugate(:a), ex) test_variations_equal(nbme1, :a, cex) test_variations_equal(nbme2, Conjugate(:a), ex + ex_extra) test_variations_equal(nbme2, :a, cex + cex_extra) end end @testset "Coulomb matrix elements symmetry" begin g = CoulombInteraction() e1 = ome([1,2], g, [1,2]) + ome([1,2], g, [2,1]) e2 = ome([2,1], g, [2,1]) + ome([2,1], g, [1,2]) test_variations_equal(e1, 1, diff(e2, 1)) test_variations_equal(e1, 2, diff(e2, 2)) end @testset "Variation of energy expression" begin g = CoulombInteraction() F12 = ome([1,2],g,[1,2]) F34 = ome([3,4],g,[3,4]) s12 = ov(1,2) s34 = ov(3,4) E = sparse(NBodyMatrixElement[F12*s34 0; 0 F34*s12]) z = zero(LinearCombinationEquation) @test diff(E, Conjugate(1)) == LinearCombinationEquation[diff(F12, Conjugate(1))*s34 z z F34*diff(s12, Conjugate(1))] @test diff(E, 1) == LinearCombinationEquation[diff(F12, 1)*s34 z z z] @test diff(E, Conjugate(3)) == LinearCombinationEquation[F12*diff(s34, Conjugate(3)) z z diff(F34, Conjugate(3))*s12] @test diff(E, 3) == LinearCombinationEquation[z z z diff(F34, 3)*s12] end end
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
1741
# EnergyExpressions.jl [![Documentation][docs-stable-img]][docs-stable-url] [![Documentation (dev)][docs-dev-img]][docs-dev-url] [![GitHub Actions CI][ci-gha-img]][ci-gha-url] [![CodeCov][codecov-img]][codecov-url] Small library for setting up energy expressions for electronic systems that can be used to derive differential equations via calculus of variations. The mathematics are not tied to atomic systems (which are spherically symmetrical), and most of the code in this library could be used to derive equations for e.g. molecules. However, the `AbstractOrbital` and `SpinOrbital` types are taken from the [AtomicLevels.jl](https://github.com/JuliaAtoms/AtomicLevels.jl) library at present. When dealing with configurations of spin-orbitals, where _all_ quantum numbers are specified, it is trivial to derive the energy expression. For e.g. configuration state functions (CSFs), which are spin-averaged linear combinations of multiple Slater determinants, the problem is much more involved and requires dealing with angular momentum coupling and tensor algebra. This library could be used as a basis for building such functionality. [ci-gha-url]: https://github.com/JuliaAtoms/EnergyExpressions.jl/actions [ci-gha-img]: https://github.com/JuliaAtoms/EnergyExpressions.jl/workflows/CI/badge.svg [codecov-url]: https://codecov.io/gh/JuliaAtoms/EnergyExpressions.jl [codecov-img]: https://codecov.io/gh/JuliaAtoms/EnergyExpressions.jl/branch/master/graph/badge.svg [docs-stable-url]: https://juliaatoms.org/EnergyExpressions.jl/stable/ [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-dev-url]: https://juliaatoms.org/EnergyExpressions.jl/dev/ [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
3454
# Calculus of Variations [Calculus of Variations](https://en.wikipedia.org/wiki/Calculus_of_variations) is a mathematical technique for deriving differential equations, whose solutions fulfil a certain criterion. For the case at hand, we are interested in solutions whose total energy matches with the one set up by the energy expression for all the electrons in a system. The following variational rules are useful: $$\begin{equation} \vary{\bra{a}}\braket{a}{b} = \ket{b}, \end{equation}$$ where the notation $\vary{\bra{a}}\braket{a}{b}$ means _vary $\braket{a}{b}$ with respect to $\bra{a}$_. $$\begin{equation} \begin{cases} \vary{\bra{l}}\onebody{l}{k} &= \vary{\bra{l}}\matrixel{l}{\hamiltonian}{k} = \hamiltonian\ket{k},\\ \vary{\ket{k}}\onebody{l}{k} &= \bra{l}\hamiltonian. \end{cases} \end{equation}$$ $$\begin{equation} \begin{aligned} \vary{\bra{a}}\twobodydx{ab}{cd} &= \vary{\bra{a}}\{\twobody{ab}{cd}-\twobody{ab}{dc}\} = \vary{\bra{a}}\{\matrixel{ab}{r_{12}^{-1}}{cd}-\matrixel{ab}{r_{12}^{-1}}{dc}\} \\ &= \matrixel{b}{r_{12}^{-1}}{d}\ket{c}- \matrixel{b}{r_{12}^{-1}}{c}\ket{d} \equiv \twobody{b}{d}\ket{c}- \twobody{b}{c}\ket{d}\defd (\direct{bd}-\exchange{bd})\ket{c}. \end{aligned} \end{equation}$$ ## Helium Returning to our helium example (now only considering the ground state): ```@meta DocTestSetup = quote using AtomicLevels using EnergyExpressions end ``` ```jldoctest helium-variation julia> he = SlaterDeterminant.(spin_configurations(c"1s2")) 1-element Array{SlaterDeterminant{SpinOrbital{Orbital{Int64}}},1}: |1s₀α 1s₀β| julia> a,b = he[1].orbitals 2-element Array{SpinOrbital{Orbital{Int64}},1}: 1s₀α 1s₀β ``` First we find the energy expression: ```jldoctest helium-variation julia> E = Matrix(OneBodyHamiltonian() + CoulombInteraction(), he) 1×1 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) + F(1s₀α,1s₀β) ``` We can now vary this expression with respect to the different spin-orbitals; by convention, we vary the expression with respect to the _conjugate_ orbitals, to derive equations for the _unconjugated_ ones (this is important for complex orbitals, which is the case when studying time-dependent problems): ```jldoctest helium-variation julia> diff(E, Conjugate(a)) 1×1 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 1 stored entry: [1, 1] = ĥ|1s₀α⟩ + [1s₀β|1s₀β]|1s₀α⟩ julia> diff(E, Conjugate(b)) 1×1 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 1 stored entry: [1, 1] = ĥ|1s₀β⟩ + [1s₀α|1s₀α]|1s₀β⟩ ``` This result means that the variation of the first integral in the one-body part of the energy expression yields the one-body Hamiltonian $\hamiltonian$ acting on the orbital `1s₀α`, whereas the second integral, not containing the first orbital, varies to yield zero. The two-body energy `F(1s₀α,1s₀β)` varies to yield the two-body potential `[1s₀β|1s₀β]`, again acting on the orbital `1s₀α`. If we instead vary with respect to the _unconjugated_ orbitals, we get ```jldoctest helium-variation julia> diff(E, a) 1×1 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 1 stored entry: [1, 1] = ⟨1s₀α|ĥ + ⟨1s₀α|[1s₀β|1s₀β] julia> diff(E, b) 1×1 SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64} with 1 stored entry: [1, 1] = ⟨1s₀β|ĥ + ⟨1s₀β|[1s₀α|1s₀α] ``` that is, we instead derived equations for the conjugated orbitals. ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
1975
# Common N-body operators ```@meta DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` A few N-body operators that are common in quantum mechanics. It is possible to form a composite Hamiltonian thus: ```jldoctest common_operators julia> H = OneBodyHamiltonian() + CoulombInteraction() ĥ + ĝ ``` If then define a set of Slater determinants, we can easily form the energy expression: ```jldoctest common_operators julia> slaters = SlaterDeterminant.([[:a, :b], [:c, :d], [:a, :c]]) 3-element Array{SlaterDeterminant{Symbol},1}: |a b| |c d| |a c| julia> Matrix(H, slaters) 3×3 Array{EnergyExpressions.NBodyMatrixElement,2}: (a|a) + (b|b) - G(a,b) + F(a,b) - [a b|d c] + [a b|c d] (b|c) - [a b|c a] + [a b|a c] - [c d|b a] + [c d|a b] (c|c) + (d|d) - G(c,d) + F(c,d) - (d|a) - [c d|c a] + [c d|a c] (c|b) - [a c|b a] + [a c|a b] - (a|d) - [a c|d c] + [a c|c d] (a|a) + (c|c) - G(a,c) + F(a,c) ``` An energy expression like this can then be used to derive the multi-configurational Hartree–Fock equations for the orbitals `a,b,c,d`. We can also specify that e.g. the orbitals `b` and `c` are non-orthogonal, and thus derive a slightly different energy expression, that takes this into account: ```jldoctest common_operators julia> Matrix(H, slaters, [OrbitalOverlap(:b,:c)]) 3×3 Array{EnergyExpressions.NBodyMatrixElement,2}: (a|a) + (b|b) - G(a,b) + F(a,b) - ⟨b|c⟩(a|d) - [a b|d c] + [a b|c d] ⟨b|c⟩(a|a) + (b|c) - [a b|c a] + [a b|a c] - ⟨c|b⟩(d|a) - [c d|b a] + [c d|a b] (c|c) + (d|d) - G(c,d) + F(c,d) - (d|a) - [c d|c a] + [c d|a c] ⟨c|b⟩(a|a) + (c|b) - [a c|b a] + [a c|a b] - (a|d) - [a c|d c] + [a c|c d] (a|a) + (c|c) - G(a,c) + F(a,c) ``` Beware that the computational complexity grows factorially with the amount of non-orthogonal orbitals! ```@docs OneBodyHamiltonian FieldFreeOneBodyHamiltonian CoulombInteraction iszero ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
446
# Conjugate orbitals ```@meta DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` A conjugated orbital, $\conj{\chi}$ (often written $\bra{\chi}$) is the dual to the unconjugated orbital $\chi$ (often written $\ket{\chi}$). In the code, conjugation of orbitals is denoted with a dagger (`†`) to avoid confusion with the multiplication operator `*`. ```@docs Conjugate conj ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
15700
# Energy expressions The average energy of the system is given by $$\begin{equation} E_{\textrm{av}} \defd \matrixel{\Psi}{\Hamiltonian}{\Psi}, \end{equation}$$ where $\Psi$ is the (multi-electron) wavefunction of the system and $\Hamiltonian$ is the full Hamiltonian. A common approach is to approximate the wavefunction as a linear combination of [Slater determinants](https://en.wikipedia.org/wiki/Slater_determinant): $$\begin{equation} \Psi \approx \sum_K D_K\Phi_K, \end{equation}$$ where each $\Phi_K$ constitutes an anti-symmetrized product of one-particle spin-orbitals $\chi_i$. Depending on whether these spin-orbitals are chosen to be orthogonal or not, with respect to each other, the energy expression takes different forms. Other choices for the expansion are possible, for instance [Configuration state functions](https://en.wikipedia.org/wiki/Configuration_state_function). The algebra for generating energy expressions from such objects is more involved, and is not implemented in this library. The examples below are for [atomic configurations](https://github.com/JuliaAtoms/AtomicLevels.jl), but the library is not limited to this case, rather, it could work with any kind of configuration constructed from single-particle spin-orbitals. For example, it possible to work with normal Julia `Symbol`s denoting the spin-orbitals. This can be used to derive equations of motion purely symbolically. ## Orthogonal case, Slater–Condon rules ```@meta DocTestSetup = quote using AtomicLevels using EnergyExpressions end ``` First, we find all configurations possible for two configurations of helium, and convert them into [`SlaterDeterminant`](@ref)s. ```jldoctest helium julia> he = SlaterDeterminant.(spin_configurations(c"1s2")) 1-element Array{SlaterDeterminant{SpinOrbital{Orbital{Int64}}},1}: |1s₀α 1s₀β| julia> he_exc = SlaterDeterminant.(spin_configurations(c"1s 2p")) 12-element Array{SlaterDeterminant{SpinOrbital{Orbital{Int64}}},1}: |1s₀α 2p₋₁α| |1s₀α 2p₋₁β| |1s₀α 2p₀α| |1s₀α 2p₀β| |1s₀α 2p₁α| |1s₀α 2p₁β| |1s₀β 2p₋₁α| |1s₀β 2p₋₁β| |1s₀β 2p₀α| |1s₀β 2p₀β| |1s₀β 2p₁α| |1s₀β 2p₁β| ``` ### One-body energy term First we create a [`OneBodyHamiltonian`](@ref), the one-body operator that corresponds to the physical quantity _energy_: ```jldoctest helium julia> h = OneBodyHamiltonian() ĥ ``` We can then evaluate matrix elements between Slater determinants corresponding to different configurations. The Slater–Condon rules state that the one-body energy expression between two configurations is - in case the configurations are identical, $\onebody{\Phi_A}{\Phi_B} = \onebody{i}{i}$: ```jldoctest helium julia> Matrix(h, he) 1×1 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) ``` - in case the configurations differ by one orbital, $\onebody{\Phi_A}{\Phi_B} = \onebody{i}{j}$: ```jldoctest helium julia> Matrix(h, [he[1],he_exc[2]]) 2×2 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) (1s₀β|2p₋₁β) (2p₋₁β|1s₀β) (1s₀α|1s₀α) + (2p₋₁β|2p₋₁β) ``` We had to choose the second excited state, since the [`OneBodyHamiltonian`](@ref) does not couple orbitals of differing spin; therefore the corresponding matrix elements would be zero. The diagonal matrix elements correspond to the first case. - in case the configurations differ by more than one orbital, $\onebody{\Phi_A}{\Phi_B} = 0$: ```jldoctest helium julia> Matrix(h, [he[1],he_exc[10]]) 2×2 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) 0 0 (1s₀β|1s₀β) + (2p₀β|2p₀β) ``` We can easily generate the full one-body matrix: ```jldoctest helium julia> Matrix(h, vcat(he,he_exc)) 13×13 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) 0 (1s₀β|2p₋₁β) … - (1s₀α|2p₁α) 0 0 (1s₀α|1s₀α) + (2p₋₁α|2p₋₁α) 0 0 0 (2p₋₁β|1s₀β) 0 (1s₀α|1s₀α) + (2p₋₁β|2p₋₁β) 0 0 0 (2p₀α|2p₋₁α) 0 0 0 (2p₀β|1s₀β) 0 (2p₀β|2p₋₁β) 0 0 0 (2p₁α|2p₋₁α) 0 … 0 0 (2p₁β|1s₀β) 0 (2p₁β|2p₋₁β) 0 0 - (2p₋₁α|1s₀α) 0 0 (2p₋₁α|2p₁α) 0 0 0 0 0 (2p₋₁β|2p₁β) - (2p₀α|1s₀α) 0 0 (2p₀α|2p₁α) 0 0 0 0 … 0 (2p₀β|2p₁β) - (2p₁α|1s₀α) 0 0 (1s₀β|1s₀β) + (2p₁α|2p₁α) 0 0 0 0 0 (1s₀β|1s₀β) + (2p₁β|2p₁β) ``` ### Two-body energy term Similar considerations apply for the two-body energy terms between two configurations. To make it more interesting, we consider lithium which has three electrons: ```jldoctest lithium julia> li = SlaterDeterminant.(spin_configurations(c"1s2 2s")) 2-element Array{SlaterDeterminant{SpinOrbital{Orbital{Int64}}},1}: |1s₀α 1s₀β 2s₀α| |1s₀α 1s₀β 2s₀β| julia> li_exc = SlaterDeterminant.(spin_configurations(c"1s 2s 2p")) 24-element Array{SlaterDeterminant{SpinOrbital{Orbital{Int64}}},1}: |1s₀α 2s₀α 2p₋₁α| |1s₀α 2s₀α 2p₋₁β| |1s₀α 2s₀α 2p₀α| |1s₀α 2s₀α 2p₀β| |1s₀α 2s₀α 2p₁α| |1s₀α 2s₀α 2p₁β| |1s₀α 2s₀β 2p₋₁α| |1s₀α 2s₀β 2p₋₁β| |1s₀α 2s₀β 2p₀α| |1s₀α 2s₀β 2p₀β| |1s₀α 2s₀β 2p₁α| |1s₀α 2s₀β 2p₁β| |1s₀β 2s₀α 2p₋₁α| |1s₀β 2s₀α 2p₋₁β| |1s₀β 2s₀α 2p₀α| |1s₀β 2s₀α 2p₀β| |1s₀β 2s₀α 2p₁α| |1s₀β 2s₀α 2p₁β| |1s₀β 2s₀β 2p₋₁α| |1s₀β 2s₀β 2p₋₁β| |1s₀β 2s₀β 2p₀α| |1s₀β 2s₀β 2p₀β| |1s₀β 2s₀β 2p₁α| |1s₀β 2s₀β 2p₁β| ``` The operator we choose is the [Coulomb repulsion](https://en.wikipedia.org/wiki/Coulomb%27s_law), implemented by [`CoulombInteraction`](@ref): ```jldoctest lithium julia> H = CoulombInteraction() ĝ ``` - in case the configurations are identical, $\twobodydx{\Phi_A}{\Phi_B} = \twobodydx{ij}{ij}$: ```jldoctest lithium julia> Matrix(H, li)[1,1] F(1s₀α,1s₀β) - G(1s₀α,2s₀α) + F(1s₀α,2s₀α) + F(1s₀β,2s₀α) ``` NB that some terms in the sum vanish due to spin-conservation in the two-body integral. - in case the configurations differ by one orbital, $\twobodydx{\Phi_A}{\Phi_B} = \twobodydx{ik}{jk}$: ```jldoctest lithium julia> Matrix(H, [li[1],li_exc[6]])[2,1] - [1s₀α 2p₁β|1s₀α 1s₀β] - [2s₀α 2p₁β|2s₀α 1s₀β] ``` - in case the configurations differ by two orbitals, $\twobodydx{\Phi_A}{\Phi_B} = \twobodydx{ij}{kl}$: ```jldoctest lithium julia> Matrix(H, [li[1],li_exc[11]])[1,2] [1s₀β 2s₀α|2s₀β 2p₁α] ``` - in case the configurations differ by more than two orbital, $\twobodydx{\Phi_A}{\Phi_B} = 0$: ```jldoctest lithium julia> Matrix(H, [li[1],li_exc[23]])[1,2] 0 ``` In this particular case, the matrix element vanishes because of spin-conservation, as well. Again, we can generate the full two-body matrix: ```jldoctest lithium julia> Matrix(H, vcat(li,li_exc)) 26×26 Array{EnergyExpressions.NBodyMatrixElement,2}: F(1s₀α,1s₀β) - G(1s₀α,2s₀α) + F(1s₀α,2s₀α) + F(1s₀β,2s₀α) 0 … 0 0 F(1s₀α,1s₀β) + F(1s₀α,2s₀β) - G(1s₀β,2s₀β) + F(1s₀β,2s₀β) 0 0 0 0 - [1s₀α 2p₋₁β|1s₀α 1s₀β] - [2s₀α 2p₋₁β|2s₀α 1s₀β] 0 0 0 0 0 - [1s₀α 2p₀β|1s₀α 1s₀β] - [2s₀α 2p₀β|2s₀α 1s₀β] 0 … 0 0 0 0 - [1s₀α 2p₁β|1s₀α 1s₀β] - [2s₀α 2p₁β|2s₀α 1s₀β] 0 0 [2s₀β 2p₋₁α|1s₀β 2s₀α] 0 0 0 - [1s₀α 2p₋₁β|1s₀α 1s₀β] - [2s₀β 2p₋₁β|2s₀β 1s₀β] + [2s₀β 2p₋₁β|1s₀β 2s₀β] 0 [2s₀β 2p₀α|1s₀β 2s₀α] 0 … 0 0 - [1s₀α 2p₀β|1s₀α 1s₀β] - [2s₀β 2p₀β|2s₀β 1s₀β] + [2s₀β 2p₀β|1s₀β 2s₀β] 0 [2s₀β 2p₁α|1s₀β 2s₀α] 0 0 0 - [1s₀α 2p₁β|1s₀α 1s₀β] - [2s₀β 2p₁β|2s₀β 1s₀β] + [2s₀β 2p₁β|1s₀β 2s₀β] 0 [1s₀β 2p₋₁α|1s₀β 1s₀α] + [2s₀α 2p₋₁α|2s₀α 1s₀α] - [2s₀α 2p₋₁α|1s₀α 2s₀α] 0 0 0 - [2s₀α 2p₋₁β|1s₀α 2s₀β] … 0 [1s₀β 2p₀α|1s₀β 1s₀α] + [2s₀α 2p₀α|2s₀α 1s₀α] - [2s₀α 2p₀α|1s₀α 2s₀α] 0 0 0 - [2s₀α 2p₀β|1s₀α 2s₀β] 0 [1s₀β 2p₁α|1s₀β 1s₀α] + [2s₀α 2p₁α|2s₀α 1s₀α] - [2s₀α 2p₁α|1s₀α 2s₀α] 0 0 0 - [2s₀α 2p₁β|1s₀α 2s₀β] 0 0 [1s₀β 2p₋₁α|1s₀β 1s₀α] + [2s₀β 2p₋₁α|2s₀β 1s₀α] … 0 0 0 - [1s₀β 2p₋₁β|2p₁β 1s₀β] + [1s₀β 2p₋₁β|1s₀β 2p₁β] - [2s₀β 2p₋₁β|2p₁β 2s₀β] + [2s₀β 2p₋₁β|2s₀β 2p₁β] 0 [1s₀β 2p₀α|1s₀β 1s₀α] + [2s₀β 2p₀α|2s₀β 1s₀α] 0 0 0 - [1s₀β 2p₀β|2p₁β 1s₀β] + [1s₀β 2p₀β|1s₀β 2p₁β] - [2s₀β 2p₀β|2p₁β 2s₀β] + [2s₀β 2p₀β|2s₀β 2p₁β] 0 [1s₀β 2p₁α|1s₀β 1s₀α] + [2s₀β 2p₁α|2s₀β 1s₀α] 0 0 0 … - G(1s₀β,2s₀β) + F(1s₀β,2s₀β) - G(1s₀β,2p₁β) + F(1s₀β,2p₁β) - G(2s₀β,2p₁β) + F(2s₀β,2p₁β) ``` ### Linear combination of N-body operators Finally, we may form a linear combination of different many-body operators: ```jldoctest helium julia> H = OneBodyHamiltonian() + CoulombInteraction() ``` which allows to generate the full energy-expression matrix simultaneously: ```jldoctest helium julia> Matrix(H, vcat(he,he_exc[1:2])) 3×3 Array{EnergyExpressions.NBodyMatrixElement,2}: (1s₀α|1s₀α) + (1s₀β|1s₀β) + F(1s₀α,1s₀β) 0 (1s₀β|2p₋₁β) + [1s₀α 1s₀β|1s₀α 2p₋₁β] 0 (1s₀α|1s₀α) + (2p₋₁α|2p₋₁α) - G(1s₀α,2p₋₁α) + F(1s₀α,2p₋₁α) 0 (2p₋₁β|1s₀β) + [1s₀α 2p₋₁β|1s₀α 1s₀β] 0 (1s₀α|1s₀α) + (2p₋₁β|2p₋₁β) + F(1s₀α,2p₋₁β) ``` ## Non-orthogonal case, Löwdin rules This case is more complex and is invoked by providing a list of [`OrbitalOverlap`](@ref)s designating those pairs of orbitals which are chosen to be _non-orthogonal_. Beware that the computation complexity increases factorially with the amount of non-orthogonalities! It is thus not a good idea to choose all orbitals to non-orthogonal to one another. For simplicity, we now consider a set of symbolic orbitals: `a,b,c`, where specify that `b` and `c` are non-orthogonal: ```jldoctest non-orthogonal julia> cfgs = SlaterDeterminant.([[:a, :b, :c], [:b, :d, :e]]) 2-element Array{SlaterDeterminant{Symbol},1}: |a b c| |b d e| ``` The pairwise non-orthogonality can be specified simply as ```jldoctest non-orthogonal julia> overlaps = [OrbitalOverlap(:b, :c)] 1-element Array{OrbitalOverlap{Symbol,Symbol},1}: ⟨b|c⟩ ``` ### One-body energy term $$\onebody{\Phi_A}{\Phi_B} = (-)^{i+j}\onebody{i}{j}D^{AB}(i|j),$$ where $D^{AB}(i|j)$ is the determinant minor, where the row `i` and column `j` are stricken out. ```jldoctest non-orthogonal julia> Matrix(OneBodyHamiltonian(), cfgs, overlaps) 2×2 Array{EnergyExpressions.NBodyMatrixElement,2}: (a|a) - (a|a)⟨c|b⟩⟨b|c⟩ + (b|b) - (b|c)⟨c|b⟩ - (c|b)⟨b|c⟩ + (c|c) 0 0 (b|b) + (d|d) + (e|e) ``` ### Two-body energy term Similarly, we have $$\matrixel{\Phi_A}{\Omega_2}{\Phi_B} = (-)^{i+j+k+l}\matrixel{ij}{\Omega_2}{kl}D^{AB}(ij|kl),$$ where $D^{AB}(ij|kl)$ is the determinant minor, where the rows `i,j` and columns `k,l` are stricken out. The expressions become rather lengthy, so we only look at one particular matrix element: ```jldoctest non-orthogonal julia> Matrix(CoulombInteraction(), cfgs, overlaps)[1,2] - ⟨c|b⟩[a b|e d] + ⟨c|b⟩[a b|d e] + [a c|e d] - [a c|d e] ``` ### Higher-order terms For details of the implementation and the general N-body case, see [N-body matrix elements](@ref). ### References - Per-Olov Löwdin (1955). Quantum Theory of Many-Particle Systems. I. Physical Interpretations by Means of Density Matrices, Natural Spin-Orbitals, and Convergence Problems in the Method of Configurational Interaction. Physical Review, 97(6), 1474–1489. [10.1103/physrev.97.1474](http://dx.doi.org/10.1103/physrev.97.1474) - Per-Olov Löwdin (1955). Quantum Theory of Many-Particle Systems. II. Study of the Ordinary Hartree-Fock Approximation. Physical Review, 97(6), 1490–1508. [10.1103/physrev.97.1490](http://dx.doi.org/10.1103/physrev.97.1490) - Per-Olov Löwdin (1955). Quantum Theory of Many-Particle Systems. III. Extension of the Hartree-Fock Scheme to Include Degenerate Systems and Correlation Effects. Physical Review, 97(6), 1509–1520. [10.1103/physrev.97.1509](http://dx.doi.org/10.1103/physrev.97.1509) ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
838
# N-body equations ```@meta DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` These types are used to represent the integro-differential equations that result from the variation of the energy expression with respect to an orbital. They can, in general, be written on the form $$\begin{equation} 0 = \Omega_1\ket{\chi}\braket{a}{b}... \end{equation}$$ when varying with respect to a conjugated orbital, and $$\begin{equation} 0 = \bra{\chi}\Omega_1\braket{a}{b}... \end{equation}$$ when varying with respect to an orbital. In both cases, $\Omega_1$ is a one-body operator, either in itself, or resulting from a contraction over all coordinates but one of a many-body operator (see [`ContractedOperator`](@ref)). ```@docs NBodyEquation LinearCombinationEquation ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
321
# EnergyExpressions.jl [EnergyExpressions.jl](https://github.com/JuliaAtoms/EnergyExpressions.jl) provides the basis for deriving equations of motion for many-body quantum systems, including, but not limited to, atoms and molecules. Please see the theory section for an overview of the mathematics and physics involved.
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
60
# Miscellaneous ```@docs coupled_states invariant_sets ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
5424
# N-body matrix elements ```@meta CurrentModule = EnergyExpressions DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` The matrix element of an $N$-body operator between two Slater determinants may be expanded according to the Löwdin rules (which reduce to the Slater–Condon rules if all single-particle orbitals are orthogonal): $$\begin{equation} \label{eqn:matrix-element-expansion} \matrixel{\Phi_A}{\Omega_n}{\Phi_B} = \frac{1}{n!}\sum_p (-)^p \matrixel{k_1k_2...k_n}{\Omega_n}{l_1l_2...l_n} D^{AB}({k_1k_2...k_n}|{l_1l_2...l_n}) \end{equation}$$ where $D^{AB}({k_1k_2...k_n}|{l_1l_2...l_n})$ is the determinant minor of the orbital overlap determinant $D^{AB}$ with the rows ${k_1k_2...k_n}$ and columns ${l_1l_2...l_n}$ stricken out, and $p$ runs over all permutations. In general, a term in the expansion is thus of the form $$\begin{equation} \alpha\matrixel{k_1k_2...k_n}{\Omega_n}{l_1l_2...l_n}\braket{a}{b}\braket{c}{d}\dots\braket{y}{z}, \end{equation}$$ where $\alpha$ is a scalar. This is represented by [`NBodyTerm`](@ref) type. ```@docs NBodyTermFactor OrbitalOverlap OrbitalMatrixElement numbodies NBodyTerm ``` ```@autodocs Modules = [EnergyExpressions] Filter = t -> (t === EnergyExpressions.NBodyMatrixElement) ``` ```@docs isdependent transform overlap_matrix EnergyExpressions.compare Base.:(==)(::EnergyExpressions.NBodyMatrixElement, ::EnergyExpressions.NBodyMatrixElement) Base.isapprox(::EnergyExpressions.NBodyMatrixElement, ::EnergyExpressions.NBodyMatrixElement) EnergyExpression Matrix ``` ## Calculation of determinants Actually computing the matrix element expansion $\eqref{eqn:matrix-element-expansion}$ is a combinatorial problem, that grows factorially with the amount of non-orthogonal orbital pairs. Furthermore, of the $(n!)^2$ terms generated from the expansion, only $n!$ are distinct, due to the integrals being symmetric with respect to interchange of the coordinates [hence the normalization factor $(n!)^{-1}$]. Thankfully, there are few symmetries that can be employed, to generate only the distinct permutations, as well as the fact that the overlap matrix is very sparse. ### Finding non-zero minors of the overlap determinant The algorithm to find which minor determinants $\Gamma^{(N)}(k_1k_2...k_N|l_1l_2...l_N)$ do not vanish, and hence which $N$ orbitals $k_1k_2...k_N,l_1l_2...l_N$ the $N$-body operator should be contracted over, is described briefly below. It is devised to be optimal for orthogonal orbitals (i.e. linear complexity $\mathcal{O}(Nn)$ where $n$ is the number of orbitals), and near-optimal for a small amount of non-orthogonal orbitals. Given: - An $N$-body operator (implying $N$ rows and $N$ need to stricken out), and - an $n\times n$ matrix, with coordinates of non-zero matrix elements: $I,J$ (from these vectors, vanishing rows/columns can easily be deduced $\implies$ $N_r$ row/$N_c$ column "rank", i.e. yet to be stricken out), do - find all $N_r$-combinations of the remaining rows, - for each such combination, find all columns which would be affected if striking out that particular combination of rows, - if the "support" (i.e. the only non-zero elements) of any of those columns vanishes when striking out the rows, that column must be stricken out, too. Total number of these columns is named $N_{cm}$, - if more than $N_c$ columns must be stricken out ($N_{cm}>N_c$), that row combination is unviable, - find all $N_c - N_{cm}$-combinations of the remaining columns, - for each such combination of columns, find all rows which would be affected, - if the support of any of those rows vanishes when striking out the candidate columns, and the row is not in the candidate set of rows to be stricken out, the column combination is unviable. ```@docs nonzero_minors ``` ### Contracting over the stricken out orbitals We use Julia's built-in `Base.Cartesian.@nloops` iterators to span the space of all possible choices of orbitals for the contraction of orbitals. If two or more orbitals are the same, the matrix element is trivially zero (the “Fermi hole”). To avoid double-counting, we also only consider those indices that are above the hyper-diagonal. ```@docs detaxis detminor # indexsum cofactor EnergyExpressions.distinct_permutations det permutation_sign powneg1 EnergyExpressions.@above_diagonal_loop EnergyExpressions.@anti_diagonal_loop ``` ## Occupation number representation As an alternative to [`SlaterDeterminant`](@ref), we also provide an implementation of the occupation number representation (i.e. second quantization). Every configuration is thus represented as a bit vector, indicating the occupation of a specific orbital by a `true` value. Excitations between two configurations are easily computed using bitwise operations. The present implementation is inspired by - Scemama, A., & Giner, E. (2013). An efficient implementation of Slater–Condon rules. CoRR, [arXiv:1311.6244](https://arxiv.org/abs/1311.6244), but extends upon it by also supporting non-orthogonal orbitals. The benefit of this approach is much more efficient identification of which cofactors in $\eqref{eqn:matrix-element-expansion}$ are non-zero, than the approach taken in [`nonzero_minors`](@ref). ```@docs BitConfigurations EnergyExpressions.Orbitals EnergyExpressions.non_zero_cofactors ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
452
# N-body operators ```@meta CurrentModule = EnergyExpressions DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` ```@docs NBodyOperator LinearCombinationOperator IdentityOperator ContractedOperator Base.in(orbital::O, co::ContractedOperator) where O Base.in(corbital::Conjugate{O}, co::ContractedOperator) where O contract complement LinearAlgebra.ishermitian(::QuantumOperator) ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
2560
Throughout, [Einstein notation](https://en.wikipedia.org/wiki/Einstein_notation) is employed, meaning that indices appearing twice on only one side of an equation are summed over, e.g.: $$c = \braket{i}{i} \iff c \equiv \sum_i \braket{i}{i},$$ whereas $$c_{ka} = \braket{a}{k}$$ implies no summation. # Spin-orbitals $$\begin{equation} \chi_a(\tau_i) \defd \psi_a(\vec{r}_i)\sigma_a(s_i), \end{equation}$$ where $\sigma(s)$ is either $\alpha$ (spin up) or $\beta$ (spin down). The overlap between two spin-orbitals is given by $$\begin{equation} \braket{i}{j} \defd \int\diff{\tau} \conj{\chi_i}(\tau) \chi_j(\tau), \end{equation}$$ which, the case of orthogonal bases (this is a matter of choice), simplifies to $$\braket{i}{j} = \delta_{ij}.$$ # One-body matrix elements $$\begin{equation} I(a,b) \equiv \onebody{a}{b} \defd \matrixel{a}{\hamiltonian}{b}, \end{equation}$$ where $$\begin{equation} \hamiltonian \defd T + V \end{equation}$$ is the (possibly time-dependent) one-body Hamiltonian. # Two-body matrix elements $$\begin{equation} \twobodydx{ab}{cd} \defd \twobody{ab}{cd} - \twobody{ab}{dc}, \end{equation}$$ where $$\begin{equation} \begin{aligned} \twobody{ab}{cd} &\defd \int\diff{\tau_1}\diff{\tau_2} \conj{\chi_a}(\tau_1) \conj{\chi_b}(\tau_2) \frac{1}{r_{12}} \chi_c(\tau_1) \chi_d(\tau_2) \\ &= \delta(\sigma_a,\sigma_c) \delta(\sigma_b,\sigma_d) \int\diff{\vec{r}_1}\diff{\vec{r}_2} \conj{\chi_a}(\vec{r}_1) \conj{\chi_b}(\vec{r}_2) \frac{1}{r_{12}} \chi_c(\vec{r}_1) \chi_d(\vec{r}_2). \end{aligned} \end{equation}$$ The special case $$\begin{equation} F(a,b) \defd \twobody{ab}{ab} \end{equation}$$ is called the *direct interaction* (gives rise to the screening potential), and the other special case $$\begin{equation} G(a,b) \defd \twobody{ab}{ba} \end{equation}$$ is called the *exchange interaction* (gives rise to the non-local potential). !!! note Since $$\begin{equation} \twobodydx{ii}{ii} = 0, \end{equation}$$ we have $$\begin{equation} \frac{1}{2}\twobodydx{ij}{ij} \equiv \sum_{i,j<i}\twobodydx{ij}{ij}, \end{equation}$$ i.e. we sum over $i,j$, divide by two to avoid double-counting and avoid automatically the case $i=j$. # Repulsion potential We also have the repulsion potential formed from two orbitals $a,b$: $$\begin{equation} \twobody{a}{b} \defd \int\diff{\tau_1}\conj{\chi_a}(\tau_1)\frac{1}{r_{12}}\chi_b(\tau_1)= \delta(\sigma_a,\sigma_b)\int\diff{\vec{r}_1}\conj{\chi_a}(\vec{r}_1)\frac{1}{r_{12}}\chi_b(\vec{r}_1). \end{equation}$$
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
842
# Slater determinants [Slater determinants](https://en.wikipedia.org/wiki/Slater_determinant) are wavefunctions constructed from anti-symmetrized one-particle states. ```@meta CurrentModule = EnergyExpressions DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` ## Construction of Slater determinants ```@docs SlaterDeterminant SlaterDeterminant(::Configuration{<:SpinOrbital}) length(::SlaterDeterminant) AdjointSlaterDeterminant adjoint(::SlaterDeterminant) length(::AdjointSlaterDeterminant) ``` ## Example usage ```jldoctest julia> sa = SlaterDeterminant([:l, :a]) l(1)a(2) - l(2)a(1) julia> sb = SlaterDeterminant([:k, :b]) k(1)b(2) - k(2)b(1) julia> using AtomicLevels julia> SlaterDeterminant(spin_configurations(c"1s2")[1]) 1s₀α(1)1s₀β(2) - 1s₀α(2)1s₀β(1) ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
10443
# System of equations When dealing with large energy expressions resulting from many configurations, when deriving the orbital equations (see [N-body equations](@ref) and [Calculus of Variations – Implementation](@ref)), many of the integrals involved will be shared between the different terms of the equations. It is therefore of interest to gather a list of integrals that can be calculated once at every iteration (in a self-consistent procedure for finding eigenstates, or in time-propagation), and whose values can then be reused when solving the individual equations. The routines described below, although primitive, aid in this effort. The idea is the following: With an energy expression on the form $$\begin{equation} E(\vec{P},\vec{c}) = \frac{\vec{c}^H \mat{H}\vec{c}}{\vec{c}^H\vec{c}} \end{equation}$$ where $\vec{P}$ is a set of orbitals, $\vec{c}$ is a vector of mixing coefficients, and $$\begin{equation} \mat{H}_{ij} \defd \matrixel{\chi_i}{\Hamiltonian}{\chi_j}, \end{equation}$$ all terms of the equations can be written on the form $$\begin{equation} \label{eqn:equation-term} \operator{A}\ket{\chi} \underbrace{\left[ \sum_n \alpha_n \conj{c}_{i_n} c_{j_n} \prod_k \int_{n_k} \right]}_{\textrm{Rank 0}}, \end{equation}$$ (or on its dual form with conjugated orbitals) where $\operator{A}$ is some one-body operator, $\alpha_n$ a coefficient due to the energy expression, $\conj{c}_{i_n} c_{j_n}$ the coefficient due to the multi-configurational expansion, and finally $\int_{n_k}$ all the extra integrals (which are necessarily zero-body operators) that may appear due to non-orthogonal orbitals (and which may be shared between many equations). The operator $\operator{A}$ can have ranks 0–2; formally, it can only have rank 0 (multiplication by a scalar) or 2 (multiplication by a matrix). What we somewhat sloppily to refer by “rank 1” is an operator of rank 2, but which is diagonal in the underlying coordinate, such as a local potential. Thus, to efficiently perform an iteration, one would first compute all common integrals $\int_k$, and then for every equation term of the form $\eqref{eqn:equation-term}$, form the coefficient in the brakets, calculate the action of the operator $\operator{A}$ on the orbital $\chi$, multiplied the coefficient. There are a few important special cases of $\eqref{eqn:equation-term}$: 1) Field-free, one-body Hamiltonian, i.e. $\operator{A}=\hamiltonian_0$. This is the contribution from the orbital $\ket{\chi}$ to itself. Rank 2. 2) One-body Hamiltonian, including field, i.e. $\operator{A}=\hamiltonian$. This is the contribution from another orbital $\ket{\chi'}$ to $\ket{\chi}$ via some off-diagonal coupling, such as an external field (e.g. an electro–magnetic field). Rank 2. 3) Direct interaction, i.e. $\operator{A}=\direct{kl}$, where two other orbitals $\ket{\chi_k}$ and $\ket{\chi_l}$ together form a potential acting on $\ket{\chi}$. “Rank 1”. 4) Exchange interaction, i.e. $\operator{A}=\exchange{kl}$, where another orbital $\ket{\chi_k}$ and $\ket{\chi}$ together form a potential acting on a third orbital $\ket{\chi_l}$. Rank 2. 5) Source term, i.e. a contribution that does not involve $\ket{\chi}$ in any way. This term arises from other configurations in the multi-configurational expansion. Case 2. is also formulated in this way. Rank 0–2. If for some reason the source orbital and/or the operator acting on it is fixed, it may be possible to precompute the effect of the operator on the source orbital and reduce the computational complexity to a rank 0-equivalent operation. ```@meta CurrentModule = EnergyExpressions DocTestSetup = quote using EnergyExpressions end ``` ## Example We start by defining a set of configurations and specifying that a few of the constituent orbitals are non-orthogonal: ```jldoctest mc-eqs julia> cfgs = [[:i, :j, :l, :k̃], [:i, :j, :k, :l̃]] 2-element Array{Array{Symbol,1},1}: [:i, :j, :l, :k̃] [:i, :j, :k, :l̃] julia> continua = [:k̃, :l̃] 2-element Array{Symbol,1}: :k̃ :l̃ julia> overlaps = [OrbitalOverlap(i,j) for i in continua for j in continua] 4-element Array{OrbitalOverlap{Symbol,Symbol},1}: ⟨k̃|k̃⟩ ⟨k̃|l̃⟩ ⟨l̃|k̃⟩ ⟨l̃|l̃⟩ ``` We then set up the energy expression as before: ```jldoctest mc-eqs julia> H = OneBodyHamiltonian() + CoulombInteraction() ĥ + ĝ julia> E = Matrix(H, SlaterDeterminant.(cfgs), overlaps) 2×2 Array{EnergyExpressions.NBodyMatrixElement,2}: (i|i)⟨k̃|k̃⟩ + (j|j)⟨k̃|k̃⟩ + (l|l)⟨k̃|k̃⟩ + (k̃|k̃) - G(i,j)⟨k̃|k̃⟩ + F(i,j)⟨k̃|k̃⟩ + … - G(i,k̃) + F(i,k̃) - G(j,k̃) + F(j,k̃) - G(l,k̃) + F(l,k̃) … (l|k)⟨k̃|l̃⟩ - [i l|k i]⟨k̃|l̃⟩ + [i l|i k]⟨k̃|l̃⟩ - [j l|k j]⟨k̃|l̃⟩ + [j l|j k]⟨k̃|l̃⟩ - [l k̃|l̃ k] + [l k̃|k l̃] (k|l)⟨l̃|k̃⟩ - [i k|l i]⟨l̃|k̃⟩ + [i k|i l]⟨l̃|k̃⟩ - [j k|l j]⟨l̃|k̃⟩ + [j k|j l]⟨l̃|k̃⟩ - [k l̃|k̃ l] + [k l̃|l k̃] (i|i)⟨l̃|l̃⟩ + (j|j)⟨l̃|l̃⟩ + (k|k)⟨l̃|l̃⟩ + (l̃|l̃) - G(i,j)⟨l̃|l̃⟩ + F(i,j)⟨l̃|l̃⟩ + … - G(i,l̃) + F(i,l̃) - G(j,l̃) + F(j,l̃) - G(k,l̃) + F(k,l̃) ``` Finally, we derive the coupled integro-differential equation system for the continuum orbitals `k̃`, `l̃`: ```jldoctest mc-eqs julia> eqs = diff(E, Conjugate.(continua)) EnergyExpressions.MCEquationSystem(EnergyExpressions.OrbitalEquation{Symbol,SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64}}[OrbitalEquation(k̃): [1, 1] = + (i|i)𝐈₁|k̃⟩ + (j|j)𝐈₁|k̃⟩ + (l|l)𝐈₁|k̃⟩ + ĥ|k̃⟩ - G(i,j)𝐈₁|k̃⟩ + F(i,j)𝐈₁|k̃⟩ - G(i,l)𝐈₁|k̃⟩ + F(i,l)𝐈₁|k̃⟩ - G(j,l)𝐈₁|k̃⟩ + F(j,l)𝐈₁|k̃⟩ - [i|k̃]|i⟩ + [i|i]|k̃⟩ - [j|k̃]|j⟩ + [j|j]|k̃⟩ - [l|k̃]|l⟩ + [l|l]|k̃⟩ [1, 2] = + (l|k)𝐈₁|l̃⟩ - [i l|k i]𝐈₁|l̃⟩ + [i l|i k]𝐈₁|l̃⟩ - [j l|k j]𝐈₁|l̃⟩ + [j l|j k]𝐈₁|l̃⟩ - [l|l̃]|k⟩ + [l|k]|l̃⟩ , OrbitalEquation(l̃): [2, 1] = + (k|l)𝐈₁|k̃⟩ - [i k|l i]𝐈₁|k̃⟩ + [i k|i l]𝐈₁|k̃⟩ - [j k|l j]𝐈₁|k̃⟩ + [j k|j l]𝐈₁|k̃⟩ - [k|k̃]|l⟩ + [k|l]|k̃⟩ [2, 2] = + (i|i)𝐈₁|l̃⟩ + (j|j)𝐈₁|l̃⟩ + (k|k)𝐈₁|l̃⟩ + ĥ|l̃⟩ - G(i,j)𝐈₁|l̃⟩ + F(i,j)𝐈₁|l̃⟩ - G(i,k)𝐈₁|l̃⟩ + F(i,k)𝐈₁|l̃⟩ - G(j,k)𝐈₁|l̃⟩ + F(j,k)𝐈₁|l̃⟩ - [i|l̃]|i⟩ + [i|i]|l̃⟩ - [j|l̃]|j⟩ + [j|j]|l̃⟩ - [k|l̃]|k⟩ + [k|k]|l̃⟩ ], Any[(i|i), (j|j), (l|l), G(i,j), F(i,j), G(i,l), F(i,l), G(j,l), F(j,l), [i|i] … [j k|l j], [j k|j l], [k|k̃], [k|l], (k|k), G(i,k), F(i,k), G(j,k), F(j,k), [k|k]]) ``` We can investigate the [`MCEquationSystem`](@ref) object `eqs` a bit. It consists of two coupled equations: ```jldoctest mc-eqs julia> eqs.equations 2-element Array{EnergyExpressions.OrbitalEquation{Symbol,SparseArrays.SparseMatrixCSC{LinearCombinationEquation,Int64}},1}: OrbitalEquation(k̃): [1, 1] = + (i|i)𝐈₁|k̃⟩ + (j|j)𝐈₁|k̃⟩ + (l|l)𝐈₁|k̃⟩ + ĥ|k̃⟩ - G(i,j)𝐈₁|k̃⟩ + F(i,j)𝐈₁|k̃⟩ - G(i,l)𝐈₁|k̃⟩ + F(i,l)𝐈₁|k̃⟩ - G(j,l)𝐈₁|k̃⟩ + F(j,l)𝐈₁|k̃⟩ - [i|k̃]|i⟩ + [i|i]|k̃⟩ - [j|k̃]|j⟩ + [j|j]|k̃⟩ - [l|k̃]|l⟩ + [l|l]|k̃⟩ [1, 2] = + (l|k)𝐈₁|l̃⟩ - [i l|k i]𝐈₁|l̃⟩ + [i l|i k]𝐈₁|l̃⟩ - [j l|k j]𝐈₁|l̃⟩ + [j l|j k]𝐈₁|l̃⟩ - [l|l̃]|k⟩ + [l|k]|l̃⟩ OrbitalEquation(l̃): [2, 1] = + (k|l)𝐈₁|k̃⟩ - [i k|l i]𝐈₁|k̃⟩ + [i k|i l]𝐈₁|k̃⟩ - [j k|l j]𝐈₁|k̃⟩ + [j k|j l]𝐈₁|k̃⟩ - [k|k̃]|l⟩ + [k|l]|k̃⟩ [2, 2] = + (i|i)𝐈₁|l̃⟩ + (j|j)𝐈₁|l̃⟩ + (k|k)𝐈₁|l̃⟩ + ĥ|l̃⟩ - G(i,j)𝐈₁|l̃⟩ + F(i,j)𝐈₁|l̃⟩ - G(i,k)𝐈₁|l̃⟩ + F(i,k)𝐈₁|l̃⟩ - G(j,k)𝐈₁|l̃⟩ + F(j,k)𝐈₁|l̃⟩ - [i|l̃]|i⟩ + [i|i]|l̃⟩ - [j|l̃]|j⟩ + [j|j]|l̃⟩ - [k|l̃]|k⟩ + [k|k]|l̃⟩ ``` The first equation consists of the following terms: ```jldoctest mc-eqs julia> eqs.equations[1].terms 6-element Array{Pair{Int64,Array{EnergyExpressions.MCTerm,1}},1}: 0 => [MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [1]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [2]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [3]), MCTerm{Int64,OneBodyHamiltonian,Symbol}(1, 1, 1, ĥ, :k̃, Int64[]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, -1, 𝐈₁, :k̃, [4]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [5]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, -1, 𝐈₁, :k̃, [6]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [7]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, -1, 𝐈₁, :k̃, [8]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 1, 1, 𝐈₁, :k̃, [9]), MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, -1, [i|k̃], :i, Int64[]), MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, -1, [j|k̃], :j, Int64[]), MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, -1, [l|k̃], :l, Int64[]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 2, 1, 𝐈₁, :l̃, [13]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 2, -1, 𝐈₁, :l̃, [14]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 2, 1, 𝐈₁, :l̃, [15]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 2, -1, 𝐈₁, :l̃, [16]), MCTerm{Int64,IdentityOperator{1},Symbol}(1, 2, 1, 𝐈₁, :l̃, [17])] 10 => [MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, 1, [i|i], :k̃, Int64[])] 19 => [MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 2, 1, [l|k], :l̃, Int64[])] 11 => [MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, 1, [j|j], :k̃, Int64[])] 12 => [MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 1, 1, [l|l], :k̃, Int64[])] 18 => [MCTerm{Int64,ContractedOperator{1,2,1,Symbol,CoulombInteraction,Symbol},Symbol}(1, 2, -1, [l|l̃], :k, Int64[])] ``` where the [`MCTerm`](@ref) objects indicate which components of the mixing coefficient vector $\vec{c}$ need to be multiplied, and all the integers are pointers to the list of common integrals: ```jldoctest mc-eqs julia> eqs.integrals 32-element Array{Any,1}: (i|i) (j|j) (l|l) G(i,j) F(i,j) G(i,l) F(i,l) G(j,l) F(j,l) [i|i] [j|j] [l|l] (l|k) [i l|k i] [i l|i k] [j l|k j] [j l|j k] [l|l̃] [l|k] (k|l) [i k|l i] [i k|i l] [j k|l j] [j k|j l] [k|k̃] [k|l] (k|k) G(i,k) F(i,k) G(j,k) F(j,k) [k|k] ``` From this we see that the `𝐈₁` (one-body identity operator) contribution to `|k̃⟩` can be written as a linear combination of `|k̃⟩` and `|l̃⟩`, weighted by different components of the mixing coefficient vector $\vec{c}$ and various other integrals. This is all the information necessary to set up an efficient equation solver. ## Implementation ```@docs MCTerm OrbitalEquation orbital_equation MCEquationSystem pushifmissing! ``` ```@meta CurrentModule = nothing DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.4
68a1812db09470298cf4b01852dd904d777d0b2d
docs
189
# Calculus of Variations – Implementation ```@meta DocTestSetup = quote using EnergyExpressions using AtomicLevels end ``` ```@docs diff ``` ```@meta DocTestSetup = nothing ```
EnergyExpressions
https://github.com/JuliaAtoms/EnergyExpressions.jl.git
[ "MIT" ]
0.1.0
00d9140789be6f702ef5846fc9b9e34a62cb8c8b
code
6953
module OwnTime export owntime, totaltime, filecontains export framecounts, frametotal, frames using Printf using Profile const StackFrame = StackTraces.StackFrame function countmap(iter) result = Dict{eltype(iter), Int64}() for i in iter if haskey(result, i) result[i] += 1 else result[i] = 1 end end result end mutable struct OwnTimeState lookups :: Dict{UInt64, Vector{StackFrame}} end const state = OwnTimeState(Dict{UInt64, Vector{StackFrame}}()) """ clear() OwnTime has an internal cache for performance. Clear that cache. See also: [`Profile.clear`](@ref) """ function clear() state.lookups = Dict{UInt64, Vector{StackFrame}}() end """ fetch() Return a 2-tuple of the form `(instruction_pointers, is_profile_buffer_full)`. This function is primarily for internal use. See also: [`Profile.fetch`](@ref) """ function fetch() maxlen = Profile.maxlen_data() len = Profile.len_data() data = Vector{UInt}(undef, len) GC.@preserve data unsafe_copyto!(pointer(data), Profile.get_data_pointer(), len) return data, len == maxlen end """ backtraces(;warn_on_full_buffer=true) Return an array of backtraces. A backtrace is an array of instruction pointers. This function is primarily for internal use, try calling `OwnTime.stacktraces()` instead. This function may give a warning if Julia's profiling buffer is full. This warning can be disabled with the relative function parameter. See also: [`backtrace`](@ref) """ function backtraces(;warn_on_full_buffer=true) profile_pointers, full_buffer = fetch() if warn_on_full_buffer && full_buffer @warn """The profile data buffer is full; profiling probably terminated before your program finished. To profile for longer runs, call `Profile.init()` with a larger buffer and/or larger delay.""" end bts = Vector{UInt64}[] i = 1 for j in 1:length(profile_pointers) # 0 is a sentinel value that indicates the start of a new backtrace. # See the source code for `tree!` in Julia's Profile package. if profile_pointers[j] == 0 push!(bts, profile_pointers[i:j-1]) i = j+1 end end filter(!isempty, bts) end """ lookup(p::UInt64) Similar to `StackTraces.lookup`, but internally caches lookup results for performance. Cache can be cleared with `OwnTime.clear()`. This function is for internal use. See also: [`StackTraces.lookup`](@ref) [`OwnTime.clear`](@ref) """ function lookup(p::UInt64) if !haskey(state.lookups, p) state.lookups[p] = StackTraces.lookup(p) end state.lookups[p] end """ stacktraces([backtraces]; warn_on_full_buffer=true) Return an array of `StackTrace`s. A `StackTrace` is an array of `StackFrame`s. This function may take several minutes if you have a large profile buffer. See also: [`stacktrace`](@ref), [`StackTraces.StackTrace`](@ref), [`StackTraces.StackFrame`](@ref) """ function stacktraces(;warn_on_full_buffer=true) bts = backtraces(warn_on_full_buffer=warn_on_full_buffer) stacktraces(bts) end function stacktraces(backtraces) map(backtraces) do backtrace filter(reduce(vcat, lookup.(backtrace))) do stackframe stackframe.from_c == false end end end struct FrameCounts counts :: Vector{Pair{StackFrame,Int64}} total :: Int64 end framecounts(fcs::FrameCounts) = fcs.counts frametotal(fcs::FrameCounts) = fcs.total frames(fcs::FrameCounts) = map(fcs -> fcs.first, fcs.counts) Base.getindex(fcs::FrameCounts, i) = framecounts(fcs)[i] Base.iterate(fcs::FrameCounts) = iterate(framecounts(fcs)) Base.iterate(fcs::FrameCounts, s) = iterate(framecounts(fcs), s) Base.length(fcs::FrameCounts) = length(framecounts(fcs)) function Base.show(io::IO, fcs::FrameCounts) for (i, (stackframe, count)) in enumerate(fcs) percent_of_time = round(count / frametotal(fcs) * 100) if percent_of_time >= 1 @printf(io, "%4s %3d%% => %s\n", @sprintf("[%d]", i), percent_of_time, stackframe) end end end """ owntime([stacktraces]; stackframe_filter, warn_on_full_buffer=true) Count the time spent on each `StackFrame` *excluding* its sub-calls. If supplied, `stackframe_filter` should be a function that accepts a single `StackFrame` and returns `true` if it should be included in the counts. More advance filtering my by done by preprocessing the `StackTrace`s from `OwnTime.stacktraces()` and then passing those `StackTrace`s to this function. See also: [`OwnTime.stacktraces`](@ref) [`StackTraces.StackFrame`](@ref) """ function owntime(;stackframe_filter=stackframe -> true, warn_on_full_buffer=true) sts = stacktraces(warn_on_full_buffer=warn_on_full_buffer) owntime(sts; stackframe_filter=stackframe_filter) end function owntime(stacktraces; stackframe_filter=stackframe -> true) filtered_stacktraces = map(stacktraces) do stackframes filter(stackframe_filter, stackframes) end nonempty_stacktraces = filter(!isempty, filtered_stacktraces) framecounts = countmap(reduce(vcat, first.(nonempty_stacktraces), init=StackFrame[])) FrameCounts(sort(collect(framecounts), by=pair -> pair.second, rev=true), length(stacktraces)) end """ totaltime([stacktraces]; stackframe_filter, warn_on_full_buffer=true) Count the time spent on each `StackFrame` *including* its sub-calls. If supplied, `stackframe_filter` should be a function that accepts a single `StackFrame` and returns `true` if it should be included in the counts. More advance filtering my by done by preprocessing the `StackTrace`s from `OwnTime.stacktraces()` and then passing those `StackTrace`s to this function. See also: [`OwnTime.stacktraces`](@ref) [`StackTraces.StackFrame`](@ref) """ function totaltime(;stackframe_filter=stackframe -> true, warn_on_full_buffer=true) sts = stacktraces(warn_on_full_buffer=warn_on_full_buffer) totaltime(sts; stackframe_filter=stackframe_filter) end function totaltime(stacktraces; stackframe_filter=stackframe -> true) filtered_stacktraces = map(stacktraces) do stackframes filter(stackframe_filter, stackframes) end framecounts = countmap(reduce(vcat, collect.(unique.(filtered_stacktraces)), init=StackFrame[])) FrameCounts(sort(collect(framecounts), by=pair -> pair.second, rev=true), length(stacktraces)) end """ filecontains(needle) A `StackFrame` filter that returns `true` if the given `StackFrame` has `needle` in its file path. # Example ```julia-repl julia> stackframe = stacktrace()[1] top-level scope at REPL[6]:1 julia> stackframe.file Symbol("REPL[6]") julia> filecontains("REPL")(stackframe) true ``` See also: [`StackTraces.StackFrame`](@ref) """ function filecontains(needle) function (stackframe) haystack = string(stackframe.file) occursin(needle, haystack) end end end # module
OwnTime
https://github.com/DevJac/OwnTime.jl.git
[ "MIT" ]
0.1.0
00d9140789be6f702ef5846fc9b9e34a62cb8c8b
code
233
using OwnTime using Profile function profile_me() A = rand(200, 200, 400) maximum(A) end Profile.init(1_000_000, 0.001) Profile.clear() @profile profile_me() owntime() t = totaltime() framecounts(t) frametotal(t) frames(t)
OwnTime
https://github.com/DevJac/OwnTime.jl.git
[ "MIT" ]
0.1.0
00d9140789be6f702ef5846fc9b9e34a62cb8c8b
docs
3558
# OwnTime.jl OwnTime provides two additional ways to view [Julia's Profile](https://docs.julialang.org/en/v1/manual/profile/) data. # Basic Usage Let's say we have the following code in `mycode.jl`: ```julia function myfunc() A = rand(200, 200, 400) maximum(A) end ``` We profile our code in the usual way: ```julia julia> include("mycode.jl") myfunc (generic function with 1 method) julia> myfunc() # run once to force JIT compilation 0.9999999760080607 julia> using Profile julia> @profile myfunc() 0.9999999988120492 ``` We can now view our profiling data using `owntime` or `totaltime`: ```julia julia> owntime() [1] 63% => dsfmt_fill_array_close_open!(::Random.DSFMT.DSFMT_state, ::Ptr{Float64}, ...) at DSFMT.jl:95 [2] 13% => _fast at reduce.jl:454 [inlined] [3] 11% => eval(::Module, ::Any) at boot.jl:330 [4] 8% => Array at boot.jl:408 [inlined] [5] 1% => != at float.jl:456 [inlined] julia> totaltime() [1] 96% => eval(::Module, ::Any) at boot.jl:330 [2] 96% => (::REPL.var"#26#27"{REPL.REPLBackend})() at task.jl:333 [3] 96% => macro expansion at REPL.jl:118 [inlined] [4] 96% => eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:86 [5] 72% => myfunc() at mycode.jl:2 [6] 72% => rand at Random.jl:277 [inlined] [7] 63% => rand(::Type{Float64}, ::Tuple{Int64,Int64,Int64}) at gcutils.jl:91 ... [11] 14% => myfunc() at mycode.jl:3 ... ``` ## `owntime` vs `totaltime` `totaltime` show the amount of time spent on a StackFrame *including* its sub-calls. `owntime` shows the amount of time spent on a StackFrame *excluding* its sub-calls. ## Filtering StackFrames We can filter [StackFrames](https://docs.julialang.org/en/v1/base/stacktraces/#Base.StackTraces.StackFrame) to shorten the output: ```julia julia> owntime(stackframe_filter=filecontains("mycode.jl")) [1] 72% => myfunc() at mycode.jl:2 [2] 14% => myfunc() at mycode.jl:3 julia> totaltime(stackframe_filter=filecontains("mycode.jl")) [1] 72% => myfunc() at mycode.jl:2 [2] 14% => myfunc() at mycode.jl:3 julia> owntime(stackframe_filter=stackframe -> stackframe.func == :myfunc) [1] 72% => myfunc() at mycode.jl:2 [2] 14% => myfunc() at mycode.jl:3 ``` It's now clear that 72% of the time was spent on line 2 of our code, and 14% on line 3. The rest of the time was spent on overhead related to Julia and profiling; for such a small example a relatively large amount of time is spent on that overhead. `stackframe_filter` should be passed a function that accepts a single [`StackFrame`](https://docs.julialang.org/en/v1/base/stacktraces/#Base.StackTraces.StackFrame) and returns `true` if that StackFrame should be included. # How does this relate to Profile in Julia's standard library? OwnTime merely provides an alternate view into the profiling data collected by Julia. It is complimentary to the [Profile](https://docs.julialang.org/en/v1/stdlib/Profile/) package in the standard library. `totaltime` provides a view of the profiling data similar to the flat format of [`Profile.print(format=:flat)`](https://docs.julialang.org/en/v1/stdlib/Profile/#Profile.print). `owntime` is a view unique to OwnTime*, hence the name. The ability to filter [StackFrames](https://docs.julialang.org/en/v1/base/stacktraces/#Base.StackTraces.StackFrame) is unique to OwnTime*. OwnTime can take a several minutes to process large amounts of profiling data. [Profile](https://docs.julialang.org/en/v1/stdlib/Profile/) in the standard library does not have this problem. (\* At this time, and as far as I'm aware.)
OwnTime
https://github.com/DevJac/OwnTime.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
771
using DifferentiableFrankWolfe using Documenter using Literate DocMeta.setdocmeta!( DifferentiableFrankWolfe, :DocTestSetup, :(using DifferentiableFrankWolfe); recursive=true, ) Literate.markdown( joinpath(@__DIR__, "..", "examples", "tutorial.jl"), joinpath(@__DIR__, "src"); documenter=true, flavor=Literate.DocumenterFlavor(), ) makedocs(; modules=[DifferentiableFrankWolfe], authors="Guillaume Dalle", sitename="DifferentiableFrankWolfe.jl", format=Documenter.HTML(; canonical="https://gdalle.github.io/DifferentiableFrankWolfe.jl", edit_link="main" ), pages=["Home" => "index.md", "Tutorial" => "tutorial.md"], ) deploydocs(; repo="github.com/gdalle/DifferentiableFrankWolfe.jl", devbranch="main")
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
1001
# # Tutorial # Necessary imports using DifferentiableFrankWolfe: DiffFW, simplex_projection using ForwardDiff: ForwardDiff using FrankWolfe: UnitSimplexOracle using Test: @test using Zygote: Zygote # Constructing the wrapper f(x, θ) = 0.5 * sum(abs2, x - θ) # minimizing the squared distance... f_grad1(x, θ) = x - θ lmo = UnitSimplexOracle(1.0) # ... to the probability simplex dfw = DiffFW(f, f_grad1, lmo); # ... is equivalent to a simplex projection # Calling the wrapper θ = rand(10) #- frank_wolfe_kwargs = (max_iteration=100, epsilon=1e-4) y = dfw(θ; frank_wolfe_kwargs) #- y_true = simplex_projection(θ) @test Vector(y) ≈ Vector(y_true) atol = 1e-3 # Differentiating the wrapper J1 = Zygote.jacobian(_θ -> dfw(_θ; frank_wolfe_kwargs), θ)[1] J1_true = Zygote.jacobian(simplex_projection, θ)[1] @test J1 ≈ J1_true atol = 1e-3 #- J2 = ForwardDiff.jacobian(_θ -> dfw(_θ; frank_wolfe_kwargs), θ) J2_true = ForwardDiff.jacobian(simplex_projection, θ) @test J2 ≈ J2_true atol = 1e-3
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
653
""" DifferentiableFrankWolfe Differentiable wrapper for [FrankWolfe.jl](https://github.com/ZIB-IOL/FrankWolfe.jl) convex optimization routines. """ module DifferentiableFrankWolfe using ChainRulesCore: ChainRulesCore, NoTangent using FrankWolfe: FrankWolfe, LinearMinimizationOracle using FrankWolfe: away_frank_wolfe, compute_extreme_point using ImplicitDifferentiation: ImplicitFunction, IterativeLinearSolver using LinearAlgebra: dot export DiffFW export LinearMinimizationOracle, compute_extreme_point # from FrankWolfe export IterativeLinearSolver # from ImplicitDifferentiation include("simplex_projection.jl") include("difffw.jl") end
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
2821
""" ForwardFW{F,G,M,A} Underlying solver for [`DiffFW`](@ref), which relies on a variant of Frank-Wolfe. """ struct ForwardFW{F,G,M,A} f::F f_grad1::G lmo::M alg::A end """ ConditionsFW{F,G,M} Differentiable optimality conditions for [`DiffFW`](@ref), which rely on a custom [`simplex_projection`](@ref) implementation. """ struct ConditionsFW{G} f_grad1::G end """ DiffFW{F,G,M,A,I} Callable parametrized wrapper for the Frank-Wolfe algorithm `θ -> argmin_{x ∈ C} f(x, θ)`, which can be differentiated implicitly wrt `θ`. Reference: <https://arxiv.org/abs/2105.15183> (section 2 + end of appendix A). # Fields - `f::F`: function `f(x, θ)` to minimize wrt `x` - `f_grad1::G`: gradient `∇ₓf(x, θ)` of `f` wrt `x` - `lmo::M`: linear minimization oracle `θ -> argmin_{x ∈ C} θᵀx` from [FrankWolfe.jl], implicitly defines the convex set `C` - `alg::A`: optimization algorithm from [FrankWolfe.jl](https://github.com/ZIB-IOL/FrankWolfe.jl) - `implicit::I`: implicit function from [ImplicitDifferentiation.jl](https://github.com/gdalle/ImplicitDifferentiation.jl) """ struct DiffFW{F,G,M<:LinearMinimizationOracle,A,I<:ImplicitFunction} f::F f_grad1::G lmo::M alg::A implicit::I end """ DiffFW(f, f_grad1, lmo[; alg=away_frank_wolfe, implicit_kwargs=(;)]) Constructor which chooses a default algorithm and creates the implicit function automatically. """ function DiffFW(f, f_grad1, lmo; alg=away_frank_wolfe, implicit_kwargs=NamedTuple()) forward = ForwardFW(f, f_grad1, lmo, alg) conditions = ConditionsFW(f_grad1) implicit = ImplicitFunction(forward, conditions; implicit_kwargs...) return DiffFW(f, f_grad1, lmo, alg, implicit) end """ dfw(θ; frank_wolfe_kwargs) Apply the Frank-Wolfe algorithm to `θ` with settings defined by `frank_wolfe_kwargs`. """ function (dfw::DiffFW)(θ::AbstractArray{<:Real}; kwargs...) p, V = dfw.implicit(θ; kwargs...) return sum(pᵢ * Vᵢ for (pᵢ, Vᵢ) in zip(p, V)) end function (forward::ForwardFW)( θ::AbstractArray{<:Real}; frank_wolfe_kwargs=NamedTuple(), kwargs... ) f, f_grad1, lmo, alg = forward.f, forward.f_grad1, forward.lmo, forward.alg obj(x) = f(x, θ) grad!(g, x) = g .= f_grad1(x, θ) x0 = compute_extreme_point(lmo, θ) x, v, primal, dual_gap, traj_data, active_set = alg( obj, grad!, lmo, x0; frank_wolfe_kwargs... ) p, V = active_set.weights, active_set.atoms return p, V end function (conditions::ConditionsFW)( θ::AbstractArray{<:Real}, p::AbstractVector{<:Real}, V::AbstractVector{<:AbstractArray{<:Real}}; kwargs..., ) f_grad1 = conditions.f_grad1 x = sum(pᵢ * Vᵢ for (pᵢ, Vᵢ) in zip(p, V)) ∇ₓf = f_grad1(x, θ) ∇ₚg = [dot(Vᵢ, ∇ₓf) for Vᵢ in V] T = simplex_projection(p .- ∇ₚg) return T .- p end
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
1312
""" simplex_projection(z) Compute the Euclidean projection of the vector `z` onto the probability simplex. This function is differentiable thanks to a custom chain rule. Reference: <https://arxiv.org/abs/1602.02068>. """ function simplex_projection(z::AbstractVector{<:Real}; kwargs...) p, _ = simplex_projection_and_support(z) return p end """ simplex_projection_and_support(z) Compute the Euclidean projection `p` of `z` on the probability simplex as well as the indicators `s` of its support, which are useful for differentiation. Reference: <https://arxiv.org/abs/1602.02068>. """ function simplex_projection_and_support(z::AbstractVector{<:Real}) d = length(z) z_sorted = sort(z; rev=true) z_sorted_cumsum = cumsum(z_sorted) k = maximum(j for j in 1:d if (1 + j * z_sorted[j]) > z_sorted_cumsum[j]) τ = (z_sorted_cumsum[k] - 1) / k p = z .- τ p .= max.(p, zero(eltype(p))) s = [Int(p[i] > eps()) for i in 1:d] return p, s end function ChainRulesCore.rrule(::typeof(simplex_projection), z::AbstractVector{<:Real}) p, s = simplex_projection_and_support(z) S = sum(s) function simplex_projection_pullback(dp) vjp = s .* (dp .- dot(dp, s) / S) return (NoTangent(), vjp) end return p, simplex_projection_pullback end
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
code
1279
using Aqua using DifferentiableFrankWolfe using Documenter using ImplicitDifferentiation using JET using JuliaFormatter using Test using Zygote @testset verbose = true "DifferentiableFrankWolfe.jl" begin @testset "Quality (Aqua.jl)" begin Aqua.test_all( DifferentiableFrankWolfe; ambiguities=false, deps_compat=(check_extras=false,) ) end @testset "Formatting (JuliaFormatter.jl)" begin @test format(DifferentiableFrankWolfe; verbose=false, overwrite=false) end @testset "Correctness (JET.jl)" begin if VERSION >= v"1.9" JET.test_package(DifferentiableFrankWolfe; target_defined_modules=true) end end @testset "Doctests (Documenter.jl)" begin doctest(DifferentiableFrankWolfe) end @testset "Tutorial" begin include(joinpath(@__DIR__, "..", "examples", "tutorial.jl")) end @testset "Constructor" begin dfw1 = DiffFW(f, f_grad1, lmo) @test !dfw1.implicit.linear_solver.accept_inconsistent implicit_kwargs = (; linear_solver=IterativeLinearSolver(; accept_inconsistent=true) ) dfw2 = DiffFW(f, f_grad1, lmo; implicit_kwargs) @test dfw2.implicit.linear_solver.accept_inconsistent end end
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
docs
1158
# DifferentiableFrankWolfe <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://gdalle.github.io/DifferentiableFrankWolfe.jl/stable/) --> [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://gdalle.github.io/DifferentiableFrankWolfe.jl/dev/) [![Build Status](https://github.com/gdalle/DifferentiableFrankWolfe.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/gdalle/DifferentiableFrankWolfe.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/gdalle/DifferentiableFrankWolfe.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/gdalle/DifferentiableFrankWolfe.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) <!-- [![PkgEval](https://JuliaCI.github.io/NanosoldierReports/pkgeval_badges/D/DifferentiableFrankWolfe.svg)](https://JuliaCI.github.io/NanosoldierReports/pkgeval_badges/report.html) --> Differentiable wrapper for [FrankWolfe.jl](https://github.com/ZIB-IOL/FrankWolfe.jl) convex optimization routines. Initially part of [InferOpt.jl](https://github.com/axelparmentier/InferOpt.jl).
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.2.1
6ee21e635eb1efb2182ba277828a35c555b7ede2
docs
349
```@meta CurrentModule = DifferentiableFrankWolfe ``` # DifferentiableFrankWolfe Documentation for [DifferentiableFrankWolfe.jl](https://github.com/gdalle/DifferentiableFrankWolfe.jl). ## Index ```@index ``` ## API reference ```@docs DifferentiableFrankWolfe DiffFW simplex_projection simplex_projection_and_support ForwardFW ConditionsFW ```
DifferentiableFrankWolfe
https://github.com/JuliaDecisionFocusedLearning/DifferentiableFrankWolfe.jl.git
[ "MIT" ]
0.17.0
325ecc57ccc9c83ab6eeaafb3eb038f8155b5357
code
1931
const outputname = joinpath(@__DIR__, "currency-data.jl") # First, check if currency-data.jl already exists isfile(outputname) && exit() # Make sure JSON3 is available using Pkg Pkg.add("JSON3") using JSON3 const src = "https://pkgstore.datahub.io/core/country-codes/country-codes_json/data/471a2e653140ecdd7243cdcacfd66608/country-codes_json.json" const inputname = joinpath(@__DIR__, "country-codes.json") const currency_list = Dict{String,Tuple{Int,Int,String}}() const SymCurr = Symbol("ISO4217-currency_alphabetic_code") const SymUnit = Symbol("ISO4217-currency_minor_unit") const SymName = Symbol("ISO4217-currency_name") const SymCode = Symbol("ISO4217-currency_numeric_code") function genfile(io) for country in country_list (abbrlist = country[SymCurr]) === nothing && continue (unitlist = country[SymUnit]) === nothing && continue (namelist = country[SymName]) === nothing && continue (codelist = country[SymCode]) === nothing && continue currencies = split(abbrlist, ',') units = split(string(unitlist), ',') names = split(namelist, ',') codes = split(string(codelist), ',') for (curr, unit, code, name) in zip(currencies, units, codes, names) length(curr) != 3 && continue haskey(currency_list, curr) && continue currency_list[curr] = (parse(Int, unit), parse(Int, code), string(name)) end end println(io, "const _currency_data = Dict(") for (curr, val) in currency_list println(io, " :$curr => (Currency{:$curr}, $(val[1]), $(lpad(val[2], 4)), \"$(val[3])\"),") end println(io, ")\n") end # Only download the file from datahub.io if not already present if !isfile(inputname) println("Downloading currency data: ", src) download(src, inputname) end const country_list = open(io -> JSON3.read(io), inputname) open(io -> genfile(io), outputname, "w")
Currencies
https://github.com/JuliaFinance/Currencies.jl.git
[ "MIT" ]
0.17.0
325ecc57ccc9c83ab6eeaafb3eb038f8155b5357
code
8499
const _currency_data = Dict( :KYD => (Currency{:KYD}, 2, 136, "Cayman Islands Dollar"), :PYG => (Currency{:PYG}, 0, 600, "Guarani"), :AWG => (Currency{:AWG}, 2, 533, "Aruban Florin"), :LAK => (Currency{:LAK}, 2, 418, "Lao Kip"), :TRY => (Currency{:TRY}, 2, 949, "Turkish Lira"), :UYU => (Currency{:UYU}, 2, 858, "Peso Uruguayo"), :NGN => (Currency{:NGN}, 2, 566, "Naira"), :QAR => (Currency{:QAR}, 2, 634, "Qatari Rial"), :EUR => (Currency{:EUR}, 2, 978, "Euro"), :TTD => (Currency{:TTD}, 2, 780, "Trinidad and Tobago Dollar"), :UAH => (Currency{:UAH}, 2, 980, "Hryvnia"), :XPF => (Currency{:XPF}, 0, 953, "CFP Franc"), :JPY => (Currency{:JPY}, 0, 392, "Yen"), :THB => (Currency{:THB}, 2, 764, "Baht"), :BHD => (Currency{:BHD}, 3, 48, "Bahraini Dinar"), :PEN => (Currency{:PEN}, 2, 604, "Sol"), :SOS => (Currency{:SOS}, 2, 706, "Somali Shilling"), :TJS => (Currency{:TJS}, 2, 972, "Somoni"), :SHP => (Currency{:SHP}, 2, 654, "Saint Helena Pound"), :AOA => (Currency{:AOA}, 2, 973, "Kwanza"), :SGD => (Currency{:SGD}, 2, 702, "Singapore Dollar"), :CHF => (Currency{:CHF}, 2, 756, "Swiss Franc"), :IDR => (Currency{:IDR}, 2, 360, "Rupiah"), :SDG => (Currency{:SDG}, 2, 938, "Sudanese Pound"), :IQD => (Currency{:IQD}, 3, 368, "Iraqi Dinar"), :EGP => (Currency{:EGP}, 2, 818, "Egyptian Pound"), :SLL => (Currency{:SLL}, 2, 694, "Leone"), :UZS => (Currency{:UZS}, 2, 860, "Uzbekistan Sum"), :MAD => (Currency{:MAD}, 2, 504, "Moroccan Dirham"), :MYR => (Currency{:MYR}, 2, 458, "Malaysian Ringgit"), :MMK => (Currency{:MMK}, 2, 104, "Kyat"), :DZD => (Currency{:DZD}, 2, 12, "Algerian Dinar"), :CAD => (Currency{:CAD}, 2, 124, "Canadian Dollar"), :HKD => (Currency{:HKD}, 2, 344, "Hong Kong Dollar"), :MWK => (Currency{:MWK}, 2, 454, "Malawi Kwacha"), :INR => (Currency{:INR}, 2, 356, "Indian Rupee"), :TZS => (Currency{:TZS}, 2, 834, "Tanzanian Shilling"), :BTN => (Currency{:BTN}, 2, 64, "Ngultrum"), :LRD => (Currency{:LRD}, 2, 430, "Liberian Dollar"), :DKK => (Currency{:DKK}, 2, 208, "Danish Krone"), :NAD => (Currency{:NAD}, 2, 516, "Namibia Dollar"), :PKR => (Currency{:PKR}, 2, 586, "Pakistan Rupee"), :JMD => (Currency{:JMD}, 2, 388, "Jamaican Dollar"), :XOF => (Currency{:XOF}, 0, 952, "CFA Franc BCEAO"), :COP => (Currency{:COP}, 2, 170, "Colombian Peso"), :HNL => (Currency{:HNL}, 2, 340, "Lempira"), :KWD => (Currency{:KWD}, 3, 414, "Kuwaiti Dinar"), :GHS => (Currency{:GHS}, 2, 936, "Ghana Cedi"), :BAM => (Currency{:BAM}, 2, 977, "Convertible Mark"), :CUC => (Currency{:CUC}, 2, 931, "Peso Convertible"), :MXN => (Currency{:MXN}, 2, 484, "Mexican Peso"), :TND => (Currency{:TND}, 3, 788, "Tunisian Dinar"), :MZN => (Currency{:MZN}, 2, 943, "Mozambique Metical"), :BOB => (Currency{:BOB}, 2, 68, "Boliviano"), :DOP => (Currency{:DOP}, 2, 214, "Dominican Peso"), :ZMW => (Currency{:ZMW}, 2, 967, "Zambian Kwacha"), :MVR => (Currency{:MVR}, 2, 462, "Rufiyaa"), :BSD => (Currency{:BSD}, 2, 44, "Bahamian Dollar"), :KPW => (Currency{:KPW}, 2, 408, "North Korean Won"), :HUF => (Currency{:HUF}, 2, 348, "Forint"), :BIF => (Currency{:BIF}, 0, 108, "Burundi Franc"), :GNF => (Currency{:GNF}, 0, 324, "Guinean Franc"), :PAB => (Currency{:PAB}, 2, 590, "Balboa"), :VEF => (Currency{:VEF}, 2, 937, "Bolívar"), :BZD => (Currency{:BZD}, 2, 84, "Belize Dollar"), :HTG => (Currency{:HTG}, 2, 332, "Gourde"), :SAR => (Currency{:SAR}, 2, 682, "Saudi Riyal"), :GYD => (Currency{:GYD}, 2, 328, "Guyana Dollar"), :GMD => (Currency{:GMD}, 2, 270, "Dalasi"), :ALL => (Currency{:ALL}, 2, 8, "Lek"), :ZAR => (Currency{:ZAR}, 2, 710, "Rand"), :PHP => (Currency{:PHP}, 2, 608, "Philippine Piso"), :MRO => (Currency{:MRO}, 2, 478, "Ouguiya"), :AZN => (Currency{:AZN}, 2, 944, "Azerbaijan Manat"), :AED => (Currency{:AED}, 2, 784, "UAE Dirham"), :ETB => (Currency{:ETB}, 2, 230, "Ethiopian Birr"), :AUD => (Currency{:AUD}, 2, 36, "Australian Dollar"), :HRK => (Currency{:HRK}, 2, 191, "Kuna"), :VND => (Currency{:VND}, 0, 704, "Dong"), :MDL => (Currency{:MDL}, 2, 498, "Moldovan Leu"), :GTQ => (Currency{:GTQ}, 2, 320, "Quetzal"), :GEL => (Currency{:GEL}, 2, 981, "Lari"), :CZK => (Currency{:CZK}, 2, 203, "Czech Koruna"), :MOP => (Currency{:MOP}, 2, 446, "Pataca"), :PLN => (Currency{:PLN}, 2, 985, "Zloty"), :SSP => (Currency{:SSP}, 2, 728, "South Sudanese Pound"), :AFN => (Currency{:AFN}, 2, 971, "Afghani"), :SYP => (Currency{:SYP}, 2, 760, "Syrian Pound"), :STD => (Currency{:STD}, 2, 678, "Dobra"), :USD => (Currency{:USD}, 2, 840, "US Dollar"), :BND => (Currency{:BND}, 2, 96, "Brunei Dollar"), :CVE => (Currency{:CVE}, 2, 132, "Cabo Verde Escudo"), :ARS => (Currency{:ARS}, 2, 32, "Argentine Peso"), :CDF => (Currency{:CDF}, 2, 976, "Congolese Franc"), :PGK => (Currency{:PGK}, 2, 598, "Kina"), :RUB => (Currency{:RUB}, 2, 643, "Russian Ruble"), :MNT => (Currency{:MNT}, 2, 496, "Tugrik"), :RWF => (Currency{:RWF}, 0, 646, "Rwanda Franc"), :SZL => (Currency{:SZL}, 2, 748, "Lilangeni"), :GBP => (Currency{:GBP}, 2, 826, "Pound Sterling"), :WST => (Currency{:WST}, 2, 882, "Tala"), :BYN => (Currency{:BYN}, 2, 933, "Belarusian Ruble"), :BGN => (Currency{:BGN}, 2, 975, "Bulgarian Lev"), :JOD => (Currency{:JOD}, 3, 400, "Jordanian Dinar"), :YER => (Currency{:YER}, 2, 886, "Yemeni Rial"), :ZWL => (Currency{:ZWL}, 2, 932, "Zimbabwe Dollar"), :LYD => (Currency{:LYD}, 3, 434, "Libyan Dinar"), :TMT => (Currency{:TMT}, 2, 934, "Turkmenistan New Manat"), :FJD => (Currency{:FJD}, 2, 242, "Fiji Dollar"), :KHR => (Currency{:KHR}, 2, 116, "Riel"), :BMD => (Currency{:BMD}, 2, 60, "Bermudian Dollar"), :KZT => (Currency{:KZT}, 2, 398, "Tenge"), :XCD => (Currency{:XCD}, 2, 951, "East Caribbean Dollar"), :NPR => (Currency{:NPR}, 2, 524, "Nepalese Rupee"), :OMR => (Currency{:OMR}, 3, 512, "Rial Omani"), :CLP => (Currency{:CLP}, 0, 152, "Chilean Peso"), :ERN => (Currency{:ERN}, 2, 232, "Nakfa"), :TOP => (Currency{:TOP}, 2, 776, "Pa’anga"), :CUP => (Currency{:CUP}, 2, 192, "Cuban Peso"), :LBP => (Currency{:LBP}, 2, 422, "Lebanese Pound"), :SCR => (Currency{:SCR}, 2, 690, "Seychelles Rupee"), :NOK => (Currency{:NOK}, 2, 578, "Norwegian Krone"), :RON => (Currency{:RON}, 2, 946, "Romanian Leu"), :MUR => (Currency{:MUR}, 2, 480, "Mauritius Rupee"), :BDT => (Currency{:BDT}, 2, 50, "Taka"), :MGA => (Currency{:MGA}, 2, 969, "Malagasy Ariary"), :SBD => (Currency{:SBD}, 2, 90, "Solomon Islands Dollar"), :ISK => (Currency{:ISK}, 0, 352, "Iceland Krona"), :GIP => (Currency{:GIP}, 2, 292, "Gibraltar Pound"), :KES => (Currency{:KES}, 2, 404, "Kenyan Shilling"), :BWP => (Currency{:BWP}, 2, 72, "Pula"), :BBD => (Currency{:BBD}, 2, 52, "Barbados Dollar"), :KMF => (Currency{:KMF}, 0, 174, "Comorian Franc"), :XAF => (Currency{:XAF}, 0, 950, "CFA Franc BEAC"), :AMD => (Currency{:AMD}, 2, 51, "Armenian Dram"), :CNY => (Currency{:CNY}, 2, 156, "Yuan Renminbi"), :KRW => (Currency{:KRW}, 0, 410, "Won"), :SEK => (Currency{:SEK}, 2, 752, "Swedish Krona"), :BRL => (Currency{:BRL}, 2, 986, "Brazilian Real"), :CRC => (Currency{:CRC}, 2, 188, "Costa Rican Colon"), :SVC => (Currency{:SVC}, 2, 222, "El Salvador Colon"), :IRR => (Currency{:IRR}, 2, 364, "Iranian Rial"), :NZD => (Currency{:NZD}, 2, 554, "New Zealand Dollar"), :SRD => (Currency{:SRD}, 2, 968, "Surinam Dollar"), :NIO => (Currency{:NIO}, 2, 558, "Cordoba Oro"), :MKD => (Currency{:MKD}, 2, 807, "Denar"), :KGS => (Currency{:KGS}, 2, 417, "Som"), :DJF => (Currency{:DJF}, 0, 262, "Djibouti Franc"), :UGX => (Currency{:UGX}, 0, 800, "Uganda Shilling"), :VUV => (Currency{:VUV}, 0, 548, "Vatu"), :LKR => (Currency{:LKR}, 2, 144, "Sri Lanka Rupee"), :RSD => (Currency{:RSD}, 2, 941, "Serbian Dinar"), :ILS => (Currency{:ILS}, 2, 376, "New Israeli Sheqel"), :ANG => (Currency{:ANG}, 2, 532, "Netherlands Antillean Guilder"), :LSL => (Currency{:LSL}, 2, 426, "Loti"), )
Currencies
https://github.com/JuliaFinance/Currencies.jl.git
[ "MIT" ]
0.17.0
325ecc57ccc9c83ab6eeaafb3eb038f8155b5357
code
2101
""" Currencies This package provides the `Currency` singleton type, based on the ISO 4217 standard together with five methods: - `symbol`: The symbol of the currency. - `currency`: The singleton type instance for a particular currency symbol - `name`: The full name of the currency. - `code`: The ISO 4217 code for the currency. - `unit`: The minor unit, i.e. number of decimal places, for the currency. See README.md for the full documentation Copyright 2019-2020, Eric Forgy, Scott P. Jones and other contributors Licensed under MIT License, see LICENSE.md """ module Currencies export Currency, @ccy_str """ This is a singleton type, intended to be used as a label for dispatch purposes """ struct Currency{S} function Currency{S}() where {S} haskey(_currency_data, S) || error("Currency $S is not defined.") new{S}() end end Currency(S::Symbol) = Currency{S}() include(joinpath(@__DIR__, "..", "deps", "currency-data.jl")) """ Returns the symbol associated with this value """ function symbol end """ Returns an instance of the singleton type Currency{sym} """ function currency end """ Returns the minor unit associated with this value """ function unit end """ Returns the ISO 4217 code associated with this value """ function code end """ Returns the ISO 4217 name associated with this value """ function name end currency(S::Symbol) = _currency_data[S][1] unit(S::Symbol) = _currency_data[S][2] code(S::Symbol) = _currency_data[S][3] name(S::Symbol) = _currency_data[S][4] currency(::Type{C}) where {C<:Currency} = C symbol(::Type{Currency{S}}) where {S} = S unit(::Type{Currency{S}}) where {S} = unit(S) code(::Type{Currency{S}}) where {S} = code(S) name(::Type{Currency{S}}) where {S} = name(S) currency(c::C) where {C<:Currency} = C symbol(::Currency{S}) where {S} = S unit(::Currency{S}) where {S} = unit(S) code(::Currency{S}) where {S} = code(S) name(::Currency{S}) where {S} = name(S) allsymbols() = keys(_currency_data) allpairs() = pairs(_currency_data) macro ccy_str(str) :( currency(Symbol($(esc(str)))) ) end end # module Currencies
Currencies
https://github.com/JuliaFinance/Currencies.jl.git
[ "MIT" ]
0.17.0
325ecc57ccc9c83ab6eeaafb3eb038f8155b5357
code
1069
using Currencies: Currency, symbol, currency, unit, name, code, _currency_data using Test currencies = ((:USD, 2, 840, "US Dollar"), (:EUR, 2, 978, "Euro"), (:JPY, 0, 392, "Yen"), (:JOD, 3, 400, "Jordanian Dinar"), (:CNY, 2, 156, "Yuan Renminbi")) # This just makes sure that the data was loaded and at least some basic values are set as expected @testset "Basic currencies" begin for (s, u, c, n) in currencies ccy = Currency(s) @test currency(s) == typeof(ccy) @test symbol(ccy) == s @test unit(ccy) == u @test name(ccy) == n @test code(ccy) == c end end # This makes sure that the values are within expected ranges @testset "Validation" begin @test length(_currency_data) >= 155 for (sym, ccy) in _currency_data (ctyp, uni, cod, nam) = ccy cur = Currency(sym) @test symbol(cur) == sym @test length(string(sym)) == 3 @test uni >= 0 @test 0 < cod < 2000 @test length(nam) < 40 end end
Currencies
https://github.com/JuliaFinance/Currencies.jl.git
[ "MIT" ]
0.17.0
325ecc57ccc9c83ab6eeaafb3eb038f8155b5357
docs
4818
# Currencies.jl [pkg-url]: https://github.com/JuliaFinance/Currencies.jl.git [eval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/report.html [eval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/C/Currencies.svg [release]: https://img.shields.io/github/release/JuliaFinance/Currencies.jl.svg [release-date]: https://img.shields.io/github/release-date/JuliaFinance/Currencies.jl.svg [julia-url]: https://github.com/JuliaLang/Julia [julia-release]:https://img.shields.io/github/release/JuliaLang/julia.svg [license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat [license-url]: LICENSE.md [travis-url]: https://travis-ci.org/JuliaFinance/Currencies.jl [travis-s-img]: https://travis-ci.org/JuliaFinance/Currencies.jl.svg [travis-m-img]: https://travis-ci.org/JuliaFinance/Currencies.jl.svg?branch=master [app-s-url]: https://ci.appveyor.com/project/JuliaFinance/currencies-jl [app-m-url]: https://ci.appveyor.com/project/JuliaFinance/currencies-jl/branch/master [app-s-img]: https://ci.appveyor.com/api/projects/status/chnj7xc6r0deux92?svg=true [app-m-img]: https://ci.appveyor.com/api/projects/status/chnj7xc6r0deux92/branch/master?svg=true [cov-url]: https://codecov.io/gh/JuliaFinance/Currencies.jl [cov-s-img]: https://codecov.io/gh/JuliaFinance/Currencies.jl/badge.svg [cov-m-img]: https://codecov.io/gh/JuliaFinance/Currencies.jl/branch/master/graph/badge.svg [contrib]: https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat [![][release]][pkg-url] [![][release-date]][pkg-url] [![][license-img]][license-url] [![contributions welcome][contrib]](https://github.com/JuliaFinance/Currencies.jl/issues) | **Info** | **Windows** | **Linux & MacOS** | **Package Evaluator** | **Coverage** | |:------------------:|:------------------:|:---------------------:|:-----------------:|:---------------------:| | [![][julia-release]][julia-url] | [![][app-s-img]][app-s-url] | [![][travis-s-img]][travis-url] | [![][eval-img]][eval-url] | [![][cov-s-img]][cov-url] | Master | [![][app-m-img]][app-m-url] | [![][travis-m-img]][travis-url] | [![][eval-img]][eval-url] | [![][cov-s-img]][cov-url] This is a core package for the JuliaFinance ecosytem. It provides bare singleton types based on the standard ISO 4217 3-character alpha codes to be used primarily for dispatch in other JuliaFinance packages together with five methods: - `symbol`: The 3-character symbol of the currency. - `currency`: The singleton type instance for a particular currency symbol - `name`: The full name of the currency. - `code`: The ISO 4217 code for the currency. - `unit`: The minor unit, i.e. number of decimal places, for the currency. Within JuliaFinance, currencies are defined in two separate packages: - [Currencies.jl](https://github.com/JuliaFinance/Currencies.jl) - [Assets.jl](https://github.com/JuliaFinance/Assets.jl) A brief explanation and motivation for each is presented below. ## [Currencies.jl](https://github.com/JuliaFinance/Currencies.jl) As mentioned, this package defines standard currencies as primordial singleton types that can be thought of as labels. For example: ```julia julia> using Currencies julia> typeof(currency(:USD)) Currency{:USD} julia> for ccy in currency.([:USD, :EUR, :JPY, :IQD]) println("Currency: $(Currencies.symbol(ccy))") println("Name: $(Currencies.name(ccy))") println("Code: $(Currencies.code(ccy))") println("Minor Unit: $(Currencies.unit(ccy))\n") end Currency: USD Name: US Dollar Code: 840 Minor Unit: 2 Currency: EUR Name: Euro Code: 978 Minor Unit: 2 Currency: JPY Name: Yen Code: 392 Minor Unit: 0 Currency: IQD Name: Iraqi Dinar Code: 368 Minor Unit: 3 ``` If all you need is a list of currencies with names, ISO 4217 codes and minor units, e.g. for building a dropdown menu in a user interface, then this lightweight package is what you want. ## [Assets.jl](https://github.com/JuliaFinance/Assets.jl) When a currency is thought of as an asset (as opposed to a mere label), we choose to refer to it as "Cash" as it would appear in a balance sheet. [Assets.jl](https://github.com/JuliaFinance/Assets.jl) provides a `Cash` asset together with `Position` that allows for basic algebraic manipulations of `Cash` and other financial instrument positions, e.g. ```julia julia> import Assets: USD, JPY julia> 10USD 10.00USD julia> 10JPY 10JPY julia> 10USD+20USD 30.00USD julia> 10USD+10JPY ERROR: Can't add Positions of different Instruments USD, JPY ``` If you need currency as an asset with corresponding asset positions, you want [Assets.jl](https://github.com/JuliaFinance/Assets.jl). ## Data Source Data for this package was obtained from https://datahub.io/core/country-codes.
Currencies
https://github.com/JuliaFinance/Currencies.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
898
using Documenter using Pkg docs_dir = joinpath(@__DIR__, "..") project_dir = isempty(ARGS) ? @__DIR__() : joinpath(pwd(), ARGS[1]) Pkg.activate(project_dir) using ForwardMethods DocMeta.setdocmeta!(ForwardMethods, :DocTestSetup, :(using ForwardMethods); recursive=true) makedocs(; modules=[ForwardMethods], authors="Curt Da Silva", repo="https://github.com/curtd/ForwardMethods.jl/blob/{commit}{path}#{line}", sitename="ForwardMethods.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://curtd.github.io/ForwardMethods.jl", edit_link="main", assets=String[], ansicolor=true ), pages=[ "Home" => "index.md", "API" => "api.md" ], warnonly=:missing_docs ) deploydocs(; repo="github.com/curtd/ForwardMethods.jl.git", devbranch="main", push_preview=true )
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
261
module ForwardMethods using MacroUtilities, MLStyle export @forward_methods, @forward_interface, @define_interface include("util.jl") include("forward_methods.jl") include("forward_interface.jl") include("define_interface.jl") end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
10648
_propertynames(T::Type) = Base.fieldnames(T) _propertynames(x) = Base.propertynames(x) @generated function validate_properties(::Type{S}, delegated_fieldnames::Type{T}) where {S, T <: Tuple} output = Expr(:block, :(unique_properties = Set{Symbol}($Base.fieldnames($S)))) recursive = fieldtype(T, 1) === Val{:recursive} for i in 2:fieldcount(T) key = fieldtype(T, i) props = Symbol(key, :_properties) child_T = fieldtype(S, key) if recursive push!(output.args, :($props = Set{Symbol}( $_propertynames($child_T)))) else push!(output.args, :($props = Set{Symbol}( $fieldnames($child_T)))) end push!( output.args, :( diff = $intersect(unique_properties, $(props)) ), :(!isempty(diff) && error("Duplicate properties `$(sort(collect(diff)))` found for type $($(S)) in child `$($(QuoteNode(key)))::$($(child_T))` ")), :($union!(unique_properties, $props))) end push!(output.args, :(return nothing)) return output end @generated function _propertynames(::Type{S}, delegated_fields::Type{T}) where {S, T <: Tuple} Base.isstructtype(S) || error("$S is not a struct type") output = Expr(:tuple, QuoteNode.(fieldnames(S))...) recursive = fieldtype(T, 1) === Val{:recursive} for i in 2:fieldcount(T) key = fieldtype(T,i) Si = fieldtype(S, key) push!(output.args, recursive ? :($_propertynames($(Si))...) : :($fieldnames($(Si))...)) end return output end _propertynames(x, delegated_fields) = _propertynames(typeof(x), delegated_fields) _hasproperty(T::Type, key::Symbol) = Base.hasfield(T, key) _hasproperty(x, key::Symbol) = key in _propertynames(x) _getproperty(x, property::Symbol) = Base.getproperty(x, property) @generated function _getproperty(x, delegated_fields::Type{T}, property::Symbol) where {T <: Tuple} if_else_exprs = Pair{Any,Any}[] recursive = fieldtype(T, 1) === Val{:recursive} for i in 2:fieldcount(T) key = fieldtype(T, i) if recursive push!( if_else_exprs, :((t = $Base.getfield(x, $(QuoteNode(key))); $_hasproperty(t, property) )) => :( return $Base.getproperty( t, property ) ) ) else push!(if_else_exprs, :( $Base.hasfield($fieldtype($(x), $(QuoteNode(key))), property) ) => :( return $Base.getfield( $Base.getfield(x, $(QuoteNode(key))), property) )) end end else_expr = :(return $Base.getfield(x, property)) return IfElseExpr(; if_else_exprs, else_expr) |> to_expr end @generated function _setproperty!(x, delegated_fields::Type{T}, property::Symbol, v) where {T <: Tuple} if_else_exprs = Pair{Any,Any}[] recursive = fieldtype(T, 1) === Val{:recursive} for i in 2:fieldcount(T) key = fieldtype(T, i) if recursive push!( if_else_exprs, :((t = $Base.getfield(x, $(QuoteNode(key))); $_hasproperty(t, property) )) => :( return $Base.setproperty!( t, property, v ) ) ) else push!(if_else_exprs, :( $Base.hasfield(fieldtype($(x), $(QuoteNode(key))), property) ) => :( return $Base.setfield!( $Base.getfield(x, $(QuoteNode(key))), property, v) )) end end else_expr = :(return $Base.setfield!(x, property, v)) return IfElseExpr(; if_else_exprs, else_expr) |> to_expr end """ properties_interface(T; delegated_fields, [recursive::Bool=false], [ensure_unique::Bool=true]) Provides amalgamated property-based access to `x::T` in terms of its fields as well as the fields of its children. So that, i.e., the fact that `x` is composed of fields `k1::T1, k2::T2, ..., kn::Tn` becomes an implementation detail of the construction of `x`. More specifically, given the set of symbols `delegated_fields` and `x::T` for a struct type `T`, defines: - `Base.propertynames(x::T)` in terms of `fieldnames(T)`, as well as the `fieldnames` of `getfield(x, k)` for each `k` in `delegated_fields`. - `Base.getproperty(x::T, name::Symbol)` to return `getfield(getfield(x, k), name)` for the first `k ∈ delegated_fields` such that `hasfield(getfield(x, k), name)`. If no such `k` exists, defaults to returning `getfield(x, name)`. - and analogously for `Base.setproperty!(x::T, name::Symbol, value)` If `recursive == true`, instances of `getfield/hasfield/setfield` in the above are replaced by internal methods that default to `Base.getproperty/Base.setproperty/Base.hasproperty`, respectively. If `ensure_unique == true`, throws an error when there are nonunique names in the amalgamation of the fields of `x` with the fields/recursive properties of each field in `delegated_fields`. If this option is `false`, any of the above setting/getting operations above will use the first (possibly recursive) child field found matching the above criteria. # Arguments `delegated_fields` can be either a `Symbol`, or a `vect` or `tuple` `Expr` of `Symbol`s, corresponding to fieldnames of `T` """ function properties_interface(T; delegated_fields, recursive::Bool=false, ensure_unique::Bool=true, kwargs...) if haskey(kwargs, :is_mutable) Base.depwarn("Passing `is_mutable` kwarg when `interface=properties` is now deprecated", Symbol("@define_interface")) is_mutable = get_kwarg(Bool, kwargs, :is_mutable, false) else is_mutable = true end delegated_fields_sym = parse_vect_of_symbols(delegated_fields; kwarg_name=:delegated_fields) delegated_fields_tuple_type = :($Tuple{$Val{$(QuoteNode(recursive ? :recursive : :non_recursive))}, $(QuoteNode.(delegated_fields_sym)...)}) line_num = current_line_num[] linenum! = t-> func_def_line_num!(t, something(line_num, not_provided)) obj = gensym(:_obj) name = gensym(:_name) value = gensym(:_value) _propertynamesT = :($ForwardMethods._propertynames(::Type{$T}) = $ForwardMethods._propertynames($T, $delegated_fields_tuple_type)) _propertynames = :($ForwardMethods._propertynames($obj::$T) = $ForwardMethods._propertynames($T)) propertynames = :($Base.propertynames($obj::$T) = $ForwardMethods._propertynames($obj)) _getproperty = :($ForwardMethods._getproperty($obj::$T, $name::Symbol) = $ForwardMethods._getproperty($obj, $delegated_fields_tuple_type, $name)) getproperty = :($Base.getproperty($obj::$T, $name::Symbol) = $ForwardMethods._getproperty($obj, $name)) _setproperty = :($ForwardMethods._setproperty!($obj::$T, $name::Symbol, $value) = $ForwardMethods._setproperty!($obj, $delegated_fields_tuple_type, $name, $value)) setproperty = :($Base.setproperty!($obj::$T, $name::Symbol, $value) = $ForwardMethods._setproperty!($obj, $name, $value)) output = Expr(:block, line_num) if ensure_unique push!(output.args, :($validate_properties($T, $delegated_fields_tuple_type))) end push!(output.args, map(linenum!, (_propertynames, _propertynamesT, propertynames, _getproperty, getproperty))...) if is_mutable push!(output.args, map(linenum!, (_setproperty, setproperty))...) end return wrap_define_interface(T, :properties, output) end """ equality_interface(T; [omit=Symbol[], equality_op=:(==), compare_fields=:fieldnames]) Defines the `equality_op` operator for two objects of type `T` in the natural way, i.e., ```julia Base.:(==)(x::T, y::T) = all( getfield(x,k) == getfield(y,k) for k in fieldnames(T)) ``` # Arguments If `equality_op == isequal`, defines `Base.isequal` instead. If `compare_fields == propertynames`, the above definition uses `getproperty` and `propertynames(x)` instead of `getfield` and `fieldnames(T)`, respectively. Any values provided in `omit` are excluded from the generator expression above. """ function equality_interface(T; omit::AbstractVector{Symbol}=Symbol[], equality_op::Symbol=:(==), compare_fields::Symbol=:fieldnames) equality_op in (:(==), :isequal) || error("equality_op (= $equality_op) must be one of (==, isequal)") if compare_fields == :fieldnames getvalue = :($Base.getfield) equal_properties = Expr(:block, :(values = $Base.fieldnames($T)), true) elseif compare_fields == :propertynames getvalue = :($Base.getproperty) equal_properties = Expr(:block, :(values = $Base.propertynames(x)), :(values == $Base.propertynames(y))) else error("compare_fields (= $compare_fields) must be one of (fieldnames, propertynames)") end if isempty(omit) body = :($Base.all( $equality_op( $getvalue(x, k), $getvalue(y, k) ) for k in values )) else body = :($Base.all( $equality_op( $getvalue(x, k), $getvalue(y, k) ) for k in values if k ∉ $(Expr(:tuple, QuoteNode.(omit)...)))) end equality_expr = :($Base.$equality_op(x::$T, y::$T) = $equal_properties && $body) return wrap_define_interface(T, :equality, equality_expr) end const default_define_interfaces = (:properties, :equality, :setfields, :getfields) for f in default_define_interfaces @eval define_interface_method(::Val{$(QuoteNode(f))}) = $(Symbol(f, :_interface)) end @method_def_constant define_interface_method(::Val{::Symbol}) define_interfaces_available function define_interface_expr(T, kwargs::Dict{Symbol,Any}=Dict{Symbol,Any}(); _sourceinfo) interfaces = interface_kwarg!(kwargs) omit = omit_kwarg!(kwargs) output = Expr(:block) interfaces_available = define_interfaces_available() for interface in interfaces interface in interfaces_available || error("No interface found with name $interface -- must be one of `$interfaces_available`") f = define_interface_method(Val(interface)) current_line_num[] = _sourceinfo try push!(output.args, f(T; omit, kwargs...)) finally current_line_num[] = nothing end end return output end """ @define_interface T [interface=name] [kwargs...] Defines the `interface` for objects of type `T` # Arguments `name` must be one of $(default_define_interfaces), with `name` value `f` corresponding to the interface definition function `\$f_interface` (e.g., `array` => `array_interface`). The `key=value` pairs will be forwarded to the corresponding interface definition method. In particular, specifying `omit=func1` or `omit=[func1,func2, ..., funcn]` will omit `func1`, ..., `funcn` from being forwarded by this macro. Refer to the documentation of each \$(name)_interface for the specific keyword arguments required, if any. """ macro define_interface(T, args...) kwargs = Dict{Symbol,Any}() for arg in args key, value = parse_kwarg_expr(arg) kwargs[key] = value end return define_interface_expr(T, kwargs; _sourceinfo=__source__) |> esc end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
13836
function forward_interface_method end interface_field_name_required(x) = false interface_at_macroexpand_time(x) = true base_forward_expr(f, args...) = Expr(:call, f, args...) function forward_interface_args(T) t = gensym(arg_placeholder) obj_arg = object_argument(t, T) type_arg = type_argument(T) wrap_expr = wrap_type_expr(T) call_expr = (f, args...) -> wrap_expr(base_forward_expr(f, args...)) return obj_arg, type_arg, call_expr end # Iteration, indexing, array interface methods from https://docs.julialang.org/en/v1/manual/interfaces/#Interfaces """ ForwardMethods.iteration_interface(T; omit=Symbol[]) Forwards the following methods for `x::T`: - `Base.iterate(x::T)` - `Base.iterate(x::T, state)` - `Base.IteratorSize(::Type{T})` - `Base.IteratorEltype(::Type{T})` - `Base.eltype(::Type{T})` - `Base.length(x::T)` - `Base.size(x::T)` - `Base.isdone(x::T)` - `Base.isdone(x::T, state)` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined """ function iteration_interface(T; omit::AbstractVector{Symbol}=Symbol[]) obj_arg, type_arg, call_expr = forward_interface_args(T) method_signatures = Any[] if :iterate ∉ omit push!(method_signatures, call_expr(:(Base.iterate), obj_arg)) push!(method_signatures, call_expr(:(Base.iterate), obj_arg, :state)) end for f in (:IteratorSize, :IteratorEltype, :eltype) f ∈ omit && continue push!(method_signatures, call_expr(:(Base.$f), type_arg)) end for f in (:length, :size, :isdone) f ∈ omit && continue push!(method_signatures, call_expr(:(Base.$f), obj_arg) ) end if :isdone ∉ omit push!(method_signatures, call_expr(:(Base.isdone), obj_arg, :state) ) end return method_signatures end interface_field_name_required(::typeof(iteration_interface)) = true """ ForwardMethods.indexing_interface(T; omit=Symbol[]) Forwards the following methods for `x::T`: - `Base.getindex(x::T, index)` - `Base.setindex!(x::T, value, index)` - `Base.firstindex(x::T)` - `Base.lastindex(x::T)` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined """ function indexing_interface(T; omit::AbstractVector{Symbol}=Symbol[]) obj_arg, _, call_expr = forward_interface_args(T) method_signatures = Any[] if :getindex ∉ omit push!(method_signatures, call_expr(:(Base.getindex), obj_arg, :i)) end if :setindex! ∉ omit push!(method_signatures, call_expr(:(Base.setindex!), obj_arg, :v, :i)) end if :firstindex ∉ omit push!(method_signatures, call_expr(:(Base.firstindex), obj_arg)) end if :lastindex ∉ omit push!(method_signatures, call_expr(:(Base.lastindex), obj_arg)) end return method_signatures end # Note: not a straightforward way to forward Base.similar for generic types, so it is not included here """ ForwardMethods.array_interface(T; index_style_linear::Bool, omit=Symbol[]) Forwards the following methods for `x::T`: - `Base.size(x::T)` - `Base.iterate(x::T)` - `Base.iterate(x::T, state)` - `Base.length(x::T)` - `Base.IndexStyle(::Type{T})` - `Base.getindex(x::T, index)` - `Base.setindex!(x::T, value, index)` The signatures for `Base.getindex` + `Base.setindex!` will be set according to the value of `index_style_linear` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined """ function array_interface(T; index_style_linear::Bool, omit::AbstractVector{Symbol}=Symbol[]) obj_arg, type_arg, call_expr = forward_interface_args(T) method_signatures = Any[ call_expr(:(Base.$f), obj_arg) for f in (:size, :iterate, :length) if f ∉ omit ] if :iterate ∉ omit push!(method_signatures, call_expr(:(Base.iterate), obj_arg, :state)) end if :IndexStyle ∉ omit push!(method_signatures, call_expr(:(Base.IndexStyle), type_arg)) end if index_style_linear if :getindex ∉ omit push!(method_signatures, call_expr(:(Base.getindex), obj_arg, :(i::Int))) push!(method_signatures, call_expr(:(Base.getindex), obj_arg, :(I::AbstractUnitRange{<:Integer}))) end if :setindex! ∉ omit push!(method_signatures, call_expr(:(Base.setindex!), obj_arg, :v, :(i::Int))) push!(method_signatures, call_expr(:(Base.setindex!), obj_arg, :v, :(I::AbstractUnitRange{<:Integer}))) end else if :getindex ∉ omit push!(method_signatures, call_expr(:(Base.getindex), obj_arg, :(I...))) end if :setindex! ∉ omit push!(method_signatures, call_expr(:(Base.setindex!), obj_arg, :v, :(I...))) end end return method_signatures end interface_field_name_required(::typeof(array_interface)) = true """ ForwardMethods.vector_interface(T; omit=Symbol[]) Forwards the methods for `x::T` from `ForwardMethods.array_interface(T; index_style_linear=true)`, `ForwardMethods.iteration_interface(T)`, and `ForwardMethods.indexing_interface(T)` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined. """ function vector_interface(T; omit::AbstractVector{Symbol}=Symbol[]) array_signatures = array_interface(T; index_style_linear=true, omit=omit) iteration_signatures = iteration_interface(T; omit=union([:iterate, :length, :size], omit)) indexing_signatures = indexing_interface(T; omit=union([:getindex, :setindex], omit)) return vcat(array_signatures, iteration_signatures, indexing_signatures) end interface_field_name_required(::typeof(vector_interface)) = true """ ForwardMethods.dict_interface(T; omit=Symbol[]) Forwards the following methods for `x::T`: - `Base.keys(x::T)` - `Base.values(x::T)` - `Base.pairs(x::T)` - `Base.length(x::T)` - `Base.isempty(x::T)` - `Base.empty!(x::T)` - `Base.iterate(x::T)` - `Base.iterate(x::T, state)` - `Base.pop!(x::T, key)` - `Base.delete!(x::T, key)` - `Base.haskey(x::T, key)` - `Base.getindex(x::T, key)` - `Base.setindex!(x::T, value, key)` - `Base.get(x::T, key, default_value)` - `Base.get!(default::Callable, x::T, key)` - `Base.in(value, x::T)` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined """ function dict_interface(T; omit::AbstractVector{Symbol}=Symbol[]) obj_arg, type_arg, call_expr = forward_interface_args(T) method_signatures = Any[ call_expr(:(Base.$f), obj_arg) for f in (:keys, :values, :pairs, :length, :isempty, :empty!, :iterate) if f ∉ omit ] for f in (:eltype, :keytype, :valtype) f in omit && continue push!(method_signatures, call_expr(:(Base.$f), type_arg)) end if :iterate ∉ omit push!(method_signatures, call_expr(:(Base.iterate), obj_arg, :state)) end for f in (:pop!, :getindex, :haskey, :delete!) f in omit && continue push!(method_signatures, call_expr(:(Base.$f), obj_arg, :key)) end if :pop! ∉ omit push!(method_signatures, call_expr(:(Base.pop!), obj_arg, :key, :default)) end if :get ∉ omit push!(method_signatures, call_expr(:(Base.get), obj_arg, :key, :default)) end if :get! ∉ omit push!(method_signatures, call_expr(:(Base.get!), :(default::Base.Callable), obj_arg, :key)) end if :setindex! ∉ omit push!(method_signatures, call_expr(:(Base.setindex!), obj_arg, :value, :key)) end if :in ∉ omit push!(method_signatures, call_expr(:(Base.in), :value, obj_arg)) end return method_signatures end interface_field_name_required(::typeof(dict_interface)) = true """ ForwardMethods.lockable_interface(T; omit=Symbol[]) Forwards the following methods for `x::T`: - `Base.lock(x::T)` - `Base.lock(f, x::T)` - `Base.unlock(x::T)` - `Base.trylock(x::T)` - `Base.islocked(x::T)` Any function names specified in `omit::AbstractVector{Symbol}` will not be defined """ function lockable_interface(T; omit::AbstractVector{Symbol}=Symbol[]) obj_arg, _, call_expr = forward_interface_args(T) method_signatures = Any[ call_expr(:(Base.$f), obj_arg) for f in (:lock, :unlock, :trylock, :islocked) if f ∉ omit ] if :lock ∉ omit push!(method_signatures, call_expr(:(Base.lock), :f, obj_arg)) end return method_signatures end """ getfields_interface(T; omit=Symbol[]) Given `x::T`, forwards the method `\$field(x::T)` to `getfield(x, \$field)`, for each `field in fieldnames(T)` """ function getfields_interface(T; field::Union{Nothing,Symbol}=nothing, omit::AbstractVector{Symbol}=Symbol[]) return wrap_define_interface(T, :getfields, Base.remove_linenums!(quote local omit_fields = $(Expr(:tuple, QuoteNode.(omit)...)) local fields = fieldnames($T) local def_fields_expr = Expr(:block) local var = gensym("x") for field in fields if field ∉ omit_fields push!(def_fields_expr.args, :($field($var::$$T) = Base.getfield($var, $(QuoteNode(field))))) end end eval(def_fields_expr) nothing end)) end interface_at_macroexpand_time(::typeof(getfields_interface)) = false """ setfields_interface(T; omit=Symbol[]) Given `x::T`, forwards the method `\$field!(x::T, value)` to `setfield!(x, \$field, value)`, for each `field in fieldnames(T)` """ function setfields_interface(T; field::Union{Nothing,Symbol}=nothing, omit::AbstractVector{Symbol}=Symbol[]) return wrap_define_interface(T, :setfields, Base.remove_linenums!(quote local omit_fields = $(Expr(:tuple, QuoteNode.(omit)...)) local fields = fieldnames($T) local def_fields_expr = Expr(:block) local var = gensym("x") for field in fields if field ∉ omit_fields push!(def_fields_expr.args, :($(Symbol(string(field)*"!"))($var::$$T, value) = Base.setfield!($var, $(QuoteNode(field)), value))) end end eval(def_fields_expr) nothing end)) end interface_at_macroexpand_time(::typeof(setfields_interface)) = false const default_forward_interfaces = (:iteration, :indexing, :array, :vector, :dict, :lockable, :getfields, :setfields) for f in default_forward_interfaces @eval forward_interface_method(::Val{$(QuoteNode(f))}) = $(Symbol(string(f)*"_interface")) end if VERSION ≥ v"1.10.0-DEV.609" _val_type(::Type{Val{S}}) where {S} = S forward_interfaces_available() = Symbol[_val_type(fieldtype(m.sig, 2)) for m in Base.methods(forward_interface_method)] else @method_def_constant forward_interface_method(::Val{::Symbol}) forward_interfaces_available end function forward_interface_expr(T, kwargs::Dict{Symbol,Any}=Dict{Symbol,Any}(); _sourceinfo=nothing) interfaces = interface_kwarg!(kwargs) omit = omit_kwarg!(kwargs) map_val = pop!(kwargs, :map, nothing) if !isnothing(map_val) && (map_func = parse_map_func_expr(map_val); !isnothing(map_func)) nothing else map_func = identity_map_expr end field_expr = pop!(kwargs, :field, nothing) if !isnothing(field_expr) field_funcs = parse_field(Expr(:(=), :field, field_expr)) else field_funcs = nothing end _output = Expr(:block) available_interfaces = forward_interfaces_available() for interface in interfaces interface in available_interfaces || error("No interface found with name $interface -- must be one of `$available_interfaces`") f = forward_interface_method(Val(interface)) if interface_at_macroexpand_time(f) isnothing(field_funcs) && error("Expected `field` from keyword arguments for interface `$interface`") if interface_field_name_required(f) isnothing(field_funcs.type_func) && error("Only fieldname mode for `field` (= $field) supported for interface (= $interface_value)") end signatures = f(T; omit, kwargs...) output = Expr(:block) for signature in signatures push!(output.args, forward_method_signature(T, field_funcs, map_func, signature; _sourceinfo)) end push!(_output.args, output) else push!(_output.args, f(T; omit, kwargs...)) end end return _output end """ @forward_interface T [field=_field] [interface=name] [map=_map] [key=value...] Forwards the methods defined for `interface` to objects of type `T` # Arguments `name` must be one of $(default_forward_interfaces), with `name` value `f` corresponding to the interface definition function `\$f_interface` (e.g., `array` => `array_interface`). If `name` is either `getfields` or `setfields`, then the `field` keyword argument is ignored Otherwise, `_field` must be one of the following expressions - `k::Symbol` or `k::QuoteNode`, or an expression of the form `getfield(_, k)`, in which case methods will be forwarded to `getfield(x, k)` - an expression of the form `getproperty(_, k)`, in which case methods will be forwarded to `getproperty(x, k)` - an expression of the form `t[args...]`, in which case methods will be forwarded to `x[args...]` - or an expression of the form `f(_)` for a single-argument function `f`, in which case methods will be forwarded to `f(x)` # Additional Arguments The `key=value` pairs will be forwarded to the corresponding interface definition method. In particular, specifying `omit=func1` or `omit=[func1,func2, ..., funcn]` will omit `func1`, ..., `funcn` from being forwarded by this macro. See also [`@forward_methods`](@ref) """ macro forward_interface(T, args...) kwargs = Dict{Symbol,Any}() for arg in args key, value = parse_kwarg_expr(arg) kwargs[key] = value end return forward_interface_expr(T, kwargs; _sourceinfo=__source__) |> esc end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
12966
const arg_placeholder = :_ const obj_placeholder = :_obj function arg_from_type_sig(expr) @switch expr begin @case :($x::$T) return x @case :($x = $y) return x @case _ return expr end end function matches_type_signature(T, UnionallType, expr) @switch expr begin @case Expr(:(::), arg, S) && if S == T end return (; matches=true, unionall=false, type=false, arg) @case (Expr(:(::), arg, Expr(:curly, :Type, S)) && if S == T end) || Expr(:(::), Expr(:curly, :Type, S)) && if S == T end return (; matches=true, unionall=false, type=true, arg=T) return (; matches=true, unionall=false, type=true, arg=T) @case Expr(:(::), arg, S) && if S == UnionallType end return (; matches=true, unionall=true, type=false, arg) @case (Expr(:(::), arg, Expr(:curly, :Type, S)) && if S == UnionallType end) || Expr(:(::), Expr(:curly, :Type, S)) && if S == UnionallType end return (; matches=true, unionall=true, type=true, arg=UnionallType) @case _ return (; matches=false) end end struct FieldFuncExprs arg_func type_func end function forward_method_signature(Type, field_funcs::FieldFuncExprs, map_func::Function, input; _sourceinfo=nothing) (func_expr, whereparams) = @switch input begin @case Expr(:where, func, params...) (func, params) @case _ (input, nothing) end if is_unionall_type(Type) UnionallType, _ = union_all_type_and_param(Type) else UnionallType = Type end (funcname, args, kwargs) = @switch func_expr begin @case Expr(:call, funcname, Expr(:parameters, kwargs...), args...) (funcname, args, kwargs) @case Expr(:call, funcname, args...) (funcname, args, []) @case ::Symbol || :($A.$f) t = gensym(arg_placeholder) S = isnothing(whereparams) ? UnionallType : Type (func_expr, [object_argument(t, S)], []) @case _ error("Unrecognized expression method (= $func_expr) -- expected expression to be of the form f(args), f(args; kwargs)") end found_arg_local_name = gensym("child_value") found = false local found_input_arg local found_arg local found_arg_expr found_arg_is_type = false input_args = [] output_args = [] for arg in args if arg === arg_placeholder matched_arg = gensym(arg_placeholder) if isnothing(whereparams) push!(input_args, object_argument(matched_arg, UnionallType)) else push!(input_args, object_argument(matched_arg, Type)) end found_input_arg = matched_arg found_arg = field_funcs.arg_func(matched_arg) elseif (_matches = matches_type_signature(Type, UnionallType, arg); _matches.matches) matched_arg = _matches.arg if _matches.type found_input_arg = _matches.unionall ? UnionallType : Type push!(input_args, type_argument(matched_arg)) isnothing(field_funcs.type_func) && error("Must forward methods with `Type{$Type}` signatures via `getfield` ") found_arg = field_funcs.type_func(matched_arg) found_arg_is_type = true else found_input_arg = matched_arg push!(input_args, arg) found_arg = field_funcs.arg_func(matched_arg) end else # Non-matching arguments, just forward argument names push!(input_args, arg) push!(output_args, arg_from_type_sig(arg)) continue end found && error("Cannot have multiple arguments matching type $Type in input = `$input`") found_arg_expr = :(local $found_arg_local_name = $found_arg) push!(output_args, found_arg_local_name) found = true end if !found error("No argument matching type $Type in input = `$input`") end func_body = Expr(:call, funcname) if !isempty(kwargs) push!(func_body.args, Expr(:parameters, kwargs...)) end push!(func_body.args, output_args...) body_block = Expr(:block) if !isnothing(_sourceinfo) push!(body_block.args, _sourceinfo) end push!(body_block.args, found_arg_expr) mapped_body = !found_arg_is_type ? map_func(found_input_arg, func_body) : func_body push!(body_block.args, mapped_body) new_sig = Expr(:call, funcname) if !isempty(kwargs) push!(new_sig.args, Expr(:parameters, kwargs...)) end push!(new_sig.args, input_args...) if !isnothing(whereparams) new_sig = Expr(:where, new_sig, whereparams...) end func_def = Expr(:(=), new_sig, body_block) return func_def end forward_method_signature(Type, field_funcs, input; kwargs...) = forward_method_signature(Type, field_funcs, identity_map_expr, input; kwargs...) function nested_dotted_field_arg_expr(field_expr, input) @switch field_expr begin @case ::Symbol return Expr(:call, :(Base.getfield), input, QuoteNode(field_expr)) @case ::QuoteNode && if (field_expr.value isa Symbol) end return nested_dotted_field_arg_expr(field_expr.value, input) @case Expr(:., lhs, rhs) arg_expr = nested_dotted_field_arg_expr(lhs, input) return Expr(:call, :(Base.getfield), arg_expr, rhs) @case _ error("Invalid nested dotted expression $field_expr") end end function nested_dotted_field_type_expr(field_expr, input) @switch field_expr begin @case ::Symbol return Expr(:call, :(Base.fieldtype), input, QuoteNode(field_expr)) @case ::QuoteNode && if (field_expr.value isa Symbol) end return nested_dotted_field_type_expr(field_expr.value, input) @case Expr(:., lhs, rhs) arg_expr = nested_dotted_field_type_expr(lhs, input) return Expr(:call, :(Base.fieldtype), arg_expr, rhs) @case _ error("Invalid nested dotted expression $field_expr") end end function nested_dotted_field_arg_func(value) return let value=value (t)->nested_dotted_field_arg_expr(value, t) end end function nested_dotted_field_type_func(value) return let value=value (t)->nested_dotted_field_type_expr(value, t) end end function FieldFuncExprs(value) f = @switch value begin @case ::Symbol || Expr(:., arg1, arg2, args...) (nested_dotted_field_arg_func(value), nested_dotted_field_type_func(value)) @case ::QuoteNode && if value.value isa Symbol end FieldFuncExprs(value.value) @case Expr(:ref, arg1, args...) (replace_first_arg_in_call_func(value), nothing) @case Expr(:call, func, arg1, arg2) if func in (:getproperty, :(Base.getproperty)) && arg2 isa QuoteNode (replace_first_arg_in_call_func(Expr(:call, :(Base.getproperty), arg1, arg2)), nothing) elseif func in (:getfield, :(Base.getfield)) && arg2 isa QuoteNode (nested_dotted_field_arg_func(arg2), nested_dotted_field_type_func(arg2)) elseif func in (:getindex, :(Base.getindex)) && arg2 isa QuoteNode (replace_first_arg_in_call_func(Expr(:call, :(Base.getindex), arg1, arg2)), nothing) else @goto error end @case Expr(:call, func, arg1) (replace_first_arg_in_call_func(value), nothing) @case _ @goto error end if f isa FieldFuncExprs return f else arg_func, type_func = f return FieldFuncExprs(arg_func, type_func) end @label error error("Invalid field expression `$value`") end function parse_field(field) @switch field begin @case Expr(:(=), :field, value) return FieldFuncExprs(value) @case _ @goto error end @label error error("Invalid field expression `$field`") end function forward_methods_expr(Type, field_expr, args...; _sourceinfo=nothing) field_funcs = parse_field(field_expr) !isempty(args) || error("Input arguments must be nonempty") firstarg, rest = Iterators.peel(args) if (map_func = parse_map_expr(firstarg); !isnothing(map_func)) method_exprs = rest else map_func = identity_map_expr method_exprs = args end output = Expr(:block) for arg in method_exprs _args = @switch arg begin @case Expr(:block, args...) filter(t->!(t isa LineNumberNode), args) @case _ [arg] end for arg in _args push!(output.args, forward_method_signature(Type, field_funcs, map_func, arg; _sourceinfo)) end end return output end """ @forward_methods T [field=_field] [map=_map] methods... Forwards the method definitions for `x::T`, depending on the value of `_field`. `_field` must be one of the following expressions - `k::Symbol` or `k::QuoteNode`, or an expression of the form `getfield(_, k)`, in which case methods will be forwarded to `getfield(x, k)` - an expression of the form `a.b.c. ...`, in which case methods will be forwarded to `getfield(getfield(getfield(x, :a), :b), :c) ...` - an expression of the form `getproperty(_, k)`, in which case methods will be forwarded to `getproperty(x, k)` - an expression of the form `t[args...]`, in which case methods will be forwarded to `x[args...]` - or an expression of the form `f(_)` for a single-argument function `f`, in which case methods will be forwarded to `f(x)` For notational purposes below, call the forwarded value `forwarded_value(x)`. Each `method` must be one of the following expressions - an expression of the form `f::Symbol` or `A.f`, which will forward the single-argument function `f(x)` or `A.f(x)` to `f(forwarded_value(x))` or `A.f(forwarded_value(x))`, respectively - a function signature of the form `f(args...)`, or `f(args...; kwargs...)`. In this form, there must be either exactly one expression of the form `x::T` or `_` (an underscore) in `args`. If this occurs at position `i`, say, this macro will forward this method to the definition `f(args[1], args[2], ..., args[i-1], forwarded_value(x), args[i+1], ..., args[end]; kwargs...)` When `field` maps to invoking `getfield` for field `k`, one can also write an argument expression of the form `::T` or `x::T`. In this case, this macro definition will define `f(args[1], ..., args[i-1], ::Type{T}, args[i+1], ..., args[end]; kwargs) = f(args[1], ..., args[i-1], fieldtype(T, k), args[i+1], ..., args[end]; kwargs)` which can be useful for forwarding, for instance, trait-based methods to the corresponding container type. Each `method` may also be a `:block` expression, where each sub-expression satisfies one of the above conditions ## Optional Arguments The optional `map=_map` parameter allows you to apply an expression transformation to the resulting forwarded expression. `_map` must be an expression containing at least one underscore `_` placeholder and optionally `_obj` placeholders. `_` and `_obj` will be replaced with the transformed function and initial object argument, respectively. For example, if we have ```julia struct LockableDict{K,V} d::Dict{K,V} lock::ReentrantLock end @forward LockableDict{K,V} field=lock Base.lock Base.unlock @forward LockableDict{K,V} field=d map=(begin lock(_obj); try _ finally unlock(_obj) end end) Base.getindex(_, k) ``` Then the expressions generated in the second statement are (roughly) of the form ```julia function Base.getindex(l::LockableDict{K,V}, k) lock(l) try Base.getindex(getfield(l, :d)) finally unlock(l) end end ``` # Notes - Parametric expressions are supported for `T`, as well as for the function signature form of `method` # Examples ```julia-repl julia> struct B{T} v::Vector{T} end julia> @forward_methods B{T} field=v Base.firstindex Base.lastindex Base.getindex(_, k::Int) Base.setindex!(x::B, v, k) (Base.eachindex(x::B{T}) where {T}) julia> b = B([1,2,3]) B{Int64}([1, 2, 3]) julia> for i in eachindex(b) b[i] = b[i]^2 end julia> b[end] 9 julia> struct C d::Dict{String,Int} end julia> @forward_methods C field=d Base.keytype(::Type{C}) Base.valtype(::Type{C}) julia> keytype(C) String julia> valtype(C) Int ``` """ macro forward_methods(Type, field, args...) return forward_methods_expr(Type, field, args...; _sourceinfo=__source__) |> esc end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
4617
object_argument(var, type) = Expr(:(::), var, type) type_argument(type) = Expr(:(::), Expr(:curly, :Type, type)) function parse_kwarg_expr(expr; expr_name::String="", throw_error::Bool=true) @match expr begin :($k = $v) => (k, v) _ => throw_error ? error("Expected a `key = value` expression" * (!isempty(expr_name) ? " from `$expr_name`" : "") * ", got `$expr") : nothing end end function is_unionall_type(ex::Expr) @switch ex begin @case Expr(:curly, T, args...) return true @case _ return false end end is_unionall_type(ex) = false function union_all_type_and_param(ex::Expr) @switch ex begin @case Expr(:curly, T, args...) return T, args @case _ error("Expression `$ex` is not of the form `A{T...}`") end end union_all_type_and_param(ex) = ex function wrap_type_expr(T; additional_params=Symbol[]) if is_unionall_type(T) _, params = union_all_type_and_param(T) all_params = [params..., additional_params...] return t->Expr(:where, t, all_params...) else return identity end end function replace_placeholder(x::Symbol, replace_values::Vector{<:Pair{Symbol,<:Any}}) for (old,new) in replace_values if x === old return new, true end end return x, false end replace_placeholder(x, replace_values) = (x, false) function replace_placeholder(x::Expr, replace_values::Vector{<:Pair{Symbol,<:Any}}) replaced = false new_expr = Expr(x.head) for arg in x.args new_arg, arg_replaced = replace_placeholder(arg, replace_values) push!(new_expr.args, new_arg) replaced |= arg_replaced end return new_expr, replaced end identity_map_expr(obj_expr, forwarded_expr) = forwarded_expr function parse_map_func_expr(map_func_expr) if ((_, arg_replaced) = replace_placeholder(map_func_expr, [arg_placeholder => arg_placeholder]); arg_replaced) return let map_func_expr=map_func_expr (obj_expr, t::Expr) -> replace_placeholder(map_func_expr, [obj_placeholder => obj_expr, arg_placeholder => t])[1] end else return nothing end end function parse_map_expr(map_expr) kv = parse_kwarg_expr(map_expr; throw_error=false) isnothing(kv) && return nothing key, value = kv key != :map && return nothing return parse_map_func_expr(value) end function replace_first_arg_in_call_func(ex::Expr) @match ex begin Expr(:call, func, arg1, args...) => let args=args; t->Expr(:call, func, t, args...) end Expr(:ref, arg1, args...) => let args=args; t->Expr(:ref, t, args...) end _ => error("Expression $ex must be a call expression") end end function parse_vect_of_symbols(expr; kwarg_name::Symbol) syms = from_expr(Vector{Symbol}, expr; throw_error=false) isnothing(syms) && error("`$kwarg_name` (= $expr) must be a Symbol or a `vect` expression of Symbols") return syms end function interface_kwarg!(kwargs::Dict{Symbol,Any}; allow_multiple::Bool=true) !haskey(kwargs, :interface) && error("Expected `interface` from keyword arguments") interface_val = pop!(kwargs, :interface) if allow_multiple return parse_vect_of_symbols(interface_val; kwarg_name=:interface) else interface_val isa Symbol || error("`interface` (= $interface_val) must be a `Symbol`, got typeof(interface) = $(typeof(interface_val))") return Symbol[interface_val] end end function omit_kwarg!(kwargs::Dict{Symbol,Any}) omit_val = pop!(kwargs, :omit, nothing) if !isnothing(omit_val) return parse_vect_of_symbols(omit_val; kwarg_name=:omit) else return Symbol[] end end function get_kwarg(::Type{T}, kwargs, key::Symbol, default) where {T} value = get(kwargs, key, default) value isa T || error("$key (= $value) must be a $T, got typeof($key) = $(typeof(value))") return value end has_defined_interface(T, interface) = false function wrap_define_interface(T, interface::Symbol, expr) return IfElseExpr(; if_else_exprs=[ :(($ForwardMethods.has_defined_interface($T, Val($(QuoteNode(interface))))) == false) => Expr(:block, expr, :($ForwardMethods.has_defined_interface(::Type{$T}, ::Val{$(QuoteNode(interface))}) = true)) ]) |> to_expr end const current_line_num = Base.RefValue{Union{Nothing, LineNumberNode}}(nothing) function func_def_line_num!(expr, line::Union{NotProvided, LineNumberNode}) f = from_expr(FuncDef, expr; throw_error=true) return FuncDef(f; line) |> to_expr end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
194
module TestForwardMethods using ForwardMethods include("test_forward_methods.jl") include("test_forward_interface.jl") include("define_interface/_test_define_interface.jl") end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
148
using ForwardMethods using TestItemRunner if VERSION ≥ v"1.9" using Aqua Aqua.test_all(ForwardMethods) end @run_package_tests verbose=true
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
716
using TestItemRunner, TestItems @testsnippet SetupTest begin using ForwardMethods.MLStyle using JET, Test, TestingUtilities macro test_throws_compat(ExceptionType, message, expr) output = Expr(:block, __source__, :($Test.@test_throws $ExceptionType $expr)) if VERSION ≥ v"1.7" push!(output.args, :($Test.@test_throws $message $expr)) end return output |> esc end struct A v::Vector{Int} end mutable struct SettableProperties key1::String key2::Int key3::Bool end mutable struct SettableProperties2 key4::Float64 key5::Vector{Int} end custom_func_to_forward(t) = t[1] end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
3958
@testitem "Forward Interfaces" setup=[SetupTest] begin function custom_interface(T; omit::AbstractVector{Symbol}=Symbol[]) return [:custom_func_to_forward] end @Test !(:custom in ForwardMethods.forward_interfaces_available()) ForwardMethods.forward_interface_method(::Val{:custom}) = custom_interface @Test :custom in ForwardMethods.forward_interfaces_available() @forward_interface A field=v interface=custom struct ForwardDict d::Dict{String,Int} end @forward_interface ForwardDict field=d interface=dict struct ForwardVector{T} v::Vector{T} end @forward_interface ForwardVector{T} field=v interface=array index_style_linear=true struct ForwardVectorNoLength{T} v::Vector{T} end @forward_interface ForwardVectorNoLength{T} field=v interface=array index_style_linear=true omit=[length] struct ForwardVectorInterface{T} v::Vector{T} end @forward_interface ForwardVectorInterface{T} field=v interface=vector struct ForwardMatrix{F} v::Matrix{F} end @forward_interface ForwardMatrix{F} field=v interface=array index_style_linear=false struct LockableDict{K,V} d::Dict{K,V} lock::ReentrantLock end @forward_interface LockableDict{K,V} field=lock interface=lockable @forward_interface LockableDict{K,V} field=d interface=dict map=begin lock(_obj); try _ finally unlock(_obj) end end struct InnerVector v::Vector{Int} end struct NestedForward h::InnerVector end @forward_interface NestedForward field=h.v interface=array index_style_linear=true @testset "@forward_interface" begin v = NestedForward(InnerVector([1,2,3])) @Test v[1] == 1 d = ForwardDict(Dict{String, Int}()) @Test isempty(d) @Test !haskey(d, "a") @Test isnothing(pop!(d, "a", nothing)) @Test isnothing(get(d, "a", nothing)) d["a"] = 1 d["b"] = 2 @Test !isempty(d) @Test haskey(d, "a") @Test d["a"] == 1 @Test keytype(typeof(d)) == String @Test valtype(typeof(d)) == Int @Test eltype(typeof(d)) == Pair{String, Int} @Test ("a" => 1) in d @Test "a" ∈ keys(d) @Test Set(collect(pairs(d))) == Set(["a" => 1, "b" => 2]) @Test 1 ∈ values(d) empty!(d) @Test isempty(d) f = ForwardVector(Int[]) @Test isempty(f) @Test size(f) == (0,) @Test length(f) == 0 f = ForwardVector([1,3,3]) @test_throws_compat MethodError "MethodError: no method matching lastindex(::$ForwardVector{Int64})" f[end] @Test f[1:3] == [1,3,3] @Test f[2] == 3 f[2] = 2 @Test f[2] == 2 @Test length(f) == 3 for (i, fi) in enumerate(f) @Test i == fi end @Test eltype(f) == Any f = ForwardVectorInterface(Int[]) @Test isempty(f) @Test size(f) == (0,) @Test length(f) == 0 @Test eltype(f) == Int @Test eltype(ForwardVectorInterface{Int}) == Int f = ForwardVectorInterface([1,3,3]) @Test f[begin] == 1 @Test f[end] == 3 @Test f[begin:end] == [1,3,3] @Test f[2] == 3 f[2] = 2 @Test f[2] == 2 @Test length(f) == 3 for (i, fi) in enumerate(f) @Test i == fi end m = ForwardMatrix([1.0 0.0; 0.0 1.0]) @Test size(m) == (2,2) @Test m[1,1] == 1.0 m[1,1] = 2.0 @Test m[1,1] == 2.0 f = ForwardVectorNoLength([1,3,3]) @test_throws MethodError length(f) @Test f[2] == 3 f[2] = 2 @Test f[2] == 2 for (i, fi) in enumerate(f) @Test i == fi end l = LockableDict(Dict{String,Int}(), ReentrantLock()) l["a"] = 1 @Test l["a"] == 1 end end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
9718
@testitem "Forward methods" setup=[SetupTest] begin using ForwardMethods @forward_methods A field=v Base.length(x::A) Base.getindex(_, k) Base.eltype(::Type{A}) test_func(v::Vector) = v[1] struct B{T} v::Vector{T} end @forward_methods B{T} field=getfield(b,:v) Base.length(x::B) (Base.getindex(_, k) where {T}) test_func struct C c::Vector{Int} end @forward_methods C field=c begin Base.length Base.getindex(_, k) end @testset "@forward_methods" begin @testset "Parsing" begin @test_cases begin input | output_x | output_y :(field=getproperty(_,:abc)) | :(Base.getproperty(x, :abc)) | :(Base.getproperty(y, :abc)) :(field=Base.getproperty(_,:abc)) | :(Base.getproperty(x, :abc)) | :(Base.getproperty(y, :abc)) :(field=getindex(x,:k)) | :(Base.getindex(x,:k)) | :(Base.getindex(y, :k)) :(field=t[]) | :(x[]) | :(y[]) :(field=t[1]) | :(x[1]) | :(y[1]) :(field=f(z)) | :(f(x)) | :(f(y)) @test (ForwardMethods.parse_field(input).arg_func)(:x) == output_x @test (ForwardMethods.parse_field(input).arg_func)(:y) == output_y @test isnothing(ForwardMethods.parse_field(input).type_func) end @test_cases begin input | output_arg_x | output_arg_y | output_type_x :(field=:abc) | :(Base.getfield(x,:abc)) | :(Base.getfield(y,:abc)) | :(Base.fieldtype(x, :abc)) :(field=abc) | :(Base.getfield(x,:abc)) | :(Base.getfield(y,:abc)) | :(Base.fieldtype(x, :abc)) :(field=abc.def.ghi) | :(Base.getfield(Base.getfield(Base.getfield(x,:abc), :def), :ghi)) | :(Base.getfield(Base.getfield(Base.getfield(y,:abc), :def), :ghi)) | :(Base.fieldtype(Base.fieldtype(Base.fieldtype(x,:abc), :def), :ghi)) :(field=getfield(_,:abc)) | :(Base.getfield(x,:abc)) | :(Base.getfield(y,:abc)) | :(Base.fieldtype(x, :abc)) :(field=Base.getfield(_,:abc)) | :(Base.getfield(x,:abc)) | :(Base.getfield(y,:abc)) | :(Base.fieldtype(x, :abc)) @test (ForwardMethods.parse_field(input).arg_func)(:x) == output_arg_x @test (ForwardMethods.parse_field(input).arg_func)(:y) == output_arg_y @test (ForwardMethods.parse_field(input).type_func)(:x) == output_type_x end @test_cases begin Type | UnionallType | expr | output :A | :A | :(x::A) | (; matches=true, unionall=false, type=false, arg=:x) :A | :A | :(x::Type{A}) | (; matches=true, unionall=false, type=true, arg=:A) :(A{B,C}) | :A | :(x::Type{A}) | (; matches=true, unionall=true, type=true, arg=:A) :(A{B,C}) | :A | :(x::A{B,C}) | (; matches=true, unionall=false, type=false, arg=:x) :(A{B,C}) | :A | :(x::Type{A{B,C}}) | (; matches=true, unionall=false, type=true, arg=:(A{B,C})) @test ForwardMethods.matches_type_signature(Type, UnionallType, expr) == output end @test_cases begin input | replace_values | output (input=:_ , replace_values=[:_ => :t], output=(:t, true)) (input=:(f(_)), replace_values=[:_ => :t], output=(:(f(t)), true)) (input=:(f(x)), replace_values=[:_ => :t], output=(:(f(x)), false)) (input=:(f(x)), replace_values=[:_ => :t, :x => :s], output=(:(f(s)), true)) @test ForwardMethods.replace_placeholder(input, replace_values) == output end ref_obj = :x ref_expr = :(Base.iterate(Base.getfield(x,k))) @test_cases begin input | output :(map=_) | ref_expr :(map=f(_)) | :(f($ref_expr)) :(map=begin z = f(_); g(z) end) | Expr(:block, :(z = f($ref_expr)), :(g(z))) :(map=begin z = f(_); g(z, _obj) end) | Expr(:block, :(z = f($ref_expr)), :(g(z, $ref_obj))) @test ForwardMethods.parse_map_expr(input)(ref_obj, ref_expr) == output end @Test isnothing(ForwardMethods.parse_map_expr(:x)) end @testset "Expression generation" begin field_funcs = ForwardMethods.FieldFuncExprs( (t)->:(Base.getproperty($t, :b)), nothing ) matches_rhs = (t, x_ref=:x)->begin @match t begin quote local $var1 = Base.getproperty($var2, :b) Base.getindex($var3, k) end => (var2 == x_ref && var1 == var3 ) _ => false end end for (T, input_expr) in ((:A, :(Base.getindex(x::A, k))), (:(A{B1,B2}), :(Base.getindex(x::A{B1,B2},k) where {B1,B2})), (:(A{B1,B2}), :(Base.getindex(x::A, k)))) output = ForwardMethods.forward_method_signature(T, field_funcs, input_expr) matches = @switch output begin @case :($lhs = $rhs) && if lhs == input_expr end matches_rhs(rhs) @case _ false end @test matches end field_funcs = ForwardMethods.FieldFuncExprs( (t)->:(Base.getfield($t, :b)), (t) -> :(Base.fieldtype($t, :b))) T = :A input_expr = :(Base.length) matches_rhs = (t, x_ref=:x)->begin @match t begin quote local $var1 = Base.getfield($var2, :b) Base.length($var3) end => (var2 == x_ref && var1 == var3 ) _ => false end end output = ForwardMethods.forward_method_signature(T, field_funcs, input_expr) matches = @switch output begin @case :($lhs = $rhs) @match lhs begin :(Base.length($var1::A)) => matches_rhs(rhs, var1) _ => false end @case _ false end @test matches input_expr = :(Base.eltype(::Type{A})) matches_rhs = (t, x_ref=:x)->begin @match t begin quote local $var1 = Base.fieldtype($var2, :b) Base.eltype($var3) end => (var2 == x_ref && var1 == var3 ) _ => false end end output = ForwardMethods.forward_method_signature(T, field_funcs, input_expr) matches = @switch output begin @case :($lhs = $rhs) @match lhs begin :(Base.eltype(::Type{A})) => matches_rhs(rhs, T) _ => false end @case _ false end @test matches # Testing underscore parameters field_funcs = ForwardMethods.FieldFuncExprs( (t)->:(Base.getfield($t, :b)), (t) -> :(Base.fieldtype($t, :b))) T = :(A{B1,B2}) input_expr = :(Base.getindex(_, k) where {B1, B2}) matches_rhs = (t, x_ref=:x)->begin @match t begin quote local $var1 = Base.getfield($var2, :b) Base.getindex($var3, k) end => (var2 == x_ref && var1 == var3 ) _ => false end end output = ForwardMethods.forward_method_signature(T, field_funcs, input_expr) matches = @switch output begin @case :($lhs = $rhs) @match lhs begin :(Base.getindex($var1::A{B1,B2}, k) where {B1,B2}) => matches_rhs(rhs, var1) _ => false end @case _ false end @test matches # If provided type is parametric but signature does not qualify where statement -- use unionall type in signature T = :(C.A{B1,B2}) input_expr = :(Base.getindex(_, k)) output = ForwardMethods.forward_method_signature(T, field_funcs, input_expr) matches = @switch output begin @case :($lhs = $rhs) @match lhs begin :(Base.getindex($var1::C.A, k)) => matches_rhs(rhs, var1) _ => false end @case _ false end @test matches end @testset "Forwarded methods" begin @Test custom_func_to_forward(A([0])) == 0 @Test length(A([0])) == 1 @Test A([0])[1] == 0 @Test eltype(A) == Int @Test length(B([0])) == 1 @Test B([0])[1] == 0 c = C([1]) @Test length(c) == 1 @static if VERSION >= v"1.9" @test_opt length(c) end end end end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
167
@testitem "@define_interface" setup=[SetupTest] begin include("test_properties.jl") include("test_equality.jl") include("test_getfields_setfields.jl") end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
664
@define_interface SettableProperties2 interface=equality struct EqualityUsingProperties d::Dict{Symbol,Int} end Base.propertynames(e::EqualityUsingProperties) = collect(keys(getfield(e, :d))) Base.getproperty(e::EqualityUsingProperties, k::Symbol) = getfield(e, :d)[k] Base.setproperty!(e::EqualityUsingProperties, k::Symbol, v::Int) = getfield(e, :d)[k] = v @define_interface EqualityUsingProperties interface=equality compare_fields=propertynames @testset "equality interface" begin e = EqualityUsingProperties(Dict(:a => 1)) @Test e == EqualityUsingProperties(Dict(:a => 1)) @Test e != EqualityUsingProperties(Dict(:a => 1, :b => 2)) end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
1892
struct ManyProperties field1::String field2::Int field3::Bool end @forward_interface ManyProperties interface=getfields @test !ForwardMethods.has_defined_interface(SettableProperties, Val(:getfields)) @test !ForwardMethods.has_defined_interface(SettableProperties, Val(:setfields)) @define_interface SettableProperties interface=(getfields, setfields) @test ForwardMethods.has_defined_interface(SettableProperties, Val(:getfields)) @test ForwardMethods.has_defined_interface(SettableProperties, Val(:setfields)) mutable struct SettablePropertiesNoKey2Key3 key1::String key2::Int key3::Bool end @define_interface SettablePropertiesNoKey2Key3 interface=(getfields, setfields) omit=(key2, key3) @testset "getfields/setfields" begin p = ManyProperties("abc", 0, true) @Test field1(p) == "abc" @Test field2(p) == 0 @Test field3(p) == true q = SettableProperties("abc", 0, true) @Test key1(q) == "abc" @Test key2(q) == 0 @Test key3(q) == true key1!(q, "zzz") @Test key1(q) == "zzz" key2!(q, 1) @Test key2(q) == 1 key3!(q, false) @Test key3(q) == false @test hasmethod(key1, Tuple{SettableProperties}) @test hasmethod(key1!, Tuple{SettableProperties, String}) @test hasmethod(key2, Tuple{SettableProperties}) @test hasmethod(key2!, Tuple{SettableProperties, Int}) @test hasmethod(key3, Tuple{SettableProperties}) @test hasmethod(key3!, Tuple{SettableProperties, Bool}) @test hasmethod(key1, Tuple{SettablePropertiesNoKey2Key3}) @test hasmethod(key1!, Tuple{SettablePropertiesNoKey2Key3, String}) @test !hasmethod(key2, Tuple{SettablePropertiesNoKey2Key3}) @test !hasmethod(key2!, Tuple{SettablePropertiesNoKey2Key3, Int}) @test !hasmethod(key3, Tuple{SettablePropertiesNoKey2Key3}) @test !hasmethod(key3!, Tuple{SettablePropertiesNoKey2Key3, Bool}) end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
code
3813
mutable struct CompositeProperties settable::SettableProperties key4::Float64 end @define_interface CompositeProperties interface=properties delegated_fields=settable mutable struct CompositeProperties2 settable::SettableProperties alsosettable::SettableProperties2 end @test !ForwardMethods.has_defined_interface(CompositeProperties2, Val(:properties)) @test !ForwardMethods.has_defined_interface(SettableProperties2, Val(:properties)) @define_interface CompositeProperties2 interface=properties delegated_fields=(settable, alsosettable) @test ForwardMethods.has_defined_interface(CompositeProperties2, Val(:properties)) @test !ForwardMethods.has_defined_interface(SettableProperties2, Val(:properties)) # Won't be a problem recursing into this type since, since unregistered types don't have recursively derived properties struct UnregisteredComposite x1::A x2::CompositeProperties end mutable struct CompositePropertiesRecursive _key1::CompositeProperties _key2::UnregisteredComposite end @define_interface CompositePropertiesRecursive interface=properties delegated_fields=(_key1, _key2) recursive=true struct ClashingKeys key1::SettableProperties key2::String end @test_throws_compat ErrorException "Duplicate properties `[:key1, :key2]` found for type $ClashingKeys in child `key1::$SettableProperties`" @define_interface ClashingKeys interface=properties delegated_fields=key1 @testset "properties interface" begin c = CompositeProperties(SettableProperties("abc", 0, true), 0.0) @Test propertynames(c) == (:settable, :key4, :key1, :key2, :key3) @Test c.settable == getfield(c, :settable) @Test c.key4 == getfield(c, :key4) @Test c.key1 == getfield(getfield(c, :settable), :key1) @Test c.key2 == getfield(getfield(c, :settable), :key2) @Test c.key3 == getfield(getfield(c, :settable), :key3) c.key1 = "zzz" @Test c.key1 == "zzz" if VERSION ≥ v"1.9" @inferred propertynames(c) f = t->t.key1 @Test @inferred f(c) == "zzz" end e = UnregisteredComposite(A([1]), CompositeProperties(SettableProperties("a", -1, false), 0.1)) d = CompositePropertiesRecursive(c, e) @Test propertynames(d) == (:_key1, :_key2, :settable, :key4, :key1, :key2, :key3, :x1, :x2) for p in (:_key1, :_key2) @Test getproperty(d, p) === getfield(d, p) end for p in (:settable, :key4) @Test getproperty(d, p) === getfield(getfield(d, :_key1), p) end for p in (:key1, :key2, :key3) @Test getproperty(d, p) === getfield(getfield(getfield(d, :_key1), :settable), p) end for p in (:x1, :x2) @Test getproperty(d, p) === getfield(getfield(d, :_key2), p) end @Test d.key1 == "zzz" d.key1 = "z" @Test d.key1 == "z" c = CompositeProperties2(SettableProperties("abc", 0, true), SettableProperties2(0.0, [0])) @Test propertynames(c) == (:settable, :alsosettable, :key1, :key2, :key3, :key4, :key5) @Test c.settable === getfield(c, :settable) @Test c.alsosettable === getfield(c, :alsosettable) @Test c.key1 === getfield(getfield(c, :settable), :key1) @Test c.key2 === getfield(getfield(c, :settable), :key2) @Test c.key3 === getfield(getfield(c, :settable), :key3) @Test c.key4 === getfield(getfield(c, :alsosettable), :key4) @Test c.key5 === getfield(getfield(c, :alsosettable), :key5) c.key3 = false c.key4 = 1.0 @Test getfield(getfield(c, :settable), :key3) == false @Test getfield(getfield(c, :alsosettable), :key4) == 1.0 @Test c.alsosettable.key4 == 1.0 @Test c.alsosettable.key5 == [0] c.alsosettable = SettableProperties2(2.0, [1]) @Test c.alsosettable.key4 == 2.0 @Test c.alsosettable.key5 == [1] @Test c.key4 == 2.0 @Test c.key5 == [1] end
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
docs
7986
# ForwardMethods [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://curtd.github.io/ForwardMethods.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://curtd.github.io/ForwardMethods.jl/dev/) [![Build Status](https://github.com/curtd/ForwardMethods.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/curtd/ForwardMethods.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage Status](https://coveralls.io/repos/github/curtd/ForwardMethods.jl/badge.svg)](https://coveralls.io/github/curtd/ForwardMethods.jl) `ForwardMethods` provides macros that automate some of the boilerplate involved when using composition for object polymorphism. This package is essentially fancy copy + paste for forwarding function definitions, as well as providing automatically generated generic interfaces for struct types. # `@forward_methods` Given a hypothetical definition for type `T` with a subfield `s` of type `S`, i.e., ```julia struct T ... s::S ... end ``` suppose that type `S` has a number of existing functions defined as `f₁(..., obj::S, ...; kwargs...)`, ..., `fₙ(..., obj::S, ...; kwargs...)`. In the argument list here, `...` indicates a fixed number of preceding or following arguments (and not a Julia splatting pattern). If you wanted to define instances of these methods for `x::T` by forwarding them to `getfield(x, :s)`, the normal boilerplate code you would have to write in standard Julia would be ```julia for f in (:f₁, ..., :fₙ) @eval $f(..., x::T, ...) = $f(..., getfield(x, :s), ...) end ``` which works fine when all of the functions `fᵢ` have same number of arguments and the position of the argument of type `S` is the same in each argument list. If this is not the case, it can be fairly tedious to generate all of the specific signature expressions to evaluate. The `@forward_methods` macro automates much of this boilerplate away by only requiring you to specify the type, the fieldname, and the signature of the methods you'd like to forward. To take a concrete example, suppose we define ```julia struct T s::Vector{Int} end ``` We'd like to forward a number of method signatures corresponding to the `AbstractArray` interface. We can write this compactly using `@forward_methods` as: ```julia @forward_methods T field=s Base.length(x::T) Base.getindex(x::T, i::Int) Base.setindex!(x::T, v, i::Int) ``` Here the position of the argument of interest will be inferred from the type annotation `::T`. We can write this even more compactly as ```julia @forward_methods T field=s Base.length Base.getindex(_, i::Int) Base.setindex!(x::T, v, i::Int) ``` Here a `0-`argument expression `Base.length` is expanded to `Base.length(x::T)` and the placeholder underscore `_` is expanded to `x::T`. Rather than defining a forwarded method with an object argument to its child value, e.g., `x::T` -> `getfield(x, :s)` as above, you can also forward the method with a type argument `::Type{T}` to `fieldtype(T, :s)` as follows ```julia @forward_methods T field=s Base.eltype(::Type{T}) Base.IndexStyle(::Type{T}) ``` Parametric types and type signatures are also supported, so if you have, say, ```julia struct A{B} d::Dict{String, B} end ``` you can easily forward parametric / non-parametric method definitions to field `d` simultaneously via ```julia @forward_methods A{B} field=d (Base.getindex(a::A{B}, k::String) where {B}) Base.keys(x::A) Base.values(_) ``` Letting `x::T` denote the object of interest, the value of the keyword argument `field = _field` has the following effects on the generated expressions: - If `_field = k` with `k::Symbol` or a `k::QuoteNode`, or an expression of the form `getfield(_, k)`, in which case methods will be forwarded to `getfield(x, k)` - If `_field = a.b.c. ... .z` is a dotted expression, methods will be forwarded to `getfield(getfield(... getfield(getfield(x, :a), :b), ...), :z)` - If `_field` is an expression of the form `getproperty(_, k)`, the method instances will be forwarded to `getproperty(x, k)` - If `_field` is an expression of the form `t[args...]`, the method instances will be forwarded to `x[args...]` - If `_field` is an expression of the form `f(_)` for a single-argument function `f`, the method instances will be forwarded to `f(x)` # `@forward_interface` If the type of `S` has a known interface (e.g., a fixed set of methods defined with a particular type signature), it may be more convenient to forward the entire suite of methods for that interface to objects `x::T`, rather than to specify each method signature individually. ```julia @forward_interface T field=_field interface=_interface [kwargs...] ``` Here `T` and `_field` are as above and `_interface` is one of a preset number of values, namely `iteration`, `indexing`, `array`, `dict`, `getfields`, and `setfields`. The value of `_interface` determines the specific forwarded method signatures that are generated, e.g., ```julia struct B b::Dict{String, Int} end @forward_interface B field=b interface=dict b = B(Dict{String,Int}()) ``` `b` can now be used as a drop-in replacement in any method where a `Dict{String,Int}` is supported. Note: certain methods for certain interfaces (e.g., `Base.similar` for the Array interface) are not included in this macro as direct method forwarding would not make sense to apply in these cases. The `getfields` and `setfields` interfaces are dynamically generated based on the fields of type `T`. When `interface=getfields`, this macro forwards methods of the form `$field(x::T) = getfield(x, $field)` for each `field ∈ fieldnames(T)` When `interface=setfields`, this macro forwards methods of the form `$field!(x::T, value) = setfield!(x, $field, value)` for each `field ∈ fieldnames(T)` # `@define_interface` Certain interfaces are defined for objects `x::T` that don't involve explicit forwarding to a fixed-field, per-se, but can be generally useful. ## `properties` interface The `properties` interface allows a unified `Base.propertynames`, `Base.getproperty`, and `Base.setproperty!` interface for `x::T` which is composed of subfields `k1, k2, ..., kn` whose fields should also be included in the properties of `x`. This pattern arises when creating composite types. For example, ```julia julia> struct A key1::Int key2::Bool end julia> struct B key3::String key4::Float64 end julia> struct C a::A b::B end julia> @define_interface C interface=properties delegated_fields=(a,b) julia> c = C(A(1, true), B("a", 0.0)) C(A(1, true), B("a", 0.0)) julia> (key1=c.key1, key2=c.key2, key3=c.key3, key4=c.key4, a=c.a, b=c.b) (key1 = 1, key2 = true, key3 = "a", key4 = 0.0, a = A(1, true), b = B("a", 0.0)) ``` Essentially the fields of `c.a` and `c.b` has been flattened to provide a unified view of the properties of `c`. ## `equality` interface The `equality` interface defines `Base.==` or `Base.isequal` for objects of `T` in the obvious way, i.e., ```julia Base.:(==)(x::T, y::T) = all( getfield(x,k) == getfield(y,k) for k in fieldnames(T) ) ``` There are some configurable options for this macro, so you can do some fancier equality comparisons such as ```julia julia> struct E d::Dict{Symbol,Int} end julia> Base.propertynames(e::E) = collect(keys(getfield(e, :d))) julia> Base.getproperty(e::E, k::Symbol) = getfield(e, :d)[k] julia> Base.setproperty!(e::E, k::Symbol, v::Int) = getfield(e, :d)[k] = v julia> @define_interface E interface=equality compare_fields=propertynames julia> julia> e = E(Dict(:a => 1)) E(Dict(:a => 1)) julia> e == E(Dict(:a => 1)) true julia> e == E(Dict(:a => 2)) false ``` ## Similar Packages/Functionality - [ReusePatterns.jl](https://github.com/gcalderone/ReusePatterns.jl) - `@forward` in [Lazy.jl](https://github.com/MikeInnes/Lazy.jl)
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
docs
412
# API ```@docs @forward_methods @forward_interface @define_interface ForwardMethods.iteration_interface ForwardMethods.indexing_interface ForwardMethods.lockable_interface ForwardMethods.array_interface ForwardMethods.vector_interface ForwardMethods.dict_interface ForwardMethods.getfields_interface ForwardMethods.setfields_interface ForwardMethods.properties_interface ForwardMethods.equality_interface ```
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "MIT" ]
1.7.0
4153d2d64ec4e0d9464e1804ab2d784773e610ac
docs
333
```@meta CurrentModule = ForwardMethods ``` # ForwardMethods The [ForwardMethods](https://github.com/curtd/ForwardMethods.jl) package provides macros that remove much of the boilerplate of *method-forwarding* i.e., defining a series of method instances for an object by forwarding to the same method applied to a particular field.
ForwardMethods
https://github.com/curtd/ForwardMethods.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
1284
module PDEngine # Include PDE solver files include("heat_eq.jl") include("wave_eq.jl") include("navier_stokes_eq.jl") include("poisson_eq.jl") # Export functions for external use export heat,heat_fdm, heat_fem,heat_nicolson,heat_spectral, wave_fdm, wave_fem,navier_stokes, poisson_fdm, poisson_fem,poisson # Wrapper functions or additional setup # initialize some parameters or configurations # basic information about the package function info() @info "PDEngine.jl: A Julia library for solving partial differential equations (PDEs)." @info "Available solvers:" @info "- heat_fdm: Solves the 1D heat equation with the finite difference method" @info "- heat_fem: Solves the 1D heat equation with the finite element method" @info "- heat_nicolson: Solves the 1D heat equation with the crank nicolson method" @info "- wave_fdm: Solves the 1D wave equation with the finite difference method" @info "- wave_fem: Solves the 1D wave equation with the finite element method" @info "- navier_stokes: Solves the 2D Navier-Stokes equations." @info "- poisson_fdm: Solves the 2D Poisson's equation with the finite difference method" @info "- poisson_fem: Solves the 2D Poisson's equation with the finite element method" end end # module PDEngine
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
8326
using LinearAlgebra,FFTW """ heat(N, α, T, Δx, Δt) is the default Wrapper function using the spectral method, for easy name access: # Arguments - `N::Int`: The number of spatial grid points (excluding boundary points). - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `T::Float64`: The total simulation time. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Vector{Float64}`: The temperature distribution at the final time step. """ # Catching too much input function heat(N, α, T, Δx, Δt) heat_spectral(N, α, T, Δt) end function heat(N, α, T, Δt) heat_spectral(N, α, T, Δt) end """ heat_spectral(N, α, T, Δx, Δt) Solve the 1D heat equation using the Spectral Method. # Arguments - `N::Int`: The number of spatial grid points (excluding boundary points). - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `T::Float64`: The total simulation time. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Vector{Float64}`: The temperature distribution at the final time step. """ function heat_spectral(N, α, T, Δt) # Define the spatial domain L = 1 dx = L / N x = dx * (0:N) # N+1 points # Initialize the temperature field with a Gaussian profile u = exp.(-((x .- 0.5).^2) / (2 * (0.1)^2)) # Compute the wavenumbers k = 2 * π * [0:div(N,2); -div(N,2)+1:-1] / L # Compute the Fourier transform of the initial condition u_hat = rfft(u) # Time-stepping loop num_steps = Int(T / Δt) for _ in 1:num_steps #DEBUG #println("Size of u_hat: ", size(u_hat)) # println("Size of k: ", size(k)) if(size(k)==size(u_hat)) # Compute the time evolution in Fourier space u_hat .*= exp.(-α * k.^2 * Δt) end end # Inverse Fourier transform to get the solution in physical space u = irfft(u_hat, N + 1) return u end """ check_stability(α, Δx, Δt) Check the stability condition for a finite difference scheme solving the heat equation. # Arguments - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Bool`: `true` if the stability condition is satisfied, otherwise `false`. - `String`: A message indicating whether the parameters satisfy the stability condition. """ function check_stability(α, Δx, Δt) stability_param = α * Δt / Δx^2 if stability_param <= 0.5 return true, "The parameters satisfy the stability condition." else return false, "The parameters do NOT satisfy the stability condition." end end """ heat_fdm(N, α, T, Δx, Δt) Solve the 1D heat equation using the Finite Difference Method (FDM). # Arguments - `N::Int`: The number of spatial grid points (excluding boundary points). - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `T::Float64`: The total simulation time. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Vector{Float64}`: The temperature distribution at the final time step. """ function heat_fdm(N, α, T, Δx, Δt) # Check if the stability condition is satisfied stability, message = check_stability(α, Δx, Δt) if !stability println(message) end # Calculate the number of time steps num_steps = Int(T / Δt) # Define the spatial domain x = 0:Δx:1 # Initialize the temperature field u = zeros(N+1) u_new = similar(u) # Set the initial condition: Gaussian profile centered at x = 0.5 for i in 1:N+1 u[i] = exp(-((x[i] - 0.5)^2) / (2 * (0.1)^2)) end # Time-stepping loop for _ in 1:num_steps # Update the temperature field using the finite difference scheme for i in 2:N u_new[i] = u[i] + α * Δt / Δx^2 * (u[i+1] - 2*u[i] + u[i-1]) end # Apply Dirichlet boundary conditions (u = 0 at the boundaries) u_new[1] = 0 u_new[end] = 0 # Swap the references to avoid unnecessary copying u, u_new = u_new, u end return u end """ heat_fem(N, α, T, Δx, Δt) Solve the 1D heat equation using the Finite Element Method (FEM). # Arguments - `N::Int`: The number of spatial grid points (excluding boundary points). - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `T::Float64`: The total simulation time. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Vector{Float64}`: The temperature distribution at the final time step. """ function heat_fem(N, α, T, Δx, Δt) # Check if the stability condition is satisfied stability, message = check_stability(α, Δx, Δt) if !stability println(message) end # Calculate the number of time steps num_steps = Int(T / Δt) # Define the spatial domain (nodes) nodes = 0:Δx:1 # Initialize the temperature field u = zeros(N+1) u_new = similar(u) # Set the initial condition: heat source at the middle of the domain mid_point = round(Int, N/2) + 1 u[mid_point] = 1.0 # Initialize the stiffness (K) and mass (M) matrices K = zeros(N+1, N+1) M = zeros(N+1, N+1) # Assemble the stiffness and mass matrices for i in 1:N x1 = nodes[i] x2 = nodes[i+1] L = x2 - x1 k_local = α / L * [1 -1; -1 1] m_local = L / 6 * [2 1; 1 2] # Assemble into global matrices K[i:i+1, i:i+1] += k_local M[i:i+1, i:i+1] += m_local end # Apply Dirichlet boundary conditions (u = 0 at the boundaries) K[1, :] .= 0 K[1, 1] = 1 M[1, :] .= 0 M[1, 1] = 1 K[end, :] .= 0 K[end, end] = 1 M[end, :] .= 0 M[end, end] = 1 # Time-stepping loop for _ in 1:num_steps # Create the load vector f = M * u # Apply boundary conditions to the load vector f[1] = 0 f[end] = 0 # Solve for the new temperature field u_new = (M + α * Δt / 2 * K) \ (M * u + α * Δt / 2 * f) # Update the temperature field for the next time step u[:] = u_new[:] end return u end """ heat_crank_nicolson(N, α, T, Δx, Δt) Solve the 1D heat equation using the Crank-Nicolson method. # Arguments - `N::Int`: The number of spatial grid points (excluding boundary points). - `α::Float64`: The thermal diffusivity or the diffusion coefficient. - `T::Float64`: The total simulation time. - `Δx::Float64`: The spatial step size. - `Δt::Float64`: The time step size. # Returns - `Vector{Float64}`: The temperature distribution at the final time step. """ function heat_nicolson(N, α, T, Δx, Δt) # Check if the stability condition is satisfied stability, message = check_stability(α, Δx, Δt) if !stability println(message) end # Calculate the number of time steps num_steps = Int(T / Δt) # Define the spatial domain x = 0:Δx:1 # Initialize the temperature field u = zeros(N+1) u_new = similar(u) # Set the initial condition: heat source at the middle of the domain mid_point = round(Int, N/2) + 1 u[mid_point] = 1.0 # Coefficients for the Crank-Nicolson method r = α * Δt / (2 * Δx^2) # Construct the tridiagonal matrices A and B A = Matrix{Float64}(I, N+1, N+1) B = Matrix{Float64}(I, N+1, N+1) for i in 2:N A[i, i-1] = -r A[i, i] = 1 + 2 * r A[i, i+1] = -r B[i, i-1] = r B[i, i] = 1 - 2 * r B[i, i+1] = r end # Apply Dirichlet boundary conditions (u = 0 at the boundaries) A[1, :] .= 0 A[1, 1] = 1 A[end, :] .= 0 A[end, end] = 1 B[1, :] .= 0 B[1, 1] = 1 B[end, :] .= 0 B[end, end] = 1 # Time-stepping loop for _ in 1:num_steps # Compute the right-hand side vector f = B * u # Solve the system of linear equations u_new = A \ f # Update the temperature field for the next time step u[:] = u_new[:] end return u end
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
3975
using LinearAlgebra """ Solve the 2D Navier-Stokes equations using the finite difference method. The Navier-Stokes equations describe the motion of viscous fluid substances. Arguments: - N: Number of grid points in each direction (excluding boundary points) - ν: Kinematic viscosity - T: Total simulation time - Δx: Spatial step size - Δt: Temporal step size Returns: - u: x-component of velocity field - v: y-component of velocity field - p: Pressure field """ function navier_stokes(N, ν, T, Δx, Δt) # Number of grid points (including boundaries) N_plus = N + 1 # Initialize velocity and pressure fields u = zeros(N_plus, N_plus) # x-component of velocity v = zeros(N_plus, N_plus) # y-component of velocity p = zeros(N_plus, N_plus) # Pressure field u_new = similar(u) v_new = similar(v) # Precompute constants r = ν * Δt / Δx^2 # Helper functions for boundary conditions function apply_boundary_conditions!(u, v, p) # Apply boundary conditions for u, v, p u[1, :] .= 0 # u = 0 at y = 0 (no-slip condition) u[end, :] .= 0 # u = 0 at y = 1 (no-slip condition) v[:, 1] .= 0 # v = 0 at x = 0 (no-slip condition) v[:, end] .= 0 # v = 0 at x = 1 (no-slip condition) # Pressure boundary conditions are implicitly handled in the pressure correction step end function compute_pressure_correction!(u, v, p) # Compute the pressure correction using a Poisson equation b = zeros(N_plus, N_plus) # Build the right-hand side of the pressure Poisson equation for i in 2:N for j in 2:N b[i, j] = (u[i, j] - u[i, j-1]) / Δx + (v[i, j] - v[i-1, j]) / Δx end end # Solve the Poisson equation for pressure correction for _ in 1:1000 # Simple iterative solver (Jacobi method for demonstration) p_old = copy(p) for i in 2:N for j in 2:N p[i, j] = (1/4) * (p_old[i+1, j] + p_old[i-1, j] + p_old[i, j+1] + p_old[i, j-1] - b[i, j] * Δx^2) end end end end function update_velocity!(u, v, p) # Update u and v fields using pressure correction for i in 2:N for j in 2:N u_new[i, j] = u[i, j] - (Δt / Δx) * (p[i, j] - p[i, j-1]) v_new[i, j] = v[i, j] - (Δt / Δx) * (p[i, j] - p[i-1, j]) end end # Swap references to avoid unnecessary copying u, u_new = u_new, u v, v_new = v_new, v end # Time-stepping loop for _ in Δt:Δt:T # Compute intermediate velocities u_star = copy(u) v_star = copy(v) # Update velocities using the advection and diffusion terms for i in 2:N for j in 2:N u_star[i, j] = u[i, j] + Δt * ( - (u[i, j] * (u[i, j] - u[i, j-1]) / Δx + v[i, j] * (u[i, j] - u[i-1, j]) / Δx) + ν * ((u[i+1, j] - 2 * u[i, j] + u[i-1, j]) / Δx^2 + (u[i, j+1] - 2 * u[i, j] + u[i, j-1]) / Δx^2) ) v_star[i, j] = v[i, j] + Δt * ( - (u[i, j] * (v[i, j] - v[i, j-1]) / Δx + v[i, j] * (v[i, j] - v[i-1, j]) / Δx) + ν * ((v[i+1, j] - 2 * v[i, j] + v[i-1, j]) / Δx^2 + (v[i, j+1] - 2 * v[i, j] + v[i, j-1]) / Δx^2) ) end end # Apply boundary conditions apply_boundary_conditions!(u_star, v_star, p) # Compute pressure correction compute_pressure_correction!(u_star, v_star, p) # Update velocities using the pressure correction update_velocity!(u_star, v_star, p) end return u, v, p end # Example usage N = 50 ν = 0.01 T = 1.0 Δx = 1.0 / N Δt = 0.001 u, v, p = navier_stokes(N, ν, T, Δx, Δt)
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
4568
using FFTW # For FFT operations function poisson(N,f,Δx) poisson_fdm(N,f,Δx) end """ Solve 2D Poisson's equation using the finite difference method. # Arguments - `N::Int`: Number of grid points along each dimension (excluding boundaries). - `f::Array{Float64,2}`: A 2D array representing the source term on the grid. - `Δx::Float64`: Spatial step size. # Returns - `u::Array{Float64,2}`: The final solution field. """ function poisson_fdm(N, f, Δx) # Initialize solution field u = zeros(N+1, N+1) u_new = similar(u) # Iterative solver to update the solution field for _ in 1:1000 # Number of iterations (could be adjusted or replaced with convergence check) # Update the solution field using finite difference scheme for i in 2:N for j in 2:N u_new[i, j] = 0.25 * (u[i+1, j] + u[i-1, j] + u[i, j+1] + u[i, j-1] - Δx^2 * f[i, j]) end end # Swap references to avoid unnecessary copying u, u_new = u_new, u end return u end """ Solve 2D Poisson's equation using the finite element method (FEM). # Arguments - `N::Int`: Number of grid points along each dimension (excluding boundaries). - `f::Function`: A function representing the source term. - `Δx::Float64`: Spatial step size. # Returns - `u::Array{Float64,2}`: The final solution field. """ function poisson_fem(N, f, Δx) # Number of nodes num_nodes = (N + 1) * (N + 1) # Initialize matrices K = zeros(num_nodes, num_nodes) F = zeros(num_nodes) # Node index function function node_index(i, j) return (i - 1) * (N + 1) + j end # Loop over each element to assemble the global stiffness matrix and load vector for i in 1:N for j in 1:N # Local node indices (in a grid) n1 = node_index(i, j) n2 = node_index(i+1, j) n3 = node_index(i, j+1) n4 = node_index(i+1, j+1) # Element stiffness matrix and load vector (2x2 element) k_local = (1 / (4 * Δx^2)) * [2 -1 -1 0; -1 2 0 -1; -1 0 2 -1; 0 -1 -1 2] f_local = (Δx^2 / 4) * [f(i, j); f(i+1, j); f(i, j+1); f(i+1, j+1)] # Assemble into global matrices K[[n1, n2, n3, n4], [n1, n2, n3, n4]] .+= k_local F[[n1, n2, n3, n4]] .+= f_local end end # Apply boundary conditions (Dirichlet: u = 0 on the boundaries) boundary_nodes = Set() for i in 1:(N+1) push!(boundary_nodes, node_index(1, i)) push!(boundary_nodes, node_index(N+1, i)) push!(boundary_nodes, node_index(i, 1)) push!(boundary_nodes, node_index(i, N+1)) end for node in boundary_nodes K[node, :] .= 0 K[node, node] = 1 F[node] = 0 end # Solve the linear system u = K \ F # Reshape the solution to a grid format u_grid = reshape(u, (N + 1, N + 1)) return u_grid end """ Solve 2D Poisson's equation using the spectral method with FFTW. # Arguments - `N::Int`: Number of grid points along each dimension (excluding boundaries). - `f::Function`: A function representing the source term. - `Δx::Float64`: Spatial step size. # Returns - `u::Array{Float64,2}`: The final solution field. """ function poisson_spectral(N, f, Δx) # Create grid x = Δx * (0:N) y = Δx * (0:N) X, Y = meshgrid(x, y) # Create source term array F = [f(xi, yi) for xi in x, yi in y] # Perform FFT F_hat = rfft(F) # Frequency arrays kx = 2π * [0:N÷2; -N÷2+1:-1] / (N * Δx) ky = 2π * [0:N÷2; -N÷2+1:-1] / (N * Δx) # Create frequency grid KX, KY = meshgrid(kx, ky) # Compute Laplacian in frequency domain L = - (KX.^2 .+ KY.^2) # Avoid division by zero (at zero frequency) L[L .== 0] .= 1 # Reshape L to match the shape of F_hat L = L[1:size(F_hat, 1), 1:size(F_hat, 2)] # Solve in frequency domain U_hat = F_hat ./ L # Perform inverse FFT to get solution in spatial domain u = irfft(U_hat) # Return real part of the solution return real(u) end """ Create a meshgrid for given vectors `x` and `y`. # Arguments - `x::AbstractVector`: Vector of x-coordinates. - `y::AbstractVector`: Vector of y-coordinates. # Returns - `X::Array{T,2}`: 2D array where each row is a copy of `x`. - `Y::Array{T,2}`: 2D array where each column is a copy of `y`. """ function meshgrid(x, y) X = [xi for xi in x, yi in y] Y = [yi for xi in x, yi in y] return X, Y end
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
3853
""""WILL BE REPLACED BY /test DIRECTORY""" include("PDE_lib.jl") using .PDEngine using LinearAlgebra function test_heat_equation(N_values, α, T, Δt) println("Heat Equation Tester : \n") for N in N_values Δx = 1.0 / N # Spatial step size # Analytical solution at final time T analytical_solution(x, t) = exp(-α * π^2 * t) * sin(π * x) # Solve using FDM u_fdm = heat_eq_1d_fdm(N, α, T, Δx, Δt) # Solve using FEM u_fem = heat_eq_1d_fem(N, α, T, Δx, Δt) # Compare with analytical solution x = 0:Δx:1 u_exact = analytical_solution.(x, T) # Calculate relative error norms error_fdm = norm(u_fdm - u_exact) / norm(u_exact) error_fem = norm(u_fem - u_exact) / norm(u_exact) println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("------------------------------------------------") end end # Example test parameters heat_N_values = [5,10, 20, 50, 100,500,1000] # Different grid resolutions heat_α = 1.0 # Thermal diffusivity heat_T = 1e-10 # Total simulation time --v heat_Δt = 1e-10 # Temporal step size --> Biggest impact on accuracy! #test_heat_equation(heat_N_values, heat_α, heat_T, heat_Δt) function test_wave_equation(N_values, c, T, Δt) println("Wave Equation Tester : \n") for N in N_values Δx = 1.0 / N # Spatial step size # Analytical solution at final time T analytical_solution(x, t) = sin(π * x) * cos(c * π * t) # Solve using FDM u_fdm = wave_eq_1d_fdm(N, c, T, Δx, Δt) # Solve using FEM u_fem = wave_eq_1d_fem(N, c, T, Δx, Δt) # Compare with analytical solution x = 0:Δx:1 u_exact = analytical_solution.(x, T) # Calculate relative error norms error_fdm = norm(u_fdm - u_exact) / norm(u_exact) error_fem = norm(u_fem - u_exact) / norm(u_exact) println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("------------------------------------------------") end end # Example test parameters wave_N_values = [5, 10, 20, 50, 100, 500, 1000] # Different grid resolutions wave_c = 1e-4 # Wave speed wave_T = 1e-7 # Total simulation time (ensure it is an appropriate value for the wave propagation) wave_Δt = 1e-7 # Temporal step size #test_wave_equation(wave_N_values, wave_c, wave_T, wave_Δt) """ Test the 2D Poisson equation solver Compares the numerical solution against an analytical solution. """ function test_poisson_2d(N_values) # Parameters for N in N_values Δx = 1.0 / N # Define the source term f as a constant function for simplicity f(x, y) = 1.0 # Convert to matrix form for finite difference method f_matrix = [f(x, y) for x in 0:Δx:1, y in 0:Δx:1] # Solve using FDM u_fdm = poisson_2d_fdm(N, f_matrix, Δx) # Solve using FEM f_func(x, y) = 1.0 u_fem = poisson_2d_fem(N, f_func, Δx) # Calculate the exact solution (for comparison, assuming f=1 leads to a simple linear solution) u_exact = [x * (1 - x) * y * (1 - y) for x in 0:Δx:1, y in 0:Δx:1] # Calculate the relative error norms error_fdm = norm(u_fdm - u_exact) / norm(u_exact) error_fem = norm(u_fem - u_exact) / norm(u_exact) println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("------------------------------------------------") end end poisson_N_values = [5, 10, 20, 50, 100] test_poisson_2d(poisson_N_values)
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
2702
""" Solve the 1D wave equation using the finite difference method. The wave equation is given by: ∂²u/∂t² = c² ∇²u where c is the wave speed. """ function wave_fdm(N, c, T, Δx, Δt) # Create a grid of spatial points x = 0:Δx:1 # Initialize velocity and displacement fields u = zeros(N+1) # Displacement v = zeros(N+1) # Velocity (time derivative of displacement) u_prev = similar(u) u_next = similar(u) # Set initial condition: a displacement in the middle of the domain u[round(Int, N/2)] = 1.0 u_prev = u # Time-stepping loop for t in Δt:Δt:T # Update the displacement field using finite difference scheme for i in 2:N u_next[i] = 2 * u[i] - u_prev[i] + (c^2 * Δt^2 / Δx^2) * (u[i+1] - 2 * u[i] + u[i-1]) end # Swap references to avoid unnecessary copying u_prev, u, u_next = u, u_next, u_prev end return u end """ Solve the 1D wave equation using the finite element method (FEM). The wave equation is given by: ∂²u/∂t² = c² ∇²u where c is the wave speed. Arguments: - N: Number of spatial grid points (excluding boundary points) - c: Wave speed - T: Total simulation time - Δx: Spatial step size - Δt: Temporal step size Returns: - u: The final displacement field """ function wave_fem(N, c, T, Δx, Δt) # Number of time steps num_steps = Int(T / Δt) # Create a grid of spatial points nodes = 0:Δx:1 # Initialize displacement and velocity fields u = zeros(N+1) # Displacement u_prev = similar(u) # Displacement at previous time step u_next = similar(u) # Displacement at next time step # Initialize stiffness matrix (K) and mass matrix (M) K = zeros(N+1, N+1) M = zeros(N+1, N+1) # Assemble stiffness matrix and mass matrix for i in 1:N # Local matrices for element i x1 = nodes[i] x2 = nodes[i+1] L = x2 - x1 k_local = (c^2 / L) * [1 -1; -1 1] m_local = L / 6 * [2 1; 1 2] # Assemble into global stiffness and mass matrices K[i:i+1, i:i+1] += k_local M[i:i+1, i:i+1] += m_local end # Apply boundary conditions (Dirichlet: u = 0 at the boundaries) K[1, :] .= 0 K[1, 1] = 1 M[1, :] .= 0 M[1, 1] = 1 K[end, :] .= 0 K[end, end] = 1 M[end, :] .= 0 M[end, end] = 1 # Time-stepping loop for _ in 1:num_steps # Compute the right-hand side vector f = M * u_next - K * u_prev # Solve for the new displacement field u_next = K \ f # Update displacement fields u_prev, u, u_next = u, u_next, u_prev end return u end
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
2411
using LinearAlgebra include("../src/PDEngine.jl") using .PDEngine function test_heat_equation() # Test parameters heat_N_values = [5, 10, 20, 50, 100, 300, 500] # Grid resolutions heat_α = 1 heat_T = 1e-3 # Total time heat_Δt = 1e-4 # Time step size for N in heat_N_values Δx = 1.0 / N # Spatial step size # Analytical solution at final time T analytical_solution(x, t) = exp(-heat_α * π^2 * t) * sin(π * x) # Grid points including both boundaries (0 and 1) x = 0:Δx:1 # Solve using FDM u_fdm = heat_fdm(N, heat_α, heat_T, Δx, heat_Δt) # Solve using FEM u_fem = heat_fem(N, heat_α, heat_T, Δx, heat_Δt) # Solve using Crank-Nicolson u_cn = heat_nicolson(N, heat_α, heat_T, Δx, heat_Δt) u_sp = heat_spectral(N, heat_α, heat_T, heat_Δt) # Analytical solution at final time u_exact = analytical_solution.(x, heat_T) # Ensure that the numerical and analytical solutions have the same length # Calculate relative error norms error_fdm = abs((norm(u_fdm - u_exact) / norm(u_exact)) - 0) error_fem = abs((norm(u_fem - u_exact) / norm(u_exact)) - 0) error_cn = abs((norm(u_cn - u_exact) / norm(u_exact)) - 0) error_sp = abs((norm(u_sp - u_exact) / norm(u_exact)) - 0) # Relative error checks if error_fdm < 1e-2 print("High relative error in FDM for N=$N" ) end if error_fem < 1e-2 print( "High relative error in FEM for N=$N") end if error_cn < 1e-2 print("High relative error in CN for N=$N") end if error_sp < 1e-2 print("High relative error in SP for N=$N") end println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("Relative Error in CN: $error_cn") println("Relative Error in SP: $error_sp") println("------------------------------------------------") end end # Run the test test_heat_equation()
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
1573
using Test using LinearAlgebra using Statistics # Import the navier_stokes_2d function from the source file include("../src/navier_stokes_eq.jl") # Test Suite for the 2D Navier-Stokes Solver # Test 1: Check if the function runs without errors and returns correct output types @testset "Navier-Stokes 2D Solver Tests" begin # Test parameters N = 50 ν = 0.01 T = 1.0 Δx = 1.0 / N Δt = 0.001 # Run the solver u, v, p = navier_stokes(N, ν, T, Δx, Δt) # Test 1.1: Ensure the output is the correct size @test size(u) == (N+1, N+1) @test size(v) == (N+1, N+1) @test size(p) == (N+1, N+1) # Test 1.2: Ensure the output values are finite numbers @test all(isfinite, u) @test all(isfinite, v) @test all(isfinite, p) # Test 2: Boundary conditions - check if boundary values are correctly set @test all(u[1, :] .== 0) # u = 0 at y = 0 @test all(u[end, :] .== 0) # u = 0 at y = 1 @test all(v[:, 1] .== 0) # v = 0 at x = 0 @test all(v[:, end] .== 0) # v = 0 at x = 1 # Test 3: Check pressure field boundary conditions @test isapprox(mean(p[:, 1]), mean(p[:, 2]), atol=1e-6) @test isapprox(mean(p[:, end]), mean(p[:, end-1]), atol=1e-6) @test isapprox(mean(p[1, :]), mean(p[2, :]), atol=1e-6) @test isapprox(mean(p[end, :]), mean(p[end-1, :]), atol=1e-6) # Test 4: Consistency Check # We expect the velocity fields to be very small due to the small timestep and viscosity @test maximum(abs.(u)) < 1e-2 @test maximum(abs.(v)) < 1e-2 end
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
1373
using LinearAlgebra include("../src/PDEngine.jl") using .PDEngine """ Test the 2D Poisson equation solver Compares the numerical solution against an analytical solution. """ function test_poisson_2d(N_values) # Parameters for N in N_values Δx = 1.0 / N # Define the source term f as a constant function for simplicity f(x, y) = 1.0 # Convert to matrix form for finite difference method f_matrix = [f(x, y) for x in 0:Δx:1, y in 0:Δx:1] # Solve using FDM u_fdm = poisson_fdm(N, f_matrix, Δx) # Solve using FEM f_func(x, y) = 1.0 u_fem = poisson_fem(N, f_func, Δx) u_sp = poisson_spectral(N, f_func, Δx) # Calculate the exact solution (for comparison, assuming f=1 leads to a simple linear solution) u_exact = [x * (1 - x) * y * (1 - y) for x in 0:Δx:1, y in 0:Δx:1] # Calculate the relative error norms error_fdm = norm(u_fdm - u_exact) / norm(u_exact) error_fem = norm(u_fem - u_exact) / norm(u_exact) error_sp = norm(u_sp - u_exact) / norm(u_exact) println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("Relative Error in SP: $error_sp") println("------------------------------------------------") end end poisson_N_values = [5, 10, 20, 50, 100] test_poisson_2d(poisson_N_values)
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
code
1357
include("../src/PDE_lib.jl") using .PDEngine using LinearAlgebra function test_wave_equation(N_values, c, T, Δt) println("Wave Equation Tester : \n") for N in N_values Δx = 1.0 / N # Spatial step size # Analytical solution at final time T analytical_solution(x, t) = sin(π * x) * cos(c * π * t) # Solve using FDM u_fdm = wave_eq_1d_fdm(N, c, T, Δx, Δt) # Solve using FEM u_fem = wave_eq_1d_fem(N, c, T, Δx, Δt) # Compare with analytical solution x = 0:Δx:1 u_exact = analytical_solution.(x, T) # Calculate relative error norms error_fdm = norm(u_fdm - u_exact) / norm(u_exact) error_fem = norm(u_fem - u_exact) / norm(u_exact) println("Grid Points: $N") println("Relative Error in FDM: $error_fdm") println("Relative Error in FEM: $error_fem") println("------------------------------------------------") end end # Example test parameters wave_N_values = [5, 10, 20, 50, 100, 500, 1000] # Different grid resolutions wave_c = 1e-4 # Wave speed wave_T = 1e-7 # Total simulation time (ensure it is an appropriate value for the wave propagation) wave_Δt = 1e-7 # Temporal step size test_wave_equation(wave_N_values, wave_c, wave_T, wave_Δt)
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "Apache-2.0" ]
0.0.99
8823713256cb9ee60c4e0f4aa0f1cff46ede3ab2
docs
2614
# PDEngine.jl [![version](https://juliahub.com/docs/General/PDEngine/stable/version.svg)](https://juliahub.com/ui/Packages/General/PDEngine) **PDEngine.jl** is a Julia library designed for solving partial differential equations (PDEs) using a variety of numerical methods. This library aims to provide efficient, flexible, and easy-to-use solvers for some of the most common PDEs encountered in scientific and engineering problems. [Documentation](https://jakubschwenkbeck.github.io/PDEngine.jl/) ## Features - **Heat Equation**: Models heat distribution over time. - **Wave Equation**: Simulates the propagation of waves through a medium. - **Navier-Stokes Equations**: Governs the motion of viscous fluid substances. - **Poisson's Equation**: Used in electrostatics, mechanical engineering, and theoretical physics. ## Numerical Methods - **Finite Difference Method (FDM)**: A straightforward approach to discretize PDEs on regular grids. - **Finite Element Method (FEM)**: Ideal for complex geometries and adaptive mesh refinement. - **Spectral Methods**: Provides high accuracy for smooth solutions and periodic boundary conditions. ## Usage (Already adjusted for not released v0.0.95, use Manual for accurate usage) **Using the Package**: ```julia using PDEngine # Example: Solving the heat equation in 1D Δx = 0.01 Δt = 0.0001 T = 0.1 α = 0.01 N = 100 temperature_distribution = heat(N, α, T, Δx, Δt) # solving the heat equation with the default (spectral method) # Example: Solving Poisson's equation in 2D f = zeros(N+1, N+1) # Example source term Δx = 0.01 poisson_solution = poisson_fem(N, f, Δx) # solving the poisson equations,set to use with the finite elements method ``` ## Currently working on: ### v0.0.95 - Better Function Naming - Impementing Spectral methods - Setting a default method with very simple Name like heat(params) ### v0.1.0 (Full release) - Parallel computing to get the full speed of julia - more methods and or PEDs - ensure all Methods work without any flaws - ... ## Papers used: - [Lehman](https://www.lehman.edu/faculty/dgaranin/Mathematical_Physics/Mathematical_physics-13-Partial_differential_equations.pdf) : Numerical Solutions for PDEs using Mathematica - [Spectral Methods](https://www.mech.kth.se/~ardeshir/courses/literature/Notes_Spectral_Methods.pdf) : Spectral Methods and tests by Phillip Schlatter - [ByJus](https://byjus.com/maths/partial-differential-equation/) : Representation of a PDE - [ScholarPedia](http://www.scholarpedia.org/article/Partial_differential_equation) : Introduction to PDEs
PDEngine
https://github.com/JakubSchwenkbeck/PDEngine.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
770
# Source this script as e.g. # # include("PATH/TO/devrepl.jl") # # from *any* Julia REPL or run it as e.g. # # julia -i --banner=no PATH/TO/devrepl.jl # # from anywhere. This will change the current working directory and # activate/initialize the correct Julia environment for you. # # You may also run this in vscode to initialize a development REPL # using Pkg using Downloads: download cd(@__DIR__) Pkg.activate("test") function _instantiate() Pkg.develop(path=".") end if !isfile(joinpath("test", "Manifest.toml")) _instantiate() end include("test/init.jl") # Disable link-checking in interactive REPL, since it is the slowest part # of building the docs. ENV["DOCUMENTER_CHECK_LINKS"] = "0" if abspath(PROGRAM_FILE) == @__FILE__ help() end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
1520
using DocumenterCitations using Documenter using Pkg PROJECT_TOML = Pkg.TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml")) VERSION = PROJECT_TOML["version"] NAME = PROJECT_TOML["name"] AUTHORS = join(PROJECT_TOML["authors"], ", ") * " and contributors" GITHUB = "https://github.com/JuliaDocs/DocumenterCitations.jl" bib = CitationBibliography( joinpath(@__DIR__, "src", "refs.bib"); style=:numeric # default ) println("Starting makedocs") include("custom_styles/enumauthoryear.jl") include("custom_styles/keylabels.jl") makedocs( authors=AUTHORS, linkcheck=(get(ENV, "DOCUMENTER_CHECK_LINKS", "1") != "0"), # Link checking is disabled in REPL, see `devrepl.jl`. warnonly=[:linkcheck,], sitename="DocumenterCitations.jl", format=Documenter.HTML( prettyurls=true, canonical="https://juliadocs.org/DocumenterCitations.jl", assets=String["assets/citations.css"], footer="[$NAME.jl]($GITHUB) v$VERSION docs powered by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl).", ), pages=[ "Home" => "index.md", "Syntax" => "syntax.md", "Citation Style Gallery" => "gallery.md", "CSS Styling" => "styling.md", "Internals" => "internals.md", "References" => "references.md", ], plugins=[bib], ) println("Finished makedocs") deploydocs(; repo="github.com/JuliaDocs/DocumenterCitations.jl.git", push_preview=true)
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
1360
using DocumenterCitations using Documenter using Pkg # Note: Set environment variable `DOCUMENTER_LATEX_DEBUG=1` in order get a copy # of the generated tex file (or, add `platform="none"` to the # `Documenter.LaTeX` call) PROJECT_TOML = Pkg.TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml")) VERSION = PROJECT_TOML["version"] NAME = PROJECT_TOML["name"] AUTHORS = join(PROJECT_TOML["authors"], ", ") * " and contributors" GITHUB = "https://github.com/JuliaDocs/DocumenterCitations.jl" bib = CitationBibliography( joinpath(@__DIR__, "src", "refs.bib"); style=:numeric # default ) println("Starting makedocs") include("custom_styles/enumauthoryear.jl") include("custom_styles/keylabels.jl") withenv("DOCUMENTER_BUILD_PDF" => "1") do makedocs( authors=AUTHORS, linkcheck=true, warnonly=[:linkcheck,], sitename="DocumenterCitations.jl", format=Documenter.LaTeX(; version=VERSION), pages=[ "Home" => "index.md", "Syntax" => "syntax.md", "Citation Style Gallery" => "gallery.md", "CSS Styling" => "styling.md", "Internals" => "internals.md", "References" => "references.md", ], plugins=[bib], ) end println("Finished makedocs")
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
555
import DocumenterCitations function DocumenterCitations.format_bibliography_reference( style::Val{:enumauthoryear}, entry ) text = DocumenterCitations.format_authoryear_bibliography_reference(style, entry) return uppercasefirst(text) end DocumenterCitations.format_citation(style::Val{:enumauthoryear}, args...) = DocumenterCitations.format_authoryear_citation(style, args...) DocumenterCitations.bib_sorting(::Val{:enumauthoryear}) = :nyt # name, year, title DocumenterCitations.bib_html_list_style(::Val{:enumauthoryear}) = :ol
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
927
import DocumenterCitations DocumenterCitations.format_bibliography_reference(style::Val{:keylabels}, entry) = DocumenterCitations.format_labeled_bibliography_reference(style, entry) function DocumenterCitations.format_bibliography_label(::Val{:keylabels}, entry, citations) return "[$(entry.id)]" end function DocumenterCitations.format_citation( style::Val{:keylabels}, cit, entries, citations ) return DocumenterCitations.format_labeled_citation(style, cit, entries, citations) # The only difference compared to `:alpha` is the citation label, which is # picked up automatically by redefining `citation_label` below. end function DocumenterCitations.citation_label(style::Val{:keylabels}, entry, citations; _...) return entry.id end DocumenterCitations.bib_sorting(::Val{:keylabels}) = :nyt # name, year, title DocumenterCitations.bib_html_list_style(::Val{:keylabels}) = :dl
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
6499
module DocumenterCitations using Documenter: Documenter, DOCUMENTER_VERSION using Documenter.Builder using Documenter.Selectors using Documenter.Expanders using Documenter.Writers.HTMLWriter import MarkdownAST import AbstractTrees using Logging using Markdown using Bibliography: Bibliography, xyear, xlink, xtitle using OrderedCollections: OrderedDict, OrderedSet using Unicode using Dates: Dates, @dateformat_str export CitationBibliography """Plugin for enabling bibliographic citations in Documenter.jl. ```julia bib = CitationBibliography(bibfile; style=:numeric) ``` instantiates a plugin object that must be passed as an element of the `plugins` keyword argument to [`Documenter.makedocs`](https://documenter.juliadocs.org/stable/lib/public/#Documenter.makedocs). # Arguments * `bibfile`: the name of the [BibTeX](https://www.bibtex.com/g/bibtex-format/) file from which to read the data. * `style`: the style to use for the bibliography and all citations. The available built-in styles are `:numeric` (default), `:authoryear`, and `:alpha`. With user-defined styles, this may be an arbitrary name or object. # Internal fields The following internal fields are used by the citation pipeline steps. These should not be considered part of the stable API. * `entries`: dict of citation keys to entries in `bibfile` * `citations`: ordered dict of citation key to citation number * `page_citations`: dict of page file name to set of citation keys cited on page. * `anchor_map`: an [`AnchorMap`](https://documenter.juliadocs.org/stable/lib/internals/anchors/#Documenter.AnchorMap) object that keeps track of the link anchors for references in bibliography blocks """ struct CitationBibliography <: Documenter.Plugin # name of bib file bibfile::String # Style name or object (built-in styles are symbols, but custom styles can # be anything) style::Any # citation key => entry (set on instantiation; private) entries::OrderedDict{String,<:Bibliography.AbstractEntry} # citation key => order index (when citation was first seen; private) citations::OrderedDict{String,Int64} # page file name => set of citation keys (private). The page file names are # relative to `doc.user.source`, which matches `doc.plueprint.pages` page_citations::Dict{String,Set{String}} # AnchorMap object that stores the link anchors to all references in # canonical bibliography blocks anchor_map::Documenter.AnchorMap end function CitationBibliography(bibfile::AbstractString=""; style=nothing) if isnothing(style) style = :numeric @debug "Using default style=$(repr(style))" elseif style == :alpha @debug "Auto-upgrading :alpha to AlphaStyle()" style = AlphaStyle() end bibfile_entries = Bibliography.import_bibtex(bibfile) entries = OrderedDict{String,eltype(values(bibfile_entries))}() for (bibfile_key, entry) in bibfile_entries # The `text` in `[text](@cite)` has to be unambiguous when # round-tripping between String and MarkdownAST.Node. Since `_` and `*` # can both indicate emphasis in markdown, we normalize to `_` (which # should be *much* more common in real-life BibTeX keys). The same # normalization happens in `read_citation_link`, so this is transparent # to the user as long as they don't have keys in their `.bib` file that # differ only by `*` vs `_`. key = replace(bibfile_key, "*" => "_") if key in keys(entries) error( "Ambiguous key $(repr(bibfile_key)) in $bibfile. CitationBibliography cannot distinguish between `*` and `_` in BibTex keys." ) else entries[key] = entry end end if length(bibfile) == 0 # Presumably, we got here because there was no `bib` object passed to # `makedocs`, and then `Documenter.getplugin` instantiated a new object # with the default (empty) constructor @warn "No `bibfile`. Did you instantiate `bib = CitationBibliography(bibfile)` and pass `bib` to `makedocs` as an element of the `plugins` keyword argument?" else if !isfile(bibfile) error("bibfile $(repr(bibfile)) does not exist") end if length(entries) == 0 @warn "No entries loaded from $(repr(bibfile))" end end citations = OrderedDict{String,Int64}() page_citations = Dict{String,Set{String}}() anchor_map = Documenter.AnchorMap() return CitationBibliography( bibfile, style, entries, citations, page_citations, anchor_map ) end """ Example An example object citing Ref. [GoerzQ2022](@cite) with a "References" section in its docstring. # References * [GoerzQ2022](@cite) Goerz et al. Quantum 6, 871 (2022) """ struct Example end # `example_bibfile` is used for doctests const example_bibfile = normpath(joinpath(@__DIR__, "..", "docs", "src", "refs.bib")) """ "Smart" alphabetic citation style (relative to the "dumb" `:alpha`). ```julia style = AlphaStyle() ``` instantiates a style for [`CitationBibliography`](@ref) that avoids duplicate labels. Any of the entries that would result in the same label will be disambiguated by appending the suffix "a", "b", etc. Any bibliography that cites a subset of the given `entries` is guaranteed to have unique labels. """ struct AlphaStyle # BibTeX key (entry.id) => rendered label, e.g. "GraceJMO2007" => "GBR+07b" label_for_key::Dict{String,String} # The internal field `label_for_key` is set by `init_bibliography!` at the # beginning of the `ExpandBibliography` pipeline step. AlphaStyle() = new(Dict{String,String}()) end Base.show(io::IO, ::AlphaStyle) = print(io, "AlphaStyle()") include("md_ast.jl") include("citation_link.jl") include("collect_citations.jl") include("expand_citations.jl") include("latex_options.jl") include("bibliography_node.jl") include("expand_bibliography.jl") include("tex_to_markdown.jl") include("formatting.jl") include("labeled_styles_utils.jl") # Built-in styles include(joinpath("styles", "numeric.jl")) include(joinpath("styles", "authoryear.jl")) include(joinpath("styles", "alpha.jl")) function __init__() for errname in (:bibliography_block, :citations) if !(errname in Documenter.ERROR_NAMES) push!(Documenter.ERROR_NAMES, errname) end end reset_latex_options() end end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
6009
"""Representation of a reference within a [`BibliographyNode`}(@ref). # Properties * `anchor_key`: the anchor key for the link target as a string (generally the BibTeX key), or `nothing` if the item is in a non-canonical bibliography block. * `label`: `MarkdownAST.Node` for the label of the entry. Usually a simple `Text` node, as labels in the default styles do not have inline formatting. or `nothing` if the style does not use labels the rendered bibliography. * `reference`: `MarkdownAST.Node` for the paragraph for the fully rendered reference. """ struct BibliographyItem anchor_key::Union{Nothing,String} label::Union{Nothing,MarkdownAST.Node{Nothing}} reference::MarkdownAST.Node{Nothing} end """Node in `MarkdownAST` corresponding to a `@bibliography` block. # Properties * `list_style`: One of `:dl`, `:ul`, `:ol`, cf. [`bib_html_list_style`](@ref) * `canonical`: Whether or not the references in the `@bibliography` block are link targets. * `items`: A list of [`BibliographyItem`](@ref) objects, one for each reference in the block """ struct BibliographyNode <: Documenter.AbstractDocumenterBlock list_style::Symbol # one of :dl, :ul, :ol canonical::Bool items::Vector{BibliographyItem} function BibliographyNode(list_style, canonical, items) if list_style in (:dl, :ul, :ol) new(list_style, canonical, items) else throw( ArgumentError( "`list_style` must be one of `:dl`, `:ul`, or `:ol`, not `$(repr(list_style))`" ) ) end end end function Documenter.MDFlatten.mdflatten(io, ::MarkdownAST.Node, b::BibliographyNode) for item in b.items Documenter.MDFlatten.mdflatten(io, item.reference) print(io, "\n\n\n\n") end end function Documenter.HTMLWriter.domify( dctx::Documenter.HTMLWriter.DCtx, node::Documenter.Node, bibliography::BibliographyNode ) @assert node.element === bibliography return domify_bib(dctx, bibliography) end function domify_bib(dctx::Documenter.HTMLWriter.DCtx, bibliography::BibliographyNode) Documenter.DOM.@tags dl ul ol li div dt dd list_tag = dl if bibliography.list_style == :ul list_tag = ul elseif bibliography.list_style == :ol list_tag = ol end html_list = list_tag() for item in bibliography.items anchor_id = isnothing(item.anchor_key) ? "" : "#$(item.anchor_key)" html_reference = Documenter.HTMLWriter.domify(dctx, item.reference.children) if bibliography.list_style == :dl html_label = Documenter.HTMLWriter.domify(dctx, item.label.children) push!(html_list.nodes, dt(html_label)) push!(html_list.nodes, dd(div[anchor_id](html_reference))) else push!(html_list.nodes, li(div[anchor_id](html_reference))) end end class = ".citation" if bibliography.canonical class *= ".canonical" else class *= ".noncanonical" end return div[class](html_list) end _hash(x) = string(hash(x)) function _wrapblock(f, io, env) if !isnothing(env) println(io, "\\begin{", env, "}") end f() if !isnothing(env) println(io, "\\end{", env, "}") end end function _labelbox(f, io; width="0in") local width_val try width_val = parse(Float64, string(match(r"[\d.]+", width).match)) catch throw(ArgumentError("width $(repr(width)) must be a valid LaTeX width")) end if width_val == 0.0 # do not use a makebox if width is zero print(io, "{") f() print(io, "} ") return end print( io, "\\makebox[{\\ifdim$(width)<\\dimexpr\\width+1ex\\relax\\dimexpr\\width+1ex\\relax\\else$(width)\\fi}][l]{" ) f() print(io, "}") end function Documenter.LaTeXWriter.latex( lctx::Documenter.LaTeXWriter.Context, node::MarkdownAST.Node, bibliography::BibliographyNode ) if bibliography.list_style == :ol texenv = "enumerate" elseif bibliography.list_style == :ul if _LATEX_OPTIONS[:ul_as_hanging] texenv = nothing else texenv = "itemize" end else @assert bibliography.list_style == :dl # We emulate a definition list manually with hangindent and labelwidth texenv = nothing end io = lctx.io function tex_item(n, item) if bibliography.list_style == :ul if _LATEX_OPTIONS[:ul_as_hanging] print(io, "\\hangindent=$(_LATEX_OPTIONS[:ul_hangindent]) ") else print(io, "\\item ") end elseif bibliography.list_style == :ol # enumerate print(io, "\\item ") else @assert bibliography.list_style == :dl print(io, "\\hangindent=$(_LATEX_OPTIONS[:dl_hangindent]) {") _labelbox(io; width=_LATEX_OPTIONS[:dl_labelwidth]) do Documenter.LaTeXWriter.latex(lctx, item.label.children) end print(io, "}") end end println(io, "{$(_LATEX_OPTIONS[:bib_blockformat])% @bibliography\n") _wrapblock(io, texenv) do for (n, item) in enumerate(bibliography.items) tex_item(n, item) if !isnothing(item.anchor_key) id = _hash(item.anchor_key) print(io, "\\hypertarget{", id, "}{}") end Documenter.LaTeXWriter.latex(lctx, item.reference.children) print(io, "\n\n") end end println(io, "}% end @bibliography") end function Documenter.linkcheck( node::MarkdownAST.Node, bibliography::BibliographyNode, doc::Documenter.Document ) success = true for item in bibliography.items success &= !(Documenter.linkcheck(item.reference, doc) === false) # `linkcheck` may return `true` / `false` / `nothing` end return success end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
6138
__RX_CMD = raw"""@(?<cmd>[cC]ite(t|p|alt|alp|num)?)(?<starred>\*)?""" __RX_KEY = raw"""[^\s"#'(),{}%]+""" __RX_KEYS = "(?<keys>$__RX_KEY(\\s*,\\s*$__RX_KEY)*)" __RX_NOTE = raw"""\s*;\s+(?<note>.*)""" __RX_STYLE = raw"""%(?<style>\w+)%""" # Regex for [_RX_TEXT_KEYS](_RX_CITE_URL), e.g. [GoerzQ2022](@cite) _RX_CITE_URL = Regex("^$__RX_CMD($__RX_STYLE)?\$") _RX_TEXT_KEYS = Regex("^$__RX_KEYS($__RX_NOTE)?\$") # Regex for [text][_RX_CITE_KEY_URL], e.g. [Semi-AD paper](@cite GoerzQ2022) _RX_CITE_KEY_URL = Regex("^@cite\\s+(?<key>$__RX_KEY)\$") """ Data structure representing a general (non-direct) citation link. ```julia cit = CitationLink(link) ``` parses the given `link` string, e.g. `"[GoerzQ2022](@cite)"`. # Attributes * `node`: The `MarkdownAST.Node` that `link` parses into * `keys`: A list of BibTeX keys being cited. e.g., `["BrumerShapiro2003", "BrifNJP2010"]` for the citation `"[BrumerShapiro2003,BrifNJP2010; and references therein][@cite]"` * `cmd`: The citation command, one of `:cite`, `:citet`, `:citep`, or (unsupported in the default styles) `:citealt`, `:citealp`, `:citenum`. Note that, e.g., `"[Goerz@2022](@Citet*)"` results in `cite_cmd=:citet` * `note`: A citation note, e.g. "Eq. (1)" in `[GoerzQ2022; Eq. (1)](@cite)` * `capitalize`: Whether the citation should be formatted to appear at the start of a sentence, as indicated by a capitalized `@Cite...` command, e.g., `"[GoerzQ2022](@Citet)"` * `starred`: Whether the citation should be rendered in "extended" form, i.e., with the full list of authors, as indicated by a `*` in the citation, e.g., `"[Goerz@2022](@Citet*)"` # See also * [`DirectCitationLink`](@ref) – data structure for direct citation links of the form `[text](@cite key)`. """ struct CitationLink node::MarkdownAST.Node cmd::Symbol style::Union{Nothing,Symbol} # style override (undocumented internal) keys::Vector{String} note::Union{Nothing,String} capitalize::Bool starred::Bool end function CitationLink(link::MarkdownAST.Node) citation_link = read_citation_link(link) if citation_link isa CitationLink return citation_link else @error "Invalid CitationLink" link error("Link parses to $(typeof(citation_link)), not CitationLink") end end function CitationLink(link::String) return CitationLink(parse_md_citation_link(link)) end function Base.show(io::IO, c::CitationLink) print(io, "CitationLink($(repr(ast_to_str(c.node))))") end """ Data structure representing a direct citation link. ```julia cit = DirectCitationLink(link) ``` parses the given `link` string of the form `[text](@cite key)`. # Attributes * `node`: The `MarkdownAST.Node` that `link` parses into * `key`: The BibTeX key being cited. Note that unlike [`CitationLink`](@ref), a `DirectCitationLink` can only reference a single key # See also * [`CitationLink`](@ref) – data structure for non-direct citation links. """ struct DirectCitationLink node::MarkdownAST.Node # the original markdown link key::String # bibtex cite keys end function DirectCitationLink(node::MarkdownAST.Node) citation_link = read_citation_link(node) if citation_link isa DirectCitationLink return citation_link else @error "Invalid DirectCitationLink" node error("Node parses to $(typeof(citation_link)), not DirectCitationLink") end end function DirectCitationLink(link::String) return DirectCitationLink(parse_md_citation_link(link)) end function Base.show(io::IO, c::DirectCitationLink) print(io, "DirectCitationLink($(repr(ast_to_str(c.node))))") end """ Instantiate [`CitationLink`](@ref) or [`DirectCitationLink`](@ref) from AST. ```julia read_citation_link(link::MarkdownAST.Node) ``` receives a `MarkdownAST.Link` node that must represent a valid (direct or non-direct) citation link, and returns either a [`CitationLink`](@ref) instance or a [`DirectCitationLink`](@ref) instance, depending on what the link text and link destination are. Throw an error if they the link text or description do not have the correct syntax. Uses [`ast_linktext`](@ref) to convert the link text to plain markdown code before applying regexes to parse it. Also normalizes `*` in citation keys to `_`. """ function read_citation_link(link::MarkdownAST.Node) if !(link.element isa MarkdownAST.Link) @error "link.element must be a MarkdownAST.Link" link error("Invalid markdown for citation link: $(repr(ast_to_str(link)))") end link_destination = link.element.destination if (m_url = match(_RX_CITE_URL, link_destination)) ≢ nothing # [GoerzQ2022](@cite) cmd = Symbol(lowercase(m_url[:cmd])) capitalize = startswith(m_url[:cmd], "C") starred = !isnothing(m_url[:starred]) style = isnothing(m_url[:style]) ? nothing : Symbol(m_url[:style]) link_text = ast_linktext(link) m_text = match(_RX_TEXT_KEYS, link_text) if isnothing(m_text) #! format: off @error "The @cite link text $(repr(link_text)) does not match required regex" ast = link error("Invalid citation: $(repr(ast_to_str(link)))") #! format: on end # Since the keys have been round-tripped between markdown and the AST, # "_" and "*" are ambiguous ("emphasis") and we normalize to "_". Cf. # the normalization in the constructor of `CitationBibliography`. keys = String[replace(strip(key), "*" => "_") for key in split(m_text[:keys], ",")] note = m_text[:note] return CitationLink(link, cmd, style, keys, note, capitalize, starred) elseif (m_url = match(_RX_CITE_KEY_URL, link_destination)) ≢ nothing # [Semi-AD Paper](@cite GoerzQ2022) key = replace(strip(convert(String, m_url[:key])), "*" => "_") return DirectCitationLink(link, key) else #! format: off @error "The @cite link destination $(repr(link_destination)) does not match required regex" ast=link error("Invalid citation: $(repr(ast_to_str(link)))") #! format: on end end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
3922
# Collect Citations # # This runs after ExpandTemplates, such that e.g. docstrings which may contain # citations have been expanded. """Pipeline step to collect citations from all pages. It walks all pages in the order they appear in the navigation bar, looking for `@cite` links. It fills the `citations` and `page_citations` attributes of the internal [`CitationBibliography`](@ref) object. Thus, the order in which `CollectCitations` encounters citations determines the numerical key that will appear in the rendered documentation (see [`ExpandBibliography`](@ref) and [`ExpandCitations`](@ref)). """ abstract type CollectCitations <: Builder.DocumentPipeline end Selectors.order(::Type{CollectCitations}) = 2.11 # After ExpandTemplates function Selectors.runner(::Type{CollectCitations}, doc::Documenter.Document) Documenter.is_doctest_only(doc, "CollectCitations") && return @info "CollectCitations" collect_citations(doc) end # Collect all citations in document function collect_citations(doc::Documenter.Document) bib = Documenter.getplugin(doc, CitationBibliography) nav_sources = [node.page for node in doc.internal.navlist] other_sources = filter(src -> !(src in nav_sources), keys(doc.blueprint.pages)) for src in Iterators.flatten([nav_sources, other_sources]) page = doc.blueprint.pages[src] @debug "CollectCitations: collecting `@cite` entries in $src" empty!(page.globals.meta) try _collect_citations(page.mdast, page.globals.meta, src, page, doc) catch exc #! format: off @error "Error collecting citations from $(repr(src))" exception=(exc, catch_backtrace()) #! format: on push!(doc.internal.errors, :citations) end end @debug "Collected citations" bib.citations end function _collect_citations(mdast::MarkdownAST.Node, meta, src, page, doc) for node in AbstractTrees.PreOrderDFS(mdast) if node.element isa Documenter.DocsNode # The docstring AST trees are not part of the tree of the page, so # we need to expand them explicitly for (docstr, docmeta) in zip(node.element.mdasts, node.element.metas) _collect_citations(docstr, docmeta, src, page, doc) end elseif node.element isa MarkdownAST.Link collect_citation(node, meta, src, page, doc) end end end # Add citation from `link` to the `citations` and `page_citations` of the # `doc.plugins[CitationBibliography]` object. The `src` is the name of the # markdown file containing the `link` and `page` is a `Page` object. # # Called on every Link node in the AST. function collect_citation(node::MarkdownAST.Node, meta, src, page, doc) @assert node.element isa MarkdownAST.Link bib = Documenter.getplugin(doc, CitationBibliography) if startswith(lowercase(node.element.destination), "@cite") cit = read_citation_link(node) if cit isa CitationLink keys = cit.keys else @assert cit isa DirectCitationLink keys = [cit.key] end for key in keys if haskey(bib.entries, key) entry = bib.entries[key] if haskey(bib.citations, key) @debug "Found non-new citation $key" else bib.citations[key] = length(bib.citations) + 1 @debug "Found new citation $(bib.citations[key]): $key" end if !haskey(bib.page_citations, src) bib.page_citations[src] = Set{String}() end push!(bib.page_citations[src], key) else @error "Key $(repr(key)) not found in entries from $(bib.bibfile)" push!(doc.internal.errors, :citations) end end end return false end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
17133
_ALLOW_PRE_13_FALLBACK = true """Pipeline step to expand all `@bibliography` blocks. Runs after [`CollectCitations`](@ref) but before [`ExpandCitations`](@ref). Each bibliography is rendered into HTML as a a [definition list](https://www.w3schools.com/tags/tag_dl.asp), a [bullet list](https://www.w3schools.com/tags/tag_ul.asp), or an [enumeration](https://www.w3schools.com/tags/tag_ol.asp) depending on [`bib_html_list_style`](@ref). For a definition list, the label for each list item is rendered via [`format_bibliography_label`](@ref) and the full bibliographic reference is rendered via [`format_bibliography_reference`](@ref). For bullet lists or enumerations, [`format_bibliography_label`](@ref) is not used and [`format_bibliography_reference`](@ref) fully determines the entry. The order of the entries in the bibliography is determined by the [`bib_sorting`](@ref) method for the chosen citation style. The `ExpandBibliography` step runs [`init_bibliography!`](@ref) before expanding the first `@bibliography` block. """ abstract type ExpandBibliography <: Builder.DocumentPipeline end Selectors.order(::Type{ExpandBibliography}) = 2.12 # after CollectCitations function Selectors.runner(::Type{ExpandBibliography}, doc::Documenter.Document) Documenter.is_doctest_only(doc, "ExpandBibliography") && return @info "ExpandBibliography: expanding `@bibliography` blocks." if (DOCUMENTER_VERSION < v"1.2") && doc.user.linkcheck @warn "Checking links in the bibliography (`linkcheck=true`) requires Documenter >= 1.2" DOCUMENTER_VERSION end expand_bibliography(doc) end # Expand all @bibliography blocks in the document function expand_bibliography(doc::Documenter.Document) bib = Documenter.getplugin(doc, CitationBibliography) style = bib.style # so that we can dispatch on different styles init_bibliography!(style, bib) for (src, page) in doc.blueprint.pages empty!(page.globals.meta) expand_bibliography(doc, page, page.mdast) end end # Expand all @bibliography blocks in one page function expand_bibliography(doc::Documenter.Document, page, mdast::MarkdownAST.Node) for node in AbstractTrees.PreOrderDFS(mdast) is_bib_block = node.element isa MarkdownAST.CodeBlock && occursin(r"^@bibliography", node.element.info) is_bib_block && expand_bibliography(node, page.globals.meta, page, doc) end end """Initialize any internal state for rendering the bibliography. ```julia init_bibliography!(style, bib) ``` is called at the beginning of the [`ExpandBibliography`](@ref) pipeline step. It may mutate internal fields of `style` or `bib` to prepare for the rendering of bibliography blocks. For the default style, this does nothing. For, e.g., [`AlphaStyle`](@ref), the call to `init_bibliography!` determines the citation labels, by generating unique suffixed labels for all the entries in the underlying `.bib` file (`bib.entries`), and storing the result in an internal attribute of the `style` object. Custom styles may implement a new method for `init_bibliography!` for similar purposes. It can be assumed that all the internal fields of the [`CitationBibliography`](@ref) `bib` object are up-to-date according to the citations seen by the earlier [`CollectCitations`](@ref) step. """ function init_bibliography!(style, bib) end # no-op for default style(s) function init_bibliography!(style::Symbol, bib) init_bibliography!(Val(style), bib) end """Format the full reference for an entry in a `@bibliography` block. ```julia mdstr = format_bibliography_reference(style, entry) ``` produces a markdown string for the full reference of a [`Bibliography.Entry`](https://humans-of-julia.github.io/Bibliography.jl/stable/internal/#BibInternal.Entry). For the default `style=:numeric`, the result is formatted like in [REVTeX](https://www.ctan.org/tex-archive/macros/latex/contrib/revtex/auguide) and [APS journals](https://journals.aps.org). That is, the full list of authors with initials for the first names, the italicized tile, and the journal reference (linking to the DOI, if available), ending with the publication year in parenthesis. """ function format_bibliography_reference(style::Symbol, entry) return format_bibliography_reference(Val(style), entry) end """Format the label for an entry in a `@bibliography` block. ```julia mdstr = format_bibliography_label(style, entry, citations) ``` produces a plain text (technically, markdown) string for the label in the bibliography for the given [`Bibliography.Entry`](https://humans-of-julia.github.io/Bibliography.jl/stable/internal/#BibInternal.Entry). The `citations` argument is a dict that maps citation keys (`entry.id`) to the order in which citations appear in the documentation, i.e., a numeric citation key. For the default `style=:numeric`, this returns a label that is the numeric citation key in square brackets, cf. [`format_citation`](@ref). In general, this function is used only if [`bib_html_list_style`](@ref) returns `:dl` for the given `style`. """ function format_bibliography_label(style::Symbol, args...) return format_bibliography_label(Val(style), args...) end """Identify the type of HTML list associated with a bibliographic style. ```julia bib_html_list_style(style) ``` must return one of * `:dl` (definition list), * `:ul` (unordered / bullet list), or * `:ol` (ordered list / enumeration), for any `style` that [`CitationBibliography`](@ref) is instantiated with. """ bib_html_list_style(style::Symbol) = bib_html_list_style(Val(style)) """Identify the sorting associated with a bibliographic style. ``` bib_sorting(style) ``` must return `:citation` or any of the `sorting_rules` accepted by [`Bibliography.sort_bibliography!`](https://humans-of-julia.github.io/Bibliography.jl/dev/#Bibliography.sort_bibliography!), e.g. `:nyt`. """ bib_sorting(style::Symbol) = bib_sorting(Val(style)) function parse_bibliography_block(block, doc, page) fields = Dict{Symbol,Any}() lines = String[] for (ex, str) in Documenter.parseblock(block, doc, page; raise=false) if Documenter.isassign(ex) key = ex.args[1] val = Core.eval(Main, ex.args[2]) fields[key] = val else line = String(strip(str)) if length(line) > 0 push!(lines, line) end end end if :Canonical ∉ keys(fields) fields[:Canonical] = true end allowed_fields = Set{Symbol}((:Canonical, :Pages, :Sorting, :Style)) # Note: :Sorting and :Style are undocumented features warn_loc = "N/A" if (doc ≢ nothing) && (page ≢ nothing) warn_loc = Documenter.locrepr( page.source, Documenter.find_block_in_file(block, page.source) ) end for field in keys(fields) if field ∉ allowed_fields @warn("Invalid field $field ∉ $allowed_fields in $warn_loc") (doc ≢ nothing) && push!(doc.internal.errors, :bibliography_block) end end if (:Canonical in keys(fields)) && !(fields[:Canonical] isa Bool) @warn "The field `Canonical` in $warn_loc must evaluate to a boolean. Setting invalid `Canonical=$(repr(fields[:Canonical]))` to `Canonical=false`" fields[:Canonical] = false (doc ≢ nothing) && push!(doc.internal.errors, :bibliography_block) end if (:Pages in keys(fields)) && !(fields[:Pages] isa Vector) @warn "The field `Pages` in $warn_loc must evaluate to a list of strings. Setting invalid `Pages = $(repr(fields[:Pages]))` to `Pages = []`" fields[:Pages] = String[] (doc ≢ nothing) && push!(doc.internal.errors, :bibliography_block) elseif :Pages in keys(fields) # Pages is a Vector, but maybe not a Vector of strings fields[:Pages] = [_assert_string(name, doc, warn_loc) for name in fields[:Pages]] end return fields, lines end function _assert_string(val, doc, warn_loc) str = string(val) # doesn't ever seem to fail if str != val @warn "The value `$(repr(val))` in $warn_loc is not a string. Replacing with $(repr(str))" (doc ≢ nothing) && push!(doc.internal.errors, :bibliography_block) end return str end # Expand a single @bibliography block function expand_bibliography(node::MarkdownAST.Node, meta, page, doc) @assert node.element isa MarkdownAST.CodeBlock @assert occursin(r"^@bibliography", node.element.info) block = node.element.code @debug "Evaluating @bibliography block in $(page.source):\n```@bibliography\n$block\n```" bib = Documenter.getplugin(doc, CitationBibliography) citations = bib.citations style::Any = bib.style page_citations = bib.page_citations fields, lines = parse_bibliography_block(block, doc, page) @debug "Parsed bibliography block into fields and lines" fields lines style = bib.style if :Style in keys(fields) # The :Style field in @bibliography is an undocumented feature. Citations # and bibliography should use the same style (set at the plugin level). # Local styles are for the Gallery in the documentation only. @assert fields[:Style] isa Symbol style = fields[:Style] if style == :alpha # same automatic upgrade as in CitationsBibliography style = AlphaStyle() init_bibliography!(style, bib) end @debug "Overriding local style with $repr($style)" end keys_to_show = OrderedSet{String}() # first, cited keys (filter by Pages) if (length(citations) > 0) && (:Pages in keys(fields)) page_folder = dirname(Documenter.pagekey(doc, page)) # The `page_folder` is relative to `doc.user.source` (corresponding to # the definition of the keys in `page_citations`) keys_in_pages = Set{String}() # not ordered (see below) Pages = _resolve__FILE__(fields[:Pages], page) @debug "filtering citations to Pages" Pages for name in Pages # names in `Pages` are supposed to be relative to the folder # containing the file containing the `@bibliography` block, # i.e., `page_folder` file = normpath(page_folder, name) # `file` should now be a valid key in `page_citations` try @debug "Add keys cited in $file to keys_to_show" push!(keys_in_pages, page_citations[file]...) catch exc @assert exc isa KeyError expected_file = normpath(doc.user.source, page_folder, name) if isfile(expected_file) @error "Invalid $(repr(name)) in Pages attribute of @bibliography block on page $(page.source): File $(repr(expected_file)) exists but no references were collected." push!(doc.internal.errors, :bibliography_block) else # try falling back to pre-1.3 behavior exists_in_src = isfile(joinpath(doc.user.source, name)) valid_pre_13 = exists_in_src && haskey(page_citations, name) if _ALLOW_PRE_13_FALLBACK && valid_pre_13 @warn "The entry $(repr(name)) in the Pages attribute of the @bibliography block on page $(page.source) appears to be relative to $(repr(doc.user.source)). Starting with DocumenterCitations 1.3, names in `Pages` must be relative to the folder containing the file which contains the `@bibliography` block." @debug "Add keys cited in $(abspath(normpath(doc.user.source, name))) to keys_to_show (pre-1.3 fallback)" push!(keys_in_pages, page_citations[name]...) else # Files that don't contain any citations don't show up in # `page_citations`. @error "Invalid $(repr(name)) in Pages attribute of @bibliography block on page $(page.source): No such file $(repr(expected_file))." push!(doc.internal.errors, :bibliography_block) end end continue end end keys_to_add = [k for k in keys(citations) if k in keys_in_pages] if length(keys_to_add) > 0 push!(keys_to_show, keys_to_add...) @debug "Collected keys_to_show from Pages" keys_to_show elseif length(lines) == 0 # Only warn if there are no explicit keys. Otherwise, the common # idiom of `Pages = []` (with explicit keys) would fail @warn "No cited keys remaining after filtering to Pages" Pages end else # all cited keys if length(citations) > 0 push!(keys_to_show, keys(citations)...) @debug "Add all cited keys to keys_to_show" keys(citations) else @warn "There were no citations" end end # second, explicitly listed keys for key in lines if key == "*" push!(keys_to_show, keys(bib.entries)...) @debug "Add all keys from $(bib.bibfile) to keys_to_show" break # we don't need to look at the rest of the lines else if key in keys(bib.entries) push!(keys_to_show, key) @debug "Add listed $key to keys_to_show" else @error "Explicit key $(repr(key)) from bibliography block not found in entries from $(bib.bibfile)" push!(doc.internal.errors, :bibliography_block) end end end @debug "Determined full list of keys to show" keys_to_show tag = bib_html_list_style(style) allowed_tags = (:ol, :ul, :dl) if tag ∉ allowed_tags error( "bib_html_list_tyle returned an invalid tag $(repr(tag)). " * "Must be one of $(repr(allowed_tags))" ) end bibliography_node = BibliographyNode(tag, fields[:Canonical], BibliographyItem[]) anchors = bib.anchor_map entries_to_show = OrderedDict{String,Bibliography.Entry}( key => bib.entries[key] for key in keys_to_show ) sorting = get(fields, :Sorting, bib_sorting(style)) # The "Sorting" field is undocumented, because the sorting is really tied # to the citation style. If someone wants to mess with that, they can, but # we probably shouldn't encourage it. if sorting ≠ :citation Bibliography.sort_bibliography!(entries_to_show, sorting) end for (key, entry) in entries_to_show if fields[:Canonical] anchor_key = key # Add anchor that citations can link to from anywhere in the docs. if Documenter.anchor_exists(anchors, key) # Skip entries that already have a canonical bib entry # elsewhere. This is expected behavior, not an error/warning, # allowing to split the canonical bibliography in multiple # parts. @debug "Skipping key=$(key) (existing anchor)" continue else @debug "Defining anchor for key=$(key)" Documenter.anchor_add!(anchors, entry, key, page.build) end else anchor_key = nothing # For non-canonical bibliographies, no anchors are generated, and # we don't skip any keys. That is, multiple non-canonical # bibliographies may contain entries for the same keys. end @debug "Expanding bibliography entry: $key." reference = MarkdownAST.@ast MarkdownAST.Paragraph() append!( reference.children, Documenter.mdparse(format_bibliography_reference(style, entry); mode=:span) ) if tag == :dl label = MarkdownAST.@ast MarkdownAST.Paragraph() append!( label.children, Documenter.mdparse( format_bibliography_label(style, entry, citations); mode=:span ) ) else label = nothing end push!(bibliography_node.items, BibliographyItem(anchor_key, label, reference)) end node.element = bibliography_node end # Deal with `@__FILE__` in `Pages`, convert it to the name of the current file. function _resolve__FILE__(Pages, page) __FILE__ = let ex = Meta.parse("_ = @__FILE__", 1; raise=false)[1] # What does a `@__FILE__` in the Pages list evaluate to? # Cf. `Core.eval` in `parse_bibliography_block`. # Should be the string "none", but that's an implementation detail. Core.eval(Main, ex.args[2]) end result = String[] for name in Pages if name == __FILE__ # Replace @__FILE__ in Pages with the current file: name = basename(page.source) @debug "__@FILE__ -> $(repr(name)) in Pages attribute of @bibliography block on page $(page.source)" end push!(result, name) end return result end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
5726
# Expand Citations # # This runs after ExpandBibliography, such that the citation anchors are # available in `bib.anchor_map`. """Pipeline step to expand all `@cite` citations. This runs after [`ExpandBibliography`](@ref), as it relies on the link targets in the expanded `@bibliography` blocks. All citations are formatted using [`format_citation`](@ref). """ abstract type ExpandCitations <: Builder.DocumentPipeline end Selectors.order(::Type{ExpandCitations}) = 2.13 # After ExpandBibliography function Selectors.runner(::Type{ExpandCitations}, doc::Documenter.Document) Documenter.is_doctest_only(doc, "ExpandCitations") && return @info "ExpandCitations" expand_citations!(doc) end # Expand all citations in document function expand_citations!(doc::Documenter.Document) for (src, page) in doc.blueprint.pages @debug "ExpandCitations: resolving links and replacement text for @cite entries in $(src)" empty!(page.globals.meta) expand_citations!(doc, page, page.mdast) end end # Expand all citations in one page (modify `mdast` in-place) function expand_citations!(doc::Documenter.Document, page, mdast::MarkdownAST.Node) bib = Documenter.getplugin(doc, CitationBibliography) replace!(mdast) do node if node.element isa Documenter.DocsNode # The docstring AST trees are not part of the tree of the page, so # we need to expand them explicitly for (docstr, meta) in zip(node.element.mdasts, node.element.metas) expand_citations!(doc, page, docstr) end node else expand_citation(node, page, bib) end end end """Expand a [`CitationLink`](@ref) into style-specific markdown code. ```julia md_text = format_citation(style, cit, entries, citations) ``` returns a string of markdown code that replaces the original citation link, rendering it for the given `style`. The resulting markdown code should make use of direct citation links (cf. [`DirectCitationLink`](@ref)). For example, for the default style, ```jldoctest using DocumenterCitations: format_citation, CitationLink, example_bibfile using Bibliography cit = CitationLink("[BrifNJP2010, Shapiro2012; and references therein](@cite)") entries = Bibliography.import_bibtex(example_bibfile) citations = Dict("BrifNJP2010" => 1, "Shapiro2012" => 2) format_citation(:numeric, cit, entries, citations) # output "[[1](@cite BrifNJP2010), [2](@cite Shapiro2012), and references therein]" ``` # Arguments * `style`: The style to render the citation in, as passed to [`CitationBibliography`](@ref) * `cit`: A [`CitationLink`](@ref) instance representing the original citation link * `entries`: A dict mapping citations `keys` to a [`Bibliography.Entry`](https://humans-of-julia.github.io/Bibliography.jl/stable/internal/#BibInternal.Entry) * `citations`: A dict mapping that maps citation keys to the order in which citations appear in the documentation, i.e., a numeric citation index. """ function format_citation(style::Symbol, args...)::String return format_citation(Val(style), args...) end # Return list of replacement nodes for single citation Link node # Any node that is not a citation link is returned unchanged. function expand_citation( node::MarkdownAST.Node, page, bib::CitationBibliography; _recursive=true # internal: expand each expanded sibling again? ) (node.element isa MarkdownAST.Link) || return node startswith(lowercase(node.element.destination), "@cite") || return node cit = read_citation_link(node) anchors = bib.anchor_map rec = _recursive ? "" : " (rec)" # _recursive=false if we're *in* a recursion if cit isa CitationLink style = isnothing(cit.style) ? bib.style : cit.style # Using the cit.style is an undocumented feature. We only use it to # render citations in a non-default style in the Gallery in the # documentation. expanded_md_str = format_citation(style, cit, bib.entries, bib.citations) @debug "expand_citation$rec: $cit → $expanded_md_str" # expanded_md_str should contain direct citation links, and we now # expand those recursively local expanded_nodes1 try expanded_nodes1 = Documenter.mdparse(expanded_md_str; mode=:span) catch @error "Cannot parse result of `format_citation`" style cit expanded_md_str error("Invalid result of `format_citation`") end expanded_nodes = [] for sibling in expanded_nodes1 expanded_sibling = expand_citation(sibling, page, bib; _recursive=false) if expanded_sibling isa Vector append!(expanded_nodes, expanded_sibling) else push!(expanded_nodes, expanded_sibling) end end return expanded_nodes else @assert cit isa DirectCitationLink # E.g., "[Semi-AD paper](@cite GoerzQ2022)" key = cit.key anchor = Documenter.anchor(anchors, key) if isnothing(anchor) link_text = ast_linktext(cit.node) @error "expand_citation$rec: No destination for key=$(repr(key)) → unlinked text $(repr(link_text))" return Documenter.mdparse(link_text; mode=:span) else expanded_node = MarkdownAST.copy_tree(node) path = relpath(anchor.file, dirname(page.build)) expanded_node.element.destination = string(path, Documenter.anchor_fragment(anchor)) @debug "expand_citation$rec: $cit → link to $(expanded_node.element.destination)" return expanded_node end end end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
20695
# helper functions to render references in various styles _URLDATE_FMT = Dates.DateFormat("u d, Y", "english") _URLDATE_ACCESSED_ON = "Accessed on " # We'll leave this not a `const`, as a way for people to "hack" this with # `eval` function linkify(text, link; text_fallback="") if isempty(link) return text else isempty(text) && (text = text_fallback) if isempty(text) return "" else return "[$text]($link)" end end end function _initial(name) initial = "" _name = Unicode.normalize(strip(name)) if length(_name) > 0 initial = "$(_name[1])." for part in split(_name, "-")[2:end] initial *= "-$(part[1])." end end return initial end # extract two-digit year from an entry.date.year function two_digit_year(year) if (m = match(r"\d{4}", year)) ≢ nothing return m.match[3:4] else @warn "Invalid year: $year" return year end end # The citation label for the :alpha style function alpha_label(entry) year = isempty(entry.date.year) ? "??" : two_digit_year(entry.date.year) if length(entry.authors) == 1 name = tex_to_markdown(entry.authors[1].last) name = Unicode.normalize(name; stripmark=true) return uppercasefirst(first(name, 3)) * year else letters = [_alpha_initial(name) for name in first(entry.authors, 4)] if length(entry.authors) > 4 letters = [first(letters, 3)..., "+"] end if length(letters) == 0 return "Anon" * year else return join(letters, "") * year end end end function _is_others(name) # Support "and others", or "and contributors" directly in the BibTeX file # (often used for citing software projects) return ( (name.last in ["others", "contributors"]) && (name.first == name.middle == name.particle == name.junior == "") ) end function _alpha_initial(name) # Initial of the last name, but including the "particle" (e.g., "von") # Used for `alpha_label` if _is_others(name) letter = "+" else letter = uppercase(Unicode.normalize(name.last; stripmark=true)[1]) if length(name.particle) > 0 letter = Unicode.normalize(name.particle; stripmark=true)[1] * letter end end return letter end function format_names( entry, editors=false; names=:full, and=true, et_al=0, et_al_text="*et al.*", editor_suffix="(Editor)", editors_suffix="(Editors)", nbsp="\u00A0", # non-breaking space ) # forces the names to be editors' name if the entry are Proceedings if !editors && entry.type ∈ ["proceedings"] return format_names( entry, true; names=names, and=and, et_al=et_al, et_al_text=et_al_text, editor_suffix=editor_suffix, editors_suffix=editors_suffix, nbsp=nbsp ) end entry_names = editors ? entry.editors : entry.authors if names == :full parts = map(s -> [s.first, s.middle, s.particle, s.last, s.junior], entry_names) elseif names == :last parts = map( s -> [_initial(s.first), _initial(s.middle), s.particle, s.last, s.junior], entry_names ) elseif names == :lastonly parts = map(s -> [s.particle, s.last, s.junior], entry_names) elseif names == :lastfirst parts = String[] # See below else throw( ArgumentError( "Invalid names=$(repr(names)) not in :full, :last, :lastonly, :lastfirst" ) ) end if names == :lastfirst formatted_names = String[] for name in entry_names last_parts = [name.particle, name.last, name.junior] last = join(filter(!isempty, last_parts), nbsp) first_parts = [_initial(name.first), _initial(name.middle)] first = join(filter(!isempty, first_parts), nbsp) if isempty(first) push!(formatted_names, last) else push!(formatted_names, "$last,$nbsp$first") end end else formatted_names = map(parts) do s return join(filter(!isempty, s), nbsp) end end needs_et_al = false if et_al > 0 if length(formatted_names) > (et_al + 1) formatted_names = formatted_names[1:et_al] and = false needs_et_al = true end end namesep = ", " if names == :lastfirst namesep = "; " end if and str = join(formatted_names, namesep, " and ") else str = join(formatted_names, namesep) end str = tex_to_markdown(replace(str, r"[\n\r ]+" => " ")) if needs_et_al str *= " $et_al_text" end if editors suffix = (length(entry_names) > 1) ? editors_suffix : editor_suffix str *= " $suffix" end return strip(str) end function format_published_in( entry; namesfmt=:last, include_date=true, nbsp="\u00A0", title_transform_case=(s -> s), article_link_doi_in_title=false, ) # We mostly follows https://www.bibtex.com/format/ urls = String[] if entry.type == "article" && !article_link_doi_in_title # Article titles link exclusively to `entry.access.url`, so # "published in" only links to DOI, if available if !isempty(entry.access.doi) push!(urls, doi_url(entry)) end else if isempty(get_title(entry)) append!(urls, get_urls(entry; skip=0)) else # The title already linked to the URL (or DOI, if no # URL available), hence we skip the first link here. append!(urls, get_urls(entry; skip=1)) end end segments = [String[], String[], String[]] # The "published in" string has three segments: First, pub info, Second, # address and date info in parenthesis, Third, page/chapter info _push!(i::Int64, s::String; _if=true) = (!isempty(s) && _if) && push!(segments[i], s) if entry.type == "article" # Journal abbreviations should use non-breaking space in_journal = tex_to_markdown(replace(entry.in.journal, " " => "~")) if !isempty(entry.in.volume) in_journal *= " **$(entry.in.volume)**" end if !isempty(entry.in.pages) page = format_pages(entry; page_prefix="", pages_prefix="") in_journal *= ", $page" end _push!(1, linkify(in_journal, pop_url!(urls))) _push!(2, format_year(entry); _if=include_date) elseif entry.type in ["book", "proceedings"] _push!(1, format_edition(entry)) _push!(1, format_vol_num_series(entry; title_transform_case=title_transform_case)) _push!(2, tex_to_markdown(entry.in.organization)) _push!(2, tex_to_markdown(entry.in.publisher)) _push!(2, tex_to_markdown(entry.in.address)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_chapter(entry)) _push!(3, format_pages(entry)) elseif entry.type ∈ ["booklet", "misc"] _push!(1, tex_to_markdown(entry.access.howpublished)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_pages(entry)) elseif entry.type == "eprint" error("Invalid bibtex type 'eprint'") # https://github.com/Humans-of-Julia/BibInternal.jl/issues/22 elseif entry.type in ["inbook", "incollection", "inproceedings"] booktitle = get_booktitle(entry) if !isempty(booktitle) url = pop_url!(urls) formatted_booktitle = format_title( entry; title=get_booktitle(entry), italicize=true, url=url, transform_case=title_transform_case ) _push!(1, "In: $formatted_booktitle") end _push!(1, format_edition(entry)) _push!(1, format_vol_num_series(entry; title_transform_case=title_transform_case)) if !isempty(entry.editors) editors = format_names( entry, true; names=namesfmt, editor_suffix="", editors_suffix="" ) _push!(1, "edited by $editors") end _push!(2, tex_to_markdown(entry.in.organization)) _push!(2, tex_to_markdown(entry.in.publisher)) _push!(2, tex_to_markdown(entry.in.address)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_chapter(entry)) _push!(3, format_pages(entry)) elseif entry.type == "manual" _push!(1, format_edition(entry)) _push!(1, tex_to_markdown(get(entry.fields, "type", ""))) _push!(2, tex_to_markdown(entry.in.organization)) _push!(2, tex_to_markdown(entry.in.address)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_pages(entry)) elseif entry.type in ["mastersthesis", "phdthesis"] default_thesis_type = Dict("mastersthesis" => "Master's thesis", "phdthesis" => "Ph.D. Thesis",) thesis_type = get(entry.fields, "type", default_thesis_type[entry.type]) _push!(1, tex_to_markdown(thesis_type)) _push!(1, tex_to_markdown(entry.in.school)) _push!(2, tex_to_markdown(entry.in.address)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_pages(entry)) _push!(3, format_chapter(entry)) elseif entry.type == "techreport" report_type = strip(get(entry.fields, "type", "Technical Report")) number = strip(entry.in.number) report_spec = tex_to_markdown("$report_type~$number") _push!(1, report_spec; _if=!isempty(number)) _push!(2, tex_to_markdown(entry.in.institution)) _push!(2, tex_to_markdown(entry.in.address)) _push!(2, format_year(entry); _if=include_date) _push!(3, format_pages(entry)) else @assert entry.type == "unpublished" "Unexpected type $(repr(entry.type))" # @unpublished should be rendered entirely via the Note field. if isempty(get(entry.fields, "note", "")) @warn "unpublished $(entry.id) does not have a 'note'" end end mdstr = join(segments[1], ", ") if length(segments[2]) > 0 segment2 = join(segments[2], ", ") if length(urls) > 0 segment2 = linkify(segment2, pop_url!(urls)) end mdstr *= " (" * segment2 * ")" end if length(segments[3]) > 0 mdstr *= "; " * join(segments[3], ", ") end if length(urls) > 0 @warn "Could not link $(repr(urls)) in \"published in\" information for entry $(entry.id). Add a Note field that links to the URL(s)." end return mdstr end function get_title(entry) title = entry.title if entry.type == "inbook" if isempty(entry.booktitle) # For @inbook, `get_title` always returns the title of, e.g., the # chapter *within* the book. See `get_booktitle` title = "" end end return title end function get_booktitle(entry) booktitle = entry.booktitle if isempty(booktitle) && (entry.type == "inbook") # It's a bit ambiguous whether the Title field for an @inbook entry # refers to the title of the book, or, e.g., the title of the chapter # in the book. If only Title is given, it is taken as the booktitle, # but if both Title and Booktitle are given, Title is the title of the # section within the book. booktitle = entry.title end return booktitle end function get_urls(entry; skip=0) # URL is first priority, DOI second (cf. `pop_url!`) # Passing `skip = 1` skips the first available link urls = String[] if !isempty(entry.access.url) if skip <= 0 push!(urls, entry.access.url) end skip = skip - 1 end if !isempty(entry.access.doi) if skip <= 0 url = doi_url(entry) push!(urls, url) end skip = skip - 1 end return urls end function doi_url(entry) doi = entry.access.doi if isempty(doi) return "" else if !startswith(doi, "10.") doi_match = match(r"\b10.\d{4,9}/.*\b", doi) if isnothing(doi_match) @warn "Invalid DOI $(repr(doi)) in bibtex entry $(repr(entry.id)). Ignoring DOI." return "" else if startswith(doi, "http") @warn "The DOI field in bibtex entry $(repr(entry.id)) should not be a URL. Extracting $(repr(doi)) -> $(repr(doi_match.match))." else @warn "Invalid DOI $(repr(doi)) in bibtex entry $(repr(entry.id)). Extracting $(repr(doi_match.match))." end doi = doi_match.match end end return "https://doi.org/$doi" end end function pop_url!(urls) try return popfirst!(urls) catch return "" end end function format_title( entry; title=get_title(entry), italicize=true, url="", transform_case=(s -> s) ) isnothing(title) && (title = "") title = tex_to_markdown(title; transform_case=transform_case) already_italics = startswith(title, "*") || endswith(title, "*") if !isempty(title) && italicize && !already_italics title = "*" * title * "*" end if !isempty(url) title = linkify(title, url) end return title end function format_pages(entry; page_prefix="p.\u00A0", pages_prefix="pp.\u00A0") pages = tex_to_markdown(strip(entry.in.pages)) range_match = match(r"^(\d+)\s*[-–—]\s*(\d+)$", pages) if isnothing(range_match) if isempty(pages) return "" else return "$page_prefix$pages" end else # page range p1 = range_match.captures[1] p2 = range_match.captures[2] return "$pages_prefix$(p1)–$(p2)" end end function format_chapter(entry; prefix="Chapter\u00A0") chapter = strip(entry.in.chapter) if isempty(chapter) return "" else if startswith(chapter, "{") return tex_to_markdown(chapter) else return "$prefix$(tex_to_markdown(chapter))" end end end function format_edition(entry; suffix="\u00A0Edition") edition = entry.in.edition if isempty(edition) return "" else formatted_edition = tex_to_markdown(edition) if startswith(edition, "{") # We allow to "protect" the edition with braces to render it # verbatim. It should include its own suffix in that case, e.g., # "{1st Edition}" return formatted_edition else # Otherwise, we assume a basic ordinal, and append the suffix return "$formatted_edition$suffix" end end end function format_vol_num_series( entry; vol_prefix="vol.\u00A0", num_prefix="no.\u00A0", title_transform_case=(s -> s) ) parts = String[] if !isempty(entry.in.volume) vol = tex_to_markdown(entry.in.volume) push!(parts, occursin(r"^\d+$", vol) ? "$vol_prefix$vol" : vol) end if !isempty(entry.in.number) num = tex_to_markdown(entry.in.number) push!(parts, occursin(r"^\d+$", num) ? "$num_prefix$num" : num) end vol_num = uppercasefirst(join(parts, " ")) if isempty(entry.in.series) return vol_num else series_title = format_title( entry; title=entry.in.series, italicize=true, transform_case=title_transform_case, ) if isempty(vol_num) return series_title else return "$vol_num of $series_title" end end end function format_note(entry) return strip(get(entry.fields, "note", "")) |> tex_to_markdown end function format_urldate(entry; accessed_on=_URLDATE_ACCESSED_ON, fmt=_URLDATE_FMT) urldate = strip(get(entry.fields, "urldate", "")) if urldate != "" if entry.access.url == "" @warn "Entry $(entry.id) defines an 'urldate' field, but no 'url' field." end formatted_date = urldate try date = Dates.Date(urldate, dateformat"yyyy-mm-dd") formatted_date = Dates.format(date, fmt) catch exc if exc isa ArgumentError @warn "Invalid field urldate = $(repr(urldate)). Must be in the format YYYY-MM-DD. $exc" # We'll continue with the unformatted `formatted_date = urldate` else # Most likely, a MethodError because there's something wrong # with `fmt`. @error "Check if fmt=$(repr(fmt)) is a valid dateformat!" rethrow() end end return "$accessed_on$formatted_date" else return "" end end const _MONTH_MAP = Dict{String,String}( # Bibliography.jl replaces month macros like `jan` with the string # "January" "January" => "Jan", "February" => "Feb", "March" => "Mar", "April" => "Apr", "May" => "May", "June" => "Jun", "July" => "Jul", "August" => "Aug", "September" => "Sep", "October" => "Oct", "November" => "Nov", "December" => "Dec", "1" => "Jan", "2" => "Feb", "3" => "Mar", "4" => "Apr", "5" => "May", "6" => "Jun", "7" => "Jul", "8" => "Aug", "9" => "Sep", "10" => "Oct", "11" => "Nov", "12" => "Dec", ) const _TYPES_WITH_MONTHS = Set{String}([ # The following types are the only ones where the month field shouldn't be # ignored. "proceedings", "booklet", "misc", "inproceedings", "manual", "mastersthesis", "phdthesis", "techreport", "unpublished" ]) function format_year(entry; include_month=:auto) year = entry.date.year |> tex_to_markdown if include_month == :auto include_month = (entry.type in _TYPES_WITH_MONTHS) end if include_month && !isempty(entry.date.month) month = tex_to_markdown(entry.date.month) month = get(_MONTH_MAP, month, month) year = "$month $year" end return year end function format_eprint(entry) eprint = entry.eprint.eprint if isempty(eprint) return "" end archive_prefix = entry.eprint.archive_prefix primary_class = entry.eprint.primary_class # standardize prefix for supported preprint repositories if isempty(archive_prefix) || (lowercase(archive_prefix) == "arxiv") archive_prefix = "arXiv" end if lowercase(archive_prefix) == "hal" archive_prefix = "HAL" end if lowercase(archive_prefix) == "biorxiv" archive_prefix = "biorXiv" end text = "$(archive_prefix):$eprint" if !isempty(primary_class) text *= " [$(primary_class)]" end # link url for supported preprint repositories link = "" if archive_prefix == "arXiv" link = "https://arxiv.org/abs/$eprint" elseif archive_prefix == "HAL" link = "https://hal.science/$eprint" elseif archive_prefix == "biorXiv" link = "https://www.biorxiv.org/content/10.1101/$eprint" end return linkify(text, link) end function _strip_md_formatting(mdstr) try ast = Documenter.mdparse(mdstr; mode=:single) buffer = IOBuffer() Documenter.MDFlatten.mdflatten(buffer, ast) return String(take!(buffer)) catch exc @warn "Cannot strip formatting from $(repr(mdstr))" exc return strip(mdstr) end end # Intelligently join the parts with appropriate punctuation function _join_bib_parts(parts) mdstr = "" if length(parts) == 0 mdstr = "" elseif length(parts) == 1 mdstr = strip(parts[1]) if !endswith(_strip_md_formatting(mdstr), r"[:.!?]") mdstr *= "." end else mdstr = strip(parts[1]) rest = _join_bib_parts(parts[2:end]) rest_text = _strip_md_formatting(rest) if endswith(_strip_md_formatting(mdstr), r"[:,;.!?]") || startswith(rest_text, "(") mdstr *= " " * rest else if uppercase(rest_text[1]) == rest_text[1] mdstr *= ". " * rest else mdstr *= ", " * rest end end end return mdstr end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
8444
# Auxiliary routines common to the implementation of the `:numeric` and # `:alpha` (both of which use citation labels) """Format a citation as in a "labeled" style. ```julia md = format_labeled_citation( style, cit, entries, citations; sort_and_collapse=true, brackets="[]", names=:lastonly, notfound="?", ) ``` may be used when implementing [`format_citation`](@ref) for custom styles, to render the given [`CitationLink`](@ref) object `cit` in a format similar to the built-in `:numeric` and `:alpha` styles. # Options * `sort_and_collapse`: whether to sort and collapse combined citations, e.g. `[1-3]` instead of `[2,1,3]`. Not applicable to `@citet`. * `brackets`: characters to use to enclose citation labels * `namesfmt`: How to format the author names in `@citet` (`:full`, `:last`, `:lastonly`) * `notfound`: citation label to use for a citation to a non-existing entry Beyond the above options, defining a custom [`citation_label`](@ref) method for the `style` controls the label to be used (e.g., the citation number for the default `:numeric` style.) """ function format_labeled_citation( style, cit, entries, citations; sort_and_collapse=true, brackets="[]", namesfmt=:lastonly, notfound="?" ) cite_cmd = cit.cmd if cite_cmd in [:citealt, :citealp, :citenum] @warn "$cite_cmd citations are not supported in the default styles." (cite_cmd == :citealt) && (cite_cmd = :citet) end if cite_cmd in [:cite, :citep] return _format_labeled_cite( style, cit, entries, citations; sort_and_collapse=sort_and_collapse, brackets=brackets, notfound=notfound ) else @assert cite_cmd == :citet return _format_labeled_citet( style, cit, entries, citations; brackets=brackets, namesfmt=namesfmt, notfound=notfound ) end end function _format_labeled_cite( style, cit, entries, citations; sort_and_collapse=false, brackets="[]", notfound="?" ) if sort_and_collapse keys = sort(cit.keys; by=(key -> get(citations, key, 0))) # collect groups of consecutive citations key = popfirst!(keys) group = [key] groups = [group] while length(keys) > 0 key = popfirst!(keys) if get(citations, key, 0) == get(citations, group[end], 0) + 1 push!(group, key) else group = [key] push!(groups, group) end end else groups = [[key] for key in cit.keys] end # collect link(s) for each group parts = String[] for group in groups if length(group) ≤ 2 for key in group try entry = entries[key] lbl = citation_label(style, entry, citations; notfound=notfound) push!(parts, "[$lbl](@cite $key)") catch exc @assert (exc isa KeyError) && (exc.key == key) # This will already have triggered an error during the # collection phase, so we can handle this silently push!(parts, notfound) end end else local lnk1, lnk2 k1 = group[begin] k2 = group[end] try entry = entries[k1] lbl = citation_label(style, entry, citations; notfound=notfound) lnk1 = "[$lbl](@cite $k1)" catch exc @assert (exc isa KeyError) && (exc.key == k1) lnk1 = notfound # handle silently (see above) end try entry = entries[k2] lbl = citation_label(style, entry, citations; notfound=notfound) lnk2 = "[$lbl](@cite $k2)" catch exc @assert (exc isa KeyError) && (exc.key == k2) lnk1 = notfound # handle silently (see above) end push!(parts, "$(lnk1)–$(lnk2)") end end if !isnothing(cit.note) push!(parts, cit.note) end return brackets[begin] * join(parts, ", ") * brackets[end] end function _format_labeled_citet( style, cit, entries, citations; brackets="[]", namesfmt=:lastonly, notfound="?" ) parts = String[] et_al = cit.starred ? 0 : 1 for (i, key) in enumerate(cit.keys) try entry = entries[key] names = format_names(entry; names=namesfmt, and=true, et_al, et_al_text="*et al.*") if i == 1 && cit.capitalize names = uppercasefirst(names) end label = citation_label(style, entry, citations) label = brackets[begin] * label * brackets[end] push!(parts, "[$names $label](@cite $key)") catch exc if exc isa KeyError label = brackets[begin] * notfound * brackets[end] @warn "citation_label: $(repr(key)) not found. Using $(repr(label))." push!(parts, label) else rethrow() end end end if !isnothing(cit.note) push!(parts, cit.note) end if isnothing(cit.note) return join(parts, ", ", " and ") else return join(parts, ", ") end end """Return a citation label. ```julia label = citation_label(style, entry, citations; notfound="?") ``` returns the label used in citations and the bibliography for the given entry in the given style. Used by [`format_labeled_citation`](@ref), and thus by the built-in styles `:numeric` and `:alpha`. For the default `:numeric` style, this returns the citation number (as found by looking up `entry.id` in the `citations` dict) as a string. May return `notfound` if the citation label cannot be determined. """ function citation_label end # implemented by various styles """Format a bibliography reference as in a "labeled" style. ```julia mdstr = format_labeled_bibliography_reference( style, entry; namesfmt=:last, urldate_accessed_on="Accessed on ", urldate_fmt=dateformat"u d, Y", title_transform_case=(s->s), article_link_doi_in_title=false, ) ``` # Options * `namesfmt`: How to format the author names (`:full`, `:last`, `:lastonly`) * `urldate_accessed_on`: The prefix for a rendered `urldate` field. * `urldate_fmt`: The format in which to render an `urldate` field. * `title_transform_case`: A function that transforms the case of a Title (Booktitle, Series) field. Strings enclosed in braces are protected from the transformation. * `article_link_doi_in_title`: If `false`, the URL is linked to the title for Article entries, and the DOI is linked to the published-in. If `true`, Article entries are handled as other entries, i.e., the first available URL (URL or, if no URL available, DOI) is linked to the title, while only in the presence of both, the DOI is linked to the published-in. """ function format_labeled_bibliography_reference( style, entry; namesfmt=:last, urldate_accessed_on=_URLDATE_ACCESSED_ON, urldate_fmt=_URLDATE_FMT, title_transform_case=(s -> s), article_link_doi_in_title=false, ) authors = format_names(entry; names=namesfmt) if entry.type == "article" && !article_link_doi_in_title title = format_title(entry; url=entry.access.url, transform_case=title_transform_case) else urls = get_urls(entry) # Link URL, or DOI if no URL is available title = format_title(entry; url=pop_url!(urls), transform_case=title_transform_case) end published_in = format_published_in( entry; namesfmt=namesfmt, title_transform_case=title_transform_case, article_link_doi_in_title=article_link_doi_in_title, ) eprint = format_eprint(entry) urldate = format_urldate(entry; accessed_on=urldate_accessed_on, fmt=urldate_fmt) note = format_note(entry) parts = String[] for part in (authors, title, published_in, eprint, urldate, note) if !isempty(part) push!(parts, part) end end mdtext = _join_bib_parts(parts) return mdtext end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
3686
const _LATEX_OPTIONS = Dict{Symbol,Any}() # _LATEX_OPTIONS are initialized with call to reset_latex_options() __init__() @doc raw""" Reset the options for how bibliographies are written in LaTeX. ```julia DocumenterCitations.reset_latex_options() ``` is equivalent to the following call to [`set_latex_options`](@ref): ```julia set_latex_options(; ul_as_hanging=true, ul_hangindent="0.33in", dl_hangindent="0.33in", dl_labelwidth="0.33in", bib_blockformat="\raggedright", ) ``` """ function reset_latex_options() global _LATEX_OPTIONS _LATEX_OPTIONS[:ul_as_hanging] = true _LATEX_OPTIONS[:ul_hangindent] = "0.33in" _LATEX_OPTIONS[:dl_hangindent] = "0.33in" _LATEX_OPTIONS[:dl_labelwidth] = "0.33in" _LATEX_OPTIONS[:bib_blockformat] = "\\raggedright" end @doc raw""" Set options for how bibliographies are written via `Documenter.LaTeXWriter`. ```julia DocumenterCitations.set_latex_options(; options...) ``` Valid options that can be passed as keyword arguments are: * `ul_as_hanging`: If `true` (default), format unordered bibliography lists (`:ul` returned by [`DocumenterCitations.bib_html_list_style`](@ref)) as a list of paragraphs with hanging indent. This matches the recommended CSS styling for HTML `:ul` bibliographies, see [CSS Styling](@ref). If `false`, the bibliography will be rendered as a standard bulleted list. * `ul_hangindent`: If `ul_as_hanging=true`, the amount of hanging indent. Must be a string that specifies a valid [LaTeX length](https://www.overleaf.com/learn/latex/Lengths_in_LaTeX), e.g., `"0.33in"` * `dl_hangindent` : Bibliographies that should render as "definition lists" (`:dl` returned by [`DocumenterCitations.bib_html_list_style`](@ref)) are emulated as a list of paragraphs with a fixed label width and hanging indent. The amount of hanging indent is specified with `dl_hangindent`, cf. `ul_hangindent`. * `dl_labelwidth` : The minimum width to use for the "label" in a bibliography rendered in the `:dl` style. * `bib_blockformat`: A LaTeX format command to apply for a bibliography block. Defaults to `"\raggedright"`, which avoids hyphenation within the bibliography. If set to an empty string, let LaTeX decide the default, which will generally result in fully justified text, with hyphenation. These should be considered experimental and not part of the the stable API. Options that are not specified remain unchanged from the defaults, respectively a previous call to `set_latex_options`. For bibliography blocks rendered in a `:dl` style, setting `dl_hangindent` and `dl_labelwidth` to the same value (slightly larger than the width of the longest label) produces results similar to the recommended styling in HTML, see [CSS Styling](@ref). For very long citation labels, it may look better to have a smaller `dl_hangindent`. Throws an `ArgumentError` if called with invalid options. The defaults can be reset with [`DocumenterCitations.reset_latex_options`](@ref). """ function set_latex_options(; reset=false, kwargs...) global _LATEX_OPTIONS for (key, val) in kwargs if haskey(_LATEX_OPTIONS, key) required_type = typeof(_LATEX_OPTIONS[key]) if typeof(val) == required_type _LATEX_OPTIONS[key] = val else throw( ArgumentError( "`$(repr(val))` for option $key in set_latex_options must be of type $(required_type), not $(typeof(val))" ) ) end else throw(ArgumentError("$key is not a valid option in set_latex_options.")) end end end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
4464
# To enable proper handling of citation links, we want to process the link as # plain text (markdown source). In the pipeline, the steps are as follows: # # * convert the AST of a citation link in a given page to text via # [`ast_linktext`](@ref). At the lowest level, the ast-to-text conversion # happens with `Markdown.plain(convert(Markdown.MD, ast))` # * Create [`CitationLink`](@ref) from that, which is processed in the # [`CollectCitations`](@ref) and [`ExpandCitations`](@ref) steps. # # For [`ExpandCitations`](@ref): # # * The [`CitationLink`](@ref) is transformed by [`format_citation`](@ref) # into new markdown (plain) text, which must be a valid in-line markup. # * That text is converted to a "span" of AST nodes with `Documenter.mdparse` # and replaces the original citation link node. `Documenter.mdparse` internally # uses `convert(MarkdownAST.Node, Markdown.parse(text))`. # # We also do some round-tripping with the `parse_md_citation_link` (str to ast) # and `ast_to_str`. These are explicitly used only for log/error messages and # such, but they use the same low-levels conversions and should thus be # completely compatible with [`ast_linktext`](@ref) and `Documenter.mdparse`. # # **In summary**: to test/understand the roundrip behavior, look at # # * [`DocumenterCitations.ast_to_str`](@ref) for ast to text conversion # * `Documenter.mdparse` for text to ast conversion # Parse a markdown text citation link into an AST. Used when instantiating # CitationLink/DirectCitationLink from a string. This is used extensively in # the documentation and for unit testing, but it is not actually part of the # pipeline (where we instantiate CitationLinks directly from the AST) function parse_md_citation_link(str) local paragraph try paragraph = Documenter.mdparse(str; mode=:single)[1] catch error("Invalid citation: $(repr(str))") end if length(paragraph.children) != 1 @error "citation $(repr(str)) must parse into a single MarkdownAST.Link" ast = collect(paragraph.children) error("Invalid citation: $(repr(str))") end link = first(paragraph.children) if !(link.element isa MarkdownAST.Link) @error "citation $(repr(str)) must parse into MarkdownAST.Link" ast = link error("Invalid citation: $(repr(str))") end if !startswith(lowercase(link.element.destination), "@cite") @error "citation link $(repr(str)) destination must start exactly with \"@cite\" or one of its variants" ast = link error("Invalid citation: $(repr(str))") end return link end # Convert a markdown node to plain text (markdown source). Used only for # showing ASTs in a more readable form in error messages / logging, and not # used otherwise in the pipeline. function ast_to_str(node::MarkdownAST.Node) if node.element isa MarkdownAST.Document document = node elseif node.element isa MarkdownAST.AbstractBlock document = MarkdownAST.@ast MarkdownAST.Document() do MarkdownAST.copy_tree(node) end else @assert node.element isa MarkdownAST.AbstractInline document = MarkdownAST.@ast MarkdownAST.Document() do MarkdownAST.Paragraph() do MarkdownAST.copy_tree(node) end end end text = Markdown.plain(convert(Markdown.MD, document)) return strip(text) end # Given a `node` that is a `MarkdownAST.Link` return the link text (as plain # markdown text). This routine is central to the pipeline, as it controls the # creation of `CitationLink` instances and thus the text that the various # `format_*` routines receive. function ast_linktext(node) @assert node.element isa MarkdownAST.Link "node must be a Link, not $(typeof(node.element))" no_nested_markdown = length(node.children) === 1 && (first_node = first(node.children); first_node.element isa MarkdownAST.Text) if no_nested_markdown text = first_node.element.text else document = MarkdownAST.@ast MarkdownAST.Document() do MarkdownAST.Paragraph() end paragraph = first(document.children) children = [MarkdownAST.copy_tree(child) for child in node.children] # append! without copy_tree would unlink the children append!(paragraph.children, children) text = Markdown.plain(convert(Markdown.MD, document)) end return strip(text) end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
15003
const _DEBUG = Logging.LogLevel(-2000) # below Logging.Debug #const _DEBUG = Logging.Info # COV_EXCL_START @static if VERSION >= v"1.7" const _replace = replace else # In principle, we really need the ability of `replace` in Julia >= 1.7 to # apply multiple substitutions at once. On Julia 1.6, we instead iterate # over the substitutions. There is a theoretical chance for a collision in # the back-substitution in `_process_tex`. Since the `_keys` function in # `_process_tex` combines a hash and a counter, there's basically zero # chance of this happening by accident, but it would definitely be possible # to hand-craft a string that produces a collision. Oh well. function _replace(str, subs...) for sub in subs str = replace(str, sub) end return str end end # COV_EXCL_STOP const _TEX_ACCENTS = Dict( # "direct" accents (non-letter commands) '`' => "\u0300", # \`o ò grave accent '\'' => "\u0301", # \'o ó acute accent '^' => "\u0302", # \^o ô circumflex '~' => "\u0303", # \~o õ tilde '=' => "\u0304", # \=o ō macron (not the same as "overline", \u0305) '.' => "\u0307", # \.o ȯ dot over letter '"' => "\u0308", # \"o ö diaeresis ) const _COMMANDS_NUM_ARGS = Dict{String,Int64}( # zero-arg commands do not need to be listed "\\url" => 1, "\\href" => 2, "\\texttt" => 1, "\\textit" => 1, "\\u" => 1, "\\r" => 1, "\\H" => 1, "\\v" => 1, "\\d" => 1, "\\c" => 1, "\\k" => 1, "\\b" => 1, "\\t" => 1, ) _url_to_md(url) = "[`$url`]($url)" function _href_to_md(url, linktext) md_linktext = _process_tex(linktext) return "[$md_linktext]($url)" end function _texttt_to_md(code) md_code = _process_tex(code) return "`$md_code`" end function _textit_to_md(text) md_text = _process_tex(text) return "_$(md_text)_" end function _accent(str, accent) a = firstindex(str) b = nextind(str, a) first = (str[a]) rest = str[b:end] return "$first$accent$rest" end const _COMMANDS_TO_MD = Dict{String,Function}( "\\url" => _url_to_md, "\\href" => _href_to_md, "\\texttt" => _texttt_to_md, "\\textit" => _textit_to_md, "\\u" => c -> _accent(c, "\u306"), # \u{o} ŏ breve over the letter "\\r" => c -> _accent(c, "\u30A"), # \r{a} å ring over the letter "\\H" => c -> _accent(c, "\u30B"), # \H{o} ő long Hungarian umlaut "\\v" => c -> _accent(c, "\u30C"), # \v{s} š caron/háček "\\d" => c -> _accent(c, "\u323"), # \d{u} ụ underdot "\\c" => c -> _accent(c, "\u327"), # \c{c} ç cedilla "\\k" => c -> _accent(c, "\u328"), # \k{a} ą ogonek "\\b" => c -> _accent(c, "\u331"), # \b{b} ḇ underbar "\\t" => c -> _accent(c, "\u361"), # \t{oo} o͡o "tie" over two letters "\\o" => () -> "\u00F8", # \o ø latin small letter O with stroke "\\O" => () -> "\u00D8", # \O Ø latin capital letter O with stroke "\\l" => () -> "\u0142", # \l ł latin small letter L with stroke "\\L" => () -> "\u0141", # \L Ł latin capital letter L with stroke "\\i" => () -> "\u0131", # \i ı latin small letter dotless I "\\j" => () -> "\u0237", # \j ȷ latin small letter dotless J "\\ss" => () -> "\u00DF", # \s ß latin small letter sharp S "\\SS" => () -> "SS", # \SS SS latin capital latter sharp S "\\OE" => () -> "\u0152", # \OE Œ latin capital ligature OE "\\aa" => () -> "\u00E5", # \aa å latin small letter A with ring above "\\ae" => () -> "\u00E6", # \ae æ latin small letter AE "\\AA" => () -> "\u00C5", # \AA Å latin capital letter A with ring above "\\oe" => () -> "\u0153", # \oe œ latin small ligature oe "\\AE" => () -> "\u00C6", # \AE Æ latin capital letter AE ) const _TEX_ESCAPED_CHARS = Set(['\$', '%', '@', '{', '}', '&']) function supported_tex_commands() return sort([["\\$s" for s in keys(_TEX_ACCENTS)]..., keys(_COMMANDS_TO_MD)...]) end function tex_to_markdown(tex_str; transform_case=s -> s, debug=_DEBUG) if contains(tex_str, "](http") # https://github.com/JuliaDocs/DocumenterCitations.jl/issues/60 @warn "The tex string $(repr(tex_str)) appears to contain a link in markdown syntax. Links in a `.bib` entry should use the `\\href` tex command." end try md_str = _process_tex(tex_str; transform_case=transform_case, debug=debug) return Unicode.normalize(md_str) catch exc if exc isa BoundsError throw(ArgumentError("Premature end of tex string: $exc")) else rethrow() end end end function _process_tex(tex_str; transform_case=(s -> s), debug=_DEBUG) @logmsg debug "_process_tex($(repr(tex_str)))" result = "" accent_chars = Set(keys(_TEX_ACCENTS)) subs = Dict{String,String}() N = lastindex(tex_str) i = firstindex(tex_str) _k = 0 _keys = Dict{String,String}() function _key(s) key = get(_keys, s, "") if key == "" _k += 1 # The key must be unique, and on Julia 1.6, the key also must not # collide with any string that might show up in the output of # `_process_tex`. Combining a hash and a counter achieves this for # anything but maliciously crafted strings. key = "{$(hash(s)):$_k}" _keys[s] = key end return key end while i <= N letter = tex_str[i] if (letter == '\\') next_letter = tex_str[nextind(tex_str, i)] if next_letter in _TEX_ESCAPED_CHARS i = nextind(tex_str, i) # eat the '\' result *= next_letter @logmsg debug "Processed escape '\\' and escaped $(repr(next_letter))" elseif next_letter in accent_chars i, cmd, replacement = _collect_accent(tex_str, i) key = _key(cmd) subs[key] = replacement result *= key @logmsg debug "Processed accent: $(repr(cmd)) -> $(repr(replacement))" else i, cmd, replacement = _collect_command(tex_str, i; debug=debug) key = _key(cmd) subs[key] = replacement result *= key @logmsg debug "Processed accent: $(repr(cmd)) -> $(repr(replacement))" end elseif (letter == '\$') i, math, replacement = _collect_math(tex_str, i) key = _key(math) subs[key] = replacement result *= key @logmsg debug "Processed math: $(repr(math)) -> $(repr(replacement))" elseif (letter == '{') i, group, replacement = _collect_group(tex_str, i) key = _key(group) subs[key] = replacement result *= key @logmsg debug "Processed group: $(repr(group)) -> $(repr(replacement))" elseif letter in _TEX_ESCAPED_CHARS throw( ArgumentError( "Character $(repr(letter)) at pos $i in $(repr(tex_str)) must be escaped" ) ) else # regular letter if letter == '~' result *= '\u00a0' # non-breaking space elseif (letter == '-') && (length(result) > 0) if result[end] == '-' result = chop(result) * '\u2013' # en-dash (–) elseif result[end] == '\u2013' result = chop(result) * '\u2014' # en-dash (—) else result *= letter end else result *= letter end @logmsg debug "Processed regular $(repr(letter))" end i = nextind(tex_str, i) end @logmsg debug "Applying back-substitution of protected groups" subs return _replace(transform_case(result), subs...) end # collect a "direct accent" from the given `tex_str`, as specified in _TEX_ACCENTS # These are special because they don't need braces: you can have # "Schr\"odinger", not just "Schr\"{o}dinger" or "Schr{\"o}dinger". On the # other hand, you have to have "Fran\c{c}oise", not "Fran\ccoise" function _collect_accent(tex_str, i) letter = tex_str[i] @assert letter == '\\' i = nextind(tex_str, i) accent = tex_str[i] cmd = "\\$accent" i = nextind(tex_str, i) next_letter = tex_str[i] if next_letter == '{' i, group, group_replacement = _collect_group(tex_str, i) cmd *= group a = firstindex(group_replacement) b = nextind(group_replacement, a) first = (group_replacement[a]) rest = group_replacement[b:end] replacement = "$first$(_TEX_ACCENTS[accent])$rest" elseif next_letter == '\\' m = match(r"^\\[a-zA-Z]+\b\s*", tex_str[i:end]) if isnothing(m) throw(ArgumentError("Invalid accent: $cmd$(tex_str[i:end])")) else # E.g., \"\i _replacement = "" try l, _cmd, _replacement = _collect_command(m.match, 1) cmd *= _cmd i = prevind(tex_str, i + l) # end of match catch exc @error "Accents may only be followed by group, a single ASCII letter, or **a supported zero-argument command**." exc throw(ArgumentError("Unsupported accent: $cmd$(tex_str[i:end]).")) end a = firstindex(_replacement) b = nextind(_replacement, a) first = (_replacement[a]) rest = _replacement[b:end] replacement = "$first$(_TEX_ACCENTS[accent])$rest" end elseif _is_ascii_letter(next_letter) cmd *= next_letter replacement = "$next_letter$(_TEX_ACCENTS[accent])" else @error "Accents may only be followed by group, a single ASCII letter, or a supported zero-argument command." throw(ArgumentError("Unsupported accent: $cmd$(tex_str[i:end]).")) end return i, cmd, replacement end _is_ascii_letter(l) = let i = Int64(l) (65 <= i <= 90) || (97 <= i <= 122) # [A-Za-z] end function _collect_command(tex_str, i; debug=_DEBUG) @logmsg debug "_process_command($(repr(tex_str[i:end])))" i0 = i letter = tex_str[i] @assert letter == '\\' m = match(r"^\\[a-z-A-Z]+\b\s*", tex_str[i:end]) cmd = "$letter" if isnothing(m) throw(ArgumentError("Invalid command: $(tex_str[i:end])")) else i += lastindex(m.match) # character after cmd cmd = strip(m.match) end n_args = get(_COMMANDS_NUM_ARGS, cmd, 0) @logmsg debug "cmd = $(repr(cmd)), n_args = $n_args" args = String[] if n_args == 0 i = prevind(tex_str, i) # go back to end of cmd elseif (n_args == 1) && (tex_str[i] != '{') # E.g. `\d o` instead of `\d{o}` (single letter arg) @logmsg debug "processing single-letter arg" push!(args, string(tex_str[i])) else i_arg = 0 while n_args > 0 i_arg += 1 @logmsg debug "starting to process arg $i_arg" arg = "" if tex_str[i] != '{' throw( ArgumentError( "Expected '{' at pos $i in $(repr(tex_str)), not $(repr(tex_str[i]))" ) ) end open_braces = 1 while true i = nextind(tex_str, i) letter = tex_str[i] if letter == '\\' i = nextind(tex_str, i) next_letter = tex_str[i] arg *= letter # we leave the escape in place arg *= next_letter @logmsg debug "Processed (keep) escape '\\' and next letter $(repr(next_letter))" elseif letter == '{' open_braces += 1 arg *= letter @logmsg debug "Processed '{'" open_braces elseif letter == '}' open_braces -= 1 @logmsg debug "Processed '}'" open_braces if open_braces == 0 push!(args, arg) @logmsg debug "finished collecting arg $i_arg" arg n_args -= 1 if n_args > 0 next_i = nextind(tex_str, i) while tex_str[next_i] == ' ' # remove spaces to next argument i = next_i next_i = nextind(tex_str, i) end i = nextind(tex_str, i) end break # next arg else arg *= letter @logmsg debug "Processed regular $(repr(letter)) (in-arg)" end else arg *= letter @logmsg debug "Processed regular $(repr(letter))" end end end end if !haskey(_COMMANDS_TO_MD, cmd) supported_commands = join(supported_tex_commands(), " ") @error "Unsupported command: $cmd.\nSupported commands are: $supported_commands" throw(ArgumentError("Unsupported command: $cmd. Please report a bug.")) end try replacement = _COMMANDS_TO_MD[cmd](args...) return i, tex_str[i0:i], replacement catch exc throw(ArgumentError("Cannot evaluate $cmd: $exc")) end end function _collect_math(tex_str, i) letter = tex_str[i] @assert letter == '\$' math = "$letter" while true # ends by return, or BoundsError for incomplete math i = nextind(tex_str, i) letter = tex_str[i] math *= letter if letter == '\\' i = nextind(tex_str, i) next_letter = tex_str[i] math *= next_letter elseif letter == '\$' replacement = "``" * chop(math; head=1, tail=1) * "``" return i, math, replacement end end end function _collect_group(tex_str, i) letter = tex_str[i] @assert letter == '{' group = "$letter" open_braces = 1 while true # ends by return, or BoundsError for incomplete math i = nextind(tex_str, i) letter = tex_str[i] group *= letter if letter == '\\' i = nextind(tex_str, i) next_letter = tex_str[i] group *= next_letter elseif letter == '{' open_braces += 1 elseif letter == '}' open_braces -= 1 if open_braces == 0 replacement = _process_tex(chop(group; head=1, tail=1)) return i, group, replacement end end end end
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
4016
# format_citation ############################################################# function format_citation(style::Union{Val{:alpha},AlphaStyle}, cit, entries, citations) format_labeled_citation(style, cit, entries, citations; sort_and_collapse=false) end function citation_label( style::Union{Val{:alpha},AlphaStyle}, entry, citations; notfound="?" ) local label if style == Val(:alpha) # dumb style label = alpha_label(entry) else # smart style @assert style isa AlphaStyle key = replace(entry.id, "*" => "_") try label = style.label_for_key[key] catch @error "No AlphaStyle label for $key. Was `init_bibliography!` called?" style.label_for_key return notfound end end return label end # init_biliography! ########################################################### function init_bibliography!(style::AlphaStyle, bib) # We determine the keys from all the entries in the .bib file # (`bib.entries`), not just the cited ones (`bib.citations`). This keeps # the rendered labels more stable, e.g., if you have one `.bib` file across # multiple related projects. Besides, `bib.citations` isn't guaranteed to # be complete at the point where `init_bibliography!` is called, since # bibliography blocks can also introduce new citations (e.g., if using `*`) entries = OrderedDict{String,Bibliography.Entry}( # best not to mutate bib.entries, so we'll create a copy before sorting key => entry for (key, entry) in bib.entries ) Bibliography.sort_bibliography!(entries, :nyt) # pass 1 - collect dumb labels, identify duplicates keys_for_label = Dict{String,Vector{String}}() for (key, entry) in entries label = alpha_label(entry) # dumb label (no suffix) if label in keys(keys_for_label) push!(keys_for_label[label], key) else keys_for_label[label] = String[key,] end end # pass 2 - disambiguate duplicates (append suffix to dumb labels) label_for_key = style.label_for_key # for in-place mutation for (key, entry) in entries label = alpha_label(entry) if length(keys_for_label[label]) > 1 i = findfirst(isequal(key), keys_for_label[label]) label *= _alpha_suffix(i) end label_for_key[key] = label end @debug "init_bibliography!(style::AlphaStyle, bib)" keys_for_label label_for_key # `style.label_for_key` is now up-to-date end function _alpha_suffix(i) if i <= 25 return string(Char(96 + i)) # 1 -> "a", 2 -> "b", etc. else # 26 -> "za", 27 -> "zb", etc. # I couldn't find any information on (and I was too lazy to test) how # LaTeX handles disambiguation of more than 25 identical labels, but # this seems sensible. But also: Seriously? I don't think we'll ever # run into this in real life. return "z" * _alpha_suffix(i - 25) end end # format_bibliography_reference ############################################### function format_bibliography_reference(style::Val{:alpha}, entry) return format_labeled_bibliography_reference(style, entry) end function format_bibliography_reference(style::AlphaStyle, entry) return format_labeled_bibliography_reference(style, entry) end # format_bibliography_label ################################################### function format_bibliography_label( style::Union{Val{:alpha},AlphaStyle}, entry, citations::OrderedDict{String,Int64} ) label = citation_label(style, entry, citations) return "[$label]" end # bib_html_list_style ######################################################### bib_html_list_style(::Val{:alpha}) = :dl bib_html_list_style(::AlphaStyle) = :dl # bib_sorting ################################################################# bib_sorting(::Val{:alpha}) = :nyt bib_sorting(::AlphaStyle) = :nyt
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
5967
# format_citation ############################################################# function format_citation(style::Val{:authoryear}, cit::CitationLink, entries, citations) format_authoryear_citation(style, cit, entries, citations) end """Format a citation as in the `:authoryear` style. ```julia md = format_authoryear_citation( style, cit, entries, citations; empty_names="Anonymous", empty_year="undated", parenthesis="()", notfound="???", ) ``` may be used when implementing [`format_citation`](@ref) for custom styles, to render the given [`CitationLink`](@ref) object `cit` in a format similar to the built-in `:authoryear` style. # Options * `namesfmt`: How to format the author names (`:full`, `:last`, `:lastonly`) * `empty_names`: String to use as "author" when the entry defines no author * `empty_year`: String to use as "year" when the entry defines no year * `parenthesis`: The parenthesis symbols to use for `@cite`/`@citep` * `notfound`: How to render a citation without a corresponding entry """ function format_authoryear_citation( style, cit, entries, citations; namesfmt=:lastonly, empty_names="Anonymous", empty_year="undated", parentheses="()", notfound="???" ) et_al = cit.starred ? 0 : 1 cite_cmd = cit.cmd if cite_cmd == :citep cite_cmd = :cite end if cite_cmd ∈ [:citealt, :citealp, :citenum] @warn "$cite_cmd citations are not supported in the default styles." (cite_cmd == :citealt) && (cite_cmd = :citet) end parts = String[] for (i, key) in enumerate(cit.keys) local entry try entry = entries[key] catch exc if exc isa KeyError @warn "citation_label: $(repr(key)) not found. Using $(repr(notfound))." push!(parts, notfound) continue else rethrow() end end names = format_names(entry; names=namesfmt, and=true, et_al, et_al_text="*et al.*") if isempty(names) names = empty_names end if i == 1 && cit.capitalize names = uppercasefirst(names) end year = format_year(entry) if isempty(year) year = empty_year end if cite_cmd == :citet push!(parts, "[$names ($year)](@cite $key)") else @assert cite_cmd in [:cite, :citep] push!(parts, "[$names, $year](@cite $key)") end end if !isnothing(cit.note) push!(parts, cit.note) end if cite_cmd == :citet return join(parts, ", ") else @assert cite_cmd in [:cite, :citep] return parentheses[begin] * join(parts, "; ") * parentheses[end] end end # format_bibliography_reference ############################################### function format_bibliography_reference(style::Val{:authoryear}, entry) return format_authoryear_bibliography_reference(style, entry) end """Format a bibliography reference as for the `:authoryear` style. ```julia mdstr = format_authoryear_bibliography_reference( style, entry; namesfmt=:lastfirst, empty_names="—", urldate_accessed_on="Accessed on ", urldate_fmt=dateformat"u d, Y", title_transform_case=(s->s), article_link_doi_in_title=false, ) ``` # Options * `namesfmt`: How to format the author names (`:full`, `:last`, `:lastonly`) * `empty_names`: String to use in place of the authors if there are no authors * `urldate_accessed_on`: The prefix for a rendered `urldate` field. * `urldate_fmt`: The format in which to render an `urldate` field. * `title_transform_case`: A function that transforms the case of a Title (Booktitle, Series) field. Strings enclosed in braces are protected from the transformation. * `article_link_doi_in_title`: If `false`, the URL is linked to the title for Article entries, and the DOI is linked to the published-in. If `true`, Article entries are handled as other entries, i.e., the first available URL (URL or, if no URL available, DOI) is linked to the title, while only in the presence of both, the DOI is linked to the published-in. """ function format_authoryear_bibliography_reference( style, entry; namesfmt=:lastfirst, empty_names="—", urldate_accessed_on=_URLDATE_ACCESSED_ON, urldate_fmt=_URLDATE_FMT, title_transform_case=(s -> s), article_link_doi_in_title=false, ) authors = format_names(entry; names=namesfmt) if entry.type == "article" && !article_link_doi_in_title title = format_title(entry; url=entry.access.url, transform_case=title_transform_case) else urls = get_urls(entry) # Link URL, or DOI if no URL is available title = format_title(entry; url=pop_url!(urls), transform_case=title_transform_case) end year = format_year(entry) if !isempty(year) if isempty(authors) authors = empty_names end year = "($year)" end published_in = format_published_in( entry; include_date=false, namesfmt=namesfmt, title_transform_case=title_transform_case ) eprint = format_eprint(entry) urldate = format_urldate(entry; accessed_on=urldate_accessed_on, fmt=urldate_fmt) note = format_note(entry) parts = String[] for part in (authors, year, title, published_in, eprint, urldate, note) if !isempty(part) push!(parts, part) end end mdtext = _join_bib_parts(parts) return mdtext end # format_bibliography_label ################################################### # N/A — this style does not use labels # bib_html_list_style ######################################################### bib_html_list_style(::Val{:authoryear}) = :ul # bib_sorting ################################################################# bib_sorting(::Val{:authoryear}) = :nyt
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
1540
# format_citation ############################################################# function format_citation(style::Val{:numeric}, cit::CitationLink, entries, citations) format_labeled_citation(style, cit, entries, citations; sort_and_collapse=true) end function citation_label(::Val{:numeric}, entry, citations; notfound="?") key = replace(entry.id, "*" => "_") try return "$(citations[key])" catch exc @warn "citation_label: $(repr(key)) not found in `citations`. Using $(repr(notfound))." return notfound end end # format_bibliography_reference ############################################### function format_bibliography_reference(style::Val{:numeric}, entry) return format_labeled_bibliography_reference(style, entry) end # format_bibliography_label ################################################### function format_bibliography_label( style::Val{:numeric}, entry, citations::OrderedDict{String,Int64} ) key = replace(entry.id, "*" => "_") i = get(citations, key, 0) if i == 0 i = length(citations) + 1 citations[key] = i @debug "Mark $key as cited ($i) because it is rendered in a bibliography" end label = citation_label(style, entry, citations) return "[$label]" end # bib_html_list_style ######################################################### bib_html_list_style(::Val{:numeric}) = :dl # bib_sorting ################################################################# bib_sorting(::Val{:numeric}) = :citation
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git
[ "MIT" ]
1.3.4
ca601b812efd1155a9bdf9c80e7e0428da598a08
code
1902
""" clean([distclean=false]) Clean up build/doc/testing artifacts. Restore to clean checkout state (distclean) """ function clean(; distclean=false, _exit=true) _glob(folder, ending) = [name for name in readdir(folder; join=true) if (name |> endswith(ending))] _glob_star(folder; except=[]) = [ joinpath(folder, name) for name in readdir(folder) if !(name |> startswith(".") || name ∈ except) ] _exists(name) = isfile(name) || isdir(name) _push!(lst, name) = _exists(name) && push!(lst, name) ROOT = dirname(@__DIR__) ########################################################################### CLEAN = String[] src_folders = ["", "src", joinpath("src", "styles"), "test", joinpath("docs", "custom_styles")] for folder in src_folders append!(CLEAN, _glob(joinpath(ROOT, folder), ".cov")) end _push!(CLEAN, joinpath(ROOT, "coverage")) _push!(CLEAN, joinpath(ROOT, "docs", "build")) append!(CLEAN, _glob(ROOT, ".info")) append!(CLEAN, _glob(joinpath(ROOT, ".coverage"), ".info")) ########################################################################### ########################################################################### DISTCLEAN = String[] for folder in ["", "docs", "test"] _push!(DISTCLEAN, joinpath(joinpath(ROOT, folder), "Manifest.toml")) end _push!(DISTCLEAN, joinpath(ROOT, "docs", "Project.toml")) ########################################################################### for name in CLEAN @info "rm $name" rm(name, force=true, recursive=true) end if distclean for name in DISTCLEAN @info "rm $name" rm(name, force=true, recursive=true) end if _exit @info "Exiting" exit(0) end end end distclean() = clean(distclean=true)
DocumenterCitations
https://github.com/JuliaDocs/DocumenterCitations.jl.git