重写自定义Julia结构的反斜杠



我正在通过扩展LinearAlgebra模块中的功能来创建一个自定义矩阵库。我一直在通过在自定义MyLinearAlgebra模块中创建自定义结构来实现这一点,该模块直接导入默认的线性代数结构并覆盖许多常见的LA功能。我的问题特别是关于如何覆盖反斜杠函数。这是我的"MyLinearAlgebra.jl":

module MyLinearAlgebra
import LinearAlgebra
import Base: getindex, setindex!, size
export
# Types
LocalMatrix,
SolutionVector,
# Functions
lp_error!,
lp_norm,
true_size
include("SolutionVector.jl")
include("LocalMatrix.jl")
end

现在只关注LocalMatrix.jl,我有:

"""
struct LocalMatrix{T} <: AbstractMatrix{T}
Block diagonal structure for local matrix. `A[:,:,iS,iK]` is a block matrix for
state iS and element iK
"""
struct LocalMatrix{T} <: AbstractMatrix{T}
data::Array{T,4}
factorizations::Array{Any,2}
function LocalMatrix(data::Array{T,4}) where {T}
new{T}(data,Array{Any}(undef, size(data,3), size(data,4)))
end
end
# [... a lot of things that are already working including: ldiv!]
"""
ldiv!(A::LocalMatrix, x::SolutionVector)
In-place linear solve A\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function LinearAlgebra.ldiv!(A::LocalMatrix, x::SolutionVector)
println("my ldiv! works fine")
x
end

# [ ... and yet this does not work ]
"""
A::LocalMatrix \ x::SolutionVector
Linear solve A\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function ()(A::LocalMatrix, x::SolutionVector)
println("my \ never prints out in any tests")
(m,n,ns,ne) = size(A.data)
(nx,nsx,nex) = size(x.data)
@assert n == nx && ne == nex && m == n
b = deepcopy(x)
LinearAlgebra.ldiv!(A, b)
end

在我的测试中,我可以完全按照预期使用ldiv!函数,但我不能使用函数——它只是使用了在其他地方编写的一些标准实现。我相信这可能是因为我的反斜杠函数不符合LinearAlgebra反斜杠函数的条件,但我不确定。尝试将函数限定为LinearAlgebra.()(A::LocalMatrix, x::SolutionVector)失败,返回语法错误invalid function name。有没有其他方法可以做到这一点,或者我错过了关于模块的一些更基本的东西?

是在Base中定义的,因此:

julia> "a"  "b"
ERROR: MethodError: no method matching adjoint(::String)
julia> Base.:(::String, ::String) = "hello"
julia> "a"  "b"
"hello"

然而,由于它被导入到LinearAlgebra,以下内容也适用于我(我使用的是新会话(:

julia> using LinearAlgebra
julia> "a"  "b"
ERROR: MethodError: no method matching adjoint(::String)
julia> LinearAlgebra.:(::String, ::String) = "hello"
julia> "a"  "b"
"hello"

因为Julia将向相同的函数(在Base中定义(添加一个方法。

相关内容

  • 没有找到相关文章

最新更新