Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API clean up #154

Merged
merged 5 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 56 additions & 21 deletions example/taylor_expansion.jl
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
using FeynmanDiagram
using FeynmanDiagram.Taylor
using FeynmanDiagram.ComputationalGraphs:
eval!, forwardAD, node_derivative, backAD, build_all_leaf_derivative, count_operation
eval!, forwardAD, node_derivative, backAD, build_all_leaf_derivative
using FeynmanDiagram.Utility:
taylorexpansion, build_derivative_backAD!
taylorexpansion!, taylorexpansion, build_derivative_backAD!, count_operation

function banchmark_AD(glist::Vector{T}) where {T<:Graph}
dcerkoney marked this conversation as resolved.
Show resolved Hide resolved
taylormap = Dict{Int,TaylorSeries{T}}()
totaloperation = [0, 0]
taylorlist = Vector{TaylorSeries{T}}()
for g in glist
@time t, taylormap = taylorexpansion!(g; taylormap=taylormap)


operation = count_operation(t)
totaloperation = totaloperation + operation
push!(taylorlist, t)
print("operation number: $(operation)\n")
t_compare = build_derivative_backAD!(g)
for (order, coeff) in (t_compare.coeffs)
@assert (eval!(coeff)) == (eval!(Taylor.taylor_factorial(order) * t.coeffs[order]))
# gs = Compilers.to_julia_str([coeff,], name="eval_graph!")
# println("$(order) ", gs, "\n")
# print("$(order) $(eval!(coeff)) $(eval!(getderivative(t5,order))) $(count_operation(coeff))\n")
end
end

total_uniqueoperation = count_operation(taylorlist)
print(" total operation number: $(length(taylorlist)) $(totaloperation) $(total_uniqueoperation)\n")
return total_uniqueoperation
end
g1 = Graph([])
g2 = Graph([])
g3 = Graph([]) #, factor=2.0)
Expand All @@ -13,6 +39,7 @@ g6 = Graph([])
G3 = g1
G4 = 1.0 * g1 * g2
G5 = 1.0 * (3.0 * G3 + 0.5 * G4)
#G5 = g5 * g6
#G6 = (0.5 * g1 * g2 + 0.5 * g2 * g3)
#G6 = (g1 + g2) * (0.5 * g1 + g3) * g1 # (0.5 * g1 + g3)
#G6 = g1 * g2 * g3 * g4 * g5 * g6
Expand All @@ -25,28 +52,36 @@ using FeynmanDiagram.Taylor:
# set_variables("x y", order=3)
# @time T5 = taylorexpansion(G5)
# print(T5)
set_variables("x y", order=[3, 2])
set_variables("x y", orders=[3, 2])
#set_variables("x y z a", order=[1, 2, 3, 2])
@time T5 = taylorexpansion(G6)
#order = [0, 0, 0, 0, 0, 0]
#@time print(T5.coeffs[order])
print("$(count_operation(T5.coeffs))\n")
# for (order, coeff) in (T5.coeffs)
# #gs = Compilers.to_julia_str([coeff,], name="eval_graph!")
# #println("$(order) ", gs, "\n")
# print("$(order) $(eval!(coeff)) $(eval!(getcoeff(T5,order))) $(coeff.id) $(count_operation(coeff))\n")
# end

print("TaylorSeries $(T5)\n")

@time T5_compare = build_derivative_backAD!(G6)
print("$(count_operation(T5_compare.coeffs))\n")
for (order, coeff) in (T5_compare.coeffs)
@assert (eval!(coeff)) == (eval!(Taylor.taylor_factorial(order) * T5.coeffs[order]))
# gs = Compilers.to_julia_str([coeff,], name="eval_graph!")
# println("$(order) ", gs, "\n")
# print("$(order) $(eval!(coeff)) $(eval!(getderivative(T5,order))) $(count_operation(coeff))\n")
end
#@time taylormap = taylorexpansion(G6)


banchmark_AD([G3, G4, G5, G6])


# T5 = taylormap[G6.id]
dcerkoney marked this conversation as resolved.
Show resolved Hide resolved
# #order = [0, 0, 0, 0, 0, 0]
# #@time print(T5.coeffs[order])
# print("$(count_operation(T5.coeffs))\n")
# # for (order, coeff) in (T5.coeffs)
# # #gs = Compilers.to_julia_str([coeff,], name="eval_graph!")
# # #println("$(order) ", gs, "\n")
# # print("$(order) $(eval!(coeff)) $(eval!(getcoeff(T5,order))) $(coeff.id) $(count_operation(coeff))\n")
# # end

# print("TaylorSeries $(T5)\n")

# @time T5_compare = build_derivative_backAD!(G6)
# print("$(count_operation(T5_compare.coeffs))\n")
# for (order, coeff) in (T5_compare.coeffs)
# @assert (eval!(coeff)) == (eval!(Taylor.taylor_factorial(order) * T5.coeffs[order]))
# # gs = Compilers.to_julia_str([coeff,], name="eval_graph!")
# # println("$(order) ", gs, "\n")
# # print("$(order) $(eval!(coeff)) $(eval!(getderivative(T5,order))) $(count_operation(coeff))\n")
# end



Expand Down
2 changes: 1 addition & 1 deletion src/computational_graph/tree_properties.jl
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ function count_operation(g::Array{G}) where {G<:Graph}
end


function count_operation(g::Dict{Array{Int,1},G}) where {G<:Graph}
function count_operation(g::Dict{Vector{Int},G}) where {G<:Graph}
visited = Set{Int}()
totalsum = 0
totalprod = 0
Expand Down
22 changes: 22 additions & 0 deletions src/frontend/diagtree.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,26 @@ function Graph!(d::DiagTree.Diagram{W}; map=Dict{Int,DiagTree.DiagramId}()) wher
map[tree.id] = d.id

return root, map
end

"""
function extract_var_dependence(map::Dict{Int,DiagTree.DiagramId}, ::Type{ID}, numvars::Int)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add where {ID<:PropagatorId} to match function signature


Given a map between graph id and DiagramId, extract the variable dependence of all graphs.

# Arguments:
- `map::Dict{Int,DiagTree.DiagramId}`: A dictionary mapping graph ids to DiagramIds. DiagramId stores the diagram information of the corresponding graph.
- `ID`: The particular type of ID that has the given variable dependence.
- `numvars`: The number of varibles which the diagram depends on.
dcerkoney marked this conversation as resolved.
Show resolved Hide resolved
"""
function extract_var_dependence(map::Dict{Int,DiagTree.DiagramId}, ::Type{ID}, numvars::Int) where {ID<:PropagatorId}
var_dependence = Dict{Int,Vector{Bool}}()
for (id, diagID) in map
if diagID isa ID
var_dependence[id] = [true for _ in 1:numvars]
else
var_dependence[id] = [false for _ in 1:numvars]
end
end
return var_dependence
end
99 changes: 72 additions & 27 deletions src/utility.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,18 @@ module Utility
using ..ComputationalGraphs
using ..ComputationalGraphs: Sum, Prod, Power, decrement_power
using ..ComputationalGraphs: build_all_leaf_derivative, eval!
import ..ComputationalGraphs: count_operation
using ..ComputationalGraphs.AbstractTrees

using ..Taylor


"""
function taylorexpansion(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}()) where {G<:Graph}

Return a taylor series of graph g. If variable dependence is not specified, by default, assume all leaves of graph depend on all variables.

#Arguments
# Internal function that performs taylor expansion on a single graph node recursively.
function _taylorexpansion!(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}(); taylormap::Dict{Int,TaylorSeries{G}}=Dict{Int,TaylorSeries{G}}()) where {G<:Graph}
if haskey(taylormap, graph.id) #If already exist, use taylor series in taylormap.
return taylormap[graph.id]

- `graph` Target graph.
- `var_dependence::Dict{Int,Vector{Bool}}` The variables graph leaves depend on. Should map each leaf ID of g to a Vector{Bool},
indicating the taylor variables it depends on. By default, assumes all leaves depend on all variables.
"""
function taylorexpansion(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}()) where {G<:Graph}
if isleaf(graph)
elseif isleaf(graph)
maxorder = get_orders()
if haskey(var_dependence, graph.id)
var = var_dependence[graph.id]
Expand All @@ -33,25 +27,58 @@ function taylorexpansion(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{I
coeff = Graph([]; operator=Sum(), factor=graph.factor)
result.coeffs[o] = coeff
end
taylormap[graph.id] = result
return result
else
taylormap = Dict{Int,TaylorSeries{G}}() #Saves the taylor series corresponding to each nodes of the graph
for g in Leaves(graph)
if !haskey(taylormap, g.id)
taylormap[g.id] = taylorexpansion(g, var_dependence)
end
end
taylormap[graph.id] = apply(graph.operator, [_taylorexpansion!(sub, var_dependence; taylormap=taylormap) for sub in graph.subgraphs], graph.subgraph_factors)
return taylormap[graph.id]
end
end

rootid = -1
for g in PostOrderDFS(graph) # postorder traversal will visit all subdiagrams of a diagram first
rootid = g.id
if isleaf(g) || haskey(taylormap, g.id)
continue
end
taylormap[g.id] = apply(g.operator, [taylormap[sub.id] for sub in g.subgraphs], g.subgraph_factors)
end
return taylormap[rootid]

"""
function taylorexpansion!(graph::G, taylormap::Dict{Int,TaylorSeries{G}}(), var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}()) where {G<:Graph}

Return a taylor series of graph g. If variable dependence is not specified, by default, assume all leaves of graph depend on all variables. The taylor series of all nodes of graph is
saved in the taylormap dictionary.

#Arguments

- `graph` Target graph.
- `var_dependence::Dict{Int,Vector{Bool}}` The variables graph leaves depend on. Should map each leaf ID of g to a Vector{Bool},
indicating the taylor variables it depends on. By default, assumes all leaves depend on all variables.
- `taylormap::Dict{Int,TaylorSeries{G}}` The taylor series correponding to graph nodes. Should map each graph node ID (does not need to belong to input graph) to a taylor series.
All new taylor series generated by taylor expansion will be added into the expansion.
"""
function taylorexpansion!(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}(); taylormap::Dict{Int,TaylorSeries{G}}=Dict{Int,TaylorSeries{G}}()) where {G<:Graph}
dcerkoney marked this conversation as resolved.
Show resolved Hide resolved
_taylorexpansion!(graph, var_dependence; taylormap=taylormap)
return taylormap[graph.id], taylormap
end


function taylorexpansion!(graphs::Vector{G}, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}(); taylormap::Dict{Int,TaylorSeries{G}}=Dict{Int,TaylorSeries{G}}()) where {G<:Graph}
result = Vector{TaylorSeries{G}}()
for graph in graphs
push!(result, _taylorexpansion!(graph, var_dependence; taylormap=taylormap))
end
return result, taylormap
end


function taylorexpansion(graph::G, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}()) where {G<:Graph}
taylormap = Dict{Int,TaylorSeries{G}}()
_taylorexpansion!(graph, var_dependence; taylormap=taylormap)
return taylormap[graph.id], taylormap
end


function taylorexpansion(graphs::Vector{G}, var_dependence::Dict{Int,Vector{Bool}}=Dict{Int,Vector{Bool}}()) where {G<:Graph}
taylormap = Dict{Int,TaylorSeries{G}}()
result = Vector{TaylorSeries{G}}()
for graph in graphs
push!(result, _taylorexpansion!(graph, var_dependence; taylormap=taylormap))
end
return taylormap[graph.id], taylormap
end

"""
Expand Down Expand Up @@ -225,4 +252,22 @@ function chainrule!(varidx::Int, dg::Array{G,1}, leaftaylor::Dict{Int,TaylorSeri
end
end

function count_operation(g::TaylorSeries{G}) where {G<:Graph}
return count_operation(g.coeffs)
end

function count_operation(graphs::Vector{TaylorSeries{G}}) where {G<:Graph}
if length(graphs) == 0
return [0, 0]
else
allcoeffs = Vector{G}()
for g in graphs
for (order, coeffs) in g.coeffs
push!(allcoeffs, coeffs)
end
end
return count_operation(allcoeffs)
end
end

end
9 changes: 5 additions & 4 deletions test/diagram_tree.jl
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ end

DiagTree.uidreset()
# We only consider the direct part of the above diagram
spin = 2.0
spin = 1.0
D = 3
kF, β, mass2 = 1.919, 0.5, 1.0
Nk, Nt = 4, 2
Expand All @@ -107,13 +107,14 @@ end
# plot_tree(droot_dg)

DiagTree.eval!(root; eval=(x -> 1.0))
@test root.weight ≈ -2 + spin
factor = 1 / (2π)^D
@test root.weight ≈ (-2 + spin) * factor

DiagTree.eval!(droot_dg; eval=(x -> 1.0))
@test root.weight ≈ (-2 + spin) * 2
@test droot_dg.weight ≈ (-2 + spin) * 2 * factor

DiagTree.eval!(droot_dv; eval=(x -> 1.0))
@test root.weight ≈ (-2 + spin) * 2
@test droot_dv.weight ≈ (-2 + spin) * 2 * factor

# #more sophisticated test of the weight evaluation
varK = rand(D, Nk)
Expand Down
Loading
Loading