minimization-0.2.1/0000755000175000017500000000000012061264660013602 5ustar boutilboutilminimization-0.2.1/LICENSE.txt0000644000175000017500000003503412061264660015432 0ustar boutilboutilGNU GENERAL PUBLIC LICENSE ************************** Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. minimization-0.2.1/metadata.yml0000644000175000017500000000711512061264660016111 0ustar boutilboutil--- !ruby/object:Gem::Specification name: minimization version: !ruby/object:Gem::Version hash: 21 prerelease: false segments: - 0 - 2 - 1 version: 0.2.1 platform: ruby authors: - Claudio Bustos autorequire: bindir: bin cert_chain: - | -----BEGIN CERTIFICATE----- MIIDMjCCAhqgAwIBAgIBADANBgkqhkiG9w0BAQUFADA/MREwDwYDVQQDDAhjbGJ1 c3RvczEVMBMGCgmSJomT8ixkARkWBWdtYWlsMRMwEQYKCZImiZPyLGQBGRYDY29t MB4XDTEwMDMyOTIxMzg1NVoXDTExMDMyOTIxMzg1NVowPzERMA8GA1UEAwwIY2xi dXN0b3MxFTATBgoJkiaJk/IsZAEZFgVnbWFpbDETMBEGCgmSJomT8ixkARkWA2Nv bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf8JVMGqE7m5kYb+PNN neZv2pcXV5fQCi6xkyG8bi2/SIFy/LyxuvLzEeOxBeaz1Be93bayIUquOIqw3dyw /KXWa31FxuNuvAm6CN8fyeRYX/ou4cw3OIUUnIvB7RMNIu4wbgeM6htV/QEsNLrv at1/mh9JpqawPrcjIOVMj4BIp67vmzJCaUf+S/H2uYtSO09F+YQE3tv85TPeRmqU yjyXyTc/oJiw1cXskUL8UtMWZmrwNLHXuZWWIMzkjiz3UNdhJr/t5ROk8S2WPznl 0bMy/PMIlAbqWolRn1zl2VFJ3TaXScbqImY8Wf4g62b/1ZSUlGrtnLNsCYXrWiso UPUCAwEAAaM5MDcwCQYDVR0TBAIwADALBgNVHQ8EBAMCBLAwHQYDVR0OBBYEFGu9 rrJ1H64qRmNNu3Jj/Qjvh0u5MA0GCSqGSIb3DQEBBQUAA4IBAQCV0Unka5isrhZk GjqSDqY/6hF+G2pbFcbWUpjmC8NWtAxeC+7NGV3ljd0e1SLfoyBj4gnFtFmY8qX4 K02tgSZM0eDV8TpgFpWXzK6LzHvoanuahHLZEtk/+Z885lFene+nHadkem1n9iAB cs96JO9/JfFyuXM27wFAwmfHCmJfPF09R4VvGHRAvb8MGzSVgk2i06OJTqkBTwvv JHJdoyw3+8bw9RJ+jLaNoQ+xu+1pQdS2bb3m7xjZpufml/m8zFCtjYM/7qgkKR8z /ZZt8lCiKfFArppRrZayE2FVsps4X6WwBdrKTMZ0CKSXTRctbEj1BAZ67eoTvBBt rpP0jjs0 -----END CERTIFICATE----- date: 2010-11-14 00:00:00 -03:00 default_executable: dependencies: - !ruby/object:Gem::Dependency name: text-table prerelease: false requirement: &id001 !ruby/object:Gem::Requirement none: false requirements: - - ~> - !ruby/object:Gem::Version hash: 11 segments: - 1 - 2 version: "1.2" type: :runtime version_requirements: *id001 - !ruby/object:Gem::Dependency name: rubyforge prerelease: false requirement: &id002 !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 7 segments: - 2 - 0 - 4 version: 2.0.4 type: :development version_requirements: *id002 - !ruby/object:Gem::Dependency name: hoe prerelease: false requirement: &id003 !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 19 segments: - 2 - 6 - 2 version: 2.6.2 type: :development version_requirements: *id003 description: Minimization algorithms on pure Ruby. email: - clbustos_AT_gmail.com executables: [] extensions: [] extra_rdoc_files: - History.txt - LICENSE.txt - Manifest.txt - README.txt files: - History.txt - LICENSE.txt - Manifest.txt - README.txt - Rakefile - lib/minimization.rb - spec/minimization_unidimensional_spec.rb - spec/spec.opts - spec/spec_helper.rb has_rdoc: true homepage: http://github.com/clbustos/minimization licenses: [] post_install_message: rdoc_options: - --main - README.txt require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" requirements: [] rubyforge_project: ruby-statsample rubygems_version: 1.3.7 signing_key: specification_version: 3 summary: Minimization algorithms on pure Ruby. test_files: [] minimization-0.2.1/Manifest.txt0000644000175000017500000000023112061264660016105 0ustar boutilboutilHistory.txt LICENSE.txt Manifest.txt README.txt Rakefile lib/minimization.rb spec/minimization_unidimensional_spec.rb spec/spec.opts spec/spec_helper.rb minimization-0.2.1/README.txt0000644000175000017500000000110612061264660015276 0ustar boutilboutil= minimization * http://github.com/clbustos/minimization == DESCRIPTION: Minimization algorithms on pure Ruby. == FEATURES/PROBLEMS: Unidimensional: * Newton-Rahpson (requires first and second derivative) * Golden Section * Brent (Port of GSL code) If you needs speed, use rb-gsl == SYNOPSIS: d=Minimization::Brent.new(-1000,20000 , proc {|x| x**2}) d.iterate puts d.x_minimum puts d.f_minimum == REQUIREMENTS: * Pure Ruby == INSTALL: sudo gem install minimization == API: http://ruby-statsample.rubyforge.org/minimization/ == LICENSE: GPL-2 (See LICENSE.txt)minimization-0.2.1/metadata.gz.sig0000644000175000017500000000040012061264660016477 0ustar boutilboutil/Z+̵K)+jaֽ'֕7  xJɭ2YOSVkc=+$X\4";C0jo_SE B{vn A?epPx f340h?P7̱*q Q$ $X+]J(awv:j5(#[t>ܛ5yz3|lmj}lͩ皫LMQ Lminimization-0.2.1/History.txt0000644000175000017500000000051512061264660016005 0ustar boutilboutil=== 0.2.1 / 2010-11-14 * Added iterations method === 0.2.0 / 2010-04-15 * New Minimization::NewtonRahpson class, which implements a naive Newton-Rahpson minimization method x=x_n-(f'(x)/f''(x)) === 0.1.1 / 2010-03-19 * New Minimization#minimize convenience method === 0.1.0 / 2010-02-24 * Golden Section and Brent Algorithm minimization-0.2.1/Rakefile0000644000175000017500000000062312061264660015250 0ustar boutilboutil# -*- ruby -*- require 'rubygems' require 'hoe' require './lib/minimization' Hoe.plugin :git Hoe.spec 'minimization' do self.version=Minimization::VERSION self.rubyforge_name = 'ruby-statsample' # if different than 'minimization' self.developer('Claudio Bustos', 'clbustos_AT_gmail.com') self.remote_rdoc_dir = 'minimization' self.extra_deps << ['text-table', "~>1.2"] end # vim: syntax=ruby minimization-0.2.1/lib/0000755000175000017500000000000012061264660014350 5ustar boutilboutilminimization-0.2.1/lib/minimization.rb0000644000175000017500000002627212061264660017415 0ustar boutilboutil# = minimization.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. # # Algorithms for unidimensional minimization require 'text-table' module Minimization VERSION="0.2.1" FailedIteration=Class.new(Exception) # Base class for unidimensional minimizers class Unidimensional # Default value for error on f(x) EPSILON=1e-6 # Default number of maximum iterations MAX_ITERATIONS=100 # Minimum value for x attr_reader :x_minimum # Minimum value for f(x) attr_reader :f_minimum # Log of iterations. Should be an array attr_reader :log # Name of fields of log attr_reader :log_header # Absolute error on x attr_accessor :epsilon # Expected value. Fast minimum finding if set attr_reader :expected # Numbers of iterations attr_reader :iterations # Create a new minimizer def initialize(lower, upper, proc) raise "first argument should be lower than second" if lower>=upper @lower=lower @upper=upper @proc=proc golden = 0.3819660; @expected = @lower + golden * (@upper - @lower); @max_iteration=MAX_ITERATIONS @epsilon=EPSILON @iterations=0 @log=[] @log_header=%w{I xl xh f(xl) f(xh) dx df(x)} end # Set expected value def expected=(v) @expected=v end def log_summary @log.join("\n") end # Convenience method to minimize # == Parameters: # * lower: Lower possible value # * upper: Higher possible value # * expected: Optional expected value. Faster the search is near correct value. # * &block: Block with function to minimize # == Usage: # minimizer=Minimization::GoldenSection.minimize(-1000, 1000) {|x| # x**2 } # def self.minimize(lower,upper,expected=nil,&block) minimizer=new(lower,upper,block) minimizer.expected=expected unless expected.nil? raise FailedIteration unless minimizer.iterate minimizer end # Iterate to find the minimum def iterate raise "You should implement this" end def f(x) @proc.call(x) end end # Classic Newton-Raphson minimization method. # Requires first and second derivative # == Usage # f = lambda {|x| x**2} # fd = lambda {|x| 2x} # fdd = lambda {|x| 2} # min = Minimization::NewtonRaphson.new(-1000,1000, f,fd,fdd) # min.iterate # min.x_minimum # min.f_minimum # class NewtonRaphson < Unidimensional # == Parameters: # * lower: Lower possible value # * upper: Higher possible value # * proc: Original function # * proc_1d: First derivative # * proc_2d: Second derivative # def initialize(lower, upper, proc, proc_1d, proc_2d) super(lower,upper,proc) @proc_1d=proc_1d @proc_2d=proc_2d end # Raises an error def self.minimize(*args) raise "You should use #new and #iterate" end def iterate # First x_prev=@lower x=@expected failed=true k=0 while (x-x_prev).abs > @epsilon and k<@max_iteration k+=1 x_prev=x x=x-(@proc_1d.call(x).quo(@proc_2d.call(x))) f_prev=f(x_prev) f=f(x) x_min,x_max=[x,x_prev].min, [x,x_prev].max f_min,f_max=[f,f_prev].min, [f,f_prev].max @log << [k, x_min, x_max, f_min, f_max, (x_prev-x).abs, (f-f_prev).abs] end raise FailedIteration, "Not converged" if k>=@max_iteration @x_minimum = x; @f_minimum = f(x); end end # = Golden Section Minimizer. # Basic minimization algorithm. Slow, but robust. # See Unidimensional for methods. # == Usage. # require 'minimization' # min=Minimization::GoldenSection.new(-1000,20000 , proc {|x| (x+1)**2} # min.expected=1.5 # Expected value # min.iterate # min.x_minimum # min.f_minimum # min.log class GoldenSection < Unidimensional # Start the iteration def iterate ax=@lower bx=@expected cx=@upper c = (3-Math::sqrt(5)).quo(2); r = 1-c; x0 = ax; x3 = cx; if ((cx-bx).abs > (bx-ax).abs) x1 = bx; x2 = bx + c*(cx-bx); else x2 = bx; x1 = bx - c*(bx-ax); end f1 = f(x1); f2 = f(x2); k = 1; while (x3-x0).abs > @epsilon and k<@max_iteration if f2 < f1 x0 = x1; x1 = x2; x2 = r*x1 + c*x3; # x2 = x1+c*(x3-x1) f1 = f2; f2 = f(x2); else x3 = x2; x2 = x1; x1 = r*x2 + c*x0; # x1 = x2+c*(x0-x2) f2 = f1; f1 = f(x1); end @log << [k, x3,x0, f1,f2,(x3-x0).abs, (f1-f2).abs] k +=1; end if f1 < f2 @x_minimum = x1; @f_minimum = f1; else @x_minimum = x2; @f_minimum = f2; end true end end # Direct port of Brent algorithm found on GSL. # See Unidimensional for methods. # == Usage # min=Minimization::Brent.new(-1000,20000 , proc {|x| (x+1)**2} # min.expected=1.5 # Expected value # min.iterate # min.x_minimum # min.f_minimum # min.log class Brent < Unidimensional GSL_SQRT_DBL_EPSILON=1.4901161193847656e-08 def initialize(lower,upper, proc) super @do_bracketing=true # Init golden = 0.3819660; #golden = (3 - sqrt(5))/2 v = @lower + golden * (@upper - @lower); w = v; @x_minimum = v ; @f_minimum = f(v) ; @x_lower=@lower @x_upper=@upper @f_lower = f(@lower) ; @f_upper = f(@lower) ; @v = v; @w = w; @d = 0; @e = 0; @f_v=f(v) @f_w=@f_v end def expected=(v) @x_minimum=v @f_minimum=f(v) @do_bracketing=false end def bracketing eval_max=10 f_left = @f_lower; f_right = @f_upper; x_left = @x_lower; x_right= @x_upper; golden = 0.3819660; # golden = (3 - sqrt(5))/2 */ nb_eval=0 if (f_right >= f_left) x_center = (x_right - x_left) * golden + x_left; nb_eval+=1; f_center=f(x_center) else x_center = x_right ; f_center = f_right ; x_right = (x_center - x_left).quo(golden) + x_left; nb_eval+=1; f_right=f(x_right); end begin @log << ["B#{nb_eval}", x_left, x_right, f_left, f_right, (x_left-x_right).abs, (f_left-f_right).abs] if (f_center < f_left ) if (f_center < f_right) @x_lower = x_left; @x_upper = x_right; @x_minimum = x_center; @f_lower = f_left; @f_upper = f_right; @f_minimum = f_center; return true; elsif (f_center > f_right) x_left = x_center; f_left = f_center; x_center = x_right; f_center = f_right; x_right = (x_center - x_left).quo(golden) + x_left; nb_eval+=1; f_right=f(x_right); else # f_center == f_right */ x_right = x_center; f_right = f_center; x_center = (x_right - x_left).quo(golden) + x_left; nb_eval+=1; f_center=f(x_center); end else # f_center >= f_left */ x_right = x_center; f_right = f_center; x_center = (x_right - x_left) * golden + x_left; nb_eval+=1; f_center=f(x_center); end end while ((nb_eval < eval_max) and ((x_right - x_left) > GSL_SQRT_DBL_EPSILON * ( (x_right + x_left) * 0.5 ) + GSL_SQRT_DBL_EPSILON)) @x_lower = x_left; @x_upper = x_right; @x_minimum = x_center; @f_lower = f_left; @f_upper = f_right; @f_minimum = f_center; return false; end # Start the minimization process # If you want to control manually the process, use brent_iterate def iterate k=0 bracketing if @do_bracketing while k<@max_iteration and (@x_lower-@x_upper).abs>@epsilon k+=1 result=brent_iterate raise FailedIteration,"Error on iteration" if !result begin @log << [k, @x_lower, @x_upper, @f_lower, @f_upper, (@x_lower-@x_upper).abs, (@f_lower-@f_upper).abs] rescue =>@e @log << [k, @e.to_s,nil,nil,nil,nil,nil] end end @iterations=k return true end # Generate one iteration. def brent_iterate x_left = @x_lower; x_right = @x_upper; z = @x_minimum; d = @e; e = @d; v = @v; w = @w; f_v = @f_v; f_w = @f_w; f_z = @f_minimum; golden = 0.3819660; # golden = (3 - sqrt(5))/2 */ w_lower = (z - x_left) w_upper = (x_right - z) tolerance = GSL_SQRT_DBL_EPSILON * z.abs midpoint = 0.5 * (x_left + x_right) _p,q,r=0,0,0 if (e.abs > tolerance) # fit parabola */ r = (z - w) * (f_z - f_v); q = (z - v) * (f_z - f_w); _p = (z - v) * q - (z - w) * r; q = 2 * (q - r); if (q > 0) _p = -_p else q = -q; end r = e; e = d; end if (_p.abs < (0.5 * q * r).abs and _p < q * w_lower and _p < q * w_upper) t2 = 2 * tolerance ; d = _p.quo(q); u = z + d; if ((u - x_left) < t2 or (x_right - u) < t2) d = (z < midpoint) ? tolerance : -tolerance ; end else e = (z < midpoint) ? x_right - z : -(z - x_left) ; d = golden * e; end if ( d.abs >= tolerance) u = z + d; else u = z + ((d > 0) ? tolerance : -tolerance) ; end @e = e; @d = d; f_u=f(u) if (f_u <= f_z) if (u < z) @x_upper = z; @f_upper = f_z; else @x_lower = z; @f_lower = f_z; end @v = w; @f_v = f_w; @w = z; @f_w = f_z; @x_minimum = u; @f_minimum = f_u; return true; else if (u < z) @x_lower = u; @f_lower = f_u; return true; else @x_upper = u; @f_upper = f_u; return true; end if (f_u <= f_w or w == z) @v = w; @f_v = f_w; @w = u; @f_w = f_u; return true; elsif f_u <= f_v or v == z or v == w @v = u; @f_v = f_u; return true; end end return false end end end minimization-0.2.1/spec/0000755000175000017500000000000012061264660014534 5ustar boutilboutilminimization-0.2.1/spec/spec.opts0000644000175000017500000000001412061264660016370 0ustar boutilboutil--color -f sminimization-0.2.1/spec/spec_helper.rb0000644000175000017500000000042712061264660017355 0ustar boutilboutil$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'minimization.rb' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end class String def deindent gsub /^[ \t]*/, '' end end minimization-0.2.1/spec/minimization_unidimensional_spec.rb0000644000175000017500000000335312061264660023704 0ustar boutilboutilrequire File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe Minimization::Unidimensional, "subclass" do before(:all) do @p1=rand(100) @p2=rand(100) @func=lambda {|x| (x-@p1)**2+@p2} @funcd=lambda {|x| 2*(x-@p1)} @funcdd=lambda {|x| 2} end describe Minimization::NewtonRaphson do before do @min = Minimization::NewtonRaphson.new(-1000,1000, @func,@funcd, @funcdd) @min.iterate end it "#x_minimum be close to expected" do @min.x_minimum.should be_close(@p1,@min.epsilon) end it "#f_minimum ( f(x)) be close to expected" do @min.f_minimum.should be_close(@p2,@min.epsilon) end context "#log" do subject {@min.log} it {should be_instance_of Array} it {should respond_to :to_table} end end describe Minimization::GoldenSection do before do @min = Minimization::GoldenSection.minimize(-1000,1000, &@func) end it "#x_minimum be close to expected" do @min.x_minimum.should be_close(@p1,@min.epsilon) end it "#f_minimum ( f(x)) be close to expected" do @min.f_minimum.should be_close(@p2,@min.epsilon) end context "#log" do subject {@min.log} it {should be_instance_of Array} it {should respond_to :to_table} end end describe Minimization::Brent do before do @min = Minimization::Brent.minimize(-1000,1000, &@func) end it "should x be correct" do @min.x_minimum.should be_close(@p1,@min.epsilon) end it "should f(x) be correct" do @min.f_minimum.should be_close(@p2,@min.epsilon) end context "#log" do subject {@min.log} it {should be_instance_of Array} it {should respond_to :to_table} end end end minimization-0.2.1/data.tar.gz.sig0000644000175000017500000000040012061264660016415 0ustar boutilboutilֹw*7 k(N\͂N;ڋrc.Yle)inU%=t dlG @l@M܃_G@Gw]ﹷ1 <,*S@Fo׺bvP~4%xbKզ%X??_;S|ah?3HC y dbC2MWx'Sj6ߗtn@LLKӻ>]`ܣ h:"A