Friday, November 21, 2008

ChemSharp - should have googled it first

Then I would have known about this...






"The safest way to sharpen tungsten without grinding."

Thursday, November 13, 2008

CSInChI v0.5 Released

The first product of the ChemSharp project is now available to the public. The CSInChI library allows programmers to call the IUPAC InChI library from CLR languages. It is compatible with Iron Python as well although Python programmers should read up on how IPy handles value types and using the clr.Reference class with methods that take out and ref parameters.

CSInChI is designed as a stand alone library which is used by ChemSharp but not dependent on the rest of the project.

This is a beta release so it's a little rough and people should expect that breaking changes may be made between now and the eventual 1.0 release. Using the default constructors of the structs and then initalizing the fields will be the best way to ensure compatibility with future releases.

The next few posts will contain examples of how to use this library. More examples are included in the documentation.

CSInChI can be downloaded from this link.

Questions and comments can be directed either to me or to the CSInChI mailing list at chemsharp-csinchi@lists.sourceforge.net

Wednesday, November 12, 2008

Languages available for use with the CLR

A recent post to the OpenBabel mailing list reminded me that many scientists who write .Net code are not fully aware of the wide array of compatible languages. In fact most popular programming languages and many not so popular ones have been ported to the CLR. The list includes:

A# (Ada)
NetCobol
IronRuby
S# (Small Talk)
FTN95 (Fortran)
F# (OCaml)

and many more...

A fairly complete list is posted here.

Sunday, November 9, 2008

Science Code .Net and Numerical Recipes

Here is an interesting project:

http://www.sciencecode.com/

It seems to be an effort to implement the classic Numerical Recipes and provide classes to do some common Physics/Math calculations from C#. When I get a chance I'll be trying it out and posting a review. If any one has some experience with it comment and let me know what you thought of it.

Friday, November 7, 2008

Interop Example: Marshalling Structures To The InChI Library

For the last week I've been finishing up CSInChI a library for using the IUPAC InChI library from C#. For those not acquainted with it, the InChI (International Chemical Identifier) is the a line notation used to represent molecular structures. Line notations are simply ways of encoding a structure as text string. Since the official InChI api provided by the IUPAC is written in C I thought this would be a good time to post an interop example. This tutorial will illustrate how to call an unmanaged function that takes structures as parameters using Platform Invoke.

The InChI library can be downloaded from: http://www.iupac.org/inchi/

In this example we'll tackle the function:

int GetStructFromINCHI(inchi_InputINCHI *inpInChI, inchi_OutputStruct *outStruct)

This function takes 2 C structs as parameters and returns an integer error code. The first one holds two strings, the inchi and a string of options.

typedef struct tagINCHI_InputINCHI {
/* the caller is responsible for the data allocation and deallocation */
char *szInChI; /* InChI ASCIIZ string to be converted to a strucure */
char *szOptions; /* InChI options: space-delimited; each is preceded by */
/* '/' or '-' depending on OS and compiler */
} inchi_InputINCHI;



We'll begin by creating a matching C# structure

public struct InChI_String_Input
{
public string inchiString;
public string options;
}


In this case we get surprisingly lucky and this struct marshals just fine with no additional attributes. The key thing here is to make sure that the fields are listed in the same order as in the unmanaged structure and that the type of each field is the same size as the C type. By default the C# compiler lays out the fields of a struct sequentially. If you want to use a class you must apply the [StructLayout(LayoutKind.Sequential)] attribute.

The C struct that holds the output from the function looks like this:

typedef struct
tagINCHI_OutputStruct {
inchi_Atom *atom;
inchi_Stereo0D
*stereo0;
S_SHORT num_atoms;
S_SHORT num_stereo0;
char *szMessage;
char *szLog;
unsigned long
WarningFlags[2][2];

}inchi_OutputStruct;

A C# equivalent looks something like this:
using System;
using System.Runtime.Interop;

public struct InChI_Struct_Output
{
public IntPtr AtomsPtr;
public IntPtr StereoPtr;

public short NumAtoms;
public short NumStereo0D;

public string Message;
public string Log;

[
MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public ulong[] WarningFlags;
}


The details of the inchi_Atom and inchi_Stereo0D structures will be discussed in a future post. For now we're only going worry about how to marshal arrays. Because a C style array is represented by a pointer to the first item in the array the C# equivalent is the IntPtr class from the InteropServices namespace. The WarningFlags array has to be changed to a 1-D array with the same total capacity because the CLR does not support marshaling nested arrays. Note that the MarshalAs attribute specifies a size. This is required both because the array has a fixed size in C and because the CLR needs to know the runtime size of an array in order to marshal it.

To convert the pointer representing a C style array to an array of C# structures write a method that takes the pointer and increments it by the size of the structure it represents calling the Marshal.PtrToStructure method at each iteration to convert the pointer to a C# structure.

public InChI_Atom[] GetAtoms()
{
int atomSize = Marshal.SizeOf(typeof(InChI_Atom));
InChI_Atom[] iAtoms = new InChI_Atom[NumAtoms];

InChI_Atom a;
IntPtr pAtom = AtomsPtr;

for (int i = 0; i < iAtoms.Length; i++)
{
a = (InChI_Atom)Marshal.PtrToStructure(pAtom, typeof(InChI_Atom));
iAtoms[i] = a;
pAtom = new IntPtr((int)pAtom + atomSize);
}
return iAtoms;
}


Finally we create a class to hold the methods that access the unmanged dll.

public static class LibInChI
{
[DllImport("libinchi.dll", EntryPoint = "GetStructFromINCHI")]
public static extern int ParseInChI(ref InChI_String_Input input, out InChI_Struct_Output output)
...
...
}


To call the method:

//All fields need to be set to non-null values
InChI_String_Input inp;
inp.Options = "";
string inchi = "InChI=1/H3N/h1H3";

InChI_Struct_Output outStruct;

int retVal = LibInChI.ParseInChI(ref inp, out outStruct);

Note the use of the ref and out keywords. When ref and out parameters are marshaled they are interpreted as &theParam. Remember that if a method has any ref or out parameters the keywords must be explicitly specified each time the method is called.

Thats it for today. The next interop example will look at the InChI_Atom struct and how to ensure that unmanaged resources are freed. For those who are interested, CSInChI will be available within the next week (fingers crossed!) from the ChemSharp project. http://sourceforge.net/projects/chemsharp

Wednesday, October 8, 2008

Using the CDK with the .Net framework and Mono

As part of my ongoing effort to create some cheminformatics options for the .Net framework I recently participated in a project to build C# bindings for the Open Babel C++ toolkit. Now that the first release of OBDotNet is out I decided to turn my attention to the other mature open source cheminformatics api that I have experience with: The java Chemistry Development Kit. For a first pass at the integration I decided to use IKVM an implementation of java for .Net. The components of IKVM include:

ikvm.exe : the VM
ikvmc.exe : a compiler that converts java byte code to msil code
ikvmstub.exe : a compiler that generates java stubs that wrap .Net classes


This post will look at using ikvmc to build a .Net dll from the CDK jar file and using it in C# and IronPython.

To build the cdk_dotnet dll first download IKVM . Then unzip it to the directory of your choice and add the directory containing the IKVM executables, the directory containing the C# compiler (csc for windows or mcs for mono), and the directory containing the java compiler (javac.exe) to the PATH environment variable. Next download the current release of the CDK.

Now we're ready to build the dll:

Change to the directory containing the CDK jar file and run the following command.

ikvmc -assembly:cdk_dotnet -target:library yourcdkjar.jar

The -debug switch can be added to generate debugging info for the assembly.

If you see alot of warnings when the dll is being built you may want to check your CLASSPATH environment variable, however in spite of the warnings most functionality seems to be unaffected, at least in C#. So go ahead an ignore them if you want to get started.

To test the dll:

Create a new C# console application project and add references to cdk_dotnet.dll and IKVM.OpenJDK.ClassLibrary.dll. Then write some code and run it. Here is an example of how to use the cdk_dotnet dll to read a file and calculate some descriptors.

using System;

namespace CDK_DotNet_Test
{
//Using aliases for convenience and to avoid importing whole
//packages
using FReader = java.io.FileReader;
using TPSA = org.openscience.cdk.qsar.descriptors.molecular.TPSADescriptor;
using LogP = org.openscience.cdk.qsar.descriptors.molecular.XLogPDescriptor;
using DoubleResult = org.openscience.cdk.qsar.result.DoubleResult;
using Builder = org.openscience.cdk.DefaultChemObjectBuilder;
using IMol = org.openscience.cdk.interfaces.IMolecule;
using MolReader = org.openscience.cdk.io.iterator.IteratingMDLReader;
using Consts = org.openscience.cdk.CDKConstants;

class Program
{
static void Main(string[] args)
{
FReader fReader = new FReader("some_mols.mol");
MolReader molReader = new MolReader(fReader,Builder.getInstance());
IMol mol;
DoubleResult dr;
LogP logP = new LogP();
TPSA tpsa = new TPSA();
double logPVal, tpsaVal;
string name;

while (molReader.hasNext())
{
mol = (
IMol)molReader.next();
dr = (
DoubleResult)logP.calculate(mol).getValue();
logPVal = dr.doubleValue();
dr = (
DoubleResult)tpsa.calculate(mol).getValue();
tpsaVal = dr.doubleValue();

//the title of each mol in the file is the name of the mol
name = (
String)mol.getProperty(Consts.TITLE);

Console.WriteLine("{0} {1} {2}",name,logPVal,tpsaVal);
}
}
//end Main
}
//end class Program
}
//end Namespace CDK_DotNet_Test


The output is:

Amitriptyline 20.01 3.24
antipyrine 11.827 23.55
carbamazepine 20.464 20.31
desipramine 17.511 3.24
lupitidine 11.036 76.32
phenserine 17.147 32.78
physostigmine 6.809 32.78
thioridazine 16.127 57.08
trifluoroperazine 17.027 35.02


IronPython:

Follow the instructions for installing IKVM and creating the cdk_dotnet dll then copy the CDK dll along with

IKVM.OpenJDK.ClassLibrary.dll and IKVM_Runtime.dll to the LIB directory of your IronPython installation.

I wanted to give an IronPython version of the C# example but for some reason the java File object throws an exception
when instantiated through IronPython. I'll be looking into this and hopefully I'll have an explanation to post soon. In the

mean time here is a simpler example using IronPython.

import clr

clr.AddReference("cdk_dotnet.dll")
clr.AddReference("IKVM.OpenJDK.ClassLibrary.dll")

from org.openscience.cdk import Molecule
from org.openscience.cdk.smiles import SmilesParser
#import the whole package for brevity
from org.openscience.cdk.qsar.descriptors.molecular import *
from org.openscience.cdk.qsar.result import DoubleResult

tpsa = TPSADescriptor()
logP = XLogPDescriptor()

smiles = SmilesParser()
mol = smiles.parseSmiles("N=CCC=O")
dr = tpsa.calculate(mol).getValue()
tpsaVal = dr.doubleValue()
dr = logP.calculate(mol).getValue()
logPVal = dr.doubleValue()
print logPVal,tpsaVal

the output is:
3.181 40.92

When I get a chance I'll do a post demonstrating how to use IKVM to call C# from java and demonstrate how to mix and match ChemSharp (currently under development with an alpha release coming soon) and OBDotNet with the CDK. It looks like we're finally getting a wide range of options for doing cheminformatics work using Mono and .Net. CODE ON!

Correction 11/12/08:

When I wrote:

"other mature open source cheminformatics api: The java Chemistry Development Kit. "

I did not mean to denigrate or ignore any of the other open source toolkits out there. What Imeant to write was "mature open source cheminformatics api that I have experience with".
Apologies all around.

Monday, October 6, 2008

PyOpenGL blunders

I was sorting though some old files recently and I came across some screen shots from of the first real programs I ever wrote using OpenGL back in my Python days. Since they were kind of funny I thought I would post them for the amusement of the readers.

The project was to render an electrostatic potential map on a VDW surface using atomic charges calculated with GAMESS (a computational chemistry package for all of you non-chemists). To create a prototype I had to manually issue the vertices for each atom sphere so that the color of the vertex could be set. Manually drawing the spheres required issuing the points in the order required to create the triangle strips used to approximate the spheres. This proved more challenging than I had anticipated....



























The Death Star here is my favorite!













And finally success! This is the oxygen in H2O.