Class: Guruby::Variable

Inherits:
Object
  • Object
show all
Defined in:
lib/guruby/var.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lb, ub, coeff, type, name = nil) ⇒ Variable

Returns a new instance of Variable.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/guruby/var.rb', line 5

def initialize(lb, ub, coeff, type, name = nil)
  @lower_bound = lb
  @upper_bound = ub
  @coefficient = coeff
  @type = type
  @name = name

  # These will be populated when this is added to a model
  @model = nil
  @index = nil
end

Instance Attribute Details

#coefficientObject (readonly)

Returns the value of attribute coefficient.



3
4
5
# File 'lib/guruby/var.rb', line 3

def coefficient
  @coefficient
end

#lower_boundObject

Returns the value of attribute lower_bound.



3
4
5
# File 'lib/guruby/var.rb', line 3

def lower_bound
  @lower_bound
end

#modelObject (readonly)

Returns the value of attribute model.



3
4
5
# File 'lib/guruby/var.rb', line 3

def model
  @model
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/guruby/var.rb', line 3

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/guruby/var.rb', line 3

def type
  @type
end

#upper_boundObject

Returns the value of attribute upper_bound.



3
4
5
# File 'lib/guruby/var.rb', line 3

def upper_bound
  @upper_bound
end

Instance Method Details

#*(coeff) ⇒ Object

Create a LinExpr consisting of a single term which is this variable multiplied by a constant



51
52
53
54
55
# File 'lib/guruby/var.rb', line 51

def *(coeff)
  fail TypeError unless coeff.is_a? Numeric

  LinExpr.new({ self => coeff })
end

#+(other) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/guruby/var.rb', line 57

def +(other)
  case other
  when LinExpr
    other + self * 1.0
  when Variable
    LinExpr.new({self => 1.0, other => 1.0})
  else
    fail TypeError
  end
end

#inspectObject

Produce the name of the variable and the value if the model is solved



69
70
71
72
73
74
75
76
77
# File 'lib/guruby/var.rb', line 69

def inspect
  if @model && @model.status == GRB_OPTIMAL
    value = self.value
  else
    value = '?'
  end

  "#{@name} = #{value}"
end

#valueObject

Get the final value of this variable



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/guruby/var.rb', line 30

def value
  # Model must be solved to have a value
  return nil unless @model && @model.status == GRB_OPTIMAL

  dblptr = FFI::MemoryPointer.new :pointer
  Gurobi::GRBgetdblattrarray @model.instance_variable_get(:@ptr),
                             GRB_DBL_ATTR_X, @index, 1, dblptr
  value = dblptr.read_array_of_double(1)[0]

  case @type
  when GRB_INTEGER
    value.round
  when GRB_BINARY
    [false, true][value.round]
  else
    value
  end
end