Sparse matrices

Hi all,

Guys, would you please recommend me the best way to work with sparse matrices in OCaml these days? I don’t need anything funny: create, set, get, save, load - are necessary, everything else would be bonus.

Up to Feb 15, 2023 something very similar to what I need was in Owl. But now it’s gone.

Please, help :slight_smile:

1 Like

Apologies in advance, this is a non-answer, but I can’t seem to find anything dealing with sparse matrices either.

It looks like this was removed from owl to remove the dependency on eigen. gsl has sparse matrices, but the bindings are not yet there in ocaml-gsl - @mmottl is seeking contributions.

I suspect you have some actual linear algebra related requirements that are not listed, but if you truly just need the things you list, here’s a poor person’s sparse matrix:

type t = {
  data : ((int*int),float) Hashtbl.t;
  nr : int;
  nc : int;

let create nr nc = {
  data = Hashtbl.create 100;

let check_indices m i j =
  assert (i <;
  assert (j <

let get m i j =
  check_indices m i j;
  match Hashtbl.find_opt (i,j) with
  | Some x -> x
  | None -> 0.

let set m i j v =
  check_indices m i j;
  Hashtbl.replace (i,j) v

Use Marshal to save or load if you’re not communicating across compiler versions.

This isn’t an answer, but … from what I understand the interface between Rust and OCaml is pretty decent? If so, you might try to wrapper the sprs package. It’s a pretty complete implementation of sparse matrices: I remember it had good support for CSR, and maybe the other relevant formats too (though I forget).

Second: I see searching that there’s a scipy package in opam. No idea if it’s any good.

And last: you might think about just mimicking sprs and implementing CSR matrices in OCaml. It’d be tedious, but given you can just mimick the Rust code, it might go faster than you fear.

1 Like