<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>genetic-algorithm &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/genetic-algorithm/</link>
	<description>Feed of posts on WordPress.com tagged "genetic-algorithm"</description>
	<pubDate>Tue, 01 Dec 2009 13:22:14 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Hybrid Multi-Agent A.I. for Tactical Games]]></title>
<link>http://jestermax.wordpress.com/2009/11/18/hybrid-multi-agent-a-i-for-tactical-games/</link>
<pubDate>Thu, 19 Nov 2009 00:21:06 +0000</pubDate>
<dc:creator>jestermax</dc:creator>
<guid>http://jestermax.wordpress.com/2009/11/18/hybrid-multi-agent-a-i-for-tactical-games/</guid>
<description><![CDATA[As part of my Intelligent Systems course in my Masters program, I am working on a project that joins]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>As part of my Intelligent Systems course in my Masters program, I am working on a project that joins two intelligent systems together. I won&#8217;t post many of the finer details of the project (check out my conference paper once I get around to writing it), but it is a rule-based and genetic algorithm hybrid.</p>
<p>The idea here is not create a &#8220;super-agent&#8221; that can win at games, but more to simulate personality in NPC characters. I&#8217;ve yet to generate a decent set of experiment results, but things are looking good so far. I have my test software written and I&#8217;m about to add my genetic algorithm library to the project to see what happens.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[my first GA]]></title>
<link>http://bradypeters.wordpress.com/2009/11/16/my-first-ga/</link>
<pubDate>Mon, 16 Nov 2009 15:43:07 +0000</pubDate>
<dc:creator>bradypeters</dc:creator>
<guid>http://bradypeters.wordpress.com/2009/11/16/my-first-ga/</guid>
<description><![CDATA[&nbsp; after months of talking about it, i finally finished a genetic algorithm to optimise reflecto]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img class="alignnone size-full wp-image-34" title="ga_01e_persp1_v2" src="http://bradypeters.wordpress.com/files/2009/11/ga_01e_persp1_v2.jpg" alt="ga_01e_persp1_v2" width="420" height="244" /></p>
<p>&#160;</p>
<p>after months of talking about it, i finally finished a genetic algorithm to optimise reflector panels. this is general digital tool using simple ray-tracing methods. from initial tests using ODEON, it seems to work!</p>
<p><img class="alignnone size-full wp-image-35" title="ga_01e_SPL500_v2" src="http://bradypeters.wordpress.com/files/2009/11/ga_01e_spl500_v2.jpg" alt="ga_01e_SPL500_v2" width="420" height="250" /></p>
<p><img class="alignnone size-full wp-image-33" title="ga_01e_table_v2" src="http://bradypeters.wordpress.com/files/2009/11/ga_01e_table_v2.jpg" alt="ga_01e_table_v2" width="420" height="213" /></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Resolve TSP (Traveling Saleman Problem) in Genetic Algorithm]]></title>
<link>http://zhanggw.wordpress.com/2009/11/07/resolve-tsp-traveling-saleman-problem-in-genetic-algorithm/</link>
<pubDate>Sat, 07 Nov 2009 15:02:54 +0000</pubDate>
<dc:creator>zgw21cnn</dc:creator>
<guid>http://zhanggw.wordpress.com/2009/11/07/resolve-tsp-traveling-saleman-problem-in-genetic-algorithm/</guid>
<description><![CDATA[A random route can be shown like this, After iteration,the result can be like this. Method of genera]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A random route can be shown like this,</p>
<p><a href="http://zhanggw.files.wordpress.com/2009/11/tspstart.png"><img style="display:inline;border-width:0;" title="TSPstart" src="http://zhanggw.files.wordpress.com/2009/11/tspstart_thumb.png?w=240&#038;h=190" border="0" alt="TSPstart" width="240" height="190" /></a></p>
<p>After iteration,the result can be like this.</p>
<p><a href="http://zhanggw.files.wordpress.com/2009/11/tspresult.png"><img style="display:inline;border-width:0;" title="TSPresult" src="http://zhanggw.files.wordpress.com/2009/11/tspresult_thumb.png?w=240&#038;h=190" border="0" alt="TSPresult" width="240" height="190" /></a></p>
<p>Method of generation routines is got from here:</p>
<p><a href="http://www.psychicorigami.com/2007/04/17/tackling-the-travelling-salesman-problem-part-one/">http://www.psychicorigami.com/2007/04/17/tackling-the-travelling-salesman-problem-part-one/</a></p>
<pre>'''
Created on 2009-10-29
@author: Administrator
'''
<span style="color:#0000ff;">import</span> <span style="color:#0000ff;">sys</span>, random
from math <span style="color:#0000ff;">import</span> sqrt
from <span style="color:#0000ff;">pickle</span> <span style="color:#0000ff;">import</span> *

PIL_SUPPORT = None
try:
   from PIL <span style="color:#0000ff;">import</span> Image, ImageDraw, ImageFont
   PIL_SUPPORT = True
except:
   PIL_SUPPORT = False 

<span style="color:#0000ff;">def</span> cartesian_matrix(coords):
   """ A distance matrix """
   matrix = {}
   for i, (x1, y1) in enumerate(coords):
      for j, (x2, y2) in enumerate(coords):
         dx, dy = x1 - x2, y1 - y2
         dist = sqrt(dx * dx + dy * dy)
         matrix[i, j] = dist
   <span style="color:#0000ff;">return</span> matrix 

<span style="color:#0000ff;">def</span> tour_length(matrix, tour):
   """ Returns the total length of the tour """
   total = 0
   num_cities = len(tour)
   for i in range(num_cities):
      j = (i + 1) % num_cities
      city_i = tour[i]
      city_j = tour[j]
      total += matrix[city_i, city_j]
   <span style="color:#0000ff;">return</span> total

<span style="color:#0000ff;">def</span> write_tour_to_img(coords, tour, img_file):
   """ The <span style="color:#0000ff;">function</span> to plot the graph """
   padding = 20
   coords = [(x + padding, y + padding) for (x, y) in coords]
   maxx, maxy = 0, 0
   for x, y in coords:
      maxx = max(x, maxx)
      maxy = max(y, maxy)
   maxx += padding
   maxy += padding
   img = Image.<span style="color:#0000ff;">new</span>("<span style="color:#8b0000;">RGB</span>", (int(maxx), int(maxy)),\
         color=(255, 255, 255))
   font = ImageFont.load_default()
   d = ImageDraw.Draw(img);
   num_cities = len(tour)
   for i in range(num_cities):
      j = (i + 1) % num_cities
      city_i = tour[i]
      city_j = tour[j]
      x1, y1 = coords[city_i]
      x2, y2 = coords[city_j]
      d.line((int(x1), int(y1), int(x2), int(y2)), fill=(0, 0, 0))
      d.text((int(x1) + 7, int(y1) - 5), str(i), \
        font=font, fill=(32, 32, 32)) 

   for x, y in coords:
      x, y = int(x), int(y)
      d.ellipse((x - 5, y - 5, x + 5, y + 5), outline=(0, 0, 0),\
                fill=(196, 196, 196))
   del d
   img.save(img_file, "<span style="color:#8b0000;">PNG</span>")
   <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">The plot was saved into the %s file.</span>" % (img_file,)  

cm = []
coords = [] 

<span style="color:#0000ff;">def</span> eval_func(chromosome):
   """ The evaluation <span style="color:#0000ff;">function</span> """
   global cm
   <span style="color:#0000ff;">return</span> tour_length(cm, chromosome) 

<span style="color:#0000ff;">def</span> cities_random(cities, xmax=800, ymax=600):
   """ get random cities/positions """
   coords = []
   for i in xrange(cities):
      x = random.randint(0, xmax)
      y = random.randint(0, ymax)
      coords.append((float(x), float(y)))
   <span style="color:#0000ff;">return</span> coords

#Individuals
<span style="color:#0000ff;">class</span> Individual:
    score = 0
    length = 30
    seperator = ' '
    <span style="color:#0000ff;">def</span> __init__(self, chromosome=None, length=30):
        self.chromosome = chromosome or self._makechromosome()
        self.length = length
        self.score = 0  # set during evaluation  

    <span style="color:#0000ff;">def</span> _makechromosome(self):
        "<span style="color:#8b0000;">makes a chromosome from randomly selected alleles.</span>"
        chromosome = []
        lst = [i for i in xrange(self.length)]
        for i in xrange(self.length):
            choice = random.choice(lst)
            lst.remove(choice)
            chromosome.append(choice)
        <span style="color:#0000ff;">return</span> chromosome

    <span style="color:#0000ff;">def</span> evaluate(self, optimum=None):
        self.score = eval_func(self.chromosome)

    <span style="color:#0000ff;">def</span> crossover(self, other):
        left, right = self._pickpivots()
        p1 = Individual()
        p2 = Individual()
        c1 = [ c for c in self.chromosome \
               <span style="color:#0000ff;">if</span> c not in other.chromosome[left:right + 1]]
        p1.chromosome = c1[:left] + other.chromosome[left:right + 1]\
                         + c1[left:]
        c2 = [ c for c in other.chromosome <span style="color:#0000ff;">\
               if</span> c not in self.chromosome[left:right + 1]]
        p2.chromosome = c2[:left] + self.chromosome[left:right + 1] \
                        + c2[left:]
        <span style="color:#0000ff;">return</span> p1, p2

    <span style="color:#0000ff;">def</span> mutate(self):
        "<span style="color:#8b0000;">swap two element</span>"
        left, right = self._pickpivots()
        temp = self.chromosome[left]
        self.chromosome[left] = self.chromosome[right]
        self.chromosome[right] = temp   

    <span style="color:#0000ff;">def</span> _pickpivots(self):
        left = random.randint(0, self.length - 2)
        right = random.randint(left, self.length - 1)
        <span style="color:#0000ff;">return</span> left, right    

    <span style="color:#0000ff;">def</span> __repr__(self):
        "<span style="color:#8b0000;">returns string representation of self</span>"
        <span style="color:#0000ff;">return</span> '&#60;%s chromosome="<span style="color:#8b0000;">%s</span>" score=%s&#62;' % \
               (self.__class__.__name__,
                self.seperator.<span style="color:#0000ff;">join</span>(map(str, self.chromosome)), self.score)  

    <span style="color:#0000ff;">def</span> <span style="color:#0000ff;">copy</span>(self):
        twin = self.__class__(self.chromosome[:])
        twin.score = self.score
        <span style="color:#0000ff;">return</span> twin

    <span style="color:#0000ff;">def</span> __cmp__(self, other):
        <span style="color:#0000ff;">return</span> cmp(self.score, other.score)

<span style="color:#0000ff;">class</span> Environment:
    size = 0
    <span style="color:#0000ff;">def</span> __init__(self, population=None, size=100, maxgenerations=1000,\
                 newindividualrate=0.6,crossover_rate=0.90,\
                 mutation_rate=0.1):
        self.size = size
        self.population = self._makepopulation()
        self.maxgenerations = maxgenerations
        self.newindividualrate = newindividualrate
        self.crossover_rate = crossover_rate
        self.mutation_rate = mutation_rate
        for individual in self.population:
            individual.evaluate()
        self.generation = 0
        self.minscore = <span style="color:#0000ff;">sys</span>.<span style="color:#0000ff;">maxint</span>
        self.minindividual = None
        #self._printpopulation()
        <span style="color:#0000ff;">if</span> PIL_SUPPORT:
            write_tour_to_img(coords, self.population[0].chromosome,\
                              "<span style="color:#8b0000;">TSPstart.png</span>")
        <span style="color:#0000ff;">else</span>:
            <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">No PIL detected,can not plot the graph</span>"

    <span style="color:#0000ff;">def</span> _makepopulation(self):
        <span style="color:#0000ff;">return</span> [Individual() for i in range(0, self.size)]

    <span style="color:#0000ff;">def</span> run(self):
        for i in range(1, self.maxgenerations + 1):
            <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">Generation no:</span>" + str(i)
            for j in range(0, self.size):
                self.population[j].evaluate()
                curscore = self.population[j].score
                <span style="color:#0000ff;">if</span> curscore &#60; self.minscore:
                    self.minscore = curscore
                    self.minindividual = self.population[j]
            <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">Best individual:</span>", self.minindividual
            <span style="color:#0000ff;">if</span> random.random() &#60; self.crossover_rate:
                children = []
                newindividual = int(self.newindividualrate * self.size / 2)
                for i in range(0, newindividual):
                    selected1 = self._selectrank()
                    selected2 = self._selectrank()
                    parent1 = self.population[selected1]
                    parent2 = self.population[selected2]
                    child1, child2 = parent1.crossover(parent2)
                    child1.evaluate()
                    child2.evaluate()
                    children.append(child1)
                    children.append(child2)
                for i in range(0, newindividual):
                    #replce with child
                    totalscore = 0
                    for k in range(0, self.size):
                        totalscore += self.population[k].score
                    randscore = random.random()
                    addscore = 0
                    for j in range(0, self.size):
                        addscore += (self.population[j].score / totalscore)
                        <span style="color:#0000ff;">if</span> addscore &#62;= randscore:
                            self.population[j] = children[i]
                            break
            <span style="color:#0000ff;">if</span> random.random() &#60; self.mutation_rate:
                selected = self._select()
                self.population[selected].mutate()
        #<span style="color:#0000ff;">end</span> loop
        for i in range(0, self.size):
                self.population[i].evaluate()
                curscore = self.population[i].score
                <span style="color:#0000ff;">if</span> curscore &#60; self.minscore:
                    self.minscore = curscore
                    self.minindividual = self.population[i]
        <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">..................Result.........................</span>"
        <span style="color:#0000ff;">print</span> self.minindividual
        #self._printpopulation()

    <span style="color:#0000ff;">def</span> _select(self):
        totalscore = 0
        for i in range(0, self.size):
            totalscore += self.population[i].score
        randscore = random.random()*(self.size - 1)
        addscore = 0
        selected = 0
        for i in range(0, self.size):
            addscore += (1 - self.population[i].score / totalscore)
            <span style="color:#0000ff;">if</span> addscore &#62;= randscore:
                selected = i
                break
        <span style="color:#0000ff;">return</span> selected

    <span style="color:#0000ff;">def</span> _selectrank(self, choosebest=0.9):
        self.population.sort()
        <span style="color:#0000ff;">if</span> random.random() &#60; choosebest:
            <span style="color:#0000ff;">return</span> random.randint(0, self.size * self.newindividualrate)
        <span style="color:#0000ff;">else</span>:
            <span style="color:#0000ff;">return</span> random.randint(self.size * self.newindividualrate,\
                   self.size - 1)

    <span style="color:#0000ff;">def</span> _printpopulation(self):
        for i in range(0, self.size):
            <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">Individual </span>", i, self.population[i]      

<span style="color:#0000ff;">def</span> main_run():
    global cm, coords
    #get cities's coords
    coords =cities_random(30)
    cm = cartesian_matrix(coords)
    ev = Environment()
    ev.run()
    <span style="color:#0000ff;">if</span> PIL_SUPPORT:
        write_tour_to_img(coords, ev.minindividual.chromosome, \
                          "<span style="color:#8b0000;">TSPresult.png</span>")
    <span style="color:#0000ff;">else</span>:
        <span style="color:#0000ff;">print</span> "<span style="color:#8b0000;">No PIL detected,can not plot the graph</span>"
<span style="color:#0000ff;">if</span> __name__ == "<span style="color:#8b0000;">__main__</span>":
    main_run()</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[William Dembski discusses new peer-reviewed paper on intelligent design]]></title>
<link>http://winteryknight.wordpress.com/2009/10/20/william-dembski-discusses-new-peer-reviewed-paper-on-intelligent-design/</link>
<pubDate>Tue, 20 Oct 2009 18:00:23 +0000</pubDate>
<dc:creator>Wintery Knight</dc:creator>
<guid>http://winteryknight.wordpress.com/2009/10/20/william-dembski-discusses-new-peer-reviewed-paper-on-intelligent-design/</guid>
<description><![CDATA[The paper talks about how to measure the amount of information required by evolutionary algorithms i]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The paper talks about how to measure the amount of information required by evolutionary algorithms in order for them to work. The paper describes accounting processes for measuring where information is put into evolutionary algorithms, so that it becomes clear how much information is needed up front. The paper shows that the information present in evolutionary algorithms does not emerge as a result of evolutionary algorithms &#8211; the &#8220;active information&#8221; has to be put into the process at different points for the process to work.</p>
<p>The paper:</p>
<p>&#8220;Conservation of Information in Search: Measuring the Cost of Success,&#8221; published in <em>IEEE Transactions on Systems, Man and Cybernetics A, Systems &#38; Humans</em>.</p>
<p><a href="http://intelligentdesign.podomatic.com/enclosure/2009-10-15T13_14_01-07_00.mp3" target="_blank">The MP3 file for Part 1 is here</a>.</p>
<p>Part 1 Topics:</p>
<ul>
<li>about the IEEE, the publisher of the paper Dembski and Marks</li>
<li>the search problem and evolutionary algorithms</li>
<li>the concept of &#8220;active information&#8221;</li>
<li>blind search versus targeted searches</li>
<li>No Free Lunch theorems</li>
<li>Conservation of information</li>
<li>Responding to an objection: is Darwinism analogous to the search problem?</li>
<li>does evolution have mathematical underpinnings?</li>
</ul>
<p><a href="http://intelligentdesign.podomatic.com/enclosure/2009-10-19T14_08_52-07_00.mp3" target="_blank">The MP3 file for Part 2 is here</a>.</p>
<p>Part 2 Topics:</p>
<ul>
<li> fitness functions and fitness landscape</li>
<li>constraints as information</li>
<li>does the paper support intelligent design?</li>
<li>how have critics responded to this paper?</li>
</ul>
<p><a href="http://evoinfo.org/Publications/CostOfSuccess.html" target="_blank">You can read the entire paper for free here</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[[書籍]多目標智慧優化演算法及其應用（簡體書）－智能科學技術著作叢書 ]]></title>
<link>http://kyledogya.wordpress.com/2009/10/14/%e6%9b%b8%e7%b1%8d%e5%a4%9a%e7%9b%ae%e6%a8%99%e6%99%ba%e6%85%a7%e5%84%aa%e5%8c%96%e6%bc%94%e7%ae%97%e6%b3%95%e5%8f%8a%e5%85%b6%e6%87%89%e7%94%a8%ef%bc%88%e7%b0%a1%e9%ab%94%e6%9b%b8%ef%bc%89%ef%bc%8d/</link>
<pubDate>Wed, 14 Oct 2009 14:10:50 +0000</pubDate>
<dc:creator>kyle02191221</dc:creator>
<guid>http://kyledogya.wordpress.com/2009/10/14/%e6%9b%b8%e7%b1%8d%e5%a4%9a%e7%9b%ae%e6%a8%99%e6%99%ba%e6%85%a7%e5%84%aa%e5%8c%96%e6%bc%94%e7%ae%97%e6%b3%95%e5%8f%8a%e5%85%b6%e6%87%89%e7%94%a8%ef%bc%88%e7%b0%a1%e9%ab%94%e6%9b%b8%ef%bc%89%ef%bc%8d/</guid>
<description><![CDATA[多目標智慧優化演算法及其應用（簡體書）－智能科學技術著作叢書 I S B N：7030236947 I S B N 13：9787030236944 作    者：雷德明 精平裝： 平裝本 出版社：科]]></description>
<content:encoded><![CDATA[多目標智慧優化演算法及其應用（簡體書）－智能科學技術著作叢書 I S B N：7030236947 I S B N 13：9787030236944 作    者：雷德明 精平裝： 平裝本 出版社：科]]></content:encoded>
</item>
<item>
<title><![CDATA[ECJ: A First/Simple Tutorial]]></title>
<link>http://cvalcarcel.wordpress.com/2009/08/22/ecj-a-firstsimple-tutorial/</link>
<pubDate>Sat, 22 Aug 2009 22:58:50 +0000</pubDate>
<dc:creator>cvalcarcel</dc:creator>
<guid>http://cvalcarcel.wordpress.com/2009/08/22/ecj-a-firstsimple-tutorial/</guid>
<description><![CDATA[(This is going to be another long one.) When we last left our heroes they were looking into JGAP as ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>(This is going to be another long one.)</p>
<p>When we last left our heroes they were looking into <a href="http://jgap.sourceforge.net/">JGAP as a cool framework</a> for the creation of genetic algorithms. One simple example left them warm and fuzzy and the second left them temporarily bewildered. Taking a better look at the <a href="https://watchmaker.dev.java.net/">Watchmaker Framework</a> helped clear their minds and made them realize that more thought was needed. They stopped, took a deep breath and ordered <a href="http://www.jaunted.com/files/4912/cappuccino_hearts.jpg">cappuccinos</a>.</p>
<p>In the course of human events, research is inevitable. In my research I ran across Mehdi Khoury&#8217;s tutorial page which included a <a href="http://userweb.port.ac.uk/~khourym/tutorials.html">comparison of different genetic programming packages as of June 2007</a>. The package he rated the highest? A package named <a href="http://cs.gmu.edu/~eclab/projects/ecj/">ECJ</a> developed at George Mason University&#8217;s <a href="http://cs.gmu.edu/~eclab">Evolutionary Computation Laboratory</a>.</p>
<p>In the course of my research in GP frameworks I decided I wanted to give ECJ a try as well. Nothing like a recommendation from a web site I&#8217;ve never heard of to influence my decision making capabilities about cool technologies.</p>
<p>I will be reversing the examples as the Hello World example is really about genetic algorithms while the Simple Math Test, taken from <a href="http://rcm.amazon.com/e/cm?t=ladybuguniver-20&#38;o=1&#38;p=8&#38;l=as1&#38;asins=0596529325&#38;fc1=000000&#38;IS2=1&#38;lt1=_blank&#38;m=amazon&#38;lc1=0000FF&#38;bc1=000000&#38;bg1=FFFFFF&#38;f=ifr">Toby Segaran&#8217;s Programming Collective Intelligence</a>, is about genetic programming. It just makes sense to do GA before GP.</p>
<p>If you disagree I look forward to reading your blog posting where you do the reverse.</p>
<h2>Hello World &#8211; A Genetic Algorithm</h2>
<p>Input: the alphabet + a comma + an exclamation point + a space<br />
Output: &#8220;Hello, world!&#8221;</p>
<h2>The ECJ Properties File</h2>
<p>The use of properties files is a very Java thing. Not to say that other programming languages don&#8217;t use something similar, but Java has made their use a virtue. In some cases, properties files are fantastic, while in other cases XML files are better. Folks who prefer verbose descriptions prefer XML and all others prefer the <em>key=value</em> format of properties; which you decide to use should be based on the problem at hand and not a knee-jerk reaction. Good luck figuring out if you&#8217;re having a brain-based knee-jerk reaction right now.</p>
<p>For this ECJ example, I rearranged the various properties so that related key/value pairs would be together. I hope this will make the explanation more coherent.</p>
<p>The first thing to bear in mind with ECJ is that you don&#8217;t get to write <code>main()</code>. The properties file tells the controller class <code>ec.Evolve</code> what to do and it does it with great verve and <em>joie de vivre</em>. I am sure you could write your own controller class to execute ECJ within your own applications, but that is left as an exercise for the reader.</p>
<p>The properties file is called from the command line like so:</p>
<pre>java ec.Evolve -file [properties file]</pre>
<p>As long as the ECJ framework is in the classpath (there is no JAR file to speak of, but you can always make your own), your custom classes are in the classpath, and the path to the properties file is accurate you should be good to go. I have run this example from within <a href="http://eclipse.org/">Eclipse</a> and on the command line (using <a href="http://www.kubuntu.org/">Kubuntu</a>) and the results are the same.</p>
<pre>verbosity    = 0

breedthreads = 1
evalthreads  = 1
seed.0       = 4357</pre>
<p>The first batch of properties are global framework configurations:</p>
<ul>
<li>log file level verbosity (0 &#8211; output everything, all the way to 5000 &#8211; output nothing). More detail <a href="http://cs.gmu.edu/~eclab/projects/ecj/docs/classdocs/ec/util/Output.html">here</a>.</li>
<li>number of threads used for crossover/breeding</li>
<li>number of threads used for population evaluation</li>
<li>random number seed</li>
</ul>
<pre>state       = ec.simple.SimpleEvolutionState

pop         = ec.Population
init        = ec.simple.SimpleInitializer
finish      = ec.simple.SimpleFinisher
breed       = ec.simple.SimpleBreeder
eval        = ec.simple.SimpleEvaluator
stat        = ec.simple.SimpleStatistics
exch        = ec.simple.SimpleExchanger

generations          = 100
quit-on-run-complete = true</pre>
<p>Next comes a number of existing classes to accomplish basic tasks. I am eternally grateful to them for the amount of work they saved me. The ones deserving of an explanation are:</p>
<ul>
<li><code>ec.simple.SimpleEvolutionState</code> &#8211; a subclass of <code>EvolutionState</code>. It contains the configuration information needed by the framework to get your genes evolving.</li>
<li><code>ec.Population</code> &#8211; contains the current collection of Individuals/chromosomes that have been bred and/or evaluated.</li>
<li><code>ec.simple.SimpleBreeder</code> &#8211; creates/breeds Individuals. While ECJ can handle multiple sub-populations the <code>SimpleBreeder</code> does not.</li>
</ul>
<p>The <code>generations</code> and <code>quit-on-run-complete</code> are complementary; continue to evolve until 100 generations are completed or our fitness function has a perfect match.</p>
<pre>checkpoint           = false
prefix               = ec
checkpoint-modulo    = 1

stat.file            = $out.stat

breed.elites.0       = 1</pre>
<p>Checkpoint file configurations are defined here. The non-obvious ones are:</p>
<ul>
<li>prefix &#8211; the prefix used for the checkpoint file (not used in this example, but necessary to run Evolve)</li>
<li>checkpoint-modulo &#8211; run a checkpoint every generation or after every N generations?</li>
<li>stat.file &#8211; name of the output file. The $ means write it in the folder where the Java process started. If a relative path is used then use the folder where the process started as the anchor for the relative path.</li>
</ul>
<pre>pop.subpops  = 1
pop.subpop.0 = ec.Subpopulation

pop.subpop.0.size                   = 100
pop.subpop.0.duplicate-retries      = 0
pop.subpop.0.species                = ec.vector.GeneVectorSpecies
pop.subpop.0.species.ind            = ec.vector.GeneVectorIndividual
pop.subpop.0.species.fitness        = ec.simple.SimpleFitness
#
# Hello, world! is 13 characters long
#
pop.subpop.0.species.genome-size    = 13
pop.subpop.0.species.crossover-type = two
pop.subpop.0.species.crossover-prob = 1.0
pop.subpop.0.species.mutation-prob  = 0.05

pop.subpop.0.species.pipe          = ec.vector.breed.VectorMutationPipeline
pop.subpop.0.species.pipe.source.0 = ec.vector.breed.VectorCrossoverPipeline
pop.subpop.0.species.pipe.source.0.source.0 = ec.select.TournamentSelection
pop.subpop.0.species.pipe.source.0.source.1 = ec.select.TournamentSelection

select.tournament.size = 2</pre>
<p>The next group defines the configuration of the population:</p>
<ul>
<li>Only one sub-population</li>
<li>Use the <code>ec.Subpopulation</code> class as its container</li>
<li>Create 100 Individuals</li>
<li>Use the GeneVectorSpecies and GeneVectorIndividual as the container for my custom gene</li>
<li>Use SimpleFitness to determine who are the current winners. Our custom fitness function will configure this for every individual</li>
<li>The genome size matches the length of our string&#8230;in this case 13. One character per gene</li>
<li>The crossover-type defines one of five possible ways to breed between the selected individuals. Type two means that the genes between two points in the chromosome will be swapped out with each other.</li>
<li>The crossover probability and mutation probability defines how often a crossover and mutation will occur: a one means all the time, 0.05 means not so often.</li>
<li>The mutation and crossover pipelines contain selection objects that decide who gets to breed and who gets mutated. <code>TounamentSelection</code> selects a number of individuals at random (how many is defined in the property select.tournament.size) and picks a winner based on the individual&#8217;s fitness value.</li>
</ul>
<pre># each of these is really on one line
pop.subpop.0.species.gene
                = hiddenclause.example.ecj.CharVectorGene
pop.subpop.0.species.gene.alphabet
                = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY Z,!

eval.problem = hiddenclause.example.ecj.HelloWorld</pre>
<p>Finally, I defined my 2 implementation classes (my gene and my fitness function) and their parameters.</p>
<p>There was no gene/individual type I could use so I defined a subclass of <code>VectorGene</code> and called it (wait for it) <code>CharVectorGene</code>. Since that gene is responsible for creating more genes, a <a href="http://en.wikipedia.org/wiki/Prototype_pattern">Prototype</a> for you Design Patterns geeks, it will also contain the alphabet containing the allowed characters to be used in this example.</p>
<p><code>HelloWorld</code> is the fitness function that will push the population into evolving into a greeting.</p>
<h2>Fitness Function</h2>
<p>ECJ has the concept of an <a href="http://cs.gmu.edu/~eclab/projects/ecj/docs/classdocs/ec/Individual.html">Individual</a> where JGAP has a <a href="http://jgap.sourceforge.net/javadoc/2.0/org/jgap/Chromosome.html">Chromosome</a> and Watchmaker has <a href="https://watchmaker.dev.java.net/nonav/api/org/uncommons/watchmaker/framework/factories/AbstractCandidateFactory.html">AbstractCandidateFactory</a>s to create the chromosomes out of any type you want. In the code I do the same check as before: check that the proper character is at the proper location; give it a point for every hit.</p>
<pre>        int fitnessValue = 0;

        GeneVectorIndividual charVectorIndividual
                              = (GeneVectorIndividual) individual;
        long length = charVectorIndividual.size();
        for (int i = 0; i &#60; length; i++) {
            CharVectorGene charVectorGene
                      = (CharVectorGene) charVectorIndividual.genome[i];
            char actual = charVectorGene.getAllele();
            if (actual == _expected[i]) {
                fitnessValue += 1;
            }
        }</pre>
<p>In ECJ I am responsible for configuring the Fitness object as we get closer to the perfect message so my fitness function is not the ultimate arbiter of a gene&#8217;s fitness.</p>
<pre>    SimpleFitness fitness = (SimpleFitness) charVectorIndividual.fitness;
    fitness.setFitness(evolutionState, fitnessValue,
                    fitnessValue == charVectorIndividual.genomeLength());</pre>
<h2><code>CharVectorGene</code> &#8211; A Gene for Chars</h2>
<p>This is where the gene is both created and initialized. The <code>setup()</code> method is only called once for the entire run to load up any parameters, in this case the desired alphabet.</p>
<pre>    public void setup(final EvolutionState state, final Parameter base) {
        super.setup(state, base);

        Parameter def = defaultBase();

        String alphabetStr = state.parameters.getStringWithDefault(
                     base.push(P_ALPHABET), def.push(P_ALPHABET), "");
        if (alphabetStr.length() == 0)
            state.output.fatal(
                  "CharVectorGene must have a default alphabet",
                  base.push(P_ALPHABET));

        alphabet = alphabetStr.toCharArray();
    }</pre>
<p>Every gene has to have a character. This method randomly assigned a character to itself.</p>
<pre>    public void reset(EvolutionState state, int thread) {
        int idx = state.random[thread].nextInt(alphabet.length);
        allele = alphabet[idx];
    }</pre>
<p>There are four standard Java methods that turn out to be quite important to ECJ.</p>
<pre>    public boolean equals(Object other)
    public int hashCode()
    public Object clone()
    public String toString()</pre>
<p>Standard Java rules apply as to how you should implement them. I probably did not do such a good job.</p>
<h2>ECJ&#8217;s HelloWorld Output</h2>
<p>After running HelloWorld I found that the output to stdout doesn&#8217;t do anything more than tell you how many generations have passed and that (maybe) a solution was found. For the really interesting output you want to look at the <code>out.stat</code> file (ECJ automatically adds a space between each letter when it collects the stringified version of each gene):</p>
<pre>...
Generation: 45
Best Individual:
Evaluated: T
Fitness: 13.0
 H e l l o ,   w o r l d !

Best Individual of Run:
Evaluated: T
Fitness: 13.0
 H e l l o ,   w o r l d !</pre>
<p>The most interesting thing about the above is that ECJ came up with the solution in the least number of generations (JGAP: 233, Watchmaker: 125, ECJ: 45). It would appear that ECJ, though it took me longer to figure out, is the best petri dish so far. I am sure there is fine tuning that could be done to make the various toy example behave similarly, but I think I&#8217;ll leave that <span style="text-decoration:line-through;">to someone who cares</span> as an exercise for the reader.</p>
<h2>Miscellaneous Comments</h2>
<p>Okay, maybe I should have titled this section <em>Miscellaneous Complaints</em>.</p>
<p>The above example took me about a week of on-and-off thought. There was no simple way for me to discover what I did not know about ECJ, but it did a great job of highlighting over and over again that I knew nothing. Since there was no existing class to handle strings I had to figure out, sans documentation, what I needed to do. While intellectually interesting, it was quite frustrating. As you might expect there were a lot of dead-ends in my search.</p>
<p>In addition, due to the flexible method of assigning classes to various categories there should be a lot of checks for class types to insure the run doesn&#8217;t crash due to a bad case of <a href="http://www.artima.com/interfacedesign/PreferPoly.html">downcasting</a>. The ECJ examples used them; I removed them from my code.</p>
<p>While I was happy to finally figure out how to make ECJ work I also have to admit I was exhausted by the time that happened. Hunting through the Javadocs and various README files was decidedly unsatisfying.</p>
<p>Without going into a lot of detail, and I won&#8217;t, the ECJ framework appears to be quite powerful. While it has <a href="http://cs.gmu.edu/~eclab/projects/ecj/docs/warts.html">self-admitted warts</a> the most interesting design choice I found was the use of properties files to glue everything together. JGAP and Watchmaker don&#8217;t use properties files at all though they might; I just didn&#8217;t run into them. ECJ&#8217;s use of them is very <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/">Spring</a>-like only without the XML and the strict usage of interfaces. I am a big fan of the Spring Framework so ECJ gained points on the use of properties as a pseudo-dependency-injection file, but lost points by not using interfaces properly.</p>
<p>My big suggestion to the ECJ team: port ECJ to Spring and use more interfaces in the implementation code (or more accurately, stop downcasting the interfaces if you know that someone could mess with the properties files). Yeah, the use of XML is ugly, but it makes extending ECJ more consistent and should make writing tests for the various framework components easier.</p>
<p>Or not. I know it is going to be a lot of work and who knows how much code you want to maintain backward compatibility with.</p>
<p>On second thought, leave it alone. How about some more documentation?</p>
<h2>The Code</h2>
<p>helloworld.params</p>
<pre>verbosity    = 0

breedthreads = 1
evalthreads  = 1
seed.0       = 4357

state  = ec.simple.SimpleEvolutionState

pop    = ec.Population
init   = ec.simple.SimpleInitializer
finish = ec.simple.SimpleFinisher
breed  = ec.simple.SimpleBreeder
eval   = ec.simple.SimpleEvaluator
stat   = ec.simple.SimpleStatistics
exch   = ec.simple.SimpleExchanger

generations             = 100
quit-on-run-complete    = true
checkpoint              = false
prefix                  = ec
checkpoint-modulo       = 1

stat.file       = $out.stat

pop.subpops     = 1
pop.subpop.0    = ec.Subpopulation

pop.subpop.0.size                  = 100
pop.subpop.0.duplicate-retries     = 0
pop.subpop.0.species               = ec.vector.GeneVectorSpecies
pop.subpop.0.species.ind           = ec.vector.GeneVectorIndividual
pop.subpop.0.species.fitness       = ec.simple.SimpleFitness

# Place on one line
pop.subpop.0.species.gene
    = hiddenclause.example.ecj.CharVectorGene
# Place on one line
pop.subpop.0.species.gene.alphabet
    = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY Z,!
#
# Hello, world! is 13 characters long
#
pop.subpop.0.species.genome-size    = 13
pop.subpop.0.species.crossover-type = two
pop.subpop.0.species.crossover-prob = 1.0
pop.subpop.0.species.mutation-prob  = 0.05

# Place on one line
pop.subpop.0.species.pipe
    = ec.vector.breed.VectorMutationPipeline
# Place on one line
pop.subpop.0.species.pipe.source.0
    = ec.vector.breed.VectorCrossoverPipeline
pop.subpop.0.species.pipe.source.0.source.0 = ec.select.TournamentSelection
pop.subpop.0.species.pipe.source.0.source.1 = ec.select.TournamentSelection

select.tournament.size = 2

eval.problem = hiddenclause.example.ecj.HelloWorld

breed.elites.0 = 1</pre>
<p>HelloWorld.java</p>
<pre>/**
 * HelloWorld.java
 *
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 */
package hiddenclause.example.ecj;

import ec.EvolutionState;
import ec.Individual;
import ec.Problem;
import ec.simple.SimpleFitness;
import ec.simple.SimpleProblemForm;
import ec.vector.GeneVectorIndividual;

public class HelloWorld extends Problem implements SimpleProblemForm {
    private char[] _expected = "Hello, world!".toCharArray();

    public void evaluate(final EvolutionState evolutionState,
                                    final Individual individual,
                                    final int subPopulation,
                                    final int threadNum) {
        if (individual.evaluated)
            return;

        int fitnessValue = 0;

        GeneVectorIndividual charVectorIndividual = (GeneVectorIndividual) individual;
        long length = charVectorIndividual.size();
        for (int i = 0; i &#60; length; i++) {
            CharVectorGene charVectorGene
                    = (CharVectorGene) charVectorIndividual.genome[i];
            char actual = charVectorGene.getAllele();
            if (actual == _expected[i]) {
                fitnessValue += 1;
            }
        }

        SimpleFitness fitness
                         = (SimpleFitness) charVectorIndividual.fitness;
        fitness.setFitness(evolutionState, fitnessValue,
                fitnessValue == charVectorIndividual.genomeLength());

        charVectorIndividual.evaluated = true;
    }

    public void describe(final Individual individual,
                         final EvolutionState state,
                         final int subPopulation,
                         final int threadNum,
                         final int log, final int verbosity) {
        // Do Nothing
    }
}</pre>
<p>CharVectorGene.java</p>
<pre>/**
 * CharVectorGene.java
 *
 * This is an example only! Use it for anything else at your own risk!
 * You have been warned! Coder/user beware!
 */
package hiddenclause.example.ecj;

import ec.EvolutionState;
import ec.util.Parameter;
import ec.vector.VectorGene;

/**
 * @author carlos
 */
public class CharVectorGene extends VectorGene {
    public final static String P_ALPHABET = "alphabet";

    private static char[]      alphabet;
    private char               allele;

    @Override
    public void setup(final EvolutionState state, final Parameter base) {
        super.setup(state, base);

        Parameter def = defaultBase();

        String alphabetStr = state.parameters.getStringWithDefault(
                          base.push(P_ALPHABET), def.push(P_ALPHABET), "");
        if (alphabetStr.length() == 0)
            state.output.fatal(
                       "CharVectorGene must have a default alphabet",
                       base.push(P_ALPHABET));

        alphabet = alphabetStr.toCharArray();
    }

    /*
     * (non-Javadoc)
     * @see ec.vector.VectorGene#reset(ec.EvolutionState, int)
     */
    @Override
    public void reset(EvolutionState state, int thread) {
        int idx = state.random[thread].nextInt(alphabet.length);
        allele = alphabet[idx];
    }

    public char getAllele() {
        return allele;
    }

    /*
     * (non-Javadoc)
     * @see ec.vector.VectorGene#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object other) {
        if (!this.getClass().isInstance(other)) {
            return false;
        }

        CharVectorGene that = (CharVectorGene) other;

        return allele == that.allele;
    }

    /*
     * @see ec.vector.VectorGene#hashCode()
     */
    @Override
    public int hashCode() {
        int hash = this.getClass().hashCode();

        hash = (hash &#60;&#60; 1 &#124; hash &#62;&#62;&#62; 31) ^ allele;

        return hash;
    }

    @Override
    public Object clone() {
        CharVectorGene charVectorGene = (CharVectorGene) (super.clone());

        return charVectorGene;
    }

    @Override
    public String toString() {
        return Character.toString(allele);
    }
}</pre>
<p>Next time: the ECJ version of Toby Segaran&#8217;s Simple Math Test.</p>
<p>Or maybe I will do that first in Watchmaker.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Link: 'Hello World' genetic algorithm]]></title>
<link>http://alanogilvy.wordpress.com/2009/08/13/hello-world-genetic-algorithm/</link>
<pubDate>Thu, 13 Aug 2009 05:46:55 +0000</pubDate>
<dc:creator>alanogilvy</dc:creator>
<guid>http://alanogilvy.wordpress.com/2009/08/13/hello-world-genetic-algorithm/</guid>
<description><![CDATA[I enjoyed a post today at Hidden Clause talking about an attempt to generate the string &#8216;hello]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I enjoyed a post today at <a title="Hidden Clause blog" href="http://cvalcarcel.wordpress.com/#" target="_blank">Hidden Clause</a> talking about an attempt to generate the string &#8216;hello, world!&#8217; using a genetic algorithm.</p>
<blockquote><p>In the first chapter of the documentation for the Watchmaker Framework Daniel W. Dyer presents<a href="http://cvalcarcel.wordpress.com/2009/08/11/jgap-a-second-example-and-observations/trackback/" target="_blank"> an interesting genetic algorithm example: what if we wanted to evolve the string “HELLO WORLD”?</a> &#8230; My first thought: implementing this in JGAP shouldn’t be that hard.</p></blockquote>
<p>The setup reminds me of the game &#8216;Mastermind&#8217; &#8212; we&#8217;re dealing with a fixed-length string and scoring based on how many of the correct characters occur in the string and if they are in the right position. You combine some better strings and sometimes mutate them to generate new strings, and repeat that process until, hopefully, you arrive at the target string, &#8216;hello, world!&#8217;.</p>
<p>Did it work? Well, almost. The first result, &#8220;&#8216;!ello,  or!d!&#8221;,  was reached after 1 million iterations on a population size of a thousand &#8212; and, it used a limited alphabet containing only the letters and punctuation in the target string (and not, for example, &#8216;z&#8217;).</p>
<p>The reason the solution was not reached, the post&#8217;s author notes, is that the algorithm doesn&#8217;t have the breadth or the convergent ability to match the statistical odds involved. Recalling the old problem of monkeys on typewriters producing Shakespeare , the author notes how unlikely it is to produce the desired result.</p>
<p>Of course, we&#8217;re not simply monkeying at typewriters. We&#8217;re making random changes and mutations, but we&#8217;re intelligently selecting the parents. Apparently, the method first tried wasn&#8217;t intelligent enough to arrive at the desired solution within that number of iterations, and increasing iterations or population size, apparently, isn&#8217;t going to be practical.  So we need to use a better way of selecting the parents.</p>
<p>We could improve the fitness function. Let&#8217;s say we take the whole alphabet and the punctuation and number them (for instance: A=1&#8230; Z=26 and space and comma and exclamation could be 27, 28, and 29, respectively). Now, assign fitness based on the difference between actual and target values of each character. Is this cheating? Well, no. Our new fitness function requires no a priori knowledge of the solution and will work equally well for a different target string. This is providing our GA with a lot more information per epoch, and therefore we should see a much faster convergence.</p>
<p>(Aside: there are much better way of numbering the letters and punctuation to encourage faster convergence, based on the frequency the characters are used in the English language. In fact, one could develop a system that took advantage of commonly grouped letters like &#8216;th&#8217; and &#8216;ing&#8217;, and if dealing with sentences, commonly grouped words&#8230;  Is <em>that</em> cheating? Well, we must remember that the more such information we encode, the more pre-disposed or biased our output will be. Also, the point of a using a genetic algorithm is to substitute computation time for programming complexity. In a contrived problem, it&#8217;s up to us where that line lies. )</p>
<p>There are a number of other ways to improve the fitness function, but my instinct is that this suggestion or a similar modification would be sufficient. I hope the Hidden Clause crew reports the result of another attempt.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JGAP: A Second Example and Observations]]></title>
<link>http://cvalcarcel.wordpress.com/2009/08/11/jgap-a-second-example-and-observations/</link>
<pubDate>Wed, 12 Aug 2009 01:32:09 +0000</pubDate>
<dc:creator>cvalcarcel</dc:creator>
<guid>http://cvalcarcel.wordpress.com/2009/08/11/jgap-a-second-example-and-observations/</guid>
<description><![CDATA[In the first chapter of the documentation for the Watchmaker Framework Daniel W. Dyer presents an in]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In the <a href="https://watchmaker.dev.java.net/nonav/manual/ch01.html">first chapter</a> of the documentation for the <a href="https://watchmaker.dev.java.net/">Watchmaker Framework</a> Daniel W. Dyer presents an interesting genetic algorithm example: what if we wanted to evolve the string &#8220;HELLO WORLD&#8221;?</p>
<p>The fitness function would be straightforward: check every letter of a possible  solution and every matching letter at a matching position would raise that chromosome&#8217;s fitness value.</p>
<p>I highly recommend you read the chapter referenced above before continuing. It is quite well written and will make the pain I describe below clearer.</p>
<p>My first thought: implementing this in <a href="http://jgap.sourceforge.net">JGAP</a> shouldn&#8217;t be that hard.</p>
<p>Implementing it: easy. Getting a good solution: not so much. This is not a problem with JGAP so much as it is a problem with <a href="http://en.wikipedia.org/wiki/Infinite_monkey_theorem">monkeys and Shakespeare</a>. Before I go into that let me present the code.</p>
<p>My target was a little bit more ambitious: instead of hello world in all upper case characters I wanted to evolve the string &#8220;hello, world!&#8221; all in lower case and containing a space, a comma and an exclamation point.</p>
<p>The fitness function was easy: check every letter and its position and if it matches the target string increment the fitness value by 1. The higher the fitness value the better the match.</p>
<p>Here is my fitness function:</p>
<pre>package hiddenclause.example;

import org.jgap.FitnessFunction;
import org.jgap.IChromosome;

public class HelloWorldFitnessFunction extends FitnessFunction {

    private char[] _expected;

    public HelloWorldFitnessFunction(String desiredMessage) {
        _expected = desiredMessage.toCharArray();
    }

    @Override
    protected double evaluate(IChromosome aSubject) {
        int fitnessValue = 0;

        String msg = (String) aSubject.getGene(0).getAllele();
        char [] actual = msg.toCharArray();
        for (int i = 0; i &#60; actual.length; i++) {
            if (actual[i] == _expected[i]) {
                fitnessValue += 1;
            }
        }

        return fitnessValue;
    }

}</pre>
<p>Next step: implement the chromosome that will contain the letters that will evolve into the target string.</p>
<p>In order to accomplish the next step I decided to use the JGAP genetic algorithm* class <a href="http://jgap.sourceforge.net/javadoc/2.0/org/jgap/impl/StringGene.html">StringGene</a>. I configured it to randomly generate a string of exactly the length desired and use an alphabet of just the letters and punctuation from the target string. Why not add the entire alphabet and punctuation to add to the diversity? Monkeys, remember? More on that later.</p>
<p>The chromosome creation code is:</p>
<pre>package hiddenclause.example;

import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.FitnessFunction;
import org.jgap.Gene;
import org.jgap.Genotype;
import org.jgap.IChromosome;
import org.jgap.InvalidConfigurationException;
import org.jgap.impl.DefaultConfiguration;
import org.jgap.impl.StringGene;

public class HelloWorld {

    private static final String MESSAGE = "hello, world!";
    private static final int MAX_EVOLUTION = 1000000;

    public static void main(String[] args) throws Exception {
        long startTime = 0;
        long endTime = 0;
        HelloWorld hello = new HelloWorld();

        Genotype population = hello.create(1000);

        startTime = System.currentTimeMillis();
        int i = 0;
        for (i = 0; i &#60; MAX_EVOLUTION; i++) {
            population.evolve();
            IChromosome solution = population.getFittestChromosome();
            if (solution.getFitnessValue() == MESSAGE.length()) {
                break;
            }
        }
        endTime = System.currentTimeMillis();

        outputSolution(population, startTime, endTime, i);
    }

    private Genotype create(int popSize) throws InvalidConfigurationException {
        Configuration conf = new DefaultConfiguration();
        conf.setPreservFittestIndividual(true);

        FitnessFunction myFunc = new HelloWorldFitnessFunction(MESSAGE);
        conf.setFitnessFunction(myFunc);

        Gene stringGene = new StringGene(conf, MESSAGE.length(), MESSAGE.length(),
                "!dehlorw ,");
        IChromosome sampleChromosome = new Chromosome(conf, stringGene, 1);
        conf.setSampleChromosome(sampleChromosome);
        conf.setPopulationSize(popSize);

        Genotype population;
        population = Genotype.randomInitialGenotype(conf);

        return population;
    }

    private static void outputSolution(Genotype population, long startTime,
            long endTime, int evolutionIdx) {
        System.out.println("Stopped at generation " + evolutionIdx);

        long totalSeconds = (endTime - startTime) / 1000;
        long actualSeconds = totalSeconds % 60;
        long actualMinutes = totalSeconds / 60;
        System.out.println("Total evolution time: " + actualMinutes + ":"
                + actualSeconds);

        IChromosome solution = population.getFittestChromosome();
        int fitnessValue = (int) solution.getFitnessValue();
        System.out.println("The best solution has a fitness value of " + fitnessValue);

        System.out.println("Looking for '" + MESSAGE + "':");
        String message = (String) solution.getGene(0).getAllele();
        System.out.println("\t '" + message + "'");
    }
}</pre>
<p>Notice that the HelloWorld class will handle any kind of incoming string; I just happened to use a hard coded constant. One of its assumptions (euphemism for <em>bug</em>) is that the incoming string and the solution string are the same length. If the two strings are not the same length the loop might try to access part of an array that doesn&#8217;t exist and there are very few exceptions that cause as severe a level of mental anguish as the <a href="http://java.sun.com/javase/6/docs/api/java/lang/ArrayIndexOutOfBoundsException.html">ArrayIndexOutOfBoundsException</a> (however, <a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a> is right up there).</p>
<pre>The above gave the following output after 1 million generations:
Break: Executed evolution 1000000 times.
Total evolution time: 76:45
The best solution has a fitness value of 10
Looking for 'hello, world!':
'!ello,  or!d!'</pre>
<p>Not pretty.</p>
<p>What happened?</p>
<p>While the use of crossover should make the evolution progress faster there are certain statistical issues that must be taken into account. For a chromosome to get a high value it has to have 2 things in its favor:</p>
<ol>
<li>it has to have one or more letters in the new string</li>
<li>the letter(s) have to be in the proper position(s)</li>
</ol>
<p>This is where the monkeys come in.</p>
<p>The more I thought of it the more I thought about the scenario of an <a href="http://i109.photobucket.com/albums/n59/bmc712/ShakespeareMonkey.jpg?t=1249850764">infinite number of monkeys trying to write Shakespeare</a>. To begin their arduous task one or more of the monkeys has to hit the proper first letter. Assuming a keyboard with just the alphabet, and no punctuation, they have a 1 in 52 chance of hitting the right first letter. Shouldn&#8217;t be too hard with an infinite number of primates.</p>
<p>The next letter becomes a little harder. Of the subset of monkeys that hit the proper first letter the chances of any of them hitting that second letter has a statistical probability of 1 in 2704. The third: 1 in 140608. The fourth: 1 in 7,311,616. The fifth: 1 in 380,204,032.</p>
<p>And that doesn&#8217;t include punctuation and white space.</p>
<p>That mean that if the letter h never makes it to the first character the system will never (never, as in&#8230;well, <a href="http://www.toothpastefordinner.com/011606/never-ever.gif">never</a>) evolve the target string. Never. In order to up the statistical odds of my chromosome succeeding I created an alphabet of just the letters that comprise the target string: &#8220;!dehlorw ,&#8221;.</p>
<p>And yet, with that small set of characters, an ever changing population of 1000 chromosomes at 1 million generations was unable to generate the string. Can it succeed? Of course. The proper population (random generation of strings) in the petri dish that is JGAP would generate the target string. But it is random and random does not mean regular.</p>
<p>So, adding more letters and punctuation adds more noise to the mix and just makes the combinations even worse (though possibly better as more randomly mixed letters could elevate the use of letters from the target string).</p>
<p>When I changed the StringGene&#8217;s alphabet to include a few more letters, &#8220;!abcdefghlmnorstwxyz ,&#8221;, this is what the output was:</p>
<pre>Stopped at generation 1000000
Total evolution time: 77:20
The best solution has a fitness value of 7
Looking for 'hello, world!':
'zblxo, ,orrdx'</pre>
<p>Defintely not an improvement.</p>
<p>Is there a way of configuring this differently to encourage a solution? Perhaps a better fitness function? Custom gene? Better randomizer? I will gladly take any suggestions and try them out. Maybe.</p>
<p>Exercise for the reader: up the population value to create more opportunities for the desired letters to end up in the desired positions. Bake overnight.</p>
<p>When I increased the population number to 800K and ran it again my Kubuntu box locked up after 2 days because I continued to do things like run Eclipse, read PDFs and back-up my work. I guess 800 trillion iterations of the fitness function was exhausting.</p>
<p><a href="http://ops.tamu.edu/x075bb/poems/casey.html">No joy in Mudville</a>.</p>
<p>Update 8/15/09: <a href="http://cvalcarcel.wordpress.com/2009/08/15/jgap-revisiting-the-second-example/">the problem solved</a>.</p>
<p>* To create a genetic program using JGAP you would create a <a href="http://jgap.sourceforge.net/javadoc/3.4.3/org/jgap/gp/impl/GPGenotype.html">GPGenotype</a> using a class that inherits from <a href="http://jgap.sourceforge.net/javadoc/3.4.3/org/jgap/gp/GPProblem.html">GPProblem</a> and a fitness function that inherits from <a href="http://jgap.sourceforge.net/javadoc/3.4.3/org/jgap/gp/GPFitnessFunction.html">GPFitnessFunction</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Computational Intelligence in Inflation Forecasting]]></title>
<link>http://prajwolkumar.wordpress.com/2009/08/11/computational-intelligence-in-inflation-forecasting/</link>
<pubDate>Tue, 11 Aug 2009 03:50:19 +0000</pubDate>
<dc:creator>Prajwol Kumar Nakarmi</dc:creator>
<guid>http://prajwolkumar.wordpress.com/2009/08/11/computational-intelligence-in-inflation-forecasting/</guid>
<description><![CDATA[Open Software Challenge Nepal 2009 was announced somewhere during early 2009. And somehow, computer-]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Open Software Challenge Nepal 2009 </strong>was announced somewhere during early 2009. And somehow, computer-half of the CSIDC team (me-Prajwol and Dipesh) decided to participate in it. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>Screen blurred, grayscale stars</strong> &#8211; To talk about CSIDC, it was CSIDC 2006, organized by the IEEE under the theme of “Preserving, Protecting and Enhancing the Environment”. Saurav Ratna Tuladhar and Nilesh Shakya (electronics), and Dipesh Karki and Prajwol Kumar Nakarmi –me (computer) were selected from Pulchowk Campus to participate in it. We had presented our project “<strong>iForest</strong> – A Monitoring and Management System for Sustainable Forestry”. The certificate of participation of this competition has definitely increased the weight of our CVs <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  – <strong>Screen normal, colorscale resumes</strong>. he he <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Dipesh and I talked in phone, texted in MSN, brainstormed in Eiden Garden and came out with what we christened “<strong>Computational Intelligence in Inflation Forecasting</strong>” (CIIF). Of course Carlsberg was there to accompany us whenever possible. LOL</p>
<p>Now on August, we both are proud to say that we made to the prestigious <strong>TOP 10</strong> among some 80+ projects. My heartfelt congratulations to the guys who made it to the TOP 3 (Y).</p>
<p>Many were expecting our project to do better before the result announcement, and of course, we were hopeful too.  But probably, the fact that our development platform was .NET pulled our legs and we didn’t make till the TOP 3 mark. We had some people asking “<strong><em>how can your software be open when I have to pay for it</em></strong>” LOL LOL a big disgrace to such a question. We tried to explain – they seemed to agree – it was apparent that they didn’t understand :’(. <strong>May the true meaning of Openness of the Software come to light to all of us, AMEN.</strong></p>
<p>Let me, now, say some about CIIF. As we know, Inflation is a persistent and significant increase in general price level and it is calculated by averaging the percentage growth rate of the prices of selected sample of commodities. It is one of the most essential macroeconomic indicator as many other economic variables like wage rate, salaries , gross domestic product, interest rate are either directly or indirectly related to change in price. However the inflation can be calculated only in hindsight by comparing present commodity price with the past. As this isn’t much help while formulating the future pricing policy, a forecasting mechanism must be introduced to estimate the future expectation of the inflation rate.</p>
<p>In this light, the software, that attempts to forecast one of the key macroeconomic indicator- ‘<strong>Inflation’</strong> using both Neural Network and Genetic Algorithm, was developed. Ladies and Gentlemen, we give to you CIIF <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . The system consists of two main engines, viz. <strong>Artificial Neural Network</strong> and <strong>Genetic Algorithm</strong>. Two flavors of the later are available as Encoding and No Encoding. Statistics are present to measure the fitness of the predicted data. For easy visualization of the output, Graph component is also available.</p>
<p>The input data consisted of inflation rates of USA for last 1143 months, dating back to January of 1914 to March of 2009.  Before beginning the training, the data set is divided into the training set and the validation (Prediction set). First 1043 months data are kept in training set while last 100 are kept in validation set. The application is supple in sense that by simply changing the parameter in the input file the size of validation set as well as training set can be changed. The value of R2 &#62;= 0.5 is acceptable for our system, which implies that at least 50pc of total variation in the data should be explained by the system. Our tests show that the results are over par. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>You can follow CIIF under <a href="http://collaborate.d2labs.org/projects/ciif/">http://collaborate.d2labs.org/projects/ciif/</a></p>
<p>Cheese and Cheers</p>
<p>Prajwol</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Jansen Walker Robot]]></title>
<link>http://cochico.wordpress.com/2009/07/29/jansen-walker-robot/</link>
<pubDate>Wed, 29 Jul 2009 18:52:31 +0000</pubDate>
<dc:creator>Cochi</dc:creator>
<guid>http://cochico.wordpress.com/2009/07/29/jansen-walker-robot/</guid>
<description><![CDATA[http://4volt.com/projects/jansen/ This is what i&#8217;m talking about, this project unites everythi]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://4volt.com/projects/jansen/">http://4volt.com/projects/jansen/</a><a></a></p>
<p><img class="alignleft" title="4 volts robot" src="http://4volt.com/projects/jansen/IMG_2043%20(edited)%20(Custom).jpg" alt="" width="320" height="213" /></p>
<p>This is what i&#8217;m talking about, this project unites everything most nerdy in the world, Genetic algorithms/Arduino/Servo motor modification. It also makes for the definitive science fair project, mwahahahaha.</p>
<p>This little bastard converts rotary motion into leg-like motion, the mechanical segments were developed by 12 numbers that means the relative distances between joints, and these numbers were found through a genetic algorithm running on an Atari STe computer for months, Jansen himself call these numbers &#8220;The 12 holy numbers&#8221;.</p>
<p>The site contains schematics and arduino code, so, turn off you TV and start roboting!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Queen Problems]]></title>
<link>http://alanogilvy.wordpress.com/2009/07/17/queen-problems/</link>
<pubDate>Fri, 17 Jul 2009 23:28:12 +0000</pubDate>
<dc:creator>alanogilvy</dc:creator>
<guid>http://alanogilvy.wordpress.com/2009/07/17/queen-problems/</guid>
<description><![CDATA[Can you place three white queens and five black queens on a 5×5 chessboard so that no queen of one c]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><blockquote><p>Can you place three white queens and five black queens on a 5×5 chessboard so that no queen of one color attacks a queen of the other? The solution is unique, except rotations and reflections.</p></blockquote>
<p>It took me longer than I first expected to solve this problem. The solution is: <img class="aligncenter size-full wp-image-119" title="Puzzle-5BQ-3WQ" src="http://alanogilvy.wordpress.com/files/2009/07/puzzle-5bq-3wq.jpg" alt="Puzzle-5BQ-3WQ" width="202" height="202" /></p>
<p>Since a queen attacks along rank, file, and diagonal, it leaving triangles between them unattacked, with a knight-move as the closest vertex of each triangle. While that is immediately obvious to anyone familiar with chess, I was able to solve the problem by thinking about placing white queens in such a way as to allow the largest triangles. Before searching for a solution in that manner, I tried other methods unsuccessfully: hit-and-miss attempts (having at first underestimated the problem); placing queens at knight-moves as one might do for the classic eight-queen problem (see below); utilizing symmetry by placing queens at, say, each corner and at the center; and so on.</p>
<p>How would a computer solve the problem? Well, a <a title="Eight Queens Problem on Wikipedia" href="http://en.wikipedia.org/wiki/Eight_queens_puzzle#The_eight_queens_puzzle_as_an_exercise_in_algorithm_design" target="_blank">wikipedia article</a> suggests, among other methods, a genetic algorithm, which struck my fancy.  So I started writing one.</p>
<p>After the skeleton of the algorithm was written and I started tinkering with parameters and the fitness function, I realized this problem would make a great introduction to genetic algorithms and also provide a simple platform for various discussions about the nuances of GAs.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Absolutly Awesome!!!]]></title>
<link>http://gravspace.wordpress.com/2009/07/09/absolutly-awesome/</link>
<pubDate>Thu, 09 Jul 2009 09:35:40 +0000</pubDate>
<dc:creator>blatherwick</dc:creator>
<guid>http://gravspace.wordpress.com/2009/07/09/absolutly-awesome/</guid>
<description><![CDATA[OK, I have always loved the idea of genetic algorithms, and specifically how they apply to solving p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>OK, I have always loved the idea of genetic algorithms, and specifically how they apply to solving problems in unorthodox ways.</p>
<p>As anyone who has read this blog knows, I am very slowly writing a game, very much like galactic arms race (<a href="http://gar.eecs.ucf.edu">http://gar.eecs.ucf.edu</a>) in look and feel, but what these guys are doing is mind blowing. They are using AI to develop new weapons based on what users use and what they like to use.</p>
<p>There is also an interview with the creator at AIGameDev (<a href="http://aigamedev.com/interviews/galactic-arms-race/">http://aigamedev.com/interviews/galactic-arms-race/</a>).</p>
<p>Both of these links are very worth a read, and while it will be a while before I get to this point, I plan to follow this project very closely.</p>
<p>Now go away &#8211; I have a game client to download&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Yann Le Cun]]></title>
<link>http://alanogilvy.wordpress.com/2009/06/13/yann-lecun/</link>
<pubDate>Sat, 13 Jun 2009 23:50:30 +0000</pubDate>
<dc:creator>alanogilvy</dc:creator>
<guid>http://alanogilvy.wordpress.com/2009/06/13/yann-lecun/</guid>
<description><![CDATA[Yann Le Cun was recently featured on NYAS&#8217;s Science and the City podcast. He spoke about visua]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Yann Le Cun was recently featured on NYAS&#8217;s <a title="Science and the City Podcasts" href="http://www.nyas.org/snc/podcasts.asp" target="_blank">Science and the City</a> podcast. He spoke about visual processing using Artificial Neural Networks (ANNs) and in particular his work on the system that reads the amounts on your cheques at the ATM.  The host, Alana Range, notes that her ATM has never gotten her cheque amounts wrong. I myself no longer bother to check.</p>
<p>The technology behind the ATMs was developed by Le Cun and others almost 10 years ago, at AT&#38;T Bell Labs [which, tragically, has been closed down]. The algorithm they developed [now] goes under the name LeNet, and is a multi-layer backpropagation Neural network called a Convolution Neural Network.  I will explain this terminology in my next post. [Update: <a title="Explanation of LeNet jargon" href="http://alanogilvy.wordpress.com/2009/06/13/explanation-of-LeNet-jargon" target="_self">explanation now posted.</a>]</p>
<p>In the object recognition demonstration, Yann Le Cun describes four output interpretations in the LeNet algorithm: 1) edges and contours, 2) motifs, 3) categories, and finally 4) objects. By narrowing down options in several steps LeNet can arrive at the final outputn (identifying the object) far more rapidly &#8212; the demonstration on the podcast proceses 4-5 pictures each second, and can recognize five different objects.  There are also <a title="LeNet-5 demonstrations" href="http://yann.lecun.com/exdb/lenet/index.html" target="_blank">demonstrations online</a> on Yann Le Cun&#8217;s website.</p>
<p>I wondered as I listened to this podcast about the comparisons drawn between mammalian visual processing and Le Cun&#8217;s algorithm. There were some very pronounced differences that suggest that our brains utilize a totally different technique, not simply a more complex version of LeNet, as was implied in the interview. These differences were:</p>
<ol>
<li>LeNet utilizes supervised learning. Our learning is largely unsupervised.</li>
<li>We extrapolate, not just interpolate. So while LeNet needs tens of thousands of samples before it starts recognizing an object, babies might see a few toy planes and recognize the one in the sky. In interview, Le Cun notes that his algorithm, when used for letter recognition, needs to be trained with both printed and handwritten samples and is unable to extrapolate from one to the other.</li>
</ol>
<p>I think there were some other differences that I do not now recall.  I got flashbacks of the TED-talk in which Handspring founder Jeff Hawkins cracked some jokes about the fundamental differences between computer and human visual processing. I&#8217;ll try to post about that; it was pretty entertaining.</p>
<p>[Update: check out a <a title="Matlab class for CNN" href="http://www.mathworks.com/matlabcentral/fileexchange/24291" target="_blank">Matlab class for CNN implementation</a> on the Matlab file exchange, by Mihail Sirotenko.]</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
