Demonstration of Operator Algebras and Kron
Let M
, D
, F
be matrix-based, diagonal-matrix-based, and function-based SciMLOperators
respectively. Here are some examples of composing operators in order to build more complex objects and using their operations.
using SciMLOperators, LinearAlgebra
N = 4
function f(v, u, p, t)
u .* v
end
function f(w, v, u, p, t)
w .= u .* v
end
u = rand(4)
p = nothing # parameter struct
t = 0.0 # time
M = MatrixOperator(rand(N, N))
D = DiagonalOperator(rand(N))
F = FunctionOperator(f, zeros(N), zeros(N); u, p, t)
FunctionOperator(4 × 4)
Then, the following codes just work.
L1 = 2M + 3F + LinearAlgebra.I + rand(N, N)
L2 = D * F * M'
L3 = kron(M, D, F)
L4 = lu(M) \ D
L5 = [M; D]' * [M F; F D] * [F; D]
((((MatrixOperator(4 × 4) * MatrixOperator(4 × 4)) + (DiagonalOperator(4 × 4) * FunctionOperator(4 × 4))) * FunctionOperator(4 × 4)) + (((MatrixOperator(4 × 4) * FunctionOperator(4 × 4)) + (DiagonalOperator(4 × 4) * DiagonalOperator(4 × 4))) * DiagonalOperator(4 × 4)))
Each L#
can be applied to AbstractVector
s of appropriate sizes:
v = rand(N)
w = L1(v, u, p, t) # == L1 * v
v_kron = rand(N^3)
w_kron = L3(v_kron, u, p, t) # == L3 * v_kron
64-element reshape(transpose(::Matrix{Float64}), 64) with eltype Float64:
0.3037537081329361
0.02788995030849714
0.11315022015324339
0.23501813132264512
0.7483101513669096
0.03861285155251637
0.8357846305318882
0.37922942335011933
0.3246219409411543
0.03202146320499467
⋮
0.22884894287389904
0.19391047790506727
0.017899380551064034
0.6610210414681349
0.449299250547997
0.06791797393886427
0.018083566813692237
0.290051432278971
0.16382097327779013
For mutating operator evaluations, call cache_operator
to generate an in-place cache, so the operation is nonallocating.
α, β = rand(2)
# allocate cache
L2 = cache_operator(L2, u)
L4 = cache_operator(L4, u)
# allocation-free evaluation
L2(w, v, u, p, t) # == mul!(w, L2, v)
L4(w, v, u, p, t, α, β) # == mul!(w, L4, v, α, β)
4-element Vector{Float64}:
-0.045203526334529835
0.05450702399847072
0.5202561171191985
0.08090978986693505