<?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>mostly a codeBlog &#187; Processing</title>
	<atom:link href="http://www.rickigregersen.com/category/processing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rickigregersen.com</link>
	<description>whatever I am currently programming... and I truly digress</description>
	<lastBuildDate>Mon, 21 Jun 2010 15:40:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Packing Circles &#8211; The Stupid Way</title>
		<link>http://www.rickigregersen.com/2009/09/21/packing-circles-the-stupid-way/</link>
		<comments>http://www.rickigregersen.com/2009/09/21/packing-circles-the-stupid-way/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 22:01:56 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Processing]]></category>
		<category><![CDATA[circle]]></category>
		<category><![CDATA[packing]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=221</guid>
		<description><![CDATA[This is a small experiment I did on &#8220;packing circles&#8221;. The circles are not really packed, the program just keeps suggesting circles of varying sizes in different positions on the screen and then tests to see if they will fit. If they fit they are drawn if not they are discarded. Example and code here]]></description>
			<content:encoded><![CDATA[<p>This is a small experiment I did on &#8220;packing circles&#8221;. The circles are not really packed, the program just keeps suggesting circles of varying sizes in different positions on the screen and then tests to see if they will fit. If they fit they are drawn if not they are discarded.</p>
<div id="attachment_222" class="wp-caption aligncenter" style="width: 521px"><a href="http://www.rickigregersen.com/wp-content/uploads/circlePacking.png"><img class="size-full wp-image-222" title="circlePacking" src="http://www.rickigregersen.com/wp-content/uploads/circlePacking.png" alt="A small 5 min. run of the program" width="511" height="510" /></a><p class="wp-caption-text">A small 5 min. run of the program</p></div>
<p><a href="http://www.rickigregersen.com/wp-content/circleapplet/">Example and code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/09/21/packing-circles-the-stupid-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DTXplorer drum kit goes Processing</title>
		<link>http://www.rickigregersen.com/2009/09/09/dtxplorer-drum-kit-goes-processing/</link>
		<comments>http://www.rickigregersen.com/2009/09/09/dtxplorer-drum-kit-goes-processing/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 00:01:27 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[drum]]></category>
		<category><![CDATA[DTXplorer]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[MIDI]]></category>
		<category><![CDATA[Midipipe]]></category>
		<category><![CDATA[OSC]]></category>
		<category><![CDATA[Osculator]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=199</guid>
		<description><![CDATA[This my DTXplorer drumkit getting feed into MidiPipe onto Osculator and finally ends up in Processing. Now thats beat detection! I have taken some time to get my Yamaha DTXplorer electronic drums to communicate nicely with my Mac, finally it worked out and I can now &#8220;harvest&#8221; the sweet, sweet MIDI coming from the drums. [...]]]></description>
			<content:encoded><![CDATA[<h5>This my DTXplorer drumkit getting feed into MidiPipe onto Osculator and finally ends up in Processing. Now thats beat detection!</h5>
<p><a href="http://www.rickigregersen.com/2009/09/09/dtxplorer-drum-kit-goes-processing/"><em>Click here to view the embedded video.</em></a></p><br />
<p><a href="http://www.rickigregersen.com/2009/09/09/dtxplorer-drum-kit-goes-processing/"><em>Click here to view the embedded video.</em></a></p>
<p>I have taken some time to get my <a href="http://www.yamaha.com/drums/drumproductdetail.html?CNTID=544640&amp;CTID=5040587">Yamaha DTXplorer</a> electronic drums to communicate nicely with my Mac, finally it worked out and I can now &#8220;harvest&#8221; the sweet, sweet MIDI coming from the drums. Im no Moby, so believe me when I say these last one and a half days of frustrations was not to immortalize the sound of my drumming. It was, of course to get the data into <a href="http://www.processing.org">Processing</a>. A friend of mine is a DJ and he wanted us to experiment with playing &#8220;live&#8221; drums along with the turntables. Furthermore, to make some sort of visualization that would be 100% true to the beat. This is very hard I found out, there are a lot of good sound libraries with beat detection out there, but they are never plug n&#8217; play. You need to tweak your code for every single song and even that is no guarantee for a consistent output. I came up with a pretty straight forward solution, if we were to use the electronic drums anyway we could just as well use the MIDI for the beat detection and then have the turntables control the colors.</p>
<p>I found out that I needed a few different applications and a MIDI cable before I got the signal all the way through. First off is the <a href="http://www.esi-audio.com/products/midimate2/">ESI MidiMate</a> cable, I actually had the old model, but I think it was broken and could not handle if the MIDI in was not connected to a ground plane. It was 295 Danish Kroner ( ≈$55 ). Then I needed <a href="http://web.mac.com/nicowald/SubtleSoft/MidiPipe.html">MidiPipe</a>. This a free application developed by Nico Wald and it is brilliant! Should I ever make any money with this setup I will run to a browser and donate some money to Nico.<br />
The idea with MidiPipe is that it &#8220;hijacks&#8221; every single MIDI port it can detect on the system, you then drag the one you need to the pipe(ESI MIDIMATE Port 1 turn up in MidiPipe the second I connected it to the drumkit) you can then drag other stuff into the pipe. I dragged in &#8220;AList&#8221; from the &#8220;Modifier&#8221; and that gave me just what it says, a list of all midi signals passing through MidiPipe.</p>
<div id="attachment_201" class="wp-caption aligncenter" style="width: 506px"><a href="http://www.rickigregersen.com/wp-content/uploads/midipipe.png"><img class="size-full wp-image-201" title="midipipe" src="http://www.rickigregersen.com/wp-content/uploads/midipipe.png" alt="MidiPipe is a life-saver" width="496" height="512" /></a><p class="wp-caption-text">MidiPipe is a life-saver</p></div>
<p>This was a cool way of testing out the drums. Lastly I dragged a &#8220;MIDI out&#8221; into the Pipe, more about that in a second. Then I went out and finally bought that license for <a href="http://www.osculator.net/wp/">OSCulator</a>. Osculator have been running my Wiimote, iPhone, Arduino and Make controller for the last year and I have been to lazy/cheap to just buy the license. Well Osculator is a $15 minimum, but Camille asks people nicely to pay $39, which I did, of course, having used his software for about a year now. What Osculator can do is just to much to explain here&#8230; I needed it to translate my MIDI into OSC (because OSC is the new MIDI <img src='http://www.rickigregersen.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ) and then relay the rewritten data to a port on localhost using UDP. This was done so I could have some control over the data, also I now get something along the lines of &#8220;snare &#8211; on &#8211; 0.6&#8243; (thats the pad sending the message, that it was &#8220;on&#8221;/hit and the strength it was hit with) into Processing instead of some MIDI byte I have to bitwise shift around to get any data from it, it just makes debugging easier and sending something through Osculator opens a world of other possibilities.</p>
<div id="attachment_204" class="wp-caption aligncenter" style="width: 522px"><a href="http://www.rickigregersen.com/wp-content/uploads/osculator1.png"><img class="size-full wp-image-204" title="osculator" src="http://www.rickigregersen.com/wp-content/uploads/osculator1.png" alt="It is just crazy how many features there can be in such a simple application" width="512" height="484" /></a><p class="wp-caption-text">It is just crazy how many features there can be in such a simple application</p></div>
<p>A note here, when I started Osculator, MidiPipe noticed Osculator was listening on port 8000 and stuffed that piece of information into the &#8220;MIDI out&#8221; I mentioned earlier, now I could just select it there. So now my MIDI came in through MidiPipe, was listed for me to see and then relayed on to Osculator. In Osculator I caught each MIDI event and by selecting the signal and going Osculator &#8211; Edit &#8211; Demux, I could split the signal into its components and rebroadcast them as OSC messages on the network. For handling OSC Protocol stuff in Processing Andreas Schlegel did a really great library, you can get it <a href="http://www.sojamo.de/libraries/oscP5/">here</a> along with some other goodies Andreas made.</p>
<p>I now had 8 different OSC messages, one for each drum pad, cymbal and foot pedal (Im going to do the high hat pedal later on) that I can read out in Processing. I did a small sketch as you see in the video and just started the &#8220;play along&#8221; feature on my DTXplorer kit, with some &#8220;Hard Rock&#8221; <img src='http://www.rickigregersen.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  selected and and the computers microphone recording.</p>
<p>And as always if there is some code or help You need just leave a mail or comment.</p>
<p><a href="http://www.rickigregersen.com/wp-content/uploads/midiProcessing.mov">A version not completely compressed by the geniuses over at youtube</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/09/09/dtxplorer-drum-kit-goes-processing/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
<enclosure url="http://www.rickigregersen.com/wp-content/uploads/midiProcessing.mov" length="1515678" type="video/quicktime" />
		</item>
		<item>
		<title>Fake Gravity Fluid</title>
		<link>http://www.rickigregersen.com/2009/08/31/fake-gravity-fluid/</link>
		<comments>http://www.rickigregersen.com/2009/08/31/fake-gravity-fluid/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 22:01:41 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Particle]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[flow field]]></category>
		<category><![CDATA[fun]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=196</guid>
		<description><![CDATA[I was playing around with the Traer Physics Library for processing/java. It is really fast but even though I had done some small experiments with it a year or so back, I still had to dig out the manual and refresh some basic stuff. Well Im looking into the whole FluidSolver thing, again, and I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with the <a href="http://www.cs.princeton.edu/~traer/physics/">Traer Physics Library</a> for processing/java. It is really fast but even though I had done some small experiments with it a year or so back, I still had to dig out the manual and refresh some basic stuff.<br />
Well Im looking into the whole FluidSolver thing, again, and I thought it could be fun to do a fast and crude Newtonian approach and just go for an effect that looks a bit like it, but is far more simple.</p>
<p><img src="http://www.rickigregersen.com/wp-content/uploads/fluid.png" alt="16834 particles fakes fluid" /></p>
<p><a href="http://www.rickigregersen.com/wp-content/uploads/fluid_applet/index.html">Example and code here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/08/31/fake-gravity-fluid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Circle Intersection</title>
		<link>http://www.rickigregersen.com/2009/08/09/circle-intersection/</link>
		<comments>http://www.rickigregersen.com/2009/08/09/circle-intersection/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 21:17:42 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Processing]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[circle]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[noise]]></category>
		<category><![CDATA[Perlin]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=190</guid>
		<description><![CDATA[&#8220;What is the point&#8221; was my first thought on this. I had to do some calculations on the intersections between circles, that was pretty straight forward and I got a class written up in Processing that could do just that. Then I started playing around and ended up moving 10 circles around the screen using [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>&#8220;What is the point&#8221;</p></blockquote>
<p> was my first thought on this.<br />
I had to do some calculations on the intersections between circles, that was pretty straight forward and I got a class written up in Processing that could do just that.<br />
Then I started playing around and ended up moving 10 circles around the screen using Perlin noise and if any of them intersects, I draw a dot. Pointless? certainly!</p>
<p>Maybe there is someone out there with an idea on how to make this into something other that a cpu hogging math feast. I would love to hear from You:)</p>
<p>Well there is some Perlin movement, some ArrayList looping and of course that class that takes 2 circles and returns their intersection, maybe someone can use that for something useful.<br />
<img src="http://rickigregersen.com/wp-content/uploads/circleIntersection.png" alt="A short run, maybe it get's better?" /></p>
<p><a href="http://www.rickigregersen.com/wp-content/uploads/circleApplet/index.html">Example and code here:</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/08/09/circle-intersection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Processing Tentacles</title>
		<link>http://www.rickigregersen.com/2009/08/08/processing-tentacles/</link>
		<comments>http://www.rickigregersen.com/2009/08/08/processing-tentacles/#comments</comments>
		<pubDate>Sat, 08 Aug 2009 16:16:38 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Particle]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=185</guid>
		<description><![CDATA[I just did a quick port to processing, important to notice that these classes are &#8220;as is&#8221;, but still, the speed of Java compared to Flash is&#8230; well lets just say the gap isn&#8217;t quite gone yet EDIT: forgot some int/float math that made the tentacles look bulky&#8230; better now. Example and code here:]]></description>
			<content:encoded><![CDATA[<p>I just did a quick port to processing, important to notice that these classes are &#8220;as is&#8221;, but still, the speed of Java compared to Flash is&#8230; well lets just say the gap isn&#8217;t quite gone yet <img src='http://www.rickigregersen.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>EDIT: forgot some int/float math that made the tentacles look bulky&#8230; better now.<br />
<a href="http://www.rickigregersen.com/wp-content/uploads/applet/index.html">Example and code here:</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/08/08/processing-tentacles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AnTrack</title>
		<link>http://www.rickigregersen.com/2009/05/02/antrack/</link>
		<comments>http://www.rickigregersen.com/2009/05/02/antrack/#comments</comments>
		<pubDate>Sat, 02 May 2009 13:52:15 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cam]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[sound]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=79</guid>
		<description><![CDATA[My friend Kenneth expressed some interest in giving Processing a spin. He is an engineering student and usually deals in C++. The learing curve in Processing is extremely flat and if you have prior programming experience you will go from having an idea to an actual prototype in minutes. So we thought up a small [...]]]></description>
			<content:encoded><![CDATA[<p>My friend Kenneth expressed some interest in giving Processing a spin. He is an engineering student and usually deals in C++.</p>
<p>The learing curve in Processing is extremely flat and if you have prior programming experience you will go from having an idea to an actual prototype in minutes. So we thought up a small project: A Processing sketch that could detect a wavy black line on a piece of paper and subsequently play a tone according to the lines y position.</p>
<p>The result was <em><strong>anTrack</strong></em>, it uses the Capture Library to read the bitmaps of a web cam and the Minim sound library to produce a sine wave. It works just fine and my friend was hooked on the simplicity of <a href="http://www.processing.org">Processing</a>, he actually wrote most of the implementations.</p>
<p>What to use this for? I have no idea, it resembles a 1979 sci-fi horror film sound effect or a <a href="http://en.wikipedia.org/wiki/Theremin" target="_blank">Theremin</a>. We thought about building some sort of a rack in lego mindstorm that would continously scroll a piece of paper infront of the camera. A seismographic reading turned into sound, I guess, but the main goal was to have a little fun with processing for a couple of hours and we achieved that just fine.</p>
<p>anTrack.pde</p>
<pre lang="java">/*
* author: Kenneth Knudsen &amp; Ricki Gregersen
* description: reads a line from a piece of paper using a webcam
*              and outputs a tone between 440 and 880 Hz
*              according to the lines y coordinate
*/
//use the minim sound library, included in processing 1.0
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;

//CamModule instance for grapping a frame from the webcam
CamModule cam;
//SoundModule instance for outputting a sine wave at a specific frequence
SoundModule sound;
//TrackModule instance for translating a y coordinate to a frequency
TrackModule track;

void setup()
{
  size(640, 480);
  frameRate(30);
  //CamModule constructor takes an input of (PApplet, width to grap, height to grap and offset)
  //this means: we will grap 30x480 pixels from the webcam starting at 320 in the x direction
  cam = new CamModule(this, 30, height, 320);
  sound = new SoundModule(this);
  track = new TrackModule();
}

void draw()
{
  //get the bitmap from the webcam
  PImage frame = cam.bitmap();
  //process it and return the position of the line as a frequency
  float freq = track.processBitmap(frame);
  //feed the frequency to the soundModule
  sound.freq(freq);
  //present the frame grabbed from the webcam to the screen
  image(frame, 320, 0);
}
//remember to close the connection made to the soundcard
void stop()
{
  super.stop();
  sound.stop();
}</pre>
<p>The CamModule:</p>
<pre lang="java">import processing.video.*;

class CamModule
{

  private Capture cam;
  private PImage frame;
  private int w, h, offSet;

  CamModule(PApplet applet, int _w, int _h, int _o)
  {
    w = _w;
    h = _h;
    offSet = _o;
    String[] devices = Capture.list();
    //println(devices);
    //comment in the above line if you don't know which port your webcam is plugged into
    cam = new Capture(applet, width, height, devices[1]);
    frame = createImage(w, h, RGB);
  }

  public PImage bitmap()
  {
    //read the full image from the webcam and copy out the pixels needed
    if (cam.available()) {
        cam.read();
        frame.copy(cam, offSet, 0, w, h, 0, 0, w, h);
    }
    return frame;
  }
}</pre>
<p>The SoundModule.pde</p>
<pre lang="java">class SoundModule
{
  Minim m;
  AudioOutput dac;
  SineWave sine;

  SoundModule(PApplet a)
  {
    m = new Minim(a);
    dac = m.getLineOut(Minim.STEREO);
    sine = new SineWave(0, 0.5, dac.sampleRate());
    //it is all in the minim documentation which is quite good, but portamento means that there
    //will be no pause when changing from one frequency to another, instead there is a 200 ms slide from
    //the original tone to the new one.
    sine.portamento(200);
    dac.addSignal(sine);
  }

  void freq(float f)
  {
    //if a frequency is present, map it to a sine with Hz between 440 and 880 (an octave)
    if(f &gt; 0)
    {
      f = map(f, 0.1, height, 440, 880);
    }
    else{
      f = 0;
    }
    sine.setFreq(f);
  }
  //again remenber to close the connection to the soundcard
  void stop()
  {
    m.stop();
    dac.close();
  }
}</pre>
<p>The TrackModule.pde</p>
<pre lang="java">class TrackModule
{

  private float th = 80; //brightness 0-255
  private int hh = 80; //percent 0-100

    TrackModule()
  {

  }

  float processBitmap(PImage bm)
  {
    int index;
    int hits;
    int successive_hits = bm.width * (hh / 100);

    /*  this is a sort of filter.
     we run through the pixels one horizontal line at the time
     if we find a pixel with a brightness below the threshold (th)
     we add a hit. So if 80 percent of a line is dark enought to
     trigger the filter we count that as a dark line spotted and we retun the
     y value were it was spotted.
     */

    for(int y = 0; y &lt; bm.height; y++)
    {
      hits = 0;
      index = y * bm.width;
      for(int x = 0; x &lt; bm.width; x++)
      {
        color c = bm.pixels[index + x];
        if( brightness(c) &lt; th)
        {
          hits++;
          if(hits &gt; successive_hits)
          {
            return y;
          }
        }
      }
    }
    return 0.0;
  }
}</pre>
<p>There is an Applet <a title="anTrack source" href="http://www.rickigregersen.com/wp-content/code/antrack/" target="_blank">here</a>, I haven&#8217;t gone through the steps to make it work in a browser so the visitor<br />
can use their own web cam, it&#8217;s mostly done so you can get the source code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/05/02/antrack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kruskals algorithm in Processing</title>
		<link>http://www.rickigregersen.com/2009/03/18/kruskals-algorithm-in-processing/</link>
		<comments>http://www.rickigregersen.com/2009/03/18/kruskals-algorithm-in-processing/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 17:41:58 +0000</pubDate>
		<dc:creator>Ricki</dc:creator>
				<category><![CDATA[Processing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Kruskal]]></category>

		<guid isPermaLink="false">http://www.rickigregersen.com/?p=4</guid>
		<description><![CDATA[I was reading Robert Sedgewicks &#8220;Algorithms in Java&#8221; and had skipped to part 5 concerning Graphs. I know I ought not skip portions of a book concerning something that difficult, but 130 pages into the first part I needed to see where all this theory was going. I stumbled over the Kruskal/Prims/Dijkstra algorithms and the visual [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_37" class="wp-caption alignnone" style="width: 707px"><img class="size-full wp-image-37" title="kruskal" src="http://www.rickigregersen.com/wp-content/uploads/kruskal.png" alt="Minimum Spanning Tree (red path)" width="697" height="496" /><p class="wp-caption-text">Minimum Spanning Tree (red path)</p></div>
<p>I was reading Robert Sedgewicks &#8220;Algorithms in Java&#8221; and had skipped to part 5 concerning <em>Graphs.</em></p>
<p>I know I ought not skip portions of a book concerning something that difficult, but 130 pages into the first part I needed to see where all this theory was going.</p>
<p>I stumbled over the Kruskal/Prims/Dijkstra algorithms and the visual representations caught my eye. They were really simple to look at but you could sense there was some sort of genius system behind it. That is one of my favorite reasons for opening up Processing and start sketching.</p>
<p><strong>A few </strong><em><span style="text-decoration: line-through;"><strong>need to know</strong></span></em><strong> things on Graphs:</strong></p>
<p>Thinking in 2 dimensions, a Graph consists of a number of points on a surface. A point is called a <em>vertex </em>and each vertex can be connected to a number of other vertices. Such a connection between 2, or more, vertexes is called and <em>edge. </em></p>
<p><em></em></p>
<p><em></em></p>
<p><em></em></p>
<p><em></em></p>
<p><em> </em></p>
<div id="attachment_26" class="wp-caption alignnone" style="width: 285px"><img class="size-medium wp-image-26" title="simple graph" src="http://www.rickigregersen.com/wp-content/uploads/graph01.png" alt="simple graph" width="275" height="235" /><p class="wp-caption-text">simple graph</p></div>
<p><em><span style="font-style: normal;">There are many different types of Graphs: </span>directed graphs, </em>where directed means, that two vertices that are connected also states which direction you can travel from one vertex to the other, e.g. V1 -&gt;V2 means you can go from V1 to V2 but not the other way. <em>Undirected Graphs </em>is then, of course, a graph where it does not matter which way you travel. Directed and undirected graphs can also be <em>weighted</em> or not. This means that &#8220;it takes a certain amount of energy&#8221; to travel from one vertex to another.</p>
<div id="attachment_28" class="wp-caption alignnone" style="width: 295px"><img class="size-full wp-image-28" title="simple directed weighted graph" src="http://www.rickigregersen.com/wp-content/uploads/graph02.png" alt="simple directed weighted graph" width="285" height="178" /><p class="wp-caption-text">simple directed weighted graph</p></div>
<p>This comes clear when we think back to the 2 dimensions and that a graph can be points/vertices on a surface. If we were looking to connect three vertices using the least amount of &#8220;energy&#8221;  and vertex v1 is situated a distance of 9 meters from vertex V2 and vertex V1 is situated 4 meters from vertex V3 and vertex V2 is situated 3 meters from vertex V3, we would connect them as such: V1-V3-V2</p>
<div id="attachment_31" class="wp-caption alignnone" style="width: 254px"><img class="size-full wp-image-31" title="Euclidian weighted graph" src="http://www.rickigregersen.com/wp-content/uploads/graph03.png" alt="Euclidian weighted graph" width="244" height="123" /><p class="wp-caption-text">Euclidian weighted graph</p></div>
<h1>Minimum Spanning Tree</h1>
<p>Having scratched the surface of Graphs it is now a bit easier to understand what a <em>minimum spanning tree</em> is.</p>
<p>In the &#8220;Algorithms in Java&#8221; book the minimum spanning tree(MST) is defined as:</p>
<blockquote><p>In a weighted graph, find a minimum-weight set of edges that connects all the vertices.</p></blockquote>
<p>It is also defined as:</p>
<blockquote><p>A minimum spanning tree of a weighted graph is a spanning tree whose weight(the sum of weights of it&#8217;s edges) is no larger than the weight of any other spanning tree.</p></blockquote>
<p>It is good to dwell on that last definition for a second. It says that there might be lots and lots of spanning trees in a graph, and that some of them can have the same combined weight. According to the definition this is okay, the more the merrier, as long as it is still a minimum spanning tree.</p>
<p>This means, that from any vertex you should be able to travel to any other vertex, not necessarily along the shortest path, that is another algorithm altogether, but all the vertices is connected in a way that adds up to the combined shortest edges.</p>
<p>There are quite a few algorithms that strives to solve this problem, two of them is Prim&#8217;s and Kruskal&#8217;s algorithm.</p>
<p>Prim&#8217;s algorithm, it goes under many different names as it has been discovered and implemented by more than one person, but that is a story for <a href="http://en.wikipedia.org/wiki/Prim_algorithm">Wikipedia</a> and not this very short post.</p>
<p>Prim&#8217;s algorithm looks at a graph, selects an arbitrary vertex and starts testing all the edges connected to this vertex, once it finds the shortest edge, the edge with the smallest weight, it adds this to the tree, e.g. V12-V65. It then goes on to look for the next shortest edge from either V12 or V65. Before the algorithm can add another edge it must test that it is not creating a <em>cycle. </em>A cycle is if V1-V2 and V2-V3 and V3-V1 is connected, meaning you could start out from V1 and then end up in V1 again. A cycle is redundant in a minimum spanning tree and not desired.</p>
<p>If the algorithm consists of N vertices the MST will be finished when N-1 edges has been added to the MST, regarding no cycles has been made.</p>
<p>The Kruskla&#8217;s algorithm works in a very similar way, the main difference is that Kruskal&#8217;s algorithm starts at the first vertex, i.e V1 and then works it&#8217;s way outwards from that.</p>
<p>This means that an identical graph will yield the same MST each time when using Kruskal and that Prim&#8217;s can yield different MST&#8217;s depending on which vertex was set as the starting point(remember the second definition&#8230;)</p>
<p><a title="Kruskal Processing example" href="http://www.rickigregersen.com/wp-content/code/kruskal/" target="_blank">Here is the Processing code for the sketch shown at the beginning</a></p>
<p>There are 101 vertices, this adds up to 5050 possible edges, they are drawn in using a transparant white. The MST will be the red path as in the picture in the start of the post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rickigregersen.com/2009/03/18/kruskals-algorithm-in-processing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
