I do not know how types work internally, so I’d like some advice on how to achieve high performance code. My script already takes into account the general performance tips: my helper functions _my_kernel_function(...)
only receive Vector
s and Matrix
s of specific type, these types never change in such functions, and I try to minimize the allocations in each function.
I have existing types Matrix{tw}
and SparseMatrixCSC{tw,tp}
. I create new ones, like:
abstract type AbstractMat{tw} end;
struct MatDPW{tu<:Integer, tv<:Integer, tw} <: AMat{tw}
#= A sparse matrix data-structure in the dictionary-of-positions-and-weights format. Element dct[(u,v)]=w represents a matrix entry X[u,v]=w. =#
size::Tuple{Int,Int}
dct::Dict{Tuple{tu,tv},tw}
end;
I’d like to have Matrix{tw}
and SparseMatrixCSC{tw,tp}
also be subtypes of AbstractMat{tw}
. How can this be achieved? I do not wish to wrap those two in a new struct just to be able to subtype it to AbstractMat{tw}
, I’d have to redefine all existing methods on Matrix{tw}
and SparseMatrixCSC{tw,tp}
to the two new structs.
I’d like to minimize any performance penalties from passing my AbstractMat{tw}
s to functions. Probably the following is not a good idea?
const global AbstractMat ::Type = Union{Matrix,SparseMatrixCSC, MatDPW}
julia> function my_func(X::AbstractMat{tw}) where {tw}
return size(X)
end
ERROR: TypeError: in Type{...} expression, expected UnionAll, got Type{AbstractMat}
Stacktrace:
[1] top-level scope
@ REPL[30]:1
Also, how do I create new functions that take as input Vector
s of AbstractMat
s (e.g. Matrix
and MatDPW
can be in the same Vector
)?
function SparseArrays.nnz(XX::Vector{<:AbstractMat{tw}}) where {tw}
return sum(nnz(X) for X in XX)
end
function SparseArrays.nnz(XXX::Vector{Vector{<:AbstractMat{tw}}}) where {tw}
return sum(nnz(XX[end]) for XX in XXX)
end
julia> nnz([X,Y])
48
julia> nnz([[X],[Y]])
ERROR: MethodError: no method matching nnz(::Vector{Vector})