Flux.jl/src/treelike.jl

40 lines
824 B
Julia
Raw Normal View History

2017-09-27 20:11:21 +00:00
children(x) = ()
mapchildren(f, x) = x
2017-10-31 16:37:41 +00:00
children(x::Tuple) = x
mapchildren(f, x::Tuple) = map(f, x)
2017-09-27 20:11:21 +00:00
function treelike(T, fs = fieldnames(T))
@eval begin
children(x::$T) = ($([:(x.$f) for f in fs]...),)
mapchildren(f, x::$T) = $T(f.(children(x))...)
end
end
2017-10-16 23:07:15 +00:00
isleaf(x) = isempty(children(x))
2017-09-27 20:11:21 +00:00
2017-10-17 00:08:15 +00:00
function mapleaves(f, x; cache = ObjectIdDict())
haskey(cache, x) && return cache[x]
cache[x] = isleaf(x) ? f(x) : mapchildren(x -> mapleaves(f, x, cache = cache), x)
end
2017-09-27 20:58:34 +00:00
2017-10-17 16:35:30 +00:00
export mapparams
@deprecate mapparams(f, x) mapleaves(f, x)
2017-09-27 20:58:34 +00:00
using DataFlow: OSet
2017-09-27 20:11:21 +00:00
2017-10-19 16:21:08 +00:00
function prefor(f, x; seen = OSet())
2017-10-17 00:08:15 +00:00
x seen && return
2017-10-19 16:21:08 +00:00
f(x)
foreach(x -> prefor(f, x, seen = seen), children(x))
2017-10-17 00:08:15 +00:00
return
end
2017-09-27 20:11:21 +00:00
function params(m)
2017-10-17 00:08:15 +00:00
ps = []
2017-10-19 16:21:08 +00:00
prefor(p -> p isa TrackedArray && push!(ps, p), m)
2017-10-10 11:16:32 +00:00
return ps
2017-09-27 20:11:21 +00:00
end
2017-11-07 19:34:35 +00:00
params(m...) = params(m)