Macs in Chemistry

Insanely Great Science

Applescript Resources

I've created a page containing a list of useful resources.

Eleven Applescript for Scientists Tutorials

A set of tutorials to get you started
Applescript Tutorial 1

This is the first of what will hopefully be a series of tutorials on Apple's own scripting language Applescript that I will be writing for
MacResearch.org. I should perhaps begin with a confession, "I'm not a programmer", by training I'm a chemist and I spent the majority of my career as a Medicinal Chemist. This might actually make me the ideal person to write this since I've always thought of Applescript as the programming language for the rest of us. Applescript is a scripting language that allows users to automate reptitive or complex tasks, or customise applications as such it is really useful for little tools or widgets that make life easier for you. In this tutorial I cover getting started, using the script editor, Applescript dictionary, folder actions and interacting with applications.
Click here to see a formatted view of this tutorial.

Applescript Tutorial 2
This is the second in the Applescript tutorials written for
MacResearch, in this tutorial I cover the use of Applescript interactions with the UNIX system, in particular the issues of Mac and UNIX paths and the use of shell scripts.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 3
This is the third Applescript tutorial written for MacResearch, reading and writing files, creation and manipulation of lists, and using ChemDaw to calculate properties.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 4
This is the fourth Applescript tutorial written for MacResearch, reading and writing UNIX files, dealing with missing properties, and using ChemDaw to calculate properties.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 5
This is the fifth Applescript tutorial written for MacResearch, creating a sub-structure searchable chemical database.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 6
This is the sixth Applescript tutorial written for MacResearch, rendering structures in a chemical database
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 7
This is the seventh Applescript tutorial written for MacResearch, actually it uses a web viewer within the FileMaker database to display a web page that uses the chemdraw plugin to render the structure.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 8
This is the eighth Applescript tutorial written for MacResearch. Rich Apodaca has been discussing
embedding molecular information in images of molecules, such as a PNG file depicting a 2D structure. As we move to a more web-centric view of the world it is apparent that much of research information will be only available via the web, whilst images of chemical structures are usually adequate for a human viewer the chemical structure cannot be indexed and subsequently searched. In a subsequent article Rich showed a method of extracting the information as text. In this tutorial I'm going to show how to use applescript to extract the information from the PNG file and then display the structure in a couple of chemical display packages in an editable form.
Click here to see a formatted view of this tutorial in a new window.

Applescript Tutorial 9
This is the ninth Applescript tutorial written for MacResearch. In this tutorial we create an applescript for ChemBioDraw (aka ChemDraw) that embeds chemical information into the meta data of an image file.
Click here to see a formatted view of this tutorial in a new window.
Applescript Tutorial 10
At my presentation on
Applescript and UNIX I was asked how to create a droplet that accessed a UNIX application so I thought it might be useful to give a very simple example
Click here to see a formatted view of this tutorial in a new window.Applescript
Applescript Tutorial 11

GeekTool is a Preference Pane (System Preferences module) for Mac OS X. It lets you display various types of information directly on you desktop. The information can be derived from a shell script or using osascript it is possible to call applescripts (or any other OSA language scripts).

Click here to see a formatted view of this tutorial in a new window.

For more information on Applescript have a look at the
Applescript Resources Page.

Send to MOE

Send to moe A script for chemdraw, that sends a selected structure to MOE, needs to be stored in the Chemdraw folder with the other chemdraw scripts

For more information on Applescript have a look at the
Applescript Resources Page.

ConvertChemDraw_to_TIFF

ChemDraw from CambridgeSoft has excellent Applescript support. I'm sure many chemists use ChemDraw to create the structures and figures for publications, and whilst ChemDraw can produce beautiful graphics some publishing companies insist on all graphics being submitted in "TIFF" format. This means that you have to open each of the ChemDraw files and then save them in "TIFF" file format. You can't only work in "TIFF" format because the image then loses all the chemical information that is available in the ChemDraw native "CDX" format. A repetative opening of files and then saving in another file format, just the task for Applescript! This folder action is available here as a zip file. It needs to be stored in "Macintosh HD:Library:Scripts:Folder Actions". Now you have the script you need to attach it to a folder. Create a folder somewhere and call it "Images", control-click (or right click) on the folder to bring up the contextual menu. By default, Folder Actions is not enabled. To turn on the Folder Actions architecture, select "Enable Folder Actions" from the contextual menu. Folder Actions will now be enabled system-wide. Now bring up the contextual menu again and select "Attach a Folder Action", navigate to and select "Convert_ChemDraw_to_TIFF". You are now already to use it. Draw a structure in ChemDraw and save it to the "Images" folder, you should find that the script is activated, it creates two folders (the first time it is used) "Original CD Files" and "TIFF Images", you should find your original ChemDraw image in "Original CD Files" and a copy of the image in TIFF format in "TIFF Images".

For more information on Applescript have a look at the
Applescript Resources Page.

Convert Applescript to HTML

This Applescript is from From Concentrate Software takes the frontmost Script Editor document and converts it into an HTML document complete with all the syntax colouring and spacing. I've used it for the tutorials and found it invaluable. To use, simply toss this script into ~/Library/Scripts/Script Editor and select this script from the scripts menu in OS X. Your current script will be parsed and exported as an HTML document. It can be downloaded from here

For more information on Applescript have a look at the Applescript Resources Page.

DupCheck

This applescript droplet, dupcheck - identifies potential duplicates of a file using Spotlight metadata, simply drop a file on the icon and the search will run, it may take 30 secs for a large drive. You will then get a list of duplicates (if any) and the option to show where they are in Finder windows.

It is based on a hint from macosxhints, see
http://www.macosxhints.com/article.php?story=20061003163429425


For more information on Applescript have a look at the Applescript Resources Page.

ChemDraw Properties

This script takes the selected structure and calculates a variety of chemical properties. Full details are in the Applescript tutorial 3 (see above).

For more information on Applescript have a look at the Applescript Resources Page.

Multi ChemDraw Properties

This script takes as input a file containing SMILES strings and calculates a variety of chemical properties. Full details are in the Applescript tutorial 4 (see above).

For more information on Applescript have a look at the
Applescript Resources Page.

Combining PDFs a Automator Workflow

Today I was sent a license agreement as a 6 page pdf file, I was asked to sign the document and send it back. All very well but I was in a hurry and wanted to get to work a little faster than the postal service might allow. I have a scanner so I figured I could sign a copy of the last page then scan it and convert to pdf. I could have then sent the original license pdf plus the last page by email but that did seem a little unprofessional.
So then how to combine the signed page with the rest of the pages of the license agreement?
Well opening the original pdf in Preview I could select pages 1 to 5 to print and then use the "Save as pdf" option from the "PDF" button so create a new pdf with just the first 5 pages.



Now create an Automator workflow to join the files.
Open Automator and you should see a three pane window. The first pane contains the library of applications that have automator actions, the next pane shows the actions available for the selected application. Double click on an action to add it to the workflow in the third pane. No add these actions
From the Finder library select:-
Get Specified Finder Items Sort Finder Items (and from the pulldown menus select "name" and "ascending"
From the PDF library select:-
Combine PDF Pages
Then finally from the Preview Library selct:- Open Images in Preview.



Now save the workflow as Combine_PDF in "username/Library/Workflows/Applications/Finder/"
Now when you select several pdf files in the Finder, control-click (or right click) will bring up a menu that includes automator actions, choose combine_PDF and Preview will open showing a single document containing all files.



Note I added a sort option, this was to give some control over how the files were combined. If you now name them alphabetically then they will be combined as desired.

Print_clipboard

I was recently asked if it was possible to print text on the clipboard without the need to open another application to paste it into. One easy way to do this is to create an applescript, seems an easy thing to do but there are a couple of interesting aspects that make this worth sharing. One way to print in the background is to use the UNIX "lp " command, there is an excellent summary of UNIX printing here. However when you copy text to the clipboard if often contains invisible non-printing characters that can cause lp to fail. So first we we convert the text to plain text and remove any application specific formatting. The as text portion grabs the stylized text from whatever other junk may be surrounding it (which can be significant), as record splits out the style and text portions, and «class ktxt» grabs the plain text portion of that. The text is then written to a file the location of which is defined within the temporary items folder. lp is then used to print the file. If you want to see how you might use this have a look here.
--Need to first remove application specific formatting from clipboard
set the clipboard to «class ktxt» of ((the clipboard as text) as record)

set the_clip to the clipboard
--
Comment out if not needed
display dialog the_clip

tell application "Finder" to set the_folder to (path to temporary items folder) as text
--
If you want to keep the file use
--
tell application "Finder" to set the_desktop to (path to desktop folder) as text

set target_file to the_folder & "JUNK"
--
display dialog target_file

my write_to_file(the_clip, target_file, false)

set posix_path to POSIX path of target_file
--
display dialog posix_pathsw

set to_print to "lp " & posix_path

do shell script to_print
--
For testing
--
tell application "Terminal"
--
activate
--
do script to_print
--
end tell

on write_to_file(this_data, target_file, append_data)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file target_file with write permission
if append_data is false then ¬
set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
--
display dialog "file_done"
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file

You can download the script here
For more information on Applescript have a look at the
Applescript Resources Page.

Comparing version numbers

I'm in the process of updating iBabel and one of the things I'm adding is the option to use some of the newer tools now available in the latest version of OpenBabel. However some users prefer not to live on the bleeding edge and want to continue to use the older version of OpenBabel so I'd like to only have the tool options available for which ever version of OpenBabel they have installed.

You can get the version number of the OpenBabel installation with the simple command

/usr/local/bin/babel -V
Open Babel 2.1.0 -- Apr 13 2007 -- 21:38:32
We can wrap this in an Applescript and use the "do shell script" command to get the returned text, simple parsing of the returned text then gives the version number.

set the_script to "/usr/local/bin/babel -V"

set the_version to (do shell script the_script)

display dialog the_version

--
Open Babel 2.1.1 -- Apr 13 2007 -- 21:38:32

set the_offset_minus to the offset of "--" in the_version
set the_offset_el to the offset of "el" in the_version



set babel_version to (characters (the_offset_el + 3) thru (the_offset_minus - 2) of the_version) as text

display dialog babel_version

Comparing version numbers however is not so straightforward since the version number could be 2.10.3 or 2.3.10, fortunately Apple have kindly provided a simple means to compare this type of numeric strings. So using "considering numeric strings".

considering numeric strings
if babel_version > "2.1" is true then --> true, if you consider each numeric string to be a single "character".
display dialog "True"
end if
end considering

The actual implementation in iBabel is this:-

considering numeric strings
--Different tools available depending on version of iBabel
if babel_version > "2.1" is true then --> true, if you consider each numeric string to be a single "character". --display dialog "2.2"
repeat with i in my tools_options_new
make new menu item at the end of menu items of menu of popup button "tools_option" of tab view item "Tools" of tab view "nstab" with properties {title:i, enabled:true}
end repeat
else if babel_version < "2.1" is true then
--display dialog "2.0"
repeat with i in my tools_options_old
make new menu item at the end of menu items of menu of popup button "tools_option" of tab view item "Tools" of tab view "nstab" with properties {title:i, enabled:true}
end repeat
end if
end considering

So depending on the version of OpenBabel I load a different list of tools options.

For more information on Applescript have a look at the Applescript Resources Page.

Print Folder Contents

I recently needed a list of all files in a particular folder, actually the folder contained sub-folders also containing files. This tedious task becomes trivial with a couple of UNIX commands and Applescript provides a convenient user interface and the glue between the UNIX commands.

Full details are here.

For more information on Applescript have a look at the Applescript Resources Page.

Lecture on Applescript and Unix

I gave a lecture at the Scientific computing meeting at Cambridge University on using Applescript to build a User interface for Unix command-line applications.
The presentation is available
here.
If anyone would like a copy of the slides let me know.
I've also been asked about good books on Unix and Shell scripting these two are highly recommended.









For more information on Applescript have a look at the
Applescript Resources Page.

Copy File to Mobileme and create email

Whilst Apple now allow you to send a link to a file to another user it requires the use of a web interface, I'm sure it will eventually be built into the Finder but until then this script helps to automate the process. The first part of the script asks you to select a file, the next part uses a shell script to compresses it to a zip file if it is not already zipped. It then gets the mobileme name and then copies the zipped file to the Public folder of your mobileme (.dot mac) account. The final part of the script creates the email that you need to send to the intended recipient.
Whilst MobileMe is being phased out this script might be a useful starting point for other similar file sharing utilities.
You can read the
details here, and download the script here. Add it to the Script Menu for easy access

The Script Menu can be added as a Menu Extra to allow easy access to many AppleScript scripts from the menu bar (Mac OS X ships with several scripts that are ready to use to accomplish some common tasks). You can also add your own scripts to this menu.
To enable the Script Menu, run AppleScript Utility (located at /Applications/AppleScript/AppleScript Utility) and check the "Show Script Menu in menu bar" checkbox.

For more information on Applescript have a look at the Applescript Resources Page.

Chemistry Workflow

As part of my day job I sometimes need to profile a compound collection, molecular weight distribution, LogP, HBA/D etc. this script calculates a range of molecular properties using the ChemAxon tools and then uses Aabel to plot charts showing the range of properties.

For more information on Applescript have a look at the
Applescript Resources Page.

Using Geektool

GeekTool is a Preference Pane (System Preferences module) for Mac OS X. It lets you display various types of information directly on you desktop. The information can be derived from a shell script or using osascript it is possible to call applescripts (or any other OSA language scripts).
I first became aware of Geektool when read this
tip on Macosxtips and it would certainly be worth looking at to get an idea of what it can be used for.
In this
tutorial I'll use a couple of simple commands to create desktop content, and then link to Applescripts to create more complex content.

For more information on Applescript have a look at the Applescript Resources Page.



Start lmgrd license manager

I use Moe for molecular modeling work, this uses a license.dat file in each installed MOE root directory that must be updated with the contents that you have been given by CCG (either by hard copy or e-mail). You can use any ASCII text editor (I used BBEdit) to edit the file. The FlexLM license manager lmgrd must be configured and run.
Usually this runs quietly in the background and needs little intervention, however I've found that on some occasions the server quits (perhaps after updates) and needs to be restarted. However since it is something I don't need to do regularly I always spend a while working out the exact syntax. So I created this short Applescript to restart the server.


set the_script to " /Applications/moe/bin-mppc/lmgrd -c /Applications/moe/license.dat -l /Applications/moe/license.log"

tell application "Terminal"

do script the_script

end tell

Whilst you could put the applescript anywhere I use the script menu, if you don't have this running go to the Applescript Editor preferences. You should get the dialog shown below, check the box "Show Script menu in menu bar", and the applescript icon should appear in the top right group of menu bar icons.

applescript_prefs

You can now save the script to Username:Library:Scripts, naming it as "start license server". You can create subfolders in the "Scripts" folder in order to organise all your scripts. If you now click on the applescript icon in the upper right menu bar, you should get a dropdown menu listing all the applescripts. Scripts that are available to all users are in Macintosh HD:Library:Scripts.

For more information on Applescript have a look at the Applescript Resources Page.



An Applescript to Extract a Safari Extension Archive

With Safari 5 one of the most interesting new features is the support for Extensions. If you’ve ever used Firefox or Chrome you might be familiar with these.
For more details you might want to take a look at
Mac OS X Tips, where these is a detailed description and links to useful Extensions. There is also the Apple Developer page that gives more details of how to create your own extension. One of the best ways to learn how to create extensions is to examine other peoples creations, you can't do this directly because they are stored as compressed archives, Mac OS X Tips has a step by ste guide to extracting these archives using the Terminal. However if you are not comfortable using the Terminal then this Applescript will do this for you.

For more information on Applescript have a look at the Applescript Resources Page.

Applescript to run a search of eMolecules from ChemBioDraw

I suspect that everyone has their own preferred online chemical supplier, I use eMolecules much of the time. However I'd prefer not to have to learn a new chemical drawing package for every online database. Fortunately most of the sites will accept a SMILES string as the query and most of the desktop drawing packages can generate a SMILES string.
This Applescript uses ChemBioDraw (aka ChemDraw) to generate the SMILES string of the selected structure,and then encodes and constructs the URL to run a search of eMolecules.
For more information on Applescript have a look at the
Applescript Resources Page.

Rule of 7 Applescript

I regularly have to profile collections of compounds, these may be from commercial suppliers or could be a virtual library created for a MedChem project. Whilst many people have there own ideas of what are the most important physicochemical properties the seven generated by this script seem to cover almost all requests. It uses Chemical Terms Evaluator from ChemAxon to generate the data and Aabel from Gigawiz to plot the results.
The eagle-eyed amoung you will have noticed that cxcalc is actually used to calculate a number of other properties, including the most acidic and basic pka, but these are not plotted. They just give you a flavour of the number of different properties that can be calculated. By editing the part of the script refering to Aabel you can pick and choose what to display, but be careful to note some are continuous properties like polar surface area (psa), whilst others are catagorical such as count of hydrogen bond donors (HBD) and use different plots. I've used this script to profile a library of 500,000 compounds, the only issue is that you might have to edit the axis display to avoid overlap of text.
profile

You can view the
full script here.

Applescript and curl

Way back in the days of Mac OS 8.6 Apple provided basic internet functions using a component called URL Access, this was made available to scripts using a small applications called URL Access Scripting. This rather rough and ready solution provided a means to upload or download files. Unfortunately I occasionally had problems with it and judging by the questions on a couple of applescript forums others have also.
Around the time that Mac OS X became available I changed all my scripts to use curl instead of URL Access Scripting and things have worked pretty smoothy since.
This script shows how to use curl

Scripting Script Editor

If you control-click (or right click) on the script editor window you get a menu listing all the script editor scripts that are avaiable. Many of these are part of the standard install whilst others might be installed by specific applications. They are all in a folder in Macintosh HD/Library/Scripts/Script Editor Scripts and you can add scripts or folders here and they will appear in the menu. Whilst the standard install includes a variety of useful and frequently used routines if you are writing scripts that interface with UNIX applications then having access to the POSIX paths to some of the standard folders is a regular need, this script shows how to add a POSIX paths script to the Script Editor.

Scripting ChemBioDraw

I was recently asked if I could help with a script to convert ChemBioDraw .cdx files to .png, whilst you can open the file in ChemBioDraw and then choose "Save As" and then choose "PNG" from the drop-down menu this is rather laborious if you have a folder of files your want to convert. This script automates this task.

Delete Restore folders for selected applications

One of the new features in Lion is the ability of applications to resume activity at the point an application was quit. This means that when you reopen an application it will open and display all the documents you were editing in the state when you quit the application. This is obviously very useful but there are times when you may not want confidential documents automatically opened and displayed when you open an application.

This
Applescript allows you to delete the restore folder for specified applications.

Scripting the Organic Chemistry Reference Resolver

The Organic Chemistry Reference Resolver is an invaluable web service that takes as input a text reference to a published article in a variety of formats and then finds and displays the corresponding publication.

The real beauty of a web service is that it can be accessed via a variety of means, including an applescript.
This applescript uses as input either text that has been copied to the clipboard or the text the user has typed into a text box, it submits the request to the web service and displays the result in the web browser.