AI-SimulatedAnnealing

 view release on metacpan or  search on metacpan

lib/AI/SimulatedAnnealing.htm  view on Meta::CPAN

    <h1><a name="description">DESCRIPTION</a></h1>
    <p>This module provides a single public function, <a
      href="#anneal"><code>anneal()</code></a>, that optimizes a list of
      numbers according to a specified cost function.</p>
    <p>Each number to be optimized has a lower bound, an upper bound, and a
      precision, where the precision is an integer in the range 0&#8211;4
      that specifies the number of decimal places to which all instances of
      the number will be rounded. The upper bound must be greater than the
      lower bound but not greater than 10 to the power of
      <code>(4&#160;-&#160;p)</code>, where <code>p</code> is the precision.
      The lower bound must be not less than <code>-1</code> times the result
      of taking 10 to the power of <code>(4&#160;-&#160;p)</code>.</p>
    <p>A bound that has a higher degree of precision than that specified for
      the number to which the bound applies is rounded inward (that is,
      downward for an upper bound and upward for a lower bound) to the
      nearest instance of the specified precision.</p>
    <p>The attributes of a number (bounds and precision) are encapsulated
      within a number specification, which is a reference to a hash
      containing <code>&quot;LowerBound&quot;</code>,
      <code>&quot;UpperBound&quot;</code>, and
      <code>&quot;Precision&quot;</code> fields.</p>
    <p>The <a href="#anneal"><code>anneal()</code></a> function takes a
      reference to an array of number specifications, a cost function, and a
      positive integer specifying the number of randomization cycles per
      temperature to perform. The <code>anneal()</code> function returns a
      reference to an array having the same length as the array of number
      specifications. The returned list represents the optimal list of
      numbers matching the specified attributes, where &quot;optimal&quot;
      means producing the lowest cost.</p>
    <p>The cost function must take a reference to an array of numbers that
      match the number specifications. The function must return a single
      number representing a cost to be minimized.</p>
    <p>In order to work efficiently with the varying precisions, the
      <code>anneal()</code> function converts each bound to an integer by
      multiplying it by 10 to the power of the precision; then the function
      performs the temperature reductions and randomization cycles (which
      include tests performed via calls to the cost function) on integers in
      the resulting ranges. When passing an integer to the cost function or
      when storing the integer in a collection of numbers to be returned by
      the function, <code>anneal()</code> first converts the integer back to
      the appropriate decimal number by dividing the integer by 10 to the
      power of the precision.</p>
    <p>The initial temperature is the size of the largest range after the
      bounds have been converted to integers. During each temperature
      reduction, the <code>anneal()</code> function multiplies the
      temperature by 0.95 and then rounds the result down to the nearest
      integer (if the result isn&#39;t already an integer). When the
      temperature reaches zero, annealing is immediately terminated.</p>
    <p style="margin-left: 13px;"><b>Note:</b>  Annealing can sometimes
      complete before the temperature reaches zero if, after a particular
      temperature reduction, a brute-force optimization approach (that is,
      testing every possible combination of numbers within the subranges
      determined by the new temperature) would produce a number of tests
      that is less than or equal to the specified cycles per temperature.
      In that case, the <code>anneal()</code> function performs the
      brute-force optimization to complete the annealing process.</p>
    <p>After a temperature reduction, the <code>anneal()</code> function
      determines each new subrange such that the current optimal integer
      from the total range is as close as possible to the center of the new
      subrange. When there is a tie between two possible positions for the
      subrange within the total range, a &quot;coin flip&quot; decides.</p>
    <hr/>
    <h1><a name="prerequisites">PREREQUISITES</a></h1>
    <p>This module requires Perl 5, version 5.10.1 or later.</p>
    <hr/>
    <h1><a name="methods">METHODS</a></h1>
    <dl>
      <dt><strong><a class="item" name="anneal">anneal($number_specs,
        $cost_function, $cycles_per_temperature);</a></strong></dt>
      <dd>
        <p>The <code>anneal()</code> function takes a reference to an array
          of number specifications (which are references to hashes
          containing <code>&quot;LowerBound&quot;</code>,
          <code>&quot;UpperBound&quot;</code>, and
          <code>&quot;Precision&quot;</code> fields), a code reference
          pointing to a cost function (which takes a list of numbers
          matching the specifications and returns a number representing a
          cost to be minimized), and a positive integer specifying the
          number of randomization cycles to perform at each temperature.</p>
        <p>The function returns a reference to an array containing the
          optimized list of numbers.</p>
      </dd>
    </dl>
    <hr/>
    <h1><a name="author">AUTHOR</a></h1>
    <p>Benjamin Fitch, &lt;<a
      href="mailto:blernflerkl@yahoo.com">blernflerkl@yahoo.com</a>&gt;</p>

lib/AI/SimulatedAnnealing.pm  view on Meta::CPAN

my $EMPTY     = "";
my $TRUE      = 1;
my $FALSE     = 0;

my $TEMPERATURE_MULTIPLIER = 0.95;

# The anneal() function takes a reference to an array of number
# specifications (which are references to hashes containing "LowerBound",
# "UpperBound", and "Precision" fields), a reference to a cost function
# (which takes a list of numbers matching the specifications and returns a
# number representing a cost to be minimized), and a positive integer
# specifying the number of randomization cycles to perform at each
# temperature during the annealing process.
#
# The function returns a reference to an array containing the
# optimized list of numbers.
sub anneal {
    my $number_specs = validate_number_specs($_[0]);
    my $cost_function = $_[1];
    my $cycles_per_temperature = $_[2];

lib/AI/SimulatedAnnealing.pm  view on Meta::CPAN

    return \@optimized_list;
} # end sub

####
# Private helper functions for use by this module:

# The use_brute_force() function takes a reference to an array of number
# specifications (which are references to hashes containing "LowerBound",
# "UpperBound", and "Precision" fields) and a reference to a cost function
# (which takes a list of numbers matching the specifications and returns a
# number representing a cost to be minimized).  The method tests every
# possible combination of numbers matching the specifications and returns a
# reference to an array containing the optimal numbers, where "optimal"
# means producing the lowest cost.
sub use_brute_force {
    my $number_specs = validate_number_specs($_[0]);
    my $cost_function = $_[1];

    my @optimized_list;
    my @lists;
    my @cursors;

lib/AI/SimulatedAnnealing.pm  view on Meta::CPAN

            elsif ($dex == 0) {
                $finished = $TRUE;
                last;
            }
            else {
                $cursors[$dex] = 0;
            } # end if
        } # next $dex
    } until ($finished);

    # Return the result:
    return \@optimized_list;
} # end sub

# The validate_number_specs() function takes a reference to an array of
# number specifications (which are references to hashes with "LowerBound",
# "UpperBound", and "Precision" fields) and returns a reference to a version
# of the array in which bounds with higher precision than that specified
# have been rounded inward.  If a number specification is not valid, the
# function calls "die" with an error message.
sub validate_number_specs {

lib/AI/SimulatedAnnealing.pm  view on Meta::CPAN

        unless (looks_like_number($lower_bound)
          && looks_like_number($upper_bound)
          && $upper_bound > $lower_bound
          && $upper_bound <= 10 ** (4 - $precision)
          && $lower_bound >= -1 * (10 ** (4 - $precision))) {
            die "ERROR:  In a number specification, the lower and upper "
              . "bounds must be numbers such that the upper bound is "
              . "greater than the lower bound, the upper bound is not "
              . "greater than 10 to the power of (4 - p) where p is the "
              . "precision, and the lower bound is not less than -1 times "
              . "the result of taking 10 to the power of (4 - p).\n";
        } # end unless

        # Round the bounds inward as necessary:
        my $integral_lower_bound = ceil( $lower_bound * (10 ** $precision));
        my $integral_upper_bound = floor($upper_bound * (10 ** $precision));

        $number_spec->{"LowerBound"}
          = $integral_lower_bound / (10 ** $precision);
        $number_spec->{"UpperBound"}
          = $integral_upper_bound / (10 ** $precision);

lib/AI/SimulatedAnnealing.pm  view on Meta::CPAN


This module provides a single public function, anneal(), that optimizes
a list of numbers according to a specified cost function.

Each number to be optimized has a lower bound, an upper bound, and a
precision, where the precision is an integer in the range 0 to 4 that
specifies the number of decimal places to which all instances of the
number will be rounded.  The upper bound must be greater than the
lower bound but not greater than 10 to the power of (4 - p), where "p"
is the precision.  The lower bound must be not less than -1 times the
result of taking 10 to the power of (4 - p).

A bound that has a higher degree of precision than that specified for
the number to which the bound applies is rounded inward (that is,
downward for an upper bound and upward for a lower bound) to the
nearest instance of the specified precision.

The attributes of a number (bounds and precision) are encapsulated
within a number specification, which is a reference to a hash
containing "LowerBound", "UpperBound", and "Precision" fields.

The anneal() function takes a reference to an array of number
specifications, a cost function, and a positive integer specifying
the number of randomization cycles per temperature to perform.  The
anneal() function returns a reference to an array having the same
length as the array of number specifications.  The returned list
represents the optimal list of numbers matching the specified
attributes, where "optimal" means producing the lowest cost.

The cost function must take a reference to an array of numbers that
match the number specifications.  The function must return a single
number representing a cost to be minimized.

In order to work efficiently with the varying precisions, the anneal()
function converts each bound to an integer by multiplying it by 10 to
the power of the precision; then the function performs the temperature
reductions and randomization cycles (which include tests performed via
calls to the cost function) on integers in the resulting ranges.  When
passing an integer to the cost function or when storing the integer in
a collection of numbers to be returned by the function, anneal() first
converts the integer back to the appropriate decimal number by
dividing the integer by 10 to the power of the precision.

The initial temperature is the size of the largest range after the
bounds have been converted to integers.  During each temperature
reduction, the anneal() function multiplies the temperature by 0.95
and then rounds the result down to the nearest integer (if the result
isn't already an integer).  When the temperature reaches zero,
annealing is immediately terminated.

  NOTE:  Annealing can sometimes complete before the temperature
  reaches zero if, after a particular temperature reduction, a
  brute-force optimization approach (that is, testing every possible
  combination of numbers within the subranges determined by the new
  temperature) would produce a number of tests that is less than or
  equal to the specified cycles per temperature.  In that case, the
  anneal() function performs the brute-force optimization to complete
  the annealing process.

After a temperature reduction, the anneal() function determines each
new subrange such that the current optimal integer from the total
range is as close as possible to the center of the new subrange.
When there is a tie between two possible positions for the subrange
within the total range, a "coin flip" decides.

=head1 PREREQUISITES

This module requires Perl 5, version 5.10.1 or later.

=head1 METHODS

=over

=item anneal($number_specs, $cost_function, $cycles_per_temperature);

The anneal() function takes a reference to an array of number specifications
(which are references to hashes containing "LowerBound", "UpperBound", and
"Precision" fields), a code reference pointing to a cost function (which
takes a list of numbers matching the specifications and returns a number
representing a cost to be minimized), and a positive integer specifying the
number of randomization cycles to perform at each temperature.

The function returns a reference to an array containing the optimized list
of numbers.

=back

=head1 AUTHOR

Benjamin Fitch, <blernflerkl@yahoo.com>

t/annealing_tests.t  view on Meta::CPAN

        push @{ $mapped_distances[$p] }, $record->{$field_names->[6 - $p]};
    } # next $p
} # end while

unless (scalar @{ $mapped_distances[$Probability::ONE_FIFTH] } == 61) {
    die "ERROR:  The input file does not contain the expected number of "
      . "records.\n";
} # end unless

# Perform simulated annealing to optimize the coefficients for each of the
# four probabilities, and then print the results to the console:
for my $p (2..5) {
    my $cost_function = cost_function_factory($mapped_distances[$p]);
    my $optimized_coefficients;
    my @number_specs;

    push @number_specs,
      {"LowerBound" =>  0.0, "UpperBound" => 3.0, "Precision" => 3};
    push @number_specs,
      {"LowerBound" => -1.0, "UpperBound" => 5.0, "Precision" => 3};
    push @number_specs,
      {"LowerBound" => -4.0, "UpperBound" => 0.0, "Precision" => 3};

    $optimized_coefficients = anneal(
      \@number_specs, $cost_function, $CYCLES_PER_TEMPERATURE);

    # Print the results for this probability to the console:
    say "\nProbability:  1/$p";
    printf("Coefficients:  a = %1.3f; b = %1.3f; c= %1.3f\n",
      $optimized_coefficients->[0],
      $optimized_coefficients->[1],
      $optimized_coefficients->[2]);
    say "Cost:  " . $cost_function->($optimized_coefficients);
} # next $p

# Perform an annealing test with integers that triggers brute-force analysis
# and uses an anonymous cost function that minimizes this sum:
#
#     (10 * abs(23 - val)) + (the total range of a, b, and c)
#
# where "val" is the result of following expression:
#
#     (a * (x ** 2)) + bx + c
#
# in which x = 3:
my $abc;
my @number_specs;

push @number_specs,
  {"LowerBound" =>  1.9, "UpperBound" => 4, "Precision" => 0};
push @number_specs,

t/annealing_tests.t  view on Meta::CPAN


say "\nHere are a, b, and c:  " . $abc->[0] . ", "
  . $abc->[1] . ", " . $abc->[2];

# Helper functions:

# The cost_function_factory() takes a reference to an array containing
# real-world market distances and returns a reference to a cost function.
# The cost function takes a reference to an array of three coefficients,
# and returns the mean absolute percentage deviation of the calculated
# results from the real-world results based on this formula:
#
#     (a * sqrt(x + b)) + c
#
# where x is a number of trading days in the range 3 to 63.
sub cost_function_factory {
    my $real_world_distances = $_[0];
    my $current_coefficients;

    my $calculate_distance
      = sub {



( run in 0.522 second using v1.01-cache-2.11-cpan-49f99fa48dc )