Anatomy of a Cheminformatics Web Application: Structure Cleanup in Java Molecular Editor
A very useful feature of many 2-D structure editors is a "clean" function that tidies up bond lengths and angles. Java Molecular Editor (JME) is a lightweight 2-D editor that lacks this functionality. In this article, I'll describe a small Web application called "Cleanup" that adds a "clean" function to JME through Ajax and server-side programming, rather than directly extending JME itself. The technique described here differs somewhat from that described in a previous article on adding InChI support to JME with Ajax.
Cleanup in Action
Let's say Bob needs to draw the structure of the H1 antagonist chlorpheniramine with JME. He mistakenly creates irregular bond angles at several points, but continues drawing anyway. His finished molecule looks like that shown below:

Rather than starting over to beautify his molecule, Bob, simply presses the Clean Molecule button. This produces a structure with much more aesthetically-pleasing atom coordinates:

If Bob needs to continue drawing at this point he can. In fact, he can press Clean Molecule as many times as he wants to clean his structure at any time. Each time he presses the button, his structure is retained within the JME window.
Download and Prerequisites
Cleanup requires Ruby on Rails and Ruby CDK. Both of these libraries can be installed using the RubyGems packaging system.
A recent article described the small amount of system configuration required for Ruby CDK on Linux. Another article showed how to install Ruby CDK on Windows.
The complete Cleanup source package can be downloaded from RubyForge. For convenience, a copy of JME is included with the distribution. The author, Peter Ertl, has kindly given permission for the bundled JME applet to be used with Cleanup. For other uses, consult the JME homepage.
Running Cleanup
After inflating the Cleanup archive, the following commands will start the server:
$ cd jme-cleanup-0.0.1 $ ruby script/server
AMD64 Linux users will need to prepend a LD_PRELOAD assignment to the script/server invocation. On my system, which uses Sun's JDK, this looks like:
$ cd jme-cleanup-0.0.1 $ LD_PRELOAD=/usr/java/jdk1.5.0_09/jre/lib/amd64/libzip.so ruby script/server
After starting the Cleanup server, pointing your browser to http://localhost:3000/editor/cleanup will run the application.
How It Works: A Web Application in Two Parts
Cleanup is a Web application consisting of two main parts - one written for a Web server, and one written for a Browser client. These two components work together to achieve an effect that, to a user, is indistinguishable from extending the JME applet with Java.
The first component consists of small Rails application that accepts a Molfile as input and produces a Molfile with re-assigned coordinates as output. A Rails Action, clean_structure accepts a Molfile encoded as form data and produces a response Molfile with re-assigned coordinates.
The second component of the Cleanup application is written in JavaScript and executed from within the Browser. Let's take a look:
<script language="JavaScript">
/*
* Returns the client-specific version of XMLHttpRequest
*/
function createXHR()
{
var xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP"); // IE 5.0+
}
catch (e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // IE 5.0-
}
catch (E)
{
xhr = false;
}
}
if (!xhr && typeof XMLHttpRequest != 'undefined')
{
xhr = new XMLHttpRequest(); // every other browser
}
return xhr;
}
function cleanStructure()
{
var molfile = document.jme.molFile();
var xhr = createXHR();
xhr.open("GET", "clean_structure?molfile=" + encodeURIComponent(molfile));
xhr.onreadystatechange=function()
{
if (xhr.readyState != 4) return;
cleanMolfile = xhr.responseText;
document.jme.readMolFile(cleanMolfile);
}
xhr.send(null);
}
</script>
As you can see, the client side of Cleanup consists of two JavaScript functions, createXHR and cleanStructure.
The purpose of createXHR is to return a valid instance of the central Ajax JavaScript object, XMLHttpRequest. This function is a standard idiom in Ajax programming, and many JavaScript toolkits eliminate the need to write it explicitly. The function is included here mainly for the purpose of illustration. Microsoft browsers define two different flavors of XMLHttpRequest, and both differ from the flavor supported by every other browser. To take this browser-specific behavior into account, a series of try/catch blocks are used.
The second function, cleanStructure does all of the JME-specific work. After obtaining an instance of XMLHttpRequest, a HTTP GET request is built from JME's molfile. Of course, the magic of this request is that it is asynchronous; it will not block the browser while it is being processed. When the request is complete, the cleaned Molfile is read by JME.
Through the coordinated action of both of Cleanup's components, the application gives the appearance that JME has cleaned its own structure.
So What?
Well-designed, rich functionality makes software interesting and useful. At the same time, users demand software that loads and responds quickly. Using the technique presented here, it's possible to satisfy both of these contradictory requirements. Delegating key tasks to a server obviates the need to transmit large Java libraries to clients. Instead, small Java libraries can be transmitted, and several small asynchronous requests will be processed along the way.
Viewed from this perspective, the capabilities of a good Java applet take on a very different character from what many have become accustomed to. In particular, extensibility and a robust, text-based communication protocol become much more important than built-in features.
For example, we could provide a much more consistent user experience if the Clean Molfile button were contained inside the JME editor itself, instead of on the Web page. In a more general sense, we'd like JME to offer the option of defining custom buttons that can be assigned arbitrary actions. Because Java/JavaScript integration is very well-supported, these custom actions could actually be written in JavaScript.
Conclusions
Java applets have been much maligned of late, partly due to the realization that in many situations they can be replaced with Ajax. However, well-designed, small, and extensible Java applets can play a key role in certain kinds of Ajax applications such as the one described here. Future articles in this series will explore some more of the many possibilities.
Anatomy of a Cheminformatics Web Application: Ajaxifying Depict
The previous tutorial in this series showed some techniques for improving the appearance and usability of a simple cheminformatics Web application. That application, Depict, rendered color images of 2-D molecular structures when given a SMILES string. Still, something is missing. Wouldn't it be better if the application responded to individual keystrokes in the input field, rather than waiting for the user to hit the return key? In this tutorial, we'll see how to quickly accomplish this effect with a technology called "Ajax."
Downloads and Prerequisites
For this tutorial, you'll need Ruby CDK (RCDK). A recent article described the small amount of system configuration required for RCDK on Linux. Another article showed how to install RCDK on Windows.
In addition, you'll need to install Ruby on Rails - something that can be done through RubyGems.
The Rails application that this tutorial starts with can be downloaded from this link. If you'd rather start working directly with the version of Depict produced by applying the changes outlined in this tutorial, the full source code can be downloaded from this link.
If you'll be running Depict on an AMD64 Linux system, you'll need to prepend your invocation of script/server with LD_PRELOAD. For example, on my system running Sun's JVM, the full command looks like:
$ LD_PRELOAD=/usr/java/jdk1.5.0_09/jre/lib/amd64/libzip.so ruby script/server
A Brief Introduction to Ajax
When stripped down to its essentials, Ajax is nothing more than an asynchronous communication channel between Web browsers and Web servers. In the pre-Ajax model of client-server Web interactions, a browser would make a request to a server and then wait until getting a server response, which would take the form of a complete Web page. In the Ajax model, a browser makes a request to a server, continuing to function while the server generates a response, which takes the form of a small section of the page that gets replaced. For this reason, Ajax-enabled Web sites are far more application-like than the document-centric sites that preceded them.
Ajax Support in Rails

Ajax is implemented in JavaScript using the HTMLHttpRequest object, although working at this level can require a lot of code to do anything meaningful. Fortunately, Rails and other Web application frameworks provide high-level interfaces to Ajax. In Rails, Ajax support takes the form of a variety of helper methods, one of which we'll use in this tutorial: observe_field. This method, an instance of the Observer Pattern, assigns an Observer to monitor input activity in a text field.
The Problem at Hand
We'd like Depict to provide immediate feedback by rendering a SMILES string as it is keyed into the input field. If the partial SMILES string is valid, it will be rendered, otherwise, an error image will be rendered. At no point will the user need to press the return key to see an image of the SMILES string they are typing.
Step 1: Ajaxify the View
Let's start by adding an observer to Depict's input field. These changes will occur to the SMILES View, contained in depict/app/views/smiles/depict.rhtml:
<html>
<head>
<title>Depict</title>
<%= stylesheet_link_tag "default", :media => "all" %>
<!-- Nothing works without this line. -->
<%= javascript_include_tag :defaults %>
</head>
<body>
<h1>Depict a SMILES String</h1>
<!-- New id attribute needed by Ajax -->
<div class="image" id="results" >
<img src="<%= image_for_smiles :smiles => @smiles %>"></img>
</div>
<br /><br />
<div class="smiles">
<%= form_tag :action=>'depict' %>
<label>SMILES: </label>
<!-- Ajaxified text field. -->
<!-- We turn off autocomplete to simplfify the interface. -->
<%= text_field_tag :smiles, @smiles, {:autocomplete => "off"} %>
<%= observe_field( :smiles,
:frequency => 0.5,
:update => :results,
:url => { :action => :ajax_depict } ) %>
<%= end_form_tag %>
</div>
</body>
<div class="about">
<!-- Update the URL to point to the new Depth-First article -->
<a href="http://depth-first.com/articles/2006/12/04/anatomy-of-a-cheminformatics-web-application-ajaxifying-depict">About this Application</a>
</div>
</html>The above code introduces three key elements:
The javascript_include_tag method is called, which is surprisingly easy to forget to do.
The original text_field method call is replaced by text_field_tag to simplify coding. We disable browser-based autocompletion by setting the autocomplete attribute to off. This removes a feature unlikely to ever be used, and leads to a more streamlined interface.
The observe_field method is called, linking activity in the text field to an Ajax action, ajax_depict, that will update the image area. To accomplish this, we assign the div containing our image the id "results."
Making these changes and refreshing the browser window gives a screen like the one below:

Although the client side of the Ajax communication channel is working, the server side is not. Let's fix that.
Step 2: Ajaxify the Server
Depict needs an Action and View that will be invoked in response to keyboard events in the SMILES input box. To do this, first add a new ajax_depict method to SmilesController, the source for which is found in depict/app/controllers/smiles_controller.rb:
class SmilesController < ApplicationController
def depict
if params[:smiles]
@smiles = params[:smiles][:value]
else
@smiles = ''
end
end
def image_for
if flash[:bytes]
send_data(flash[:bytes], :type => "image/png", :disposition => "inline", :filename => "#{flash[:smiles]}.png")
end
end
# The new ajax_depict method.
def ajax_depict
@smiles=request.raw_post
end
endMaking the above changes and refreshing your browser should give an error message:

The new ajax_depict method is being called, but no associated template exits. This template contains the HTML that will be inserted into the div with the results id attribute that we set up in Step 1. We can resolve the error we're getting by simply creating a new file (depict/app/views/smiles/ajax_depict.rhtml) containing the following partial template:
<img src="<%= image_for_smiles :smiles => @smiles %>"></img>Now, refreshing your browser should produce a screen like that shown below. We have now Ajaxified Depict, but we're not quite done yet.

Step 3: Update the Cascading Style Sheet
As you type a SMILES string into the input window, you may have noticed the input box being repositioned toward the top of the application window just prior to the display of a new image. This is due to the image area being resized to zero height as the new image is generated.
Fortunately, the fix is simple; we'll just specify that the image area must be 400 pixels high, whether an image is being displayed or not. This is done by editing the image selector in the CSS file at depict/public/stylesheets/default.css:
.image {
margin-left: auto;
margin-right: auto;
width: 400px;
/* Keeps the input box from moving during image refresh.*/
height: 400px;
}Refreshing the Depict window should now give a statically-positioned SMILES input field.
Step 4: Backward Compatibility
As it stands, if the user presses the return key, they will see the "Enter SMILES Below" message. This is due to the change in the way SMILES strings are transmitted into the application. To fix this problem, we simply change the way that SmilesController assigns the smiles instance variable (depict/app/controllers/smiles_controller.rb):
def depict
# Uses new input method.
if params[:smiles]
@smiles = params[:smiles]
else
@smiles = ''
end
endMaking this change produces an interface that will render the correct image whether the return key is typed or not. If JavaScript is disabled, Depict will work exactly the same way as it did in the non-Ajax version.
Conclusions
Ajax makes the Web more attractive than ever as an application development platform. In this tutorial, we've seen how using Rails made it very easy to give Depict the feel of an interactive SMILES depiction tool using Ajax. But a few details remain before we're ready to deploy this application on a Web server for the public to use. For example, we need to take server load and network latency into account, and we need to make sure Depict works well on all major browsers. The next articles in this series will address these issues.
Look Ma, No Applets!

The state of the art in structure editors for chemical Web services is Java applets. Although closed editors have long dominated this field, Open Source editors are a possibly viable option. Java applets are great from a developer's perspective. But applets are avoided by some end users and IT support for their underlying need to install a Java plug-in of some kind and long startup times.
Through David Bradly's sciencebase, I came across a non-Java solution to the structure editor problem. The software is called WebME. WebME looks and feels similar to Java Molecular Editor. It loads quickly and provides a clean, inviting user interface. It should work in any modern browser. Most interesting of all, WebME works without a browser plugin of any kind.
The magic behind WebME is AJAX, which has been summarized by Paul Graham as "Javascript now works". By asynchronously interacting with a Web server as user interface events occur, WebME is able to cram a lot of functionality into a relatively small deployment package. The user interface is written in a mixture of HTML and JavaScript, thus eliminating the need for Java.
Although WebME's use of AJAX is innovative, other non-Java solutions to the structure editor problem have also been implemented. For example, PubChem have developed an editor in JavaScript/HTML for use with their popular service.
Despite its advantages, the AJAX approach does involve some trade-offs. For example, WebME is not nearly as responsive as, say, JME. I would imagine that unusually high network latency could further erode WebME's responsiveness. Furthermore, the subtle visual cues that make JME a productive tool, such as highlighting the node or edge the cursor is about to edit, are non-existent. It's unclear if this is a limitation of this particular version of WebME I used or the underlying technology.
AJAX is a promising new technology that may well have a place in producing ergonomic user interfaces for chemistry Web services. On the other hand, it wasn't too long ago that JavaScript "didn't work", was loathed, or simply ignored altogether. It may well be that Java applets undergo a revival similar to that of JavaScript, perhaps triggered by built-in support for applets made possible through an open source Java implementation. Regardless of how Java applet technology evolves, WebME's approach is worth serious consideration.

