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:-
- ChEMBL
- DrugBank
- PDBe (Protein Data Bank Europe)
- International Union of Basic and Clinical Pharmacology
- PubChem (‘Drugs of the Future’ subset)
- KEGG (Kyoto Encyclopedia of Genes and Genomes) Ligand
- ChEBI (Chemical Entities of Biological Interest).
- NIH Clinical Collection
- ZINC
- eMolecules
- IBM strategic IP insight platform and the National Institutes of Health
- Gene Expression Atlas
- IBM strategic IP insight platform and the National Institutes of Health.
- FDA/USP Substance Registration System (SRS)
- SureChem
- PharmGKB
- Human Metabolome Database (HMDB)
- Selleck
- PubChem (‘Thomson Pharma’ subset)
- PubChem Compounds
- Mcule
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
1 2 |
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.
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
1 2 |
vortex/unichem/unichem_linkpagetemplate.html |
As shown in the image below.
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.
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.
If you now click on the hypertext link the corresponding page will open in your web browser.
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,
1 2 3 4 5 6 7 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
#Authored by Sune Askjaer, (http://www.linkedin.com/in/saskjaer) with help from Chris Swain (http://www.macinchem.org) #Copyright (c) 2013, Sune Askj&aelig;r & Chris Swain&nbsp; #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:
1 2 |
dataBlock = dataBlock + '<tr><td>' + col.getName() + '</td><td>' + col.getValueAsString(r) + '</td></tr>' |
with the 4 lines
1 2 3 4 5 |
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
Page Updated 20 March 2014
3 thoughts on “Using Un1Chem from within Vortex”
Comments are closed.