Class: Glpk::Problem

Inherits:
Object
  • Object
show all
Defined in:
lib/glpk/problem.rb

Instance Method Summary collapse

Constructor Details

#initializeProblem

Returns a new instance of Problem.



3
4
5
6
# File 'lib/glpk/problem.rb', line 3

def initialize
  @model = FFI.glp_create_prob
  @model.free = FFI["glp_delete_prob"]
end

Instance Method Details

#freeObject



8
9
10
11
12
# File 'lib/glpk/problem.rb', line 8

def free
  model.free = nil
  FFI.glp_delete_prob(model)
  @model = nil
end

#load_problem(obj_dir:, obj_coef:, mat_ia:, mat_ja:, mat_ar:, col_kind:, col_lower:, col_upper:, row_lower:, row_upper:) ⇒ Object



14
15
16
17
18
19
20
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
48
49
50
51
52
53
54
55
56
# File 'lib/glpk/problem.rb', line 14

def load_problem(obj_dir:, obj_coef:, mat_ia:, mat_ja:, mat_ar:, col_kind:, col_lower:, col_upper:, row_lower:, row_upper:)
  num_cols = col_lower.size
  num_rows = row_lower.size
  ne = mat_ia.size

  # some checks will always pass
  check_size(obj_coef, num_cols)
  check_size(mat_ia, ne)
  check_size(mat_ja, ne)
  check_size(mat_ar, ne)
  check_size(col_kind, num_cols)
  check_size(col_lower, num_cols)
  check_size(col_upper, num_cols)
  check_size(row_lower, num_rows)
  check_size(row_upper, num_rows)

  FFI.glp_erase_prob(model)
  FFI.glp_add_rows(model, num_rows) if num_rows > 0
  FFI.glp_add_cols(model, num_cols)

  obj_coef.each_with_index do |v, i|
    FFI.glp_set_obj_coef(model, i + 1, v)
  end
  FFI.glp_set_obj_dir(model, FFI::OBJ_DIR.fetch(obj_dir))

  # indexing starts at 1
  ia = [0] + mat_ia
  ja = [0] + mat_ja
  ar = [0] + mat_ar
  FFI.glp_load_matrix(model, ne, int_array(ia), int_array(ja), double_array(ar))

  col_kind.each_with_index do |k, i|
    FFI.glp_set_col_kind(model, i + 1, FFI::COL_KIND.fetch(k))
  end

  col_lower.zip(col_upper).each_with_index do |(lb, ub), i|
    FFI.glp_set_col_bnds(model, i + 1, 4, lb, ub)
  end

  row_lower.zip(row_upper).each_with_index do |(lb, ub), i|
    FFI.glp_set_row_bnds(model, i + 1, row_type(lb, ub), lb, ub)
  end
end

#read_lp(filename) ⇒ Object



58
59
60
# File 'lib/glpk/problem.rb', line 58

def read_lp(filename)
  check_status FFI.glp_read_lp(model, nil, filename)
end

#read_mps(filename) ⇒ Object



62
63
64
# File 'lib/glpk/problem.rb', line 62

def read_mps(filename)
  check_status FFI.glp_read_mps(model, 2, nil, filename)
end

#solve(**options) ⇒ Object



74
75
76
77
78
79
80
# File 'lib/glpk/problem.rb', line 74

def solve(**options)
  if FFI.glp_get_num_int(model) > 0
    solve_mip(**options)
  else
    solve_lp(**options)
  end
end

#write_lp(filename) ⇒ Object



66
67
68
# File 'lib/glpk/problem.rb', line 66

def write_lp(filename)
  check_status FFI.glp_write_lp(model, nil, filename)
end

#write_mps(filename) ⇒ Object



70
71
72
# File 'lib/glpk/problem.rb', line 70

def write_mps(filename)
  check_status FFI.glp_write_mps(model, 2, nil, filename)
end