Class: SCS::Matrix

Inherits:
Object
  • Object
show all
Defined in:
lib/scs/matrix.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(m, n) ⇒ Matrix

Returns a new instance of Matrix.



5
6
7
8
9
# File 'lib/scs/matrix.rb', line 5

def initialize(m, n)
  @m = m
  @n = n
  @data = {}
end

Instance Attribute Details

#mObject (readonly)

Returns the value of attribute m.



3
4
5
# File 'lib/scs/matrix.rb', line 3

def m
  @m
end

#nObject (readonly)

Returns the value of attribute n.



3
4
5
# File 'lib/scs/matrix.rb', line 3

def n
  @n
end

Class Method Details

.from_dense(data) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/scs/matrix.rb', line 57

def self.from_dense(data)
  data = data.to_a
  m = data.size
  n = m > 0 ? data.first.size : 0

  mtx = Matrix.new(m, n)
  data.each_with_index do |row, i|
    raise ArgumentError, "row has different number of columns" if row.size != n
    row.each_with_index do |v, j|
      mtx[i, j] = v if v != 0
    end
  end
  mtx
end

Instance Method Details

#[]=(row_index, column_index, value) ⇒ Object

Raises:

  • (IndexError)


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/scs/matrix.rb', line 11

def []=(row_index, column_index, value)
  raise IndexError, "row index out of bounds" if row_index < 0 || row_index >= @m
  raise IndexError, "column index out of bounds" if column_index < 0 || column_index >= @n
  # dictionary of keys, optimized for converting to CSC
  # TODO try COO for performance
  if value == 0
    (@data[column_index] ||= {}).delete(row_index)
  else
    (@data[column_index] ||= {})[row_index] = value
  end
end

#initialize_copy(other) ⇒ Object



52
53
54
55
# File 'lib/scs/matrix.rb', line 52

def initialize_copy(other)
  super
  @data = @data.transform_values(&:dup)
end

#nnzObject

private, for tests



48
49
50
# File 'lib/scs/matrix.rb', line 48

def nnz
  @data.sum { |_, v| v.count }
end

#to_cscObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/scs/matrix.rb', line 23

def to_csc
  cx = []
  ci = []
  cp = []

  # CSC format
  # https://www.gormanalysis.com/blog/sparse-matrix-storage-formats/
  cp << 0
  n.times do |j|
    (@data[j] || {}).sort_by { |k, v| k }.each do |k, v|
      cx << v
      ci << k
    end
    # cumulative column values
    cp << cx.size
  end

  {
    start: cp,
    index: ci,
    value: cx
  }
end