Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Programmatic construction of sparse symbolic arrays #1319

Open
johannesnauta opened this issue Oct 21, 2024 · 1 comment
Open

Programmatic construction of sparse symbolic arrays #1319

johannesnauta opened this issue Oct 21, 2024 · 1 comment

Comments

@johannesnauta
Copy link

As mentioned in this discussion on Discourse, I am trying to programmatically construct symbols using sparse arrays. That is to say, I would like to programmatically generate/define a sparse array for which the non-zero entries are of type Sym, that can then subsequently be used in symbolic calculations and or other modules (e.g., ModelingToolkit.jl/DifferentialEquations.jl).

In general, I would be happy to use existing sparse array packages, like SparseArrays, and convert the sparse arrays to symbolic ones, i.e. something along the lines of

julia> a = sprand(10, 10, 0.1)
julia> nzrows, nzcols, nzvals = findnz(a)
julia> for (row,col) in zip(nzrows,nzcols)
           ## Make symbols A[row,col] B[row,col]
       end
julia> A*B
(A*B)[Base.OneTo(10),Base.OneTo(10)]

Is this possible? If yes, how? If not, how should I proceed? Note that the above example is just an illustrative example of what I would like to achieve. My personal use-case is to use sparse arrays as input variables of ODESystems (see the mentioned discussion), but in general I believe creating sparse array symbols that support sparse array methods can perhaps be useful.

If this is not the right place, or if anything is unclear, please let me know. Thanks a lot.

@AlCap23
Copy link
Contributor

AlCap23 commented Nov 11, 2024

I think this is not 100% what you have in mind, but it should work roughly.

using SparseArrays
using Symbolics

a = sprand(10, 10, 0.1)
nzrows, nzcols, nzvals = findnz(a)

A = map(CartesianIndices(a)) do id
    iszero(a[id]) && return Num(0) # Gets detected
    Symbolics.variable(:A, Tuple(id)...) # Return a variable for a nonzero entry
end |> SparseMatrixCSC # Wrap in SparseMatrix

(A*A')[Base.OneTo(10),Base.OneTo(10)] # Still sparse

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants