Macs in Chemistry

Insanely great science

 

Scripting Vortex 18

Un1Chem is a new web resource provided by the EBI, it is a 'Unified Chemical Identifier' system, designed to assist in the rapid cross-referencing of chemical structures, and their identifiers, between databases. Currently the uniChem contains data from 21 different data sources:-

Un1Chem's primary function is to maintain cross references between EBI chemistry resources. These include primary chemistry resources (ChEMBL, ChEBI and PDBeChem), and other resources where the main focus is not small molecules, but which may nevertheless contain some small molecule information (eg: Gene Expression Atlas). When I last looked UniChem contained 62,187,830 structures.

Chambers, J., Davies, M., Gaulton, A., Hersey, A., Velankar, S., Petryszak, R., Hastings, J., Bellis, L., McGlinchey, S. and Overington, J.P. UniChem: A Unified Chemical Structure Cross-Referencing and Identifier Tracking System. Journal of Cheminformatics 2013, 5:3 (January 2013). DOI.

Searching uses either the source compound Id, InChI or InChI Key and has the following format

https://www.ebi.ac.uk/unichem/frontpage/results?queryText=SMWDFEZZVXVKRB-UHFFFAOYSA-N&kind=InChIKey&sources=&incl=exclude

More details can be found here.

The InChIKey is a short, fixed-length character signature based on a hash code of the InChI string. By definition, hashing is a one-way conversion procedure and the original structure cannot be restored from the InChiKey allowing confidential searching, however it should be noted that this script does search a public resource.

Recently Sune Askjær contacted me about a Vortex script he had written and he has kindly agreed for this to be described on this site. This script has a couple of dependences, it requires jyson-1.0.2.jar, which can be downloaded from here the jar file should be placed in [profile]/vortex/libs from where it will be imported automatically.

jysonpath

It also requires the file unichem_linkpagetemplate.html to be placed in a folder called “unichem’” that needs to be created your Vortex folder. The path to the template file will thus be

vortex/unichem/unichem_linkpagetemplate.html

As shown in the image below.

unchemwindow

If you now import an sdf file into a Vortex workspace and run the script you are first presented with a dialog asking which data sources are of interest and whether to store the InChIKey in the table in the workspace. It should be noted that this scripts searches and external public resource, whilst only InChiKeys are used you may want to check that this is acceptable for your institution.

unichem1

Once you click “OK” the script works through the table generating InChIKeys and submitting them to Un1Chem web service. A new column is created containing the InChIKey if requested, and a column indicating how many data source hits were obtained together with a link to a locally generated web page (stored in the temporary item folder) containing all the information.

unichem2

If you now click on the hypertext link the corresponding page will open in your web browser.

unichemResults

Vortex Script

The script is shown below and a couple of points are worth commenting on. One of the issues of writing scripts like this is dealing with the different file paths used by Mac OSX, Linux and Windows, this can be resolved using, as suggested by Matt,

import os

vortexFolder = os.path.normpath(vortex.getVortexFolder())
template_file = os.path.join(vortexFolder, 'unichem', 'unichem_linkpagetemplate.html')

f = open(template_file, 'r')

Most of the scripts I’ve created have little or no user interface, in this script the java swing GUI toolkit is used to create a sophisticated dialog box that allows the user to customise the input. The data from Un1chem is parsed using the json library and then inserted into the html template file. It should be very easy to customise the template file if needed.

#Authored by Sune Askjaer, (http://www.linkedin.com/in/saskjaer) with help from Chris Swain (http://www.macinchem.org)
#Copyright (c) 2013, Sune Askjær & Chris Swain 
#All rights reserved.


# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met: 

# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the   distribution. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# Jython imports
import subprocess
import re
import httplib
import time
# Vortex imports
import com.dotmatics.vortex.util.Util as Util
import com.dotmatics.vortex.mol2img.jni.genImage as genImage
import com.dotmatics.vortex.mol2img.Mol2Img as mol2Img
import jarray
import binascii
import string
import os

# This path to the jyson-1.0.2.jar is placed in [profile]/vortex/libs and is imported automatically
from com.xhaus.jyson import JysonCodec as json

import java.lang as lang

class unichem(lang.Runnable):

    def __init__(self):

        self.host = "www.ebi.ac.uk"
        # Unichem source id classification into broad categories used to order link results
        self.srcIdCategory =    {'1':'Pharmacology','2':'Pharmacology','3':'Pharmacology','4':'Pharmacology','5':'Pharmacology','6':'Pharmacology','7':'Pharmacology','8':'Pharmacology','12':'Pharmacology','21':'Pharmacology','11':'Patents & Literature','13':'Patents & Literature','15':'Patents & Literature','9':'Commercial-availability','10':'Commercial-availability','20':'Commercial-availability','17':'Pharmacology','22':'Pharmacology'} 
        self.categorySortOrder = {'Pharmacology':1, 'Patents & Literature':2, 'Commercial-availability':3, 'Other' : 50}

        self.doGUI()


def run(self):
    selectedSources = self.duallist.getItems()
    self.selectedSrcIds = []
    for selectedSource in selectedSources:          
        self.selectedSrcIds.append(self.sourceIds[selectedSource])

    self.inChIKeys = self.calcInChIKeysVortex()
    self.searchUniChemByInChIKey()


def searchUniChemByInChIKey(self):
    testColumn = vtable.addColumn("Source Links via UniChem")
    testColumn.setType(vortex.STRING)
    tempFolder = os.path.normpath(vortex.getTempFolder())
    vortexFolder = os.path.normpath(vortex.getVortexFolder())
    votexUserName = vortex.getUsername()
    emptyMol = mol2Img.EMPTY_MOL
    cols = vtable.getColumns(range(0,vtable.getColumnCount()-1))

    uniChemCon = httplib.HTTPSConnection(self.host)
    rows = vtable.getRealRowCount()
    for r in range(0, int(rows)):
        if self.checkBoxSelectedOnly.isSelected() and not vtable.getRowSelected(r):
            continue

        if self.inChIKeys[r] == None:
            continue
        try:    
            # Structure image generation
            mol = vtable.molFileManager.getMolFileAtRow(r)
            mol = 'name_prefix'+mol  # adding the prefix to ensure that the image creation does not fail if input mol has no mol-name
            # Generating the image of the molecule to go into the template html doc.
            b = jarray.zeros(512000, 'b')
            size = genImage.generateImage(mol, 1, emptyMol, 300, 300, '', b)    
            strucImg64bit = binascii.b2a_base64(b[0:size].tostring())
            # Row data block
            dataBlock = '<table width="600" border="1"><col width="200"><col width="400"><th>Column</th><th>Value</th>'
            for col in cols:
                if col.isMolfileColumn():
                    continue
                else:
                    dataBlock = dataBlock + '<tr><td>' + col.getName() + '</td><td>' + col.getValueAsString(r) + '</td></tr>'

            dataBlock = dataBlock + '</table>'
            # HTML template page

            template_file = os.path.normpath(os.path.join(vortexFolder,'unichem','unichem_linkpagetemplate.html'))
            f = open(template_file, 'r')
            linksHTMLTemplate = f.read()
            f.close()
            linksHTMLTemplate = linksHTMLTemplate.replace("$INSERT_STRUCTURE_IMG_CODE_HERE",strucImg64bit)
            linksHTMLTemplate = linksHTMLTemplate.replace("$INSERT_CMPD_DATA_BLOCK_HERE", dataBlock)
            linksHTMLTemplate = linksHTMLTemplate.replace("$INSERT_PAGE_TITLE", 'UniChem search for ' + self.inChIKeys[r] + ' by ' + votexUserName)

            print "Calling Unichem with the InChIKey: " + self.inChIKeys[r]
            uniChemCon.request("GET", "/unichem/rest/verbose_inchikey/"+ self.inChIKeys[r])
            print "Getting the reponse"
            response = uniChemCon.getresponse()
            responseData = response.read()
            data = json.loads(responseData)

            linkCount = 0
            linkList = []
            if isinstance(data, list):
                for record in data:
                    for src_id in self.selectedSrcIds:
                        if (record.get('src_id',None) == src_id) and (record.get('base_id_url_available',0) == '1'):
                            url = record.get('base_id_url', "error")
                            nameLabel = record.get('name_label', "Missing")
                            cmpd_ids = record.get('src_compound_id',None)
                            categoryLabel = self.srcIdCategory.get(src_id, 'Other')
                            sortOrder = self.categorySortOrder.get(categoryLabel, 99)
                            links = []
                            for cmpd_id in cmpd_ids:

                                if (record.get('aux_for_url',0)) == '1':
                                    links.append('<a target="_blank" href="' + url + record.get('aux_src',None).get(cmpd_id).get('url_id') + '">' + cmpd_id +'</a>')                                        
                                else:
                                    links.append('<a target="_blank" href="' + url + cmpd_id + '">' + cmpd_id +'</a>')                                      
                                linkCount = linkCount + 1
                            linkRow = '<tr><td><b>' + categoryLabel + '</b></td><td><b>' + nameLabel + '</b></td><td>' + ", ".join(links) + '</td></tr>'
                            linkList.append((linkRow,sortOrder))                        


                sortedLinks =  [i for i,j in sorted(linkList, key=lambda link: link[1])]
                linksHTMLTemplate = linksHTMLTemplate.replace("$INSERT_LINK_TABLE_ROWS_HERE", "".join(sortedLinks))                 

            if linkCount == 0:
                testLink = "<html>UniChem link count: <b>" + str(linkCount) + "</b><br><b>Not</b> known to UniChem</html>"
            else:
                linkFileName = os.path.normpath(os.path.join(tempFolder, self.inChIKeys[r] + ".html"))
                target = open (linkFileName, 'w')
                target.write(linksHTMLTemplate.encode('utf-8'))
                target.close()
                testLink = "<html>UniChem link count: <b>" + str(linkCount) + "</b><br><a href=\"file://"  + linkFileName + "\">Click for direct source links</a><br></html>"
            testColumn.setValueFromString(r, testLink)
        except Exception, e:            
            print e
            testLink = "<html>UniChem produced an error for this InCkIKey</html>"
            testColumn.setValueFromString(r, testLink)
            uniChemCon = httplib.HTTPSConnection(self.host)
            continue

    uniChemCon.close()


def calcInChIKeysVortex(self):
    if self.checkBoxInChIKey.isSelected():
        newColumn = vtable.addColumn("InChIKey")
        newColumn.setType(vortex.STRING)

    self.mols = []
    rows = vtable.getRealRowCount()
    keys = [None] * rows
    for r in range(0, int(rows)):
        try:
            if self.checkBoxSelectedOnly.isSelected() and not vtable.getRowSelected(r):
                    continue
            mol = vtable.molFileManager.getMolFileAtRow(r)
            inChIKey = vortex.getMolProperty(mol, 'InChIKey')
            keys[r] = inChIKey
            if self.checkBoxInChIKey.isSelected():                  
                newColumn.setValueFromString(r, inChIKey)

        except Exception, e:
            print e

    return keys


def doGUI(self):
    self.getSourceList()

    content = javax.swing.JPanel()
    label = javax.swing.JLabel("<html>Vortex will query the <b>public</b> resource UniChem using<br>encrypted InChIKeys representations of the structures<br>and add hyperlinks to the origianl data sources in a new column.</html>")
    layout.fill(content, label, 3, 0)

    preSelected = range(0,len(self.sourceNames))    
    self.duallist = com.dotmatics.vortex.components.VortexDualList()
    self.duallist.setSourceString("Excluded sources")
    self.duallist.setDestString("Included sources")
    self.duallist.setItems(self.sourceNames, preSelected)
    label = javax.swing.JLabel("<html><b>Select the data sources of interest:</b></html>")
    layout.fill(content, label, 3, 2)
    layout.fill(content, self.duallist, 3, 3)
    button = swing.JButton("Source Information", actionPerformed=self.sourceInfo)
    layout.nofill(content, button, 3, 1)

    contentChbx = javax.swing.JPanel()

    label = javax.swing.JLabel("<html><b>Selected rows ONLY</b></html>")
    layout.fill(contentChbx, label, 0, 1)
    self.checkBoxSelectedOnly = javax.swing.JCheckBox()
    layout.fill(contentChbx, self.checkBoxSelectedOnly, 1, 1)
    label = javax.swing.JLabel("<html><b>Store InChIKey in table</b></html>")
    layout.fill(contentChbx, label, 0, 2)
    self.checkBoxInChIKey = javax.swing.JCheckBox()
    layout.fill(contentChbx, self.checkBoxInChIKey, 1, 2)
    layout.fill(content, contentChbx, 3, 4)
    self.checkBoxInChIKey.setSelected(True)

    ret = vortex.showInDialog(content, "Un1Chem public database lookup")

    if ret == vortex.OK:
        vortex.run(self, "Search against UniChem...")

def getSourceList(self):
    self.sourceNames = []
    self.sourceDescriptions = []
    self.sourceIds = []
    self.sourceUrls = []
    self.sourceName2Id = {}
    uniChemCon = httplib.HTTPSConnection(self.host)
    uniChemCon.request("GET", "/unichem/rest/src_ids")
    response = uniChemCon.getresponse()
    if response.status != 200:
        vortex.alert("<html>UniChem web service returned the http error code: " + str(response.status) + ".<br>Please close the panel and try again later.</html>")
        return
    #print response.status, response.reason
    # implement check to see if status is 200
    sourceIds = json.loads(response.read())
    uniChemCon.close()
    for record in sourceIds:
        src_id = record.get('src_id',None)
        if src_id:  
            uniChemCon.request("GET", "/unichem/rest/sources/" + str(src_id))
            response = uniChemCon.getresponse()
            if response.status == 200:
                sourceInfo = json.loads(response.read())
                if (int(sourceInfo[0].get('base_id_url_available',0))) == 1:  # only add if url is available
                    name = sourceInfo[0].get('name_label',"Missing")
                    self.sourceNames.append(name)
                    self.sourceIds.append(src_id)
                    self.sourceName2Id[name] = src_id                       
                    description = sourceInfo[0].get('description',"Missing")
                    self.sourceDescriptions.append(description)
                    url = sourceInfo[0].get('src_url')
                    self.sourceUrls.append(url)
            else:
                vortex.alert("UniChem webservice failed with error code : " + str(response.status) + " \nPlease try again later")

    uniChemCon.close()  

def sourceInfo(self, event):
    infoHTML = """<html><table border="1" width="950"><col width="250"><col width="670"><th>Data Source Name</th><th>Data Source Description</th>"""
    endHTML = "</table></html>"

    for i in range(len(self.sourceNames)):
            infoHTML = infoHTML + """<tr><td><b>""" + self.sourceNames[i] + """</b></td><td>""" + self.sourceDescriptions[i] + """</td></tr>""" 

    vortex.alert(infoHTML + endHTML)

if vws is None:
    vortex.alert("You must have a workspace loaded...")
else:
    if vortex.getVersion() < 'v2013.09.25803':
        vortex.alert('<html>Sorry your version of Vortex does not support this script.<br/>Please consider updating to the newest version.</html>')
    else:
        unichem()

Update

There was a minor bug in the above script, if there were blank cells in the workspace the script would fail.

If you replace the line 97 reading:

            dataBlock = dataBlock + '<tr><td>' + col.getName() + '</td><td>' + col.getValueAsString(r) + '</td></tr>'

with the 4 lines

            value = col.getValueAsString(r)
            if value is None:
                value = ''
            dataBlock = dataBlock + '<tr><td>' + col.getName() + '</td><td>' + value + '</td></tr>'

The script now functions fine.

The updated script, template file and installation instructions can be downloaded from here, Un1chem.zip.

There are a number of other similar scripts in the Other Hints, Tips and Tutorials

Page Updated 20 March 2014