class MIPPeR::LinExpr

Attributes

terms[R]

Public Class Methods

new(terms = {}) click to toggle source
# File lib/mipper/expression.rb, line 5
def initialize(terms = {})
  @terms = terms
end

Public Instance Methods

+(other) click to toggle source

Add two {LinExpr}s

# File lib/mipper/expression.rb, line 10
def +(other)
  case other
  when LinExpr
    # Add the terms of two expressions
    # For now, this assumes variables are not duplicated
    LinExpr.new(@terms.merge(other.terms) { |_, c1, c2| c1 + c2 })
  when Variable
    # Add the variable to the expression
    self + other * 1.0
  else
    fail TypeError
  end
end
add(other) click to toggle source

Add terms from the other expression to this one

# File lib/mipper/expression.rb, line 25
def add(other)
  case other
  when LinExpr
    @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 }
  when Variable
    if @terms.key? other
      @terms[other] += 1.0
    else
      @terms[other] = 1.0
    end
  else
    fail TypeError
  end

  self
end
inspect() click to toggle source

Produce a string representing the expression

# File lib/mipper/expression.rb, line 43
def inspect
  @terms.map do |var, coeff|
    # Skip if the coefficient is zero or the value is zero
    value = var.value
    next if coeff == 0 || value == 0 || value == false

    coeff == 1 ? var.name : "#{var.name} * #{coeff}"
  end.compact.join(' + ')
end