-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathallocfree.jl
More file actions
66 lines (56 loc) · 1.69 KB
/
allocfree.jl
File metadata and controls
66 lines (56 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function identity_scenarios(x::Number; dx::Number, dy::Number)
f = identity
dy_from_dx = dx
dx_from_dy = dy
der = one(x)
return [
Scenario{:pushforward,:out}(f, x, (dx,); res1=(dy_from_dx,)),
Scenario{:pullback,:out}(f, x, (dy,); res1=(dx_from_dy,)),
Scenario{:derivative,:out}(f, x; res1=der),
]
end
function sum_scenarios(x::AbstractArray; dx::AbstractArray, dy::Number)
f = sum
dy_from_dx = sum(dx)
dx_from_dy = (similar(x) .= dy)
grad = similar(x)
grad .= one(eltype(x))
return [
Scenario{:pushforward,:out}(f, x, (dx,); res1=(dy_from_dx,)),
Scenario{:pullback,:in}(f, x, (dy,); res1=(dx_from_dy,)),
Scenario{:gradient,:in}(f, x; res1=grad),
]
end
function copyto!_scenarios(x::AbstractArray; dx::AbstractArray, dy::AbstractArray)
f! = copyto!
y = similar(x)
f!(y, x)
dy_from_dx = dx
dx_from_dy = dy
jac = Matrix(Diagonal(ones(eltype(x), length(x))))
return [
Scenario{:pushforward,:in}(f!, y, x, (dx,); res1=(dy_from_dx,)),
Scenario{:pullback,:in}(f!, y, x, (dy,); res1=(dx_from_dy,)),
Scenario{:jacobian,:in}(f!, y, x; res1=jac),
]
end
"""
allocfree_scenarios()
Create a vector of [`Scenario`](@ref)s with functions that do not allocate.
!!! warning
At the moment, second-order scenarios are excluded.
"""
function allocfree_scenarios()
x_ = 0.42
dx_ = 3.14
dy_ = -1 / 12
x_6 = float.(1:6)
dx_6 = float.(-1:-1:-6)
dy_6 = float.(-5:2:5)
scens = vcat(
identity_scenarios(x_; dx=dx_, dy=dy_), #
sum_scenarios(x_6; dx=dx_6, dy=dy_),
copyto!_scenarios(x_6; dx=dx_6, dy=dy_6),
)
return scens
end