module - 覆盖自定义 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 中定义)添加一个方法。
推荐阅读
- jquery - 无法从数组中获取相关值,出现 Uncaught TypeError "Cannot use 'in' operator to search 'length"
- r - 更改 gtsummary::tbl_merge 中的空单元格
- c++ - 如何在我的 C++ 库中包含来自另一个库的 pdb 信息
- reactjs - setState 不改变数据
- azure - 监视 Azure 函数何时缩放
- javascript - Angular js安装外部库无法实例化模块npm
- c# - 如何在运行时只知道泛型类型参数的字符串名称动态调用泛型方法?
- firebase - Flutter:通过存储库对 Firebase Firestore 进行单元测试
- powershell - 需要帮助将本地用户日期导出到 csv ... powershell
- jquery - 我正在尝试获取元素并将它们添加到新元素中