Tag Archive: “code”

Working on a Model of Flocking Behavior

A month or so ago I started working on a simple model of “flocking” behavior, based on work presented at a seminar I attended. I implemented most of the math, but left the visualization for later. It lay fallow for a few weeks. Over the past two days, I dusted off the project and added some simple graphics. It works!

Try it out for yourself right here (Java plugin required). The current camera controls are designed with a three-button mouse in mind, but support for the center button (scroll wheel) seems inconsistent across browsers. Hey, it’s just a demo.

Here are a few slides from a brief presentation I gave to my colleagues when I began this project.

Iain Couzin gave a talk in March as part of the EvoS seminar series. Iain’s research program involves computer modeling and experimental observation of collective animal behavior systems (schools of fish, flocks of birds, herds of ungulates). Rigorous feedback between theory and observation was evident in his work. It was inspiring.

Iain’s presentation catalyzed interest in agent-based modeling in our lab (I am an affiliated staff member). Others jumped in with NetLogo, but I decided to see what I could do with Processing due mainly to my recently rekindled interest in the language. The Obsessive Camera Direction library makes it easy to navigate the visualization.

My implementation is derived from two of the publications which formed the basis for much of the work displayed during Iain’s EvoS seminar. The first paper describes the basic rules from which a variety of flocking behaviors can be elicited, depending on particular parameter values:

Couzin, I. D., Krause, J., James, R., Ruxton, G. D., & Franks, N. R. (2002). Collective Memory and Spatial Sorting in Animal Groups. Journal of Theoretical Biology, 218(1), 1-11. [PDF]

The second paper adds goal-oriented behavior to the model and explores the effect of different proportions of “leaders” in a group (how many cooks constitute too many cooks in the kitchen?):

Couzin, I. D., Krause, J., Franks, N. R., & Levin, S. A. (2005). Effective leadership and decision-making in animal groups on the move. Nature, 433(7025), 513-516. [PDF]

My implementation does not yet include any goal-oriented behavior, but it is designed with the addition of this and other extensions in mind:

Here’s a conceptual diagram of how the pieces of the simulation are arranged. Every speck you see flying about is an Agent, and every agent may exhibit one or more Behaviors. A Collective behavior dictates the direction an agent will move based on its proximity to other visible agents. This design may be be extended to model the interaction of multiple agent types.

Whether I proceed with all or any of the potential improvements to this model is an open question. I may decide to apply this approach to other problems more closely matched to existing research programs at BU. However, I do think it would be swell to develop and test this implementation sufficiently to replicate the varied patterns presented by Iain Couzin.

Posted on Tuesday, May 11th, 2010.

Processing Syntax Coloring in TextWrangler

Processing is based on Java. TextWrangler supports syntax highlighting for Java code, but it doesn’t automatically recognize that Processing uses Java syntax. So, head over to the Languages pane of TextWrangler’s preferences and click Add next to the Suffix Mappings list. Enter .pde as the Extension and select Java as the language that should be associated with .pde files.

Now if you open a Processing source code file in TextWrangler, it will be displayed with basic syntax highlighting.

Posted on Thursday, March 18th, 2010.

XML Parsing in AppleScript

I recently wrote a script that posts bookmarks from Yojimbo to Pinboard. Now that I have a nice system for posting links, I find that I’d like even more integration. For instance, I’d like to be able to keep Yojimbo in sync by downloading any links I post to Pinboard via other interfaces.

The Pinboard/Delicious API provides a variety of methods for retrieving link information, but there isn’t a straightforward way to parse the results in AppleScript. In my posting script, I just search the response for code="done". This is sufficient to tell if the add method succeeded, but methods that return more detailed information need more rigorous handling.

Incidentally, AppleScript supports direct interaction with SOAP or XML-RPC web services; see the documentation here. However, the Pinboard API uses a different architecture, REST (sort of).

Essentially, a query is represented as a URL, with parameters, and the XML results are returned by the server like the content of any other web page. (I use do shell script and curl to make the request and get the raw results; I don’t know if there is a better AppleScript idiom for general HTTP transactions. URL Access Scripting is dusty and requires writing temporary files.) The task is to extract the relevant bookmark information from the response.

As it turns out, the System Events scripting dictionary includes an XML suite, pictured above. Some experiments based on the examples given in this discussion at MacScripter confirm that it can be used to parse data returned by the Pinboard API. So, all the pieces necessary to implement a more sophisticated AppleScript bookmark syncing system are available.

Posted on Saturday, February 20th, 2010.

Online LDraw Viewer

Click here to view some digital bricks right in your browser.

It’s a quick late-nite first-draft online adaptation of the Processing LDraw viewer I’ve been playing with.

Posted on Tuesday, January 12th, 2010.

Setting up Andy’s LDraw Viewer

Andy has posted the Processing code for the nifty little LDraw viewer I mentioned in my previous post.

Processing gives you a decent among of guidance, but for your reference here’s what I did to get this up and running:

  1. Download and unzip ProcessingLcad-Oct2008.zip.
  2. Rename the LcadTest-Oct2008 folder to LcadTest01 in order to match the project file it contains.
  3. Move the contents of the LcadTest01/libs/ folder to your Processing sketchbook libraries folder. In my case, it is /Users/anoved/Documents/Processing/libraries/.
  4. Move the contents of the LcadTest01/models/ folder to the models subfolder of your LDraw library. Alternatively, you can edit LcadTest01.pde to load a model of your choice.
  5. Open LcadTest01.pde and edit BaseDir to identify your LDraw library folder. In my case, it is /Users/anoved/Documents/LDraw/.

Lastly, if the capitalization of the LDConfig.ldr file in your LDraw library does not match that specified later in LcadTest10.pde, edit one or the other so they are in agreement.

Now you can take it for a spin. And, yes, this viewer can load files with Unix line endings. ☺

Posted on Monday, January 11th, 2010.

Beginning Processing

Processing is a system that makes it as straightforward as possible to do some pretty sophisticated graphics programming. Based on Java, it abstracts enough technical details to let you focus, more or less, on the basic logic of the idea you want to animate. From the web site:

It is used by students, artists, designers, researchers, and hobbyists for learning, prototyping, and production. It is created to teach fundamentals of computer programming within a visual context and to serve as a software sketchbook and professional production tool.

Check out the Exhibition for some examples of what’s possible and the Tutorials to see how easy it is get started. There is a great collection of examples for specific topics, too, most of which include illustrative applets embedded in the page. The ability to export Processing programs (or “sketches”) as applets is particularly appealing, although my understanding is that some features, such as file I/O, are available only in application or development mode. It works cross-platform.

I know I have encountered Processing before, but my current interest began as I read Andy Lynch’s description of a simple LDraw renderer he implemented as a Processing sketch. That lit a fire under some related ideas of my own that have been simmering for want of an optimal outlet.

But there’s more to my interest than digital bricks: if there isn’t already a decent library (which would be surprising, as many useful libraries seem to be available), I might be tempted to write a shapefile loader, if for no other reason than to complement the shapefile parser I once wrote for Chipmunk Basic. I think it could be fun to experiment with some raster GIS and remote sensing ideas in Processing, too. (Just get the spectral signatures – click, click, click – and you do it. That’s all what it is!) Last but not least, per its original intent, I can envision using Processing as a superior tool to visualize certain data.

What sort of Process will you invent?

Posted on Monday, January 11th, 2010.

Kitgen Build System for Tcl/Tk

In the past I have written a variety of posts about Starkits and Starpacks. Briefly, Starkits provide a way to package complex Tcl/Tk programs in a single file, and Starpacks allow those packages to be combined with self-contained interpreters to deliver stand-alone applications. However, the Tclkit interpreters I originally used for this purpose have not generally been maintained, at least for Mac OS X (Pat Thoyts has done a good job providing current Windows and Linux versions).

Of course, there are various ways to build your own Tclkit equivalent, but I usually found the process slightly too tedious to sustain my interest (although I did succeed with Pat’s version of kitgen shortly before discovering the method described below).

As it turns out, self-contained Tcl/Tk installations functionally equivalent to Tclkits can quite easily be created with the kitgen build system. This comprises a single Tcl script (kbs.tcl) that automates the process of downloading, compiling, and assembling the elements of a “kbskit”. The script is robust – it worked successfully on the first try, without any knowledge of what options to use beyond those given in the Quick Start examples.

If you simply run a fresh copy of kbs.tcl, it will retrieve the Tcl/Tk sources.

Build a Metakit-based kbskit (like Tclkit) with:

./kbs.tcl -r -mk install kbskit8.5

Build a Vlerq-based kbskit (like Tclkit Lite) with:

./kbs.tcl -r -vq install kbskit8.5

In either case, three executables will actually be built:

  1. A Tcl-only executable, denoted by -cli suffix
  2. An executable that loads Tk from an external library if needed, denoted by -dyn suffix
  3. An all-in-one Tcl/Tk executable, denoted by -gui

On Mac OS X, these executables are found in the buildDarwin subdirectory relative to kbs.tcl. The subdirectory name will presumably differ on other operating systems.

Happily, the kbskits created with the kitgen build system can be used with Starpacker. Check the “Other” box and select the kbskit you prefer to use as the executable in your Starpack:

You can bundle other packages into your kbskits using the -mk-bi or -vq-bi options (-bi stands for “Batteries Included”). This will ensure that those packages (typically useful extensions) are always available to code being run by that kit. Of course, a different approach, with different advantages and disadvantages, is to bundle packages in your application Starkit, which can be executed with different kits.

Additional topics to explore include building the --enable-aqua option and the best method to update both kbs.tcl and the source code it retrieves.

Posted on Sunday, January 10th, 2010.

List splicing with foreach

Tcl’s foreach command is commonly used to iterate through items in a list. However, I had not realized that it can step through more than one list at once. Here’s a handy application of this property based on an example from the documentation:

proc splice {l1 l2} {
    set s {}
    foreach i $l1 j $l2 {
        lappend s $i $j
    }
    return $s
}

This procedure combines two lists into a new list comprised of alternating items from each input:

% splice {a b c} {1 2 3}
a 1 b 2 c 3

One use for this is to join a list of keys to a list of values to establish a dictionary or an array:

% set dimensions [splice {length width height} {10 16 33}]
length 10 width 16 height 33

% dict get $dimensions height
33

% array set d $dimensions
% set d(width)
16

So if you’ve got an ordered list of values you’d like to access as named fields, you can combine it with a list of field names using foreach and be on your way.

Posted on Monday, April 28th, 2008.

Starpacker

Starpacker is a utility that helps join Starkits and Tclkits to create stand-alone Starpacks. This can already be done with SDX, which is a superior tool in many ways, but Starpacker provides a simpler interface to this particular aspect of SDX.

Starpacker Mac OS X Screenshot Starpacker Windows Screenshot

More extensive help is included with the program.

Demonstration

Drag an application Starkit onto Starpacker, select a Tclkit, and click Pack to create a stand-alone executable for the indicated platform. The Tclkit is downloaded automatically if needed. (May not work with all Starkits.)

I recommend watching the video full screen for maximum clarity.

Download

Posted on Wednesday, March 26th, 2008.

Msgcat and Mac OS X

The Tcl core library includes msgcat, a package which facilities program localization. msgcat provides means to define a catalog of messages in multiple languages and a procedure to retrieve messages appropriate to a specific locale, typically determined by cues from the operating system.

In general, to localize puts "Hello, world!", you provide equivalent strings for each supported locale and select the appropriate one at runtime by stating puts [mc "Hello, world!"]. For example, this command might print ¡Hola, mundo! if the locale is es. Default strings in the programmer’s native language can usually be used as keys to the message catalog.

Anyway, msgcat looks at a couple environment variables (or the Windows registry) to determine the proper locale. On Mac OS X, this works fine for scripts launched from the command line, but spiffy desktop applications don’t necessarily have access to the same environment variables. If no supported environment variables are available, msgcat uses the locale implied by the “Region” setting of the “Formats” pane of Mac OS X’s “International” system preferences. You can query this string from the command line with:

defaults read 'Apple Global Domain' AppleLocale

It is also available from within Tcl as the variable ::tcl::mac::locale.


To test localized Tcl desktop applications on Mac OS X without changing your system region, you can define the locale in ~/.MacOSX/environment.plist. Environment variables specified in this file are available to programs launched from the Finder, so msgcat will see these settings before resorting to the system locale. For instance, to set the locale to es, add this property to environment.plist:

<key>LANG</key>
<string>es</string>

See QA1067 for more information about environment.plist, including how to create it if it does not already exist. Note that variables defined in this file will be visible to all programs, and may therefore affect other applications.


Here’s how I usually comment the code I use to initialize msgcat:

# localization courtesy of Message Cat:
#
#  |\        /|
#  | \______/ |
#  /  _    _  \
#  | <l>  <l> |
#  \    __    /
# ----- \/ -----
#  --\__/\__/--
#

Posted on Tuesday, January 29th, 2008.