Class: OSQP::Solver

Inherits:
Object
  • Object
show all
Defined in:
lib/osqp/solver.rb

Instance Method Summary collapse

Instance Method Details

#setup(p, q, a, l, u, **settings) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/osqp/solver.rb', line 3

def setup(p, q, a, l, u, **settings)
  # settings
  set = create_settings(settings)

  # ensure bounds within OSQP infinity
  l = l.map { |v| v < -FFI::OSQP_INFTY ? -FFI::OSQP_INFTY : v }
  u = u.map { |v| v > FFI::OSQP_INFTY ? FFI::OSQP_INFTY : v }

  # data
  # do not assign directly to struct to keep refs
  p = csc_matrix(p, upper: true)
  q = float_array(q)
  a = csc_matrix(a)
  l = float_array(l)
  u = float_array(u)

  data = FFI::Data.malloc
  data.n = a.n
  data.m = a.m
  data.p = matrix_ptr(p)
  data.q = q
  data.a = matrix_ptr(a)
  data.l = l
  data.u = u

  # work
  work = FFI::Workspace.malloc
  check_result FFI.osqp_setup(work.to_ptr.ref, data, set)
  @work = work
end

#solve(*args, **settings) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/osqp/solver.rb', line 34

def solve(*args, **settings)
  setup(*args, **settings) if args.any? || settings.any?

  check_result FFI.osqp_solve(@work)

  # solution
  solution = FFI::Solution.new(@work.solution)
  data = FFI::Data.new(@work.data)
  x = read_float_array(solution.x, data.n)
  y = read_float_array(solution.y, data.m)

  # info
  info = FFI::Info.new(@work.info)

  # TODO prim_inf_cert and dual_inf_cert
  {
    x: x,
    y: y,
    iter: info.iter,
    status: read_string(info.status),
    status_val: info.status_val,
    status_polish: info.status_polish,
    obj_val: info.obj_val,
    pri_res: info.pri_res,
    dua_res: info.dua_res,
    setup_time: info.setup_time,
    solve_time: info.solve_time,
    update_time: info.update_time,
    polish_time: info.polish_time,
    run_time: info.run_time,
    rho_estimate: info.rho_estimate,
    rho_updates: info.rho_updates
  }
end

#warm_start(x, y) ⇒ Object

Raises:



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/osqp/solver.rb', line 69

def warm_start(x, y)
  # check dimensions
  m, n = dimensions
  raise Error, "Expected x to be size #{n}, got #{x.size}" if x && x.size != n
  raise Error, "Expected y to be size #{m}, got #{y.size}" if y && y.size != m

  if x && y
    check_result FFI.osqp_warm_start(@work, float_array(x), float_array(y))
  elsif x
    check_result FFI.osqp_warm_start_x(@work, float_array(x))
  elsif y
    check_result FFI.osqp_warm_start_y(@work, float_array(y))
  else
    raise Error, "Must set x or y"
  end
end