<?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>Raymond Cabrera's Blog</title>
	<atom:link href="http://www.raymondcabrera.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.raymondcabrera.com/blog</link>
	<description>notes on simulation, geography, engineering and the way they somehow intersect</description>
	<lastBuildDate>Mon, 27 Apr 2009 14:00:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Repast Simphony on Ubuntu</title>
		<link>http://www.raymondcabrera.com/blog/2009/04/repast-simphony-on-ubuntu/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/04/repast-simphony-on-ubuntu/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 14:00:16 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[repast simphony]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://www.raymondcabrera.com/blog/?p=53</guid>
		<description><![CDATA[I&#8217;m liking Ubuntu 9.04 (Jaunty Jackalope). Now how to do model development on this platform&#8230;

Install Java 6
First, we need to get Java and Eclipse installed. I&#8217;ve had some troubles with OpenJDK, so I&#8217;ll be using Sun&#8217;s (now Oracle&#8217;s) JDK. You can install the sun-java6-jdk package with synaptic or at the command line:

  sudo apt-get install sun-java6-jdk

Double-check that you&#8217;re using Sun&#8217;s JDK. Run java -version at the command-line. You should get something like this:

 java version "1.6.0_13"
  Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
  Java HotSpot(TM) 64-Bit Server VM ...]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m liking <a href="http://www.ubuntu.org/">Ubuntu 9.04 (Jaunty Jackalope)</a>. Now how to do model development on this platform&#8230;</p>
<p><span id="more-53"></span></p>
<h3>Install Java 6</h3>
<p>First, we need to get Java and Eclipse installed. I&#8217;ve had some troubles with OpenJDK, so I&#8217;ll be using Sun&#8217;s (now Oracle&#8217;s) JDK. You can install the <code>sun-java6-jdk</code> package with synaptic or at the command line:</p>
<blockquote>
<pre>  sudo apt-get install sun-java6-jdk</pre>
</blockquote>
<p>Double-check that you&#8217;re using Sun&#8217;s JDK. Run <code>java -version</code> at the command-line. You should get something like this:</p>
<blockquote>
<pre> java version "1.6.0_13"
  Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
  Java HotSpot(TM) 64-Bit Server VM (build 11.3-b02, mixed mode)</pre>
</blockquote>
<p>If OpenJDK, IcedTea, or GIJ is still being used by default, you can change it with the following command (more info <a href="https://help.ubuntu.com/community/Java">here</a>):</p>
<blockquote>
<pre>  sudo update-java-alternatives -s java-6-sun</pre>
</blockquote>
<p>All set?</p>
<h3>Install Eclipse Ganymede</h3>
<p>Unfortunately, even Jaunty still comes packaged with Eclipse 3.2 (Callisto) and not 3.4 (Ganymede). Repast Simphony calls for Ganymede, so here goes a manual install:</p>
<p>With <code>wget</code> or your favourite web browser, download <a href="http://www.eclipse.org/downloads/">Eclipse Classic</a> appropriate to your Linux install (32-bit or 64-bit). Extract it to a directory (replacing the filename with the file you&#8217;ve downloaded):</p>
<blockquote>
<pre>  tar xzvf eclipse-SDK-3.4.2-linux-gtk-x86_64.tar.gz</pre>
</blockquote>
<p>For me, this extracted it to a subdirectory called <code>eclipse</code>. Feel free to move it and delete the .tar.gz archive. I moved my install to <code>/opt/eclipse</code> and changed the owner to root (by running <code>sudo mv eclipse /opt &#038;&#038; sudo chown root:root -R /opt/eclipse</code>).</p>
<h4>GUI and Command-Line Shortcuts to Eclipse</h4>
<p>If you want a shortcut from the GNOME Applications menu, you can right-click on the Applications menu and click Edit Menus. Select the Programming menu and click Add New Item.</p>
<div id="attachment_65" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-add-new-item1.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-add-new-item1-300x235.png" alt="Adding an item to the Programming menu" title="Edit Menus screenshot" width="300" height="235" class="size-medium wp-image-65" /></a><p class="wp-caption-text">Adding an item to the Programming menu</p></div>
<p>From here, you can add a shortcut to your Eclipse executable.</p>
<div id="attachment_67" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-launcher-properties.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-launcher-properties-300x135.png" alt="Edit the item to point to the Eclipse executable" title="Launcher Properties" width="300" height="135" class="size-medium wp-image-67" /></a><p class="wp-caption-text">Edit the item to point to the Eclipse executable</p></div>
<p>Want a command-line shortcut to Eclipse? You can add a soft-link to Eclipse in /usr/bin by running <code>sudo ln -s /opt/eclipse/eclipse /usr/bin/eclipse</code>. Now you can run Eclipse by running <code>eclipse</code> at the command line or with the Run Application window (Alt-F2).</p>
<h3>Other components (JOGL, JAI, Java3D)</h3>
<h4>JAI</h4>
<p>Download the current binary build from the <a href="https://jai.dev.java.net/binary-builds.html">JAI</a> site. You can read the installation instructions <a href="http://download.java.net/media/jai/builds/release/1_1_3/INSTALL.html#Linux">here</a>. This installs JAI right into the JDK.</p>
<p>Note that the JDK is (likely) installed in <code>/usr/lib/jvm/java-6-sun</code>.</p>
<h4>Java3D</h4>
<p>Download the zipped binary build from the <a href="https://java3d.dev.java.net/binary-builds.html">Java3D</a> site. Installation instructions are <a href="http://download.java.net/media/java3d/builds/release/1.5.2/README-download.html">here</a>. The installation&#8217;s a bit tougher, since it&#8217;s not recommended to install directly into the JDK, but here&#8217;s what I did:</p>
<p>Unzip the libraries and move them to /opt:</p>
<blockquote>
<pre>  unzip j3d-1_5_2-linux-amd64.zip
  unzip j3d-1_5_2-linux-amd64/j3d-jre.zip
  rm j3d-1_5_2-linux-amd64/j3d-jre.zip
  sudo mv j3d-1_5_2-linux-amd64 /opt</pre>
</pre>
</blockquote>
<p>From here, you should add it to the classpath, but we'll do that later, once Repast Simphony is installed.</p>
<h4>JOGL</h4>
<p>Download the current release build from the <a href="https://jogl.dev.java.net/">JOGL</a> development site. Installation is similar to the above libraries: Extract to some directory and make sure it's on your classpath (later).</p>
<h3>Install Repast Simphony</h3>
<p>Almost.</p>
<p>This is important: If you ran the <code>chown</code> command earlier to change the owner to root, start Eclipse as root:</p>
<blockquote>
<pre>  gksudo eclipse &#038;</pre>
</blockquote>
<p>If you're still the owner of Eclipse's files, start Eclipse normally.</p>
<p>You'll need to install Groovy. Also, if it's not already there, you'll need to add the Ganymede update site since some dependencies will be needed. From the Software Updates window (Help > Software Updates), click the Manage Sites button.</p>
<div id="attachment_81" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/manage-sites-button.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/manage-sites-button-300x189.png" alt="Eclipse Update: Manage Sites button" title="Eclipse Update: Manage Sites button" width="300" height="189" class="size-medium wp-image-81" /></a><p class="wp-caption-text">Eclipse Update: Manage Sites button</p></div>
<p>Add <code>http://download.eclipse.org/releases/ganymede</code> and <code>http://dist.codehaus.org/groovy/distributions/update/</code>. Eclipse should be able to find the dependencies from there.</p>
<p>Repast Simphony can be installed as an Eclipse plugin from the update site, <code>http://mirror.anl.gov/pub/repastsimphony</code>. Check off Repast and Groovy and install!</p>
<div id="attachment_88" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-software-updates-and-add-ons.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-software-updates-and-add-ons-300x189.png" alt="Select Repast Simphony and Groovy" title="Software Updates and Add-ons" width="300" height="189" class="size-medium wp-image-88" /></a><p class="wp-caption-text">Select Repast Simphony and Groovy</p></div>
<h4>Adding libraries to the Classpath</h4>
<p>Since JAI was installed right into the JDK, it's already included in the classpath. Java3D and JOGL still need to be added to the classpath. If you installed Java3D and JOGL right into the JDK (<em>tsk, tsk</em>), you can skip this section: You're all done! (But other things might be broken... who knows)</p>
<p>From Window > Preferences, then under Java > Build Path > User Libraries, add JOGL. Click New and type the library name. With the new library selected, click Add Jars and select both JAR files (hold down Ctrl). Click OK.</p>
<div id="attachment_92" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-jar-selection1.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-jar-selection1-300x225.png" alt="Add both JAR files" title="JAR Selection" width="300" height="225" class="size-medium wp-image-92" /></a><p class="wp-caption-text">Add both JAR files</p></div>
<p>Not done with JOGL yet... select Native library location and click Edit. Set it to the same directory as the JAR files (/opt/jogl-1.1.1-linux-amd64/lib in my case).</p>
<p>Do the same thing for Java3D, except the JAR files come from /opt/j3d-1_5_2-linux-amd64/lib/ext and the native libraries come from /opt/j3d-1_5_2-linux-amd64/lib/amd64. (Locations might vary based on your Linux build and library versions.)</p>
<p>When you create a new project, you'll have to add JOGL and Java3D to the build path (Libraries tab).</p>
<div id="attachment_90" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-properties-for-mariaprototype.png" rel="lightbox[53]"><img src="http://www.raymondcabrera.com/blog/wp-content/uploads/2009/04/screenshot-properties-for-mariaprototype-300x215.png" alt="Add JOGL and Java3D to the Build Path" title="screenshot-properties-for-mariaprototype" width="300" height="215" class="size-medium wp-image-90" /></a><p class="wp-caption-text">Add JOGL and Java3D to the Build Path</p></div>
<p>All done!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/04/repast-simphony-on-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>R, JDBC and SQL for model data analysis</title>
		<link>http://www.raymondcabrera.com/blog/2009/03/r-jdbc-and-sql-for-model-data-analysis/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/03/r-jdbc-and-sql-for-model-data-analysis/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 20:02:53 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[r]]></category>
		<category><![CDATA[repast simphony]]></category>

		<guid isPermaLink="false">http://simulatedlife.wordpress.com/?p=50</guid>
		<description><![CDATA[Now that the model&#8217;s data is stored in a database, how can the data be retrieved for analysis? Today, I&#8217;ll discuss how to retrieve data from a database to R. R is an open-source statistical software environment and functional programming language, a modern implementation of S.
Since JDBC&#8217;s been introduced in previous posts, a similar approach can be used by using the RJDBC package and MySQL Connector/J. There&#8217;s also a package called RMySQL to connect R to MySQL without JDBC, but I&#8217;ll discuss the JDBC approach.

If you haven&#8217;t done so already, ...]]></description>
			<content:encoded><![CDATA[<p>Now that the model&#8217;s data is stored in a database, how can the data be retrieved for analysis? Today, I&#8217;ll discuss how to retrieve data from a database to <a href="http://www.r-project.org/">R</a>. R is an open-source statistical software environment and functional programming language, a modern implementation of <a href="http://en.wikipedia.org/wiki/S_programming_language">S</a>.</p>
<p>Since JDBC&#8217;s been introduced in previous posts, a similar approach can be used by using the <a href="http://www.rforge.net/RJDBC/">RJDBC package</a> and <a href="http://www.mysql.com/products/connector-j">MySQL Connector/J</a>. There&#8217;s also a package called <a href="http://cran.r-project.org/web/packages/RMySQL/index.html">RMySQL</a> to connect R to MySQL without JDBC, but I&#8217;ll discuss the JDBC approach.</p>
<p><span id="more-52"></span></p>
<p>If you haven&#8217;t done so already, download and install <a href="http://www.r-project.org/index.html">R</a>. You can install the RJDBC package within R using the menu (Package &gt; Install Package(s) &gt; RJDBC) or with the following command:</p>
<blockquote>
<pre>  install.packages("RJDBC")</pre>
</blockquote>
<p>Assuming you&#8217;ve downloaded the MySQL Connector/J earlier, you&#8217;re ready to collect some data. Taking the same conventions for <code>jdbcUrl</code>, <code>jdbcUser</code> and <code>jdbcPass</code> as last time, initialize a connection to the database:</p>
<blockquote>
<pre>  library(RJDBC)
  drv &lt;- JDBC("com.mysql.jdbc.Driver",
    "/etc/jdbc/mysql-connector-java-5.1.7-bin.jar",
    identifier.quote="`")
    conn &lt;- dbConnect(drv, jdbcUrl, jdbcUser, jdbcPass)
</pre>
</blockquote>
<p>The &#8220;com.mysql.jdbc.Driver&#8221; argument refers to the same one used in the <code>Class.forName</code> method used in the earlier post. Now that you have a connection, grab a data frame using a SELECT query. Say I wanted to read the input parameters for a particular run:</p>
<blockquote>
<pre>  runID = 7
  d &lt;- dbGetQuery(conn,
    "SELECT param1, param2 FROM runs WHERE runID=?",
    runID)
  str(d) // show structure of data frame
  d    // print data frame</pre>
</blockquote>
<p>Wasn&#8217;t too useful? Here&#8217;s a basic function to plot a single variable over time given an agent&#8217;s run and household ID.</p>
<blockquote>
<pre>  plotSingleHouseholdCapital = function (runID, householdID) {
    d &lt;- dbGetQuery(conn, "SELECT tick, capital
      FROM householdState WHERE runID = ? and householdID = ?",
      runID, householdID)
    plot(capital ~ tick, data = d,
      xlab="tick (Year)", ylab="Household Capital")
  }</pre>
</blockquote>
<p>For better performance in most cases, using stored procedures helps. A stored procedure is a block of statements which is executed on the database server. To create a stored procedure, see the <a href="http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html">MySQL documentation</a>. Here&#8217;s an example:</p>
<blockquote>
<pre>  DELIMITER $$

  CREATE PROCEDURE avghouseholdstate (IN runID INT)
  BEGIN
    select runID, tick, avg(capital) AS capital
    from householdstate
    where runID = runID
    group by runID,tick;
  END $$

  DELIMITER ;</pre>
</blockquote>
<p>If you&#8217;ve created a stored procedure called <code>avghouseholdstate</code> with a single parameter <code>runID</code>, like the one above, it can be called from R like this:</p>
<blockquote>
<pre>  avgCapital = function (runID) {
    d &lt;- dbGetQuery(conn, "call avghouseholdstate(?)", runID)
    plot(capital ~ tick, data = d,
      xlab="tick (Year)", ylab="Avg Household Capital")
  }</pre>
</blockquote>
<p>This is a very simplified version of a stored procedure I use myself, but hopefully it&#8217;s enough to illustrate at least the basics of retrieving data from MySQL (or any other JDBC driver) to R.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/03/r-jdbc-and-sql-for-model-data-analysis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using MySQL to record Repast model results: Part 2</title>
		<link>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-data-part-2/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-data-part-2/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 04:59:07 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[abm]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[repast simphony]]></category>

		<guid isPermaLink="false">http://simulatedlife.wordpress.com/2009/03/02/using-mysql-to-record-model-data-part-2/</guid>
		<description><![CDATA[Part 1 of the MySQL guide stopped just short of integrating the database into the model. In this part, I’ll discuss how to use MySQL Connector/J and generally any other JDBC driver for logging agent data. The SQL syntax and Java code may differ slightly in other database implementations, such as H2, HSQLDB and SQL Server, but the general idea should be the same.

Defining a Database class
If you haven’t done so already, download the latest version of MySQL Connector/J and add it to your classpath. Create a new class called ...]]></description>
			<content:encoded><![CDATA[<p>Part 1 of the MySQL guide stopped just short of integrating the database into the model. In this part, I’ll discuss how to use MySQL Connector/J and generally any other JDBC driver for logging agent data. The SQL syntax and Java code may differ slightly in other database implementations, such as H2, HSQLDB and SQL Server, but the general idea should be the same.</p>
<p><span id="more-44"></span></p>
<h3>Defining a Database class</h3>
<p>If you haven’t done so already, download the latest version of MySQL Connector/J and add it to your classpath. Create a new class called <code>Database</code>, which will act as the interface to the actual database, containing all of the methods you&#8217;ll need to log agent and model data. This will simplify the rest of the model by allowing agents to call “friendly” methods like <code>logAgent</code> instead of raw SQL code.</p>
<div id='extendedEntryBreak'></div>
<h4>Establishing a Connection</h4>
<p>First, you&#8217;ll need to make a connection from your <code>Database</code> object to the actual MySQL database server, where <code>conn</code> is a <code>Connection</code> field. The following code can be put into the Database&#8217;s constructor or intialization method:</p>
<blockquote><pre>  Class.forName("com.mysql.jdbc.Driver");
  conn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
  conn.setAutoCommit(false);
</pre>
</blockquote>
<p>If you&#8217;re using a JDBC 4.0 driver (like MySQL Connector/J 5.1) and Java 6, the first line can be omitted. I usually leave it in, just in case I need to deploy to a pre-Java 6 environment. In the above, <code>jdbcUrl</code> can be replaced or assigned &#8220;jdbc:mysql://localhost:3306/[schema_name]&#8220;, where [schema_name] should be replaced with the name of the schema (without square brackets) created in Part 1. The default jdbcUser is &#8220;root&#8221;.</p>
<h4>Transactions</h4>
<p>What does that last line do? It turns off auto-commit and implicitly turns on transactions. In an ideal <a href="" rel="external">ACID-compliant</a> world, transactions are atomic (as well as concurrent, isolated and durable). That means that if any part of the transaction fails, the whole transaction fails. So if you abort a run midway, none of the run&#8217;s results are recorded, which is the way I would prefer it. If that&#8217;s your cup of tea, you&#8217;ll need to end each run with a call to <code>conn.commit()</code> and abort a failed run (if possible) with <code>conn.rollback()</code>. If the connection closes without a commit, any uncommitted changes are rolled back anyway.</p>
<h4>Closing the Database Connection</h4>
<p>Since it&#8217;s inefficient to create and destroy connections frequently, the connection created above can be used for the entirety of the batch run. It&#8217;s a best practice to close the connection when you&#8217;re done with it. This can be done with a shutdown hook, which is a thread that runs when the Java Virtual Machine terminates. The shutdown hook below closes the connection. If it fails to close the connection, it silently fails, as shown by the empty <code>catch</code> block. This code can also be added to the Database&#8217;s constructor or intialization method.</p>
<blockquote>
<pre>  Thread shutdownThread = new Thread() {
    @Override
    public void run() {
      try {
        conn.close();
      } catch (SQLException e) {}
    }
  };
  Runtime.getRuntime().addShutdownHook(shutdownThread);
</pre>
</blockquote>
<h4>Creating Data Recording Methods</h4>
<p>Continuing on from the tables created from Part 1, some useful methods to create are: <code>initRun()</code>, <code>logAgent(Agent a)</code> and <code>logAgentState(Agent a)</code>.</p>
<blockquote>
<pre>  public int initRun() {
    int runID;
    Parameters p = RunEnvironment.getInstance().getParameters();

    PreparedStatement s = conn.prepareStatement(
      "INSERT INTO tblRun(rundate, param1, param2) " +
      "VALUES (?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS);
    s.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
    s.setDouble(2, (Double) p.getValue("param1"));
    s.setDouble(3, (Double) p.getValue("param2"));

    s.executeUpdate();

    // get the auto-generated runID
    ResultSet rs = s.getGeneratedKeys();
    if (rs.next()) {
      runID = rs.getInt(1);
    } else {
      runID = -1; // something went wrong: abort or use some default
    }
    s.close();
    return runID;
  }
</pre>
</blockquote>
<p>I&#8217;ll leave the other methods unimplemented. They are quite similar to the <code>initRun()</code> method, except instead of pulling parameters from the <code>RunEnvironment</code>, agent attributes are retrieved using <code>get</code> methods. A useful method for getting the current tick is:</p>
<blockquote>
<pre>  RunState.getInstance().getScheduleRegistry()
    .getModelSchedule().getTickCount();</pre>
</blockquote>
<p>Maybe there&#8217;s a shorter way of doing that.</p>
<h3>Using the Database class</h3>
<p>Every class (agent, context, etc.) that wishes to write to the database will need a reference to the Database instance. You have a few options to handle that.</p>
<ol>
<li>Pass a reference of the Database instance to every agent. </li>
<li>Use the singleton design pattern to allow any Java object to get the reference to the instance. </li>
<li>Use Simphony’s general registry to store the Database instance. </li>
</ol>
<p>With the first approach, every agent writing to the database must have a reference to the Database instance. That could introduce a lot of overhead if there are many agents. (Alternatively, you could set up database logging from the parent context only, in which case each agent would not require a reference to the Database instance.</p>
<p>I prefer to use the singleton pattern in this case, since there is less overhead than in the retrieval of the instance. With the singleton pattern, the instance of the database is stored in a static field in the Database class. Outside classes cannot create new instances of the database, but may only retrieve the instance referenced by the Database class. This ensures that one and only one Database instance exists.</p>
<p>To use the singleton pattern, make the Database&#8217;s constructor(s) a private method and put this line inside the Database class definition:</p>
<blockquote>
<pre>  private static final Database instance = new Database();</pre>
</blockquote>
<p>Finally, make a new method inside Database to retrieve the singleton instance:</p>
<blockquote>
<pre>  public static Database getInstance() {
    return instance;
  }</pre>
</blockquote>
<p>Now that the database is set up as a singleton, any class may make reference to the singleton instance by calling <code>Database.getInstance()</code>. If I have an agent wishing to log its own data, I could call: </p>
<blockquote>
<pre>  Database.getInstance().logAgentState(this);</pre>
</blockquote>
<p>If the singleton pattern isn’t appropriate, you can use the general registry. On model startup, say in the master context&#8217;s build method, load a new instance of the Database and put it into the registry.</p>
<blockquote>
<pre>  Database db = new Database();
  RunState.getInstance().addToRegistry(&quot;database&quot;, db);</pre>
</blockquote>
<p>When an agent needs to read from the database, retrieve its instance from the registry.</p>
<blockquote>
<pre>  Database db = RunState.getInstance().getFromRegistry(&quot;database&quot;);</pre>
</blockquote>
<p>On model termination, close the Database connection and remove it from the registry.</p>
<blockquote>
<pre>  Database db = (Database) RunState.getInstance()
    .removeFromRegistry(&quot;database&quot;);
  db.close();</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-data-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using MySQL to record Repast model results: Part 1</title>
		<link>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-results-part-1/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-results-part-1/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 22:47:38 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[abm]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[repast simphony]]></category>

		<guid isPermaLink="false">http://simulatedlife.wordpress.com/?p=28</guid>
		<description><![CDATA[When analyzing a large parameter sweep, or even a lot of data from a single run, it&#8217;s useful to use SQL queries to slice the data any which way. For that, I like to collect the data into a MySQL server instance. Originally, I used H2 and HSQLDB as embedded servers (for performance reasons), but after I moved into distributed parameter sweeps, a client-server database was necessary. I&#8217;ll discuss installing a MySQL server and its integration into a Java-based model. For brevity, I won&#8217;t discuss the security of a MySQL ...]]></description>
			<content:encoded><![CDATA[<p>When analyzing a large parameter sweep, or even a lot of data from a single run, it&#8217;s useful to use SQL queries to slice the data any which way. For that, I like to collect the data into a MySQL server instance. Originally, I used H2 and HSQLDB as embedded servers (for performance reasons), but after I moved into distributed parameter sweeps, a client-server database was necessary. I&#8217;ll discuss installing a MySQL server and its integration into a Java-based model. For brevity, I won&#8217;t discuss the security of a MySQL installation.<br />
<span id="more-28"></span></p>
<h3>Installing and Configuring MySQL</h3>
<p>Download and install the latest version of MySQL Community Server (currently at version <a href="http://dev.mysql.com/downloads/mysql/5.1.html">5.1</a>) appropriate to your platform. After installation, the Server Instance Config Wizard should load. Selecting most of the defaults throughout the wizard should suffice for a typical development workstation. At the very least, you should set a root password and, if desired, start the MySQL server upon startup as a service. This will save you from restarting the MySQL server whenever the computer reboots. Also download and install the <a href="http://dev.mysql.com/downloads/gui-tools/5.0.html">MySQL GUI Tools</a>.</p>
<p>(Bonus points: Start MySQL Administrator and create a limited user account with SELECT and INSERT access to your database only. This account will be used within your model.)</p>
<h3>Creating the database schema</h3>
<p>A relational database is arranged into tables, where each row is a records. Generally, you can have a table listing the runs and their parameters, a table of agents and their initial and constant attributes, and a table of agent states which contains a record at each tick or at each change in state.</p>
<p>I personally prefer to create the database schema prior to running the model. It&#8217;s also possible to create tables if they don&#8217;t exist on model start-up.</p>
<p>Start MySQL Query Browser (part of MySQL Gui Tools which was installed earlier). Log in as <code>root</code> with the password specified in the config wizard. Create a new database schema by right-clicking in the Schemata area and selecting Create New Schema. Name it after your model. In my case, my schemata is named <code>maria</code>. You&#8217;ll later connect to your database with the URL <code>jdbc:mysql://localhost:3306/[schema_name]</code>.</p>
<p>Once your schema is created, you&#8217;re ready to create some tables. Right-click on your new schema and select Make Default Schema, to save yourself from re-typing your schema name from now on. Starting with the <em>run</em> table, some useful columns would be a run ID and the input parameters.</p>
<blockquote>
<pre>CREATE TABLE runs (
  runID INT NOT NULL AUTO_INCREMENT,
  rundate DATETIME DEFAULT NULL,
  param1 DOUBLE NOT NULL,
  param2 DOUBLE NOT NULL,
  PRIMARY KEY (`runID`)
)
</pre>
</blockquote>
<p>What does all of the above mean? The above statement creates a table named <code>runs</code> with columns containing an automatically generated run ID, a run date, and 2 double-precision floating-point parameters. The <code>NOT NULL</code> constraint in each column specifies that these blanks cannot be null or blank. (Optionally, a default value may be specified after the NOT NULL constraint.) The <code>PRIMARY KEY</code> clause at the end of the statement indicates that <code>runID</code> should be used to uniquely identify each row in the table. Check the MySQL documentation on the <a href="http://dev.mysql.com/doc/refman/5.1/en/create-table.html" rel="external">CREATE TABLE</a> if you want details.</p>
<p>A second table lists all of the agents, in which a row is created when an agent is created. You may want a separate table for each agent type (say, a mosquito table and a person table), but I&#8217;ll just list a single agent table below. You can also add the agent&#8217;s initial conditions here.</p>
<blockquote>
<pre>CREATE TABLE agents (
  agentID INT NOT NULL,
  runID INT NOT NULL,
  PRIMARY KEY (agentID ,runID),
  FOREIGN KEY (runID) REFERENCES runs (runID) ON DELETE CASCADE
)
</pre>
</blockquote>
<p>The above table is similar to the first, except for the addition of a <code>FOREIGN KEY</code>. The foreign key references the <code>runs</code> table. Specifically, it links the runID column of the <code>agents</code> table to the runID column of the <code>runs</code> table. When inserting a row into the agent table, the runID must also exist in the runs table. The <code>ON DELETE CASCADE</code></p>
<p>I like to use a third type of table to store agent states. It is like the above table, with columns for the agent ID, run ID and any attributes related to the agent state, plus the addition of a <code>tick</code> or <code>step</code> column.</p>
<p>Next post, I&#8217;ll discuss how to integrate the database into the model.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/03/using-mysql-to-record-model-results-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Loading grid coordinates into a GIS projection in Repast Simphony</title>
		<link>http://www.raymondcabrera.com/blog/2009/02/loading-grid-coordinates-into-a-gis-projection-in-repast-simphony/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/02/loading-grid-coordinates-into-a-gis-projection-in-repast-simphony/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 21:39:28 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[abm]]></category>
		<category><![CDATA[arcmap]]></category>
		<category><![CDATA[ascii grid]]></category>
		<category><![CDATA[gis]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[repast simphony]]></category>

		<guid isPermaLink="false">http://simulatedlife.wordpress.com/?p=11</guid>
		<description><![CDATA[Yes, I want my Repast Simphony model to use a fancy 3D World Wind-integrated display.
I don&#8217;t have a shapefile of agents, but I do have an ASCII grid to load into a GIS projection. (Much of my model is based on cellular automata, where households are placed into the model by assigning them to a grid cell.) Fortunately, the grid is georeferenced with a .prj projection file. The grid uses the SAD69 projection and World Wind uses WGS84. Need to convert from SAD69 (or any other CRS) to WGS84? Not ...]]></description>
			<content:encoded><![CDATA[<p>Yes, I want my Repast Simphony model to use a fancy 3D World Wind-integrated display.</p>
<p>I don&#8217;t have a shapefile of agents, but I do have an ASCII grid to load into a GIS projection. (Much of my model is based on cellular automata, where households are placed into the model by assigning them to a grid cell.) Fortunately, the grid is georeferenced with a <code>.prj</code> projection file. The grid uses the SAD69 projection and World Wind uses WGS84. Need to convert from SAD69 (or any other CRS) to WGS84? Not a problem.<br />
<span id="more-11"></span><br />
Using OpenGIS and Geotools (both included in Simphony&#8217;s referenced libraries), you can read an ArcMap projection file (which is just an ASCII file containing <a href="http://en.wikipedia.org/wiki/Well-known_text" rel="external">well-known text</a>) to get a <code>CoordinateReferenceSystem</code> object. From that, you can find a transformation to the CoordinateReferenceSystem of your target GIS projection. That&#8217;s just what this code snippet does, for a target GIS projection, <code>myGeography</code>:</p>
<pre>
CoordinateReferenceSystem sourceCRS =
    CRS.parseWKT(new BufferedReader(
        new FileReader(projectionFile)).readLine());
GeometryFactory fac = new GeometryFactory();
MathTransform mf =
    CRS.findMathTransform(sourceCRS, myGeography.getCRS());
</pre>
<p>Using the GeometryFactory and MathTransform, SAD69-referenced agents can be added to the WGS84-referenced GIS projection. You will need to specify (x,y) coordinates as well as the lower-left coordinates and cellsize of the source ASCII grid.</p>
<pre>
com.vividsolutions.jts.geom.Point point = fac.createPoint(
    getCoordinates(x, y, originx, originy, cellsize));
Geometry geom = JTS.transform(point, mf);
// or: Geometry geom = WWUtils.projectGeometryToWGS84(point, sourceCRS);
personGeography.move(h, geom);
</pre>
<p>The <code>getCoordinates</code> method referenced above (and shown below) converts grid coordinates to easting/northing. This code assumes that originx and originy refer to the coordinates of the lower-left corner of the grid (indicated by xllcorner and yllcorner in the ASCII grid header), hence the addition of 0.5 to x and y to offset the coordinate to the center of the cell. Alternatively, if your ASCII grid header uses xllcenter and yllcenter, you shouldn&#8217;t add 0.5.</p>
<pre>
public Coordinate getCoordinates(int x, int y,
        double originx, double originy, double cellSize) {
    double easting = (x + 0.5) * cellSize + originx;
    double northing = (y + 0.5) * cellSize + originy;
    return new Coordinate(easting, northing);
}
</pre>
<p>If you get a warning about missing Bursa Wolf parameters, there&#8217;s some extra work to be done. You&#8217;ll need to add a TOWGS84 parameter to your projection file. A guide on how to do that is summarized well on <a href="http://jgrasstechtips.blogspot.com/2008/03/how-to-find-and-use-bursa-wolf.html" rel="external">this blog post</a> (external link).<!--more--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/02/loading-grid-coordinates-into-a-gis-projection-in-repast-simphony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modelling with POJOs in Repast Simphony: Sub-contexts</title>
		<link>http://www.raymondcabrera.com/blog/2009/02/modelling-with-pojos-in-repast-simphony/</link>
		<comments>http://www.raymondcabrera.com/blog/2009/02/modelling-with-pojos-in-repast-simphony/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 19:07:43 +0000</pubDate>
		<dc:creator>Raymond</dc:creator>
				<category><![CDATA[agent-based modelling]]></category>
		<category><![CDATA[abm]]></category>
		<category><![CDATA[batch runs]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[repast simphony]]></category>

		<guid isPermaLink="false">http://simulatedlife.wordpress.com/?p=3</guid>
		<description><![CDATA[I&#8217;ve been creating agent-based models with Repast Simphony (a Java-based agent simulation toolkit) for the last few months, and all has been well, except for a small memory leak when doing large batch runs. Now my model is arranged into two sub-contexts, which was the source of the problem. It turns out that while Repast Simphony constructs a new master context for each run, it doesn&#8217;t do the same for sub-contexts. That is, in a master context&#8217;s build(...) method, it&#8217;s safe to assume you&#8217;re working on a new instance of ...]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been creating agent-based models with <a href="http://repast.sourceforge.net" rel="external">Repast Simphony</a> (a Java-based agent simulation toolkit) for the last few months, and all has been well, except for a small memory leak when doing large batch runs. Now my model is arranged into two sub-contexts, which was the source of the problem. It turns out that while Repast Simphony constructs a new master context for each run, it doesn&#8217;t do the same for sub-contexts. That is, in a master context&#8217;s <code>build(...)</code> method, it&#8217;s safe to assume you&#8217;re working on a new instance of that context. This isn&#8217;t true in a sub-context: that context, its state and its references might be carried over from a previous run. While you could attempt to reset the state of the context within its <code>build(...)</code> method, it&#8217;s best to create a new context explicitly from its master context. Assuming you&#8217;re creating your contexts using POJOs (plain old Java objects), your master context builder code would look something like this:</p>
<pre>
	public Context build(Context context) {
		/* ... master context initialization ... */

		context.addSubContext(new SubContextA("SubContextA"));
		context.addSubContext(new SubContextB("SubContextB"));

		return context;
	}
</pre>
<p>SubContextA and SubContextB should be in your model.score file as sub-contexts of your root context. After that, make sure sure you add Data Loaders for these sub-contexts from the Repast Simphony Scenario Tree. (I won&#8217;t explain that in this post, but if there&#8217;s interest, I&#8217;ll make a later post about creating a Repast Simphony model from scratch.)</p>
<p>There&#8217;s a hint in the <a href="http://repast.sourceforge.net/docs/reference/SIM/Context%20Loading.html" rel="external">Simphony reference documentation</a>, which probably wasn&#8217;t there when I started the model.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.raymondcabrera.com/blog/2009/02/modelling-with-pojos-in-repast-simphony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
