~kb/sparse

7e066be399500dde8ad0c7787d6574fee28cd093 — Kim Burgess 3 years ago e6876df main
Stub Matrix type
3 files changed, 53 insertions(+), 0 deletions(-)

A spec/sparse/matrix_spec.cr
A src/sparse/matrix.cr
M src/sparse/vector.cr
A spec/sparse/matrix_spec.cr => spec/sparse/matrix_spec.cr +16 -0
@@ 0,0 1,16 @@
require "../spec_helper"

describe Sparse::Matrix do
  describe ".new" do
    it "initializes with an empty element set" do
      Sparse::Matrix(UInt8, 10000, 10000).new
    end

    it "supports pre-allocation for element storage" do
      Sparse::Matrix(UInt8, 10000, 10000).new initial_capacity: 500
      expect_raises(IndexError) do
        Sparse::Matrix(UInt8, 10, 10).new initial_capacity: 500
      end
    end
  end
end

A src/sparse/matrix.cr => src/sparse/matrix.cr +32 -0
@@ 0,0 1,32 @@
module Sparse
  # `Sparse::Matrix` provides the ability to model matrices with up 2^64 rows
  # and 2^64 columns and perform type-safe operations on these.
  #
  # It stores set elemenents only in compressed sparse column form, with all
  # other elements assumed to be T.zero.
  struct Matrix(T, M, N)

    @row : Array(UInt64)
    @col : Array(UInt64)
    @val : Array(T)

    def initialize(initial_capacity : Int = 0)
      raise IndexError.new if initial_capacity > (M * N)
      @row = typeof(@row).new
      @col = typeof(@col).new
      @val = typeof(@val).new initial_capacity
    end

    # :nodoc:
    def initialize(@row, @col, @val)
    end

    # Creates a new `Matrix` with the same domain, size and contents.
    def dup : Matrix(T, M, N)
      row = @row.dup
      vol = @col.dup
      val = @val.dup
      Matrix(T, M, N).new row, col, val
    end
  end
end

M src/sparse/vector.cr => src/sparse/vector.cr +5 -0
@@ 1,6 1,11 @@
require "set"

module Sparse
  # `Sparse::Vector`'s provides the ability to model and work wth sparesly
  # populated Vectors or with up to 2^64 dimensions.
  #
  # Only set elements are stored in a compressed form. Any element that has not
  # been explicitly set is assumed to be T.zero.
  struct Vector(T, N)
    include Indexable(T)