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 AbstractVectors 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_kron64-element reshape(transpose(::Matrix{Float64}), 64) with eltype Float64:
0.13596288339610935
0.11031482834583692
0.18513093435682995
0.8920762039881974
0.14206044642190185
0.10542084299986391
0.1757260900695838
0.7527638964713262
0.09956358320591711
0.106752172172626
⋮
0.9095334122512186
0.11231217896614316
0.12159691502272371
0.1899599075245275
0.6141525556687356
0.056213307897891335
0.04790333992844833
0.04236522174928477
0.19014607685196377For 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}:
41.2945721446925
-71.27510553617826
-35.64840305939155
36.12716555170891