November 2, 2009
Fast building SMILES structure viewer with Dingo and WPF
Indigo is recently introduced as open-source chemoinformatics toolkit <1>, <2>.
Dingo is a molecule and reaction rendering library included in Indigo and with .NET C# wrapper to make it possible for me to build a WPF app with it. Dingo and WPF make things so simple.
Amazing feeling to stand on the giant’s shoulder. Not too much code pasted here
Compound class to transform SMILES to Bitmap objects with Dingo
public class Compound
{
public String smi{ get; set;}
public Compound(String smiles)
{
smi = smiles;
}
public BitmapSource bmp {
get{
return Smi2Bitmap(smi, 160, 160);
}
}
public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
public static BitmapSource Smi2Bitmap(String smi, int Width, int Height)
{
Dingo dg = new Dingo();
dg.loadMolecule(smi);
dg.setBackgroundColor(System.Drawing.Color.White);
System.Drawing.Bitmap bmp = dg.renderToBitmap(Width, Height);
return loadBitmap(bmp);
}
}
SMILES file reader
public class SMIReader: System.Collections.IEnumerable
{
private StreamReader sr;
public SMIReader(String path)
{
sr = new StreamReader(path);
}
public IEnumerator GetEnumerator()
{
String line;
while ((line = sr.ReadLine()) != null)
{
yield return new Compound(line.Split('\t')[0].Split(' ')[0]);
}
}
}
XAML code of the listbox
Notes: To show as many structure pictures blocks on screen the WrapPanel is used as ItemsPanel. This depresses performance for large file that all SMILES are read in but lazy loaded in the default StackPanel mode.
<ListBox Name="list1" Height="539" Width="790"
ItemTemplate="{StaticResource MolListboxTemplate}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
IsSynchronizedWithCurrentItem ="True">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Item template of the listbox to support structure images displaying
<Window.Resources>
<DataTemplate x:Key="MolListboxTemplate">
<WrapPanel Margin="3">
<StackPanel>
<Image Source="{Binding bmp}" Height="160" Width="160"></Image>
<TextBox Text="{Binding smi}" Width="160"></TextBox>
</StackPanel>
</WrapPanel>
</DataTemplate>
</Window.Resources>
Button event to trigger databinding
private void button1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Filter = "SMILES file(*.smi)|*.smi";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
String path = ofd.FileName;
textBlock1.Text = path;
list1.ItemsSource = new nchem.SMIReader(path);
}
}
Done.
Filed by
charlie
at 11:40 pm under Coding, chemoinformatics
1 Comment







