class RAMS::Expression

A RAMS::Expression is a dot product of variables, cofficients, and a constant offset:

3 * x1 + 1.5 * x3 - 4

Expressions must be linear. They can be added and subtracted.

Attributes

coefficients[R]
constant[R]

Public Class Methods

new(coefficients = {}, constant = 0.0) click to toggle source
# File lib/rams/expression.rb, line 14
def initialize(coefficients = {}, constant = 0.0)
  @coefficients = coefficients.dup
  @coefficients.default = 0.0
  @constant = constant.to_f
end

Public Instance Methods

*(other) click to toggle source
# File lib/rams/expression.rb, line 40
def *(other)
  if other.is_a? Numeric
    return Expression.new(coefficients.map do |v, c|
      [v, c * other]
    end.to_h, constant * other)
  end
  raise NotImplementedError
end
+(other) click to toggle source
# File lib/rams/expression.rb, line 24
def +(other)
  if other.is_a? Numeric
    return Expression.new({}, 0.0) unless other
    return Expression.new(coefficients, constant + other)
  end
  Expression.new add_coefficients(other), constant + other.constant
end
-(other) click to toggle source
# File lib/rams/expression.rb, line 32
def -(other)
  if other.is_a? Numeric
    return Expression.new({}, 0.0) unless other
    return Expression.new(coefficients, constant - other)
  end
  Expression.new add_coefficients(other, -1), constant - other.constant
end
-@() click to toggle source
# File lib/rams/expression.rb, line 20
def -@
  Expression.new coefficients.map { |v, c| [v, -c] }.to_h, -constant
end
/(other) click to toggle source
# File lib/rams/expression.rb, line 49
def /(other)
  if other.is_a? Numeric
    return Expression.new(coefficients.map do |v, c|
      [v, c / other]
    end.to_h, constant / other)
  end
  raise NotImplementedError
end
<=(other) click to toggle source
# File lib/rams/expression.rb, line 58
def <=(other)
  RAMS::Constraint.new(lhs(other), :<=, rhs(other))
end
==(other) click to toggle source
# File lib/rams/expression.rb, line 62
def ==(other)
  RAMS::Constraint.new(lhs(other), :==, rhs(other))
end
>=(other) click to toggle source
# File lib/rams/expression.rb, line 66
def >=(other)
  RAMS::Constraint.new(lhs(other), :>=, rhs(other))
end

Private Instance Methods

add_coefficients(other, sign = +1) click to toggle source
# File lib/rams/expression.rb, line 76
def add_coefficients(other, sign = +1)
  vars = merge_variables(other)
  vars.map do |v|
    [v, coefficients[v] + (sign * other.coefficients[v])]
  end.to_h
end
lhs(other) click to toggle source
# File lib/rams/expression.rb, line 83
def lhs(other)
  (self - other).coefficients
end
merge_variables(other) click to toggle source
# File lib/rams/expression.rb, line 72
def merge_variables(other)
  (coefficients.keys + other.coefficients.keys).uniq
end
rhs(other) click to toggle source
# File lib/rams/expression.rb, line 87
def rhs(other)
  return other - constant if other.is_a? Numeric
  other.constant - constant
end