class Modelling::Equation

Equation class

Constants

RESERVED_IDENTS

things which can’t be used as identifiers because they are built-in functions in MATLAB

Attributes

comments[RW]
formula[RW]
name[RW]

Public Class Methods

new(eq = nil, comment = "") click to toggle source
# File lib/modelling/equation.rb, line 19
def initialize(eq = nil, comment = "")
    @name = "equation_#{@@insts}"

    if eq
        @formula = self.from_matlab(eq)
    else
        @formula = "1"
    end
    @comments = comment
    @@insts += 1
end

Public Instance Methods

add(term) click to toggle source

add a term string

# File lib/modelling/equation.rb, line 63
def add(term)
    @formula = "(#{@formula}) + (#{term})"
end
all_idents() click to toggle source

get all identifiers in this formula

# File lib/modelling/equation.rb, line 68
def all_idents
    idents = []
    @formula.scan(/([A-Za-z_][_A-Za-z0-9]*)/) {|x| idents.push($1)}
    idents.uniq.reject { |e| RESERVED_IDENTS.include? e  }
end
from_matlab(matlab_eq) click to toggle source

Convert from MATLAB

Reads the formula from matlab, and does some normalising

# File lib/modelling/equation.rb, line 34
def from_matlab(matlab_eq)
    @formula = matlab_eq.gsub(/\.\.\..*([\n\r]+|$)/, "")                  .gsub(/\%.*([\n\r]+|$)/, "")                     .gsub(/\s*([\/*])\s*/, '\1')                     .gsub(/\s+/, " ")                                .gsub(/\s*\(\s*/, "(")                               .gsub(/\s*\)/, ")")                              .strip
    raise "Empty formula" if @formula == ""
    @formula
end
has_ident?(id) click to toggle source

Check if formula has an identifier

# File lib/modelling/equation.rb, line 58
def has_ident?(id)
    !@formula.match(/(^|[^_A-Za-z0-9])#{Regexp.quote(id)}($|[^_A-Za-z0-9])/).nil?
end
replace_ident(oldid, newid) click to toggle source

Replace an identifier

Replace an identifier and make sure it’s a whole word

# File lib/modelling/equation.rb, line 49
def replace_ident(oldid, newid)
    # sometimes matches overlap, so we do it a few times
    while @formula.match(/(^|[^_A-Za-z0-9])#{Regexp.quote(oldid)}($|[^_A-Za-z0-9])/)
        @formula = @formula.gsub(/(^|[^_A-Za-z0-9])#{Regexp.quote(oldid)}($|[^_A-Za-z0-9])/) { $1 + newid + $2}
    end
    @formula
end
to_s() click to toggle source
# File lib/modelling/equation.rb, line 74
def to_s
    @formula
end