Module: CTioga2::Utils

Defined in:
lib/ctioga2/utils.rb

Overview

Various utilities

Class Method Summary collapse

Class Method Details

.cnk(n, k) ⇒ Object

Binomial coefficients (for the smooth filter)



134
135
136
137
138
139
# File 'lib/ctioga2/utils.rb', line 134

def self.cnk(n,k)
  res = 1.0
  n.downto(n - k) { |i| res *= i}
  k.downto(1) {|i| res = res/i }
  return res
end

.mix_objects(a, b, r) ⇒ Object

Takes two arrays of the same size (vectors) and mix them a * r + b * (1 - r)



109
110
111
112
113
114
115
# File 'lib/ctioga2/utils.rb', line 109

def self.mix_objects(a,b,r)
  ret = a.dup
  a.each_index do |i|
    ret[i] = a[i] * r + b[i] * (1 - r)
  end
  return ret
end

.parse_formula(formula, parameters = nil, header = nil) ⇒ Object

This converts a text formula that can contain:

  • any litteral thing

  • references to columns in the form of $1 for column 1 (ie the second one)

  • references to named columns in the form $name$

  • references to parameters

The return value is ready to be passed to Dvector.compute_formula



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/ctioga2/utils.rb', line 149

def self.parse_formula(formula, parameters = nil, header = nil)
  formula = formula.dup
  if parameters
    for k,v in parameters
      formula.gsub!(/\b#{k}\b/, v.to_s)
    end
  end
  formula.gsub!(/\$(\d+)/, 'column[\1]')
  if header
    for k,v in header
      formula.gsub!("$#{k}$", "column[#{v}]")
    end
  end
  return formula
end

.pdftex_quote_string(str) ⇒ Object

Quotes a string so it can be included directly within a pdfinfo statement (for instance).



119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/ctioga2/utils.rb', line 119

def self.pdftex_quote_string(str)
  return str.gsub(/([%#])|([()])|([{}~_^])|\\/) do 
    if $1
      "\\#{$1}"
    elsif $2                  # Quoting (), as they can be quite nasty !!
      "\\string\\#{$2}"
    elsif $3
      "\\string#{$3}"
    else                      # Quoting \
      "\\string\\\\"
    end
  end
end

.shell_quote_string(str) ⇒ Object

Takes a string a returns a quoted version that should be able to go through shell expansion.



94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/ctioga2/utils.rb', line 94

def self.shell_quote_string(str)
  if str =~ /[\s"*$()\[\]{}';\\]/
    if str =~ /'/
      a = str.gsub(/(["$\\])/) { "\\#$1" }
      return "\"#{a}\""
    else 
      return "'#{str}'"
    end
  else
    return str
  end
end