File: powell.rb

package info (click to toggle)
ruby-minimization 0.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 232 kB
  • sloc: ruby: 1,243; makefile: 3
file content (319 lines) | stat: -rw-r--r-- 10,451 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# = powell.rb -
# Minimization- Minimization algorithms on pure Ruby
# Copyright (C) 2010 Claudio Bustos
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# This algorith was adopted and ported into Ruby from Apache-commons
# Math library's PowellOptimizer.java and
# BaseAbstractMultivariateVectorOptimizer.java 
# files. Therefore this file is under Apache License Version 2.
#
# Powell's Algorithm for Multidimensional minimization
require "#{File.expand_path(File.dirname(__FILE__))}/point_value_pair.rb"
require "#{File.expand_path(File.dirname(__FILE__))}/../minimization.rb"

module Minimization
  class ConjugateDirectionMinimizer
    attr_accessor :max_iterations
    attr_accessor :max_brent_iterations
    attr_accessor :x_minimum
    attr_accessor :f_minimum

    # default maximum Powell's iteration value
    Max_Iterations_Default      = 100
    # default Brent iteration value
    MAX_BRENT_ITERATION_DEFAULT = 10   # give a suitable value

    def initialize(f, initial_guess, lower_bound, upper_bound)
      @iterations           = 0
      @max_iterations       = Max_Iterations_Default
      @evaluations          = 0
      @max_brent_iterations = MAX_BRENT_ITERATION_DEFAULT
      @converging           = true

      # set minimizing function
      @f                    = f
      @start                = initial_guess
      @lower_bound          = lower_bound
      @upper_bound          = upper_bound

      # set maximum and minimum coordinate value a point can have
      # while minimization process
      @min_coordinate_val   = lower_bound.min
      @max_coordinate_val   = upper_bound.max

      # validate input parameters
      check_parameters
    end

    # return the convergence of the search
    def converging?
      return @converging
    end

    # set minimization function
    def f(x)
      @f.call(x)
    end
    
    # validate input parameters
    def check_parameters
      if (!@start.nil?)
        dim = @start.length
        if (!@lower_bound.nil?)
          # check for dimension mismatches
          raise "dimension mismatching #{@lower_bound.length} and #{dim}" if @lower_bound.length != dim
          # check whether start point exeeds the lower bound
          0.upto(dim - 1) do |i|
            v = @start[i]
            lo = @lower_bound[i]
            raise "start point is lower than lower bound" if v < lo
          end
        end
        if (!@upper_bound.nil?)
          # check for dimension mismatches
          raise "dimension mismatching #{@upper_bound.length} and #{dim}" if @upper_bound.length != dim
          # check whether strating point exceeds the upper bound
          0.upto(dim - 1) do |i|
            v = @start[i]
            hi = @upper_bound[i]
            raise "start point is higher than the upper bound" if v > hi
          end
        end

        if (@lower_bound.nil?)
          @lower_bound = Array.new(dim)
          0.upto(dim - 1) do |i|
            @lower_bound[i] = Float::INFINITY # eventually this will occur an error
          end
        end
        if (@upper_bound.nil?)
          @upper_bound = Array.new(dim)
          0.upto(dim - 1) do |i|
            @upper_bound[i] = -Float::INFINITY # eventually this will occur an error
          end
        end
      end
    end

    # line minimization using Brent's minimization
    # == Parameters:
    # * <tt>point</tt>: Starting point
    # * <tt>direction</tt>: Search direction
    #
    def brent_search(point, direction)
      n = point.length
      # Create a proc to minimize using brent search
      # Function value varies with alpha value and represent a point
      # of the minimizing function which is on the given plane
      func = proc{ |alpha|
        x = Array.new(n)
        0.upto(n - 1) do |i|
          # create a point according to the given alpha value
          x[i] = point[i] + alpha * direction[i]
        end
        # return the function value of the obtained point
        f(x)
      }

      # create Brent minimizer
      line_minimizer = Minimization::Brent.new(@min_coordinate_val, @max_coordinate_val, func)
      # iterate Brent minimizer for given number of iteration value
      0.upto(@max_brent_iterations) do
        line_minimizer.iterate
      end
      # return the minimum point
      return {:alpha_min => line_minimizer.x_minimum, :f_val => line_minimizer.f_minimum}
    end

  end

  # = Powell's Minimizer.
  # A multidimensional minimization methods
  # == Usage.
  #  require 'minimization'
  #  f = proc{ |x| (x[0] - 1)**2 + (2*x[1] - 5)**2 + (x[2]-3.3)**2}
  #  min = Minimization::Powell.minimize(f, [1, 2, 3], [0, 0, 0], [5, 5, 5])
  #  min.f_minimum
  #  min.x_minimum
  #
  class Powell < ConjugateDirectionMinimizer

    attr_accessor :relative_threshold
    attr_accessor :absolute_threshold

    # default of relative threshold
    RELATIVE_THRESHOLD_DEFAULT = 0.1
    # default of absolute threshold
    ABSOLUTE_THRESHOLD_DEFAULT =0.1
    
    # == Parameters:
    # * <tt>f</tt>: Minimization function
    # * <tt>initial_guess</tt>: Initial position of Minimization
    # * <tt>lower_bound</tt>: Lower bound of the minimization
    # * <tt>upper_bound</tt>: Upper bound of the minimization
    #
    def initialize(f, initial_guess, lower_bound, upper_bound)
      super(f, initial_guess.clone, lower_bound, upper_bound)
      @relative_threshold = RELATIVE_THRESHOLD_DEFAULT
      @absolute_threshold = ABSOLUTE_THRESHOLD_DEFAULT
    end

    # Obtain new point and direction from the previous point,
    # previous direction and a parameter value
    # == Parameters:
    # * <tt>point</tt>: Previous point
    # * <tt>direction</tt>: Previous direction
    # * <tt>minimum</tt>: parameter value
    #
    def new_point_and_direction(point, direction, minimum)
      n         = point.length
      new_point = Array.new(n)
      new_dir   = Array.new(n)
      0.upto(n - 1) do |i|
        new_dir[i]   = direction[i] * minimum
        new_point[i] = point[i] + new_dir[i]
      end
      return {:point => new_point, :dir => new_dir}
    end

    # Iterate Powell's minimizer one step
    # == Parameters:
    # * <tt>f</tt>: Function to minimize
    # * <tt>starting_point</tt>: starting point
    # * <tt>lower_bound</tt>: Lowest possible values of each direction
    # * <tt>upper_bound</tt>: Highest possible values of each direction
    # == Usage:
    #   minimizer = Minimization::Powell.new(proc{|x| (x[0] - 1)**2 + (x[1] -1)**2},
    #                               [0, 0, 0], [-5, -5, -5], [5, 5, 5])
    #   while minimizer.converging?
    #     minimizer.iterate
    #   end
    #   minimizer.x_minimum
    #   minimizer.f_minimum
    #
    def iterate 
      @iterations += 1

      # set initial configurations
      if(@iterations <= 1)
        guess = @start
        @n     = guess.length
        # initialize all to 0
        @direc = Array.new(@n) { Array.new(@n) {0} }
        0.upto(@n - 1) do |i|
          # set diagonal values to 1
          @direc[i][i] = 1
        end

        @x     = guess
        @f_val = f(@x)
        @x1    = @x.clone
      end

      fx        = @f_val
      fx2       = 0
      delta     = 0
      big_ind   = 0
      alpha_min = 0

      0.upto(@n - 1) do |i|
        direction = @direc[i].clone
        fx2       = @f_val
        # Find line minimum
        minimum   = brent_search(@x, direction)
        @f_val    = minimum[:f_val]
        alpha_min = minimum[:alpha_min]
        # Obtain new point and direction
        new_pnd   = new_point_and_direction(@x, direction, alpha_min)
        new_point = new_pnd[:point]
        new_dir   = new_pnd[:dir]
        @x         = new_point

        if ((fx2 - @f_val) > delta) 
          delta   = fx2 - @f_val
          big_ind = i
        end
      end

      # convergence check
      @converging = !(2 * (fx - @f_val) <= (@relative_threshold * (fx.abs + @f_val.abs) + @absolute_threshold))

      # storing results
      if((@f_val < fx))
        @x_minimum = @x
        @f_minimum = @f_val
      else
        @x_minimum = @x1
        @f_minimum = fx
      end

      direction  = Array.new(@n)
      x2         = Array.new(@n)
      0.upto(@n -1) do |i|
        direction[i]  = @x[i] - @x1[i]
        x2[i]         = 2 * @x[i] - @x1[i]
      end

      @x1  = @x.clone
      fx2 = f(x2)

      if (fx > fx2)
        t    = 2 * (fx + fx2 - 2 * @f_val)
        temp = fx - @f_val - delta
        t   *= temp * temp
        temp = fx - fx2
        t   -= delta * temp * temp

        if (t < 0.0)
          minimum   = brent_search(@x, direction)
          @f_val     = minimum[:f_val]
          alpha_min = minimum[:alpha_min]
          # Obtain new point and direction
          new_pnd   = new_point_and_direction(@x, direction, alpha_min)
          new_point = new_pnd[:point]
          new_dir   = new_pnd[:dir]
          @x         = new_point

          last_ind        = @n - 1
          @direc[big_ind]  = @direc[last_ind]
          @direc[last_ind] = new_dir
        end
      end
    end

    # Convenience method to minimize
    # == Parameters:
    # * <tt>f</tt>: Function to minimize
    # * <tt>starting_point</tt>: starting point
    # * <tt>lower_bound</tt>: Lowest possible values of each direction
    # * <tt>upper_bound</tt>: Highest possible values of each direction
    # == Usage:
    #   minimizer = Minimization::Powell.minimize(proc{|x| (x[0] - 1)**2 + (x[1] -1)**2},
    #                               [0, 0, 0], [-5, -5, -5], [5, 5, 5])
    #   minimizer.x_minimum
    #   minimizer.f_minimum
    #
    def self.minimize(f, starting_point, lower_bound, upper_bound)
      min = Minimization::Powell.new(f, starting_point, lower_bound, upper_bound)
      while min.converging?
        min.iterate
      end
      return min
    end

  end
end