Class: OSQP::Matrix

Inherits:
Object
  • Object
show all
Defined in:
lib/osqp/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/osqp/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/osqp/matrix.rb', line 3

def m
  @m
end

#nObject (readonly)

Returns the value of attribute n.



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

def n
  @n
end

Class Method Details

.from_dense(data) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/osqp/matrix.rb', line 49

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
# File 'lib/osqp/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
  if value == 0
    (@data[column_index] ||= {}).delete(row_index)
  else
    (@data[column_index] ||= {})[row_index] = value
  end
end

#to_ptrObject



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

def to_ptr
  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

  nnz = cx.size
  cx = Utils.float_array(cx)
  ci = Utils.int_array(ci)
  cp = Utils.int_array(cp)

  ptr = FFI.csc_matrix(m, n, nnz, cx, ci, cp)
  # save refs
  ptr.instance_variable_set(:@osqp_refs, [cx, ci, cp])
  ptr
end