<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>大千世界 &#187; JGAP</title>
	<atom:link href="http://www.zhangdaqian.net/blog/tag/jgap/feed" rel="self" type="application/rss+xml" />
	<link>http://www.zhangdaqian.net</link>
	<description>Hold Infinity in the palm of your hand</description>
	<lastBuildDate>Tue, 17 Aug 2010 12:00:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Getting Started With JGAP</title>
		<link>http://www.zhangdaqian.net/blog/getting-started-with-jgap.htm</link>
		<comments>http://www.zhangdaqian.net/blog/getting-started-with-jgap.htm#comments</comments>
		<pubDate>Tue, 21 Apr 2009 12:31:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[JGAP]]></category>
		<category><![CDATA[遗传算法]]></category>

		<guid isPermaLink="false">http://www.zhangdaqian.net/blog/getting-started-with-jgap.htm</guid>
		<description><![CDATA[Preface: Please note that this documentation could be correlated to a former JGAP version. Therefor we recommend having a look at the examples provided with JGAP and then read this document in order to get an idea.
To use JGAP in an application, there are five basic things that you must do:


Plan your Chromosome.


Implement a &#8220;fitness [...]]]></description>
			<content:encoded><![CDATA[<p class="text"><a id="top" name="top"><strong>Preface: Please note that this documentation could be correlated to a former JGAP version. Therefor we recommend having a look at the examples provided with JGAP and then read this document in order to get an idea.</strong></a></p>
<p class="text"><a id="top" name="top">To use JGAP in an application, there are five basic things that you must do:</a></p>
<ol>
<li>
<p class="text"><a href="http://jgap.sourceforge.net/doc/tutorial.html#step1">Plan your Chromosome.</a></p>
</li>
<li>
<p class="text"><a href="http://jgap.sourceforge.net/doc/tutorial.html#step2">Implement a &#8220;fitness function&#8221;.</a></p>
</li>
<li>
<p class="text"><a href="http://jgap.sourceforge.net/doc/tutorial.html#step3">Setup a Configuration object.</a></p>
</li>
<li>
<p class="text"><a href="http://jgap.sourceforge.net/doc/tutorial.html#step4">Create a population of potential solutions.</a></p>
</li>
<li>
<p class="text"><a href="http://jgap.sourceforge.net/doc/tutorial.html#step5">Evolve the population!</a></p>
</li>
</ol>
<p class="text">Through the course of this tutorial, we&#8217;ll build a simple example program that makes use of JGAP. The goal of our program will be to produce a user-specified amount of change in the fewest possible American coins (quarters, dimes, nickels, and pennies).</p>
<p> <span id="more-214"></span><br />
<h3 class="subheader"><a id="step1" name="step1">Step 1: Plan your Chromosome</a></h3>
<p class="text"><a id="step1" name="step1">At the heart of the genetic algorithm is the Chromosome. The Chromosome represents a potential solution and is divided into multiple genes. Genes in JGAP represent distinct aspects of the solution as a whole, just as human genes represent distinct aspects of individual people, such as their sex or eye color. During the JGAP evolution process, chromosomes are exposed to multiple genetic operators that represent mating, mutation, etc. and then are chosen for the next generation during a natural selection phase based upon their &#8220;fitness,&#8221; which is a measure of how optimal that solution is relative to other potential solutions. The entire goal of the genetic algorithm is to mimic the natural process of evolution in order to produce superior solutions.</a></p>
<p class="text"><a id="step1" name="step1">Step 1, therefore, is to decide on the makeup of your chromosomes, which includes how many genes you want and what those genes will represent. In our sample program, we want to create a pile of change that contains the fewest possible American coins that total up to the amount specified by the user. Since a chromosome represents a potential solution, in our sample it will represent a pile of change. We&#8217;ll setup our genes to represent the different denominations of coins so that we&#8217;ll have a total of four genes per chromosome (one each for quarters, dimes, nickels, and pennies).</a></p>
<p style="TEXT-ALIGN: center"><a id="step1" name="step1"><img src="http://jgap.sourceforge.net/doc/chromosome.png" alt="(Diagram of a Chromosome with four genes: quarters, dimes, nickels, and pennies.)" height="150" class="diagram" width="300"/></a></p>
<p class="text"><a id="step1" name="step1">We&#8217;ll actually write the code to setup our Chromosome objects in</a> <a href="http://jgap.sourceforge.net/doc/tutorial.html#step3">step 3</a>.</p>
<h3 class="subheader"><a id="step2" name="step2">Step 2: Implementing a Fitness Function</a></h3>
<p class="text">JGAP is designed to do almost all of the evolutionary work for you in a relatively generic fashion. However, it has no knowledge of the specific problem you&#8217;re actually trying to solve, and hence has no intrinsic way of deciding if one potential solution is any better than another potential solution for your specific problem. That&#8217;s where the fitness function comes in: it&#8217;s a single method that you must implement that accepts a potential problem solution and returns an integer value that indicates how good (or &#8220;fit&#8221;) that solution is relative to other possible solutions. The higher the number, the better the solution. The lower the number (1 being the lowest legal fitness value), the poorer the solution. JGAP will use these fitness measurements to evolve the population of solutions toward a more optimal set of solutions.</p>
<p class="text">Let&#8217;s start with a fully-working example of a fitness function, the details of which will be explained below. Since the goal of our small program is to produce an amount of change in American coins equal to a target amount in the fewest possible number of coins, it seems reasonable that the measure of fitness for a particular solution would be a combination of the relative closeness of the amount of change it represented to the target amount of change, and the total number of coins represented by the solution (fewer being better).</p>
<pre class="Listing">
<tt>
            <strong>
              <span style="COLOR: #000080">package</span>
            </strong> <span style="COLOR: #000000">examples;</span>

<strong>
              <span style="COLOR: #000080">import</span>
            </strong> <span style="COLOR: #000000">org.jgap.Chromosome;</span>
<strong>
              <span style="COLOR: #000080">import</span>
            </strong> <span style="COLOR: #000000">org.jgap.FitnessFunction;</span>

<em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* This class provides an implementation of the classic "Make change" problem</span>
            </em>
<em>
              <span style="COLOR: #808080">* using a genetic algorithm. The goal of the problem is to provide a</span>
            </em>
<em>
              <span style="COLOR: #808080">* specified amount of change (from a cash purchase) in the fewest coins</span>
            </em>
<em>
              <span style="COLOR: #808080">* possible. This example implementation uses American currency (quarters,</span>
            </em>
<em>
              <span style="COLOR: #808080">* dimes, nickels, and pennies).</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* This example may be seen as somewhat significant because it demonstrates</span>
            </em>
<em>
              <span style="COLOR: #808080">* the use of a genetic algorithm in a less-than-optimal problem space.</span>
            </em>
<em>
              <span style="COLOR: #808080">* The genetic algorithm does best when there is a smooth slope of fitness</span>
            </em>
<em>
              <span style="COLOR: #808080">* over the problem space towards the optimum solution. This problem exhibits</span>
            </em>
<em>
              <span style="COLOR: #808080">* a more choppy space with more local optima. However, as can be seen from</span>
            </em>
<em>
              <span style="COLOR: #808080">* running this example, the genetic algorithm still will get the correct</span>
            </em>
<em>
              <span style="COLOR: #808080">* answer virtually everytime.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
<strong>
              <span style="COLOR: #000080">public</span>
            </strong> <strong>
              <span style="COLOR: #000080">class</span>
            </strong> <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction</span> <strong>
              <span style="COLOR: #000080">extends</span>
            </strong> <span style="COLOR: #000000">FitnessFunction</span>
<span style="COLOR: #000000">{</span>
    <strong>
              <span style="COLOR: #000080">private</span>
            </strong> <strong>
              <span style="COLOR: #000080">final</span>
            </strong> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">m_targetAmount;</span>

    <em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* Constructs this MinimizingMakeChangeFitnessFunction with the desired</span>
            </em>
<em>
              <span style="COLOR: #808080">* amount of change to make.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_targetAmount The desired amount of change, in cents. This</span>
            </em>
<em>
              <span style="COLOR: #808080">* value must be between 1 and 99 cents.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
    <strong>
              <span style="COLOR: #000080">public</span>
            </strong> <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction(</span> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">a_targetAmount</span> <span style="COLOR: #000000">)</span>
    <span style="COLOR: #000000">{</span>
        <strong>
              <span style="COLOR: #000080">if</span>
            </strong>
            <span style="COLOR: #000000">(</span> <span style="COLOR: #000000">a_targetAmount</span> <span style="COLOR: #000000">&lt;</span> <span style="COLOR: #0000ff">1</span> <span style="COLOR: #000000">||</span> <span style="COLOR: #000000">a_targetAmount</span> <span style="COLOR: #000000">&gt;</span> <span style="COLOR: #0000ff">99</span> <span style="COLOR: #000000">)</span>
        <span style="COLOR: #000000">{</span>
            <strong>
              <span style="COLOR: #000080">throw</span>
            </strong> <strong>
              <span style="COLOR: #000080">new</span>
            </strong> <span style="COLOR: #000000">IllegalArgumentException(</span>
                <strong>
              <span style="COLOR: #009900">"Change amount must be between 1 and 99 cents."</span>
            </strong> <span style="COLOR: #000000">);</span>
        <span style="COLOR: #000000">}</span>

        <span style="COLOR: #000000">m_targetAmount</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">a_targetAmount;</span>
    <span style="COLOR: #000000">}</span>

    <em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* Determine the fitness of the given Chromosome instance. The higher the</span>
            </em>
<em>
              <span style="COLOR: #808080">* return value, the more fit the instance. This method should always</span>
            </em>
<em>
              <span style="COLOR: #808080">* return the same fitness value for two equivalent Chromosome instances.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_subject: The Chromosome instance to evaluate.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @return A positive integer reflecting the fitness rating of the given</span>
            </em>
<em>
              <span style="COLOR: #808080">* Chromosome.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
    <strong>
              <span style="COLOR: #000080">public</span>
            </strong> <strong>
              <span style="COLOR: #000080">double</span>
            </strong> <span style="COLOR: #000000">evaluate(</span> I<span style="COLOR: #000000">Chromosome</span> <span style="COLOR: #000000">a_subject</span> <span style="COLOR: #000000">)</span>
    <span style="COLOR: #000000">{</span>
        <em>
              <span style="COLOR: #808080">// The fitness value measures both how close the value is to the</span>
            </em>
        <em>
              <span style="COLOR: #808080">// target amount supplied by the user and the total number of coins</span>
            </em>
        <em>
              <span style="COLOR: #808080">// represented by the solution. We do this in two steps: first,</span>
            </em>
        <em>
              <span style="COLOR: #808080">// we consider only the represented amount of change vs. the target</span>
            </em>
        <em>
              <span style="COLOR: #808080">// amount of change and calculate higher fitness values for amounts</span>
            </em>
        <em>
              <span style="COLOR: #808080">// closer to the target, and lower fitness values for amounts further</span>
            </em>
        <em>
              <span style="COLOR: #808080">// away from the target. If the amount equals the target, then we go</span>
            </em>
        <em>
              <span style="COLOR: #808080">// to step 2, which adjusts the fitness to a higher value for</span>
            </em>
        <em>
              <span style="COLOR: #808080">// solutions representing fewer total coins, and lower fitness</span>
            </em>
        <em>
              <span style="COLOR: #808080">// values for solutions representing a larger total number of coins.</span>
            </em>
        <em>
              <span style="COLOR: #808080">// ------------------------------------------------------------------</span>
            </em>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">changeAmount</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">amountOfChange(</span> <span style="COLOR: #000000">a_subject</span> <span style="COLOR: #000000">);</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">totalCoins</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">getTotalNumberOfCoins(</span> <span style="COLOR: #000000">a_subject</span> <span style="COLOR: #000000">);</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">changeDifference</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">Math.abs(</span> <span style="COLOR: #000000">m_targetAmount</span> <span style="COLOR: #000000">-</span> <span style="COLOR: #000000">changeAmount</span> <span style="COLOR: #000000">);</span>

        <em>
              <span style="COLOR: #808080">// Step 1: Determine the distance of the amount represented by the</span>
            </em>
        <em>
              <span style="COLOR: #808080">// solution from the target amount. Since we know the maximum amount</span>
            </em>
        <em>
              <span style="COLOR: #808080">// of change is 99 cents, we'll subtract from that the difference</span>
            </em>
        <em>
              <span style="COLOR: #808080">// between the solution amount and the target amount. That will give</span>
            </em>
        <em>
              <span style="COLOR: #808080">// the desired effect of returning higher values for amounts close</span>
            </em>
        <em>
              <span style="COLOR: #808080">// to the target amount and lower values for amounts further away</span>
            </em>
        <em>
              <span style="COLOR: #808080">// from the target amount.</span>
            </em>
        <em>
              <span style="COLOR: #808080">// ------------------------------------------------------------------</span>
            </em>
        <strong>
              <span style="COLOR: #000080">double</span>
            </strong> <span style="COLOR: #000000">fitness</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">(</span> <span style="COLOR: #0000ff">99</span> <span style="COLOR: #000000">-</span> <span style="COLOR: #000000">changeDifference</span> <span style="COLOR: #000000">);</span>

        <em>
              <span style="COLOR: #808080">// Step 2: If the solution amount equals the target amount, then</span>
            </em>
        <em>
              <span style="COLOR: #808080">// we add additional fitness points for solutions representing fewer</span>
            </em>
        <em>
              <span style="COLOR: #808080">// total coins.</span>
            </em>
        <em>
              <span style="COLOR: #808080">// -----------------------------------------------------------------</span>
            </em>
        <strong>
              <span style="COLOR: #000080">if</span>
            </strong>
            <span style="COLOR: #000000">(</span> <span style="COLOR: #000000">changeAmount</span> <span style="COLOR: #000000">==</span> <span style="COLOR: #000000">m_targetAmount</span> <span style="COLOR: #000000">)</span>
        <span style="COLOR: #000000">{</span>
            <span style="COLOR: #000000">fitness</span> <span style="COLOR: #000000">+=</span> <span style="COLOR: #0000ff">100</span> <span style="COLOR: #000000">-</span> <span style="COLOR: #000000">(</span> <span style="COLOR: #0000ff">10</span> <span style="COLOR: #000000">*</span> <span style="COLOR: #000000">totalCoins</span> <span style="COLOR: #000000">);</span>
        <span style="COLOR: #000000">}</span>

        <strong>
              <span style="COLOR: #000080">return</span>
            </strong> <span style="COLOR: #000000">fitness;</span>
    <span style="COLOR: #000000">}</span>

    <em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* Calculates the total amount of change (in cents) represented by</span>
            </em>
<em>
              <span style="COLOR: #808080">* the given chromosome and returns that amount.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_potentialSolution The potential solution to evaluate.</span>
            </em>
<em>
              <span style="COLOR: #808080">* @return The total amount of change (in cents) represented by the</span>
            </em>
<em>
              <span style="COLOR: #808080">* given solution.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
    <strong>
              <span style="COLOR: #000080">public</span>
            </strong> <strong>
              <span style="COLOR: #000080">static</span>
            </strong> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">amountOfChange(</span> I<span style="COLOR: #000000">Chromosome</span> <span style="COLOR: #000000">a_potentialSolution</span> <span style="COLOR: #000000">)</span>
    <span style="COLOR: #000000">{</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">numQuarters</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> <span style="COLOR: #000000">a_potentialSolution,</span> <span style="COLOR: #0000ff">0</span> <span style="COLOR: #000000">);</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">numDimes</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> <span style="COLOR: #000000">a_potentialSolution,</span> <span style="COLOR: #0000ff">1</span> <span style="COLOR: #000000">);</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">numNickels</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> <span style="COLOR: #000000">a_potentialSolution,</span> <span style="COLOR: #0000ff">2</span> <span style="COLOR: #000000">);</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">numPennies</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> <span style="COLOR: #000000">a_potentialSolution,</span> <span style="COLOR: #0000ff">3</span> <span style="COLOR: #000000">);</span>

        <strong>
              <span style="COLOR: #000080">return</span>
            </strong> <span style="COLOR: #000000">(</span> <span style="COLOR: #000000">numQuarters</span> <span style="COLOR: #000000">*</span> <span style="COLOR: #0000ff">25</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <span style="COLOR: #000000">(</span> <span style="COLOR: #000000">numDimes</span> <span style="COLOR: #000000">*</span> <span style="COLOR: #0000ff">10</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <span style="COLOR: #000000">(</span> <span style="COLOR: #000000">numNickels</span> <span style="COLOR: #000000">*</span> <span style="COLOR: #0000ff">5</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span>
               <span style="COLOR: #000000">numPennies;</span>
    <span style="COLOR: #000000">}</span>

    <em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* Retrieves the number of coins represented by the given potential</span>
            </em>
<em>
              <span style="COLOR: #808080">* solution at the given gene position.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_potentialSolution The potential solution to evaluate.</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_position The gene position to evaluate.</span>
            </em>
<em>
              <span style="COLOR: #808080">* @return the number of coins represented by the potential solution</span>
            </em>
<em>
              <span style="COLOR: #808080">* at the given gene position.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
    <strong>
              <span style="COLOR: #000080">public</span>
            </strong> <strong>
              <span style="COLOR: #000080">static</span>
            </strong> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> I<span style="COLOR: #000000">Chromosome</span> <span style="COLOR: #000000">a_potentialSolution,</span>
                                              <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">a_position</span> <span style="COLOR: #000000">)</span>
    <span style="COLOR: #000000">{</span>
        <span style="COLOR: #000000">Integer</span> <span style="COLOR: #000000">numCoins</span> <span style="COLOR: #000000">=</span>
          <span style="COLOR: #000000">(Integer)</span> <span style="COLOR: #000000">a_potentialSolution.getGene(a_position).getAllele();</span>

        <strong>
              <span style="COLOR: #000080">return</span>
            </strong> <span style="COLOR: #000000">numCoins.intValue();</span>
    <span style="COLOR: #000000">}</span>

    <em>
              <span style="COLOR: #808080">/**</span>
            </em>
<em>
              <span style="COLOR: #808080">* Returns the total number of coins represented by all of the genes in</span>
            </em>
<em>
              <span style="COLOR: #808080">* the given chromosome.</span>
            </em>
<em>
              <span style="COLOR: #808080">*</span>
            </em>
<em>
              <span style="COLOR: #808080">* @param a_potentialsolution The potential solution to evaluate.</span>
            </em>
<em>
              <span style="COLOR: #808080">* @return The total number of coins represented by the given Chromosome.</span>
            </em>
<em>
              <span style="COLOR: #808080">*/</span>
            </em>
    <strong>
              <span style="COLOR: #000080">public</span>
            </strong> <strong>
              <span style="COLOR: #000080">static</span>
            </strong> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">getTotalNumberOfCoins(</span> I<span style="COLOR: #000000">Chromosome</span> <span style="COLOR: #000000">a_potentialsolution</span> <span style="COLOR: #000000">)</span>
    <span style="COLOR: #000000">{</span>
        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">totalCoins</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #0000ff">0</span>
            <span style="COLOR: #000000">;</span>

        <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">numberOfGenes</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">a_potentialsolution.size();</span>
        <strong>
              <span style="COLOR: #000080">for</span>
            </strong>
            <span style="COLOR: #000000">(</span> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">i</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #0000ff">0</span>
            <span style="COLOR: #000000">;</span> <span style="COLOR: #000000">i</span> <span style="COLOR: #000000">&lt;</span> <span style="COLOR: #000000">numberOfGenes;</span> <span style="COLOR: #000000">i++</span> <span style="COLOR: #000000">)</span>
        <span style="COLOR: #000000">{</span>
            <span style="COLOR: #000000">totalCoins</span> <span style="COLOR: #000000">+=</span> <span style="COLOR: #000000">getNumberOfCoinsAtGene(</span> <span style="COLOR: #000000">a_potentialsolution,</span> <span style="COLOR: #000000">i</span> <span style="COLOR: #000000">);</span>
        <span style="COLOR: #000000">}</span>

        <strong>
              <span style="COLOR: #000080">return</span>
            </strong> <span style="COLOR: #000000">totalCoins;</span>
    <span style="COLOR: #000000">}</span>
<span style="COLOR: #000000">}</span>
          </tt>
</pre>
<p class="text">Let&#8217;s tackle our example fitness function bit by bit. To start, we define our own class and extend the org.jgap.FitnessFunction class. All fitness functions must extend the FitnessFunction class. We then define a constructor and an evaluate() method. The evaluate() method is a standard method that all fitness functions must implement. That is the method that will be called by the genetic engine when it needs to know the fitness value of a chromosome.</p>
<p class="text">Our constructor isn&#8217;t very exciting: it merely accepts a target change amount that the user desires, verifies that the amount meets our constraint of being between 1 and 99 cents, and then stores the amount in an instance variable for later use.</p>
<p class="text">The interesting part of the whole class is the evaluate() method, which is where the work is done. The evaluate method is always passed in a Chromosome, which represents a potential solution. A Chromosome is made up of genes, each of which represents a respective part of the solution. In our example, the Chromosome represents an amount of change, while the genes represent the specific kinds of coins: quarters for the first gene, dimes for the second gene, nickels for the third gene, and pennies for the fourth gene. The value of a gene is called an allele. In our example, the allele would be the number of a given type of coin (for example, 2 pennies).</p>
<p class="text">The first thing the evaluate() method does is invoke a couple of helper methods which conveniently return the total amount of change that is represented by the potential solution and the total number of coins represented by the solution. We&#8217;ll take a closer look at how these work later. It then subtracts the amount of change represented by the solution from the target amount, and takes the absolute value of the difference to measure how close the solution amount is to the target amount. We then set about calculating our fitness value.</p>
<p class="text">As the comments indicate, we&#8217;re going to calculate fitness in two stages. The first stage calculates an initial fitness value based on how far away the solution amount is from the target amount. Then, if the solution amount happens to equal the target amount, we go to stage two, which adjusts the fitness value based upon the total number of coins represented by the solution. In the end, we want to return high fitness values for solutions that match the target amount with very few coins, and return lower fitness values for solutions that are far away from the target amount or represent a large number of coins.</p>
<p class="text">Moving beyond the evaluate() method, we encounter those helper methods we mentioned earlier. The amountOfChange() method calculates the total amount of change (in cents) represented by a Chromosome that is passed to it. Internally, it defers to the getNumberOfCoinsAtGene() method to actually extract the number of each type of coin. It then calculates the total amount of change and returns it.</p>
<p class="text">The next convenience method, getNumberOfCoinsAtGene(), is responsible for determining the number of coins represented by a specific gene in the given Chromosome. As mentioned earlier, the value of each gene in the Chromosome is called an allele. This method gets the allele for the gene at the provided position in the Chromosome and then returns it as an int primitive.</p>
<p class="text">Finally, there&#8217;s a getTotalNumberOfCoins() method that determines the total number of coins represented by a given Chromosome. It simply tallies up the number of coins represented by each gene&#8211;using the getNumberOfCoinsAtGene() method&#8211;and then returns the tally.</p>
<p class="text">And that&#8217;s the end of the fitness function. If you&#8217;re feeling a little bit overwhelmed, don&#8217;t worry about it and take some comfort in the fact that it&#8217;s all down hill from here! The fitness function is the hardest part of using JGAP and, after writing a few, you&#8217;ll get the hang of it.</p>
<h3 class="subheader"><a id="step3" name="step3">Step 3: Setup a Configuration Object</a></h3>
<p class="text"><a id="step3" name="step3">JGAP is designed to be very flexible and pluggable. If you want, you can create your own genetic operators, random number generators, natural selectors, and so on. To support all of this, JGAP uses a Configuration object that must be setup with all of the settings you want prior to using the genetic engine. Fortunately, we realize that most people will want to use the stock components, and so we include a DefaultConfiguration class that comes already setup with the most common settings. You just need to provide three extra pieces of information: what fitness function you want to use, how you want your Chromosomes to be setup, and how many Chromosomes you want in your population. Let&#8217;s look at some sample code that you might want to include in the same class as the above snippets.</a></p>
<pre class="Listing">
<tt>
            <a id="step2" name="step2">
              <strong>
                <span style="COLOR: #000080">public</span>
              </strong> <strong>
                <span style="COLOR: #000080">static</span>
              </strong> </a>
          </tt>
          <tt>
            <a id="step2" name="step2">void main<span style="COLOR: #000000">(</span>String[] args<span style="COLOR: #000000">) throws Exception {</span>
</a>  </tt>
          <a id="step3" name="step3">
            <tt>
              <em>
                <span style="COLOR: #808080">// Start with a DefaultConfiguration, which comes setup with the</span>
              </em>
  <span style="COLOR: #808080">
                <em>// most common settings.</em>
              </span>
  <span style="COLOR: #808080">
                <em>// -------------------------------------------------------------</em>
              </span>
  <span style="COLOR: #000000">Configuration</span> <span style="COLOR: #000000">conf</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">DefaultConfiguration();</span>

  <span style="COLOR: #808080">
                <em>// Set the fitness function we want to use, which is our</em>
              </span>
  <span style="COLOR: #808080">
                <em>// MinimizingMakeChangeFitnessFunction that we created earlier.</em>
              </span>
  <span style="COLOR: #808080">
                <em>// We construct it with the target amount of change provided</em>
              </span>
  <span style="COLOR: #808080">
                <em>// by the user.</em>
              </span>
  <span style="COLOR: #808080">
                <em>// ------------------------------------------------------------</em>
              </span>
  int targetAmount = Integer.parseInt(args[0])<span style="COLOR: #000000">; FitnessFunction</span> <span style="COLOR: #000000">myFunc</span> <span style="COLOR: #000000">=</span>
    <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction(</span> <span style="COLOR: #000000">targetAmount</span> <span style="COLOR: #000000">);</span>

  <span style="COLOR: #000000">conf.setFitnessFunction(</span> <span style="COLOR: #000000">myFunc</span> <span style="COLOR: #000000">);</span>

  <span style="COLOR: #808080">
                <em>// Now we need to tell the Configuration object how we want our</em>
              </span>
  <span style="COLOR: #808080">
                <em>// Chromosomes to be setup. We do that by actually creating a</em>
              </span>
  <span style="COLOR: #808080">
                <em>// sample Chromosome and then setting it on the Configuration</em>
              </span>
  <span style="COLOR: #808080">
                <em>// object. As mentioned earlier, we want our Chromosomes to</em>
              </span>
  <span style="COLOR: #808080">
                <em>// each have four genes, one for each of the coin types. We</em>
              </span>
  <span style="COLOR: #808080">
                <em>// want the values of those genes to be integers, which represent</em>
              </span>
  <span style="COLOR: #808080">
                <em>// how many coins of that type we have. We therefore use the</em>
              </span>
  <span style="COLOR: #808080">
                <em>// IntegerGene class to represent each of the genes. That class</em>
              </span>
  <span style="COLOR: #808080">
                <em>// also lets us specify a lower and upper bound, which we set</em>
              </span>
  <span style="COLOR: #808080">
                <em>// to sensible values for each coin type.</em>
              </span>
  <span style="COLOR: #808080">
                <em>// --------------------------------------------------------------</em>
              </span>
  <span style="COLOR: #000000">Gene[]</span> <span style="COLOR: #000000">sampleGenes</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">Gene[</span> <span style="COLOR: #0000ff">4</span> <span style="COLOR: #000000">];</span>

  <span style="COLOR: #000000">sampleGenes[</span>
              <span style="COLOR: #0000ff">0</span>
              <span style="COLOR: #000000">]</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">IntegerGene(conf,</span> <span style="COLOR: #0000ff">0</span>
              <span style="COLOR: #000000">,</span> <span style="COLOR: #0000ff">3</span> <span style="COLOR: #000000">);</span>  <em>
                <span style="COLOR: #808080">// Quarters</span>
              </em>
  <span style="COLOR: #000000">sampleGenes[</span>
              <span style="COLOR: #0000ff">1</span>
              <span style="COLOR: #000000">]</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">IntegerGene(conf,</span> <span style="COLOR: #0000ff">0</span>
              <span style="COLOR: #000000">,</span> <span style="COLOR: #0000ff">2</span> <span style="COLOR: #000000">);</span>  <em>
                <span style="COLOR: #808080">// Dimes</span>
              </em>
  <span style="COLOR: #000000">sampleGenes[</span>
              <span style="COLOR: #0000ff">2</span>
              <span style="COLOR: #000000">]</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">IntegerGene(conf,</span> <span style="COLOR: #0000ff">0</span>
              <span style="COLOR: #000000">,</span> <span style="COLOR: #0000ff">1</span> <span style="COLOR: #000000">);</span>  <em>
                <span style="COLOR: #808080">// Nickels</span>
              </em>
  <span style="COLOR: #000000">sampleGenes[</span>
              <span style="COLOR: #0000ff">3</span>
              <span style="COLOR: #000000">]</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">IntegerGene(conf,</span> <span style="COLOR: #0000ff">0</span>
              <span style="COLOR: #000000">,</span> <span style="COLOR: #0000ff">4</span> <span style="COLOR: #000000">);</span>  <em>
                <span style="COLOR: #808080">// Pennies</span>
              </em>

  <span style="COLOR: #000000">Chromosome</span> <span style="COLOR: #000000">sampleChromosome</span> <span style="COLOR: #000000">=</span> <strong>
                <span style="COLOR: #000080">new</span>
              </strong> <span style="COLOR: #000000">Chromosome(conf,</span> <span style="COLOR: #000000">sampleGenes</span> <span style="COLOR: #000000">);</span>

  <span style="COLOR: #000000">conf.setSampleChromosome(</span> <span style="COLOR: #000000">sampleChromosome</span> <span style="COLOR: #000000">);</span>

  <span style="COLOR: #808080">
                <em>// Finally, we need to tell the Configuration object how many</em>
              </span>
  <span style="COLOR: #808080">
                <em>// Chromosomes we want in our population. The more Chromosomes,</em>
              </span>
  <span style="COLOR: #808080">
                <em>// the larger the number of potential solutions (which is good</em>
              </span>
  <span style="COLOR: #808080">
                <em>// for finding the answer), but the longer it will take to evolve</em>
              </span>
  <span style="COLOR: #808080">
                <em>// the population each round. We'll set the population size to</em>
              </span>
  <span style="COLOR: #808080">
                <em>// 500 here.</em>
              </span>
  <span style="COLOR: #808080">
                <em>// --------------------------------------------------------------</em>
              </span>
  <span style="COLOR: #000000">conf.setPopulationSize(</span> <span style="COLOR: #0000ff">500</span> <span style="COLOR: #000000">); // TODO: Add the code following below in this example here}</span>
            </tt>
          </a>
</pre>
<p class="text"><a id="step3" name="step3">Hopefully most of the above code is pretty self-explanatory, with maybe the exception of setting up the sample Chromosome. Let&#8217;s look at that bit in a little more detail.</a></p>
<p class="text"><a id="step3" name="step3">As mentioned earlier, a Chromosome is made up of genes. JGAP lets you choose what Gene class to use to represent each gene in the Chromosome (for more information on creating custom Gene classes, please see the</a> <a href="http://jgap.sourceforge.net/doc/genes.html">Creating Custom Genes</a> document). That provides the most flexibility and convenience. If we wanted to, we could have actually written a separate Gene class for each coin type in our example, such as a QuarterGene, DimeGene, NickelGene, and PennyGene. In fact, we look at what a QuarterGene might look like in the <em>Creating Custom Genes</em> document that we just mentioned.</p>
<p class="text">As it happens, we decided that the IntegerGene (which comes with JGAP) would suffice. You&#8217;ll notice, however, that we did take advantage of the ability to specify different Gene implementations for each gene in the Chromosome by creating separate IntegerGenes with different lower and upper bounds for each coin type. We set the upper bounds to be the largest number of coins of that respective type that would appear in an optimal solution. Limiting the solution space this way helps JGAP arrive at better solutions with fewer evolutions.</p>
<p class="text">So to get back to the code, we first create an array of Genes with a length of 4, since we want to represent 4 genes (one for each coin type). We then set each Gene in the array to an IntegerGene that is constructed with appropriate lower and upper bounds for that coin type. Finally, we construct a new Chromosome and pass it the array of Genes, and then set that sample Chromosome on the Configuration object.</p>
<p class="text">The final part of this step is setting the population size, which is the number of Chromosomes we want in the population. A larger population size means more potential solutions to choose from and more genetic diversity, but it also means more work to evolve that population. Ultimately, you&#8217;ll need to settle on a value that balances your need for a nice selection of potential solutions against how much time you&#8217;re willing to spend waiting for your population to evolve. The population size is chosen higher than the number of possible solutions here (as 3*2*1*4 = 24). But as Genetic Algorithms is a stochastic system, the more tries the GA is allowed to make, the higher the chances finding a good solution. Besides, the population size should not be correlated too specifically to a narrowed search space, but be usable in a more generic way. Meaning: if the 24 possible combinations mentioned above was raised, then the population wouldn&#8217;t need to be adapted. And if the 24 is kept, the population size of 500 will not have a negative impact, because fewer evolutions are needed finding a good solutions than with smaller population size.</p>
<h3 class="subheader"><a id="step4" name="step4">Step 4: Create a Population</a></h3>
<p class="text"><a id="step4" name="step4">Recall that each potential solution is represented by a Chromosome. A population of Chromosomes is called a Genotype, and that is the class we need to construct to create our population. If you want, you can construct each Chromosome individually and then pass them all into a new Genotype (much like we constructed each Gene and passed them into the sample Chromosome in step 3), but JGAP provides a much quicker and easier way of creating a random population. In fact, it only takes one line of code</a> <a id="step5" name="step5">(append all following code lines to the above code in method main)</a>:</p>
<pre class="Listing">
<tt>
            <span style="COLOR: #000000">Genotype</span> <span style="COLOR: #000000">population</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">Genotype.randomInitialGenotype(</span> <span style="COLOR: #000000">conf</span> <span style="COLOR: #000000">);</span>
          </tt>
</pre>
<p>The randomInitialGenotype() method takes in a Configuration object (which we setup in step 3) and returns a Genotype with the correct number of Chromosomes, each of which has its genes set to random values. In other words, it generates a random population. For most applications, this is all that&#8217;s necessary to create your initial population of potential solutions.</p>
<h3 class="subheader"><a id="step5" name="step5">Step 5: Evolve the Population!</a></h3>
<p class="text">Now that we&#8217;ve gotten everything setup and ready to go, it&#8217;s time to start evolving the population until it contains some potential solutions that we&#8217;re satisfied with. Evolving the population one cycle is another one-liner:</p>
<pre class="Listing">
<tt>
            <span style="COLOR: #000000">population.evolve();</span>
          </tt>
</pre>
<p class="text">Typically, after each evolution cycle, you&#8217;ll want to check if the population contains any satisfactory solutions. The easiest way to do this is to invoke the getFittestChromosome() method on the population:</p>
<pre class="Listing">
<tt>
            <span style="COLOR: #000000">IChromosome</span> <span style="COLOR: #000000">bestSolutionSoFar</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #000000">population.getFittestChromosome();</span>
          </tt>
</pre>
<p class="text">If the best solution so far is good enough for you, then you&#8217;re done. If not, then you can evolve the population again. Alternatively, you may just choose to evolve the population a set number of times and then see what the best solution is that was produced at the end (or a combination thereof). For our example problem, we&#8217;ll take this latter approach.</p>
<pre class="Listing">
<tt>
            <span style="COLOR: #000000">IChromosome</span> <span style="COLOR: #000000">bestSolutionSoFar;</span>

<strong>
              <span style="COLOR: #000080">for</span>
            </strong>
            <span style="COLOR: #000000">(</span> <strong>
              <span style="COLOR: #000080">int</span>
            </strong> <span style="COLOR: #000000">i</span> <span style="COLOR: #000000">=</span> <span style="COLOR: #0000ff">0</span>
            <span style="COLOR: #000000">;</span> <span style="COLOR: #000000">i</span> <span style="COLOR: #000000">&lt;</span> <span style="COLOR: #000000">MAX_ALLOWED_EVOLUTIONS;</span> <span style="COLOR: #000000">i++</span> <span style="COLOR: #000000">)</span>
<span style="COLOR: #000000">{</span>
    <span style="COLOR: #000000">population.evolve();</span>
<span style="COLOR: #000000">}</span>

<span style="COLOR: #000000">System.out.println(</span> <strong>
              <span style="COLOR: #009900">"The best solution contained the following: "</span>
            </strong> <span style="COLOR: #000000">);</span>

<span style="COLOR: #000000">System.out.println(</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(</span>
        <span style="COLOR: #000000">bestSolutionSoFar,</span> <span style="COLOR: #0000ff">0</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" quarters."</span>
            </strong> <span style="COLOR: #000000">);</span>

<span style="COLOR: #000000">System.out.println(</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(</span>
        <span style="COLOR: #000000">bestSolutionSoFar,</span> <span style="COLOR: #0000ff">1</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" dimes."</span>
            </strong> <span style="COLOR: #000000">);</span>

<span style="COLOR: #000000">System.out.println(</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(</span>
        <span style="COLOR: #000000">bestSolutionSoFar,</span> <span style="COLOR: #0000ff">2</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" nickels."</span>
            </strong> <span style="COLOR: #000000">);</span>

<span style="COLOR: #000000">System.out.println(</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(</span>
        <span style="COLOR: #000000">bestSolutionSoFar,</span> <span style="COLOR: #0000ff">3</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" pennies."</span>
            </strong> <span style="COLOR: #000000">);</span>

<span style="COLOR: #000000">System.out.println(</span> <strong>
              <span style="COLOR: #009900">"For a total of "</span>
            </strong> <span style="COLOR: #000000">+</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.amountOfChange(</span>
        <span style="COLOR: #000000">bestSolutionSoFar</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" cents in "</span>
            </strong> <span style="COLOR: #000000">+</span>
    <span style="COLOR: #000000">MinimizingMakeChangeFitnessFunction.getTotalNumberOfCoins(</span>
        <span style="COLOR: #000000">bestSolutionSoFar</span> <span style="COLOR: #000000">)</span> <span style="COLOR: #000000">+</span> <strong>
              <span style="COLOR: #009900">" coins."</span>
            </strong> <span style="COLOR: #000000">);</span>
          </tt>
</pre>
<p class="text">Now we&#8217;ve got ourselves a full-fledged genetic application! To view all of the code for this example, see the MinimizingMakeChange.java and MinimizingMakeChangeFitnessFunction.java files in the examples/src directory of the JGAP distribution.</p>
<h3 class="subheader"><a id="step1" name="step1">Further resources</a></h3>
<ul>
<li>
<p class="subheader">See the examples under package <em>examples</em>. They are located in subdirectory <em>examples/src</em> of the JGAP source distribution.</p>
</li>
<li>
<p class="subheader">See the external <a href="http://jcraane.blogspot.com/2009/02/introduction-to-genetic-algorithms-with.html" target="_blank">blog entry from Jamie Craane</a> or <a href="http://jgap.sourceforge.net/doc/references/Introduction to Genetic Algorithms with JGAP.pdf" target="_blank">download a local copy of the article as PDF</a>.</p>
</li>
</ul>
<h3>Random Posts</h3>
<ul class="related_post">
<li><a href="http://www.zhangdaqian.net/blog/%e8%bf%99%e4%b8%8d%e6%98%af%e5%86%b7%e7%ac%91%e8%af%9d%ef%bc%8c%e8%bf%99%e6%98%af%e5%93%b2%e7%90%86.htm" title="这个笑话不太冷">这个笑话不太冷</a></li>
<li><a href="http://www.zhangdaqian.net/blog/%e5%bc%b1%e5%bc%b1%e7%9a%84%e8%b4%b4%e4%b8%80%e4%b8%8b.htm" title="弱弱的贴一下">弱弱的贴一下</a></li>
<li><a href="http://www.zhangdaqian.net/blog/%e5%85%b3%e4%ba%8e%e9%9b%86%e4%bd%93%e4%b8%8b%e7%ba%bf%e7%9a%84%e7%8c%9c%e6%b5%8b.htm" title="关于集体下线的猜测">关于集体下线的猜测</a></li>
<li><a href="http://www.zhangdaqian.net/blog/ieee%e7%9a%84%e8%af%bb%e9%9f%b3.htm" title="IEEE的读音">IEEE的读音</a></li>
<li><a href="http://www.zhangdaqian.net/blog/%e6%97%a0%e9%a2%98-2.htm" title="无题">无题</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.zhangdaqian.net/blog/getting-started-with-jgap.htm/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
