ChemmineR-V2 Manual 

Authors: Eddie Cao, Tyler Backman, Yan Wang and Thomas Girke, UC Riverside

Introduction

 [ PDF Manual ]   [ R Code ]   [ Slide Show ]

ChemmineR is a cheminformatics package for analyzing drug-like small molecule and screening data in R. Its new version ChemmineR-V2 contains functions for processing SDFs (structure data files), molecule depictions, structural similarity searching, clustering/diversity analyses of compound libraries with a wide spectrum of algorithms and utilities for managing complex data sets from high-throughput compound bio-assays. In addition, it offers visualization functions for compound clustering results and chemical structures. The integration of chemoinformatic tools with the R programming environment has many advantages, such as easy access to a wide spectrum of statistical methods, machine learning algorithms and graphic utilities. The first version of this package was published in 2008 in Bioinformatics: 24, 1733-1734 (please cite where appropriate). Since then many additional utilities have been added to the package and many more are under development for future releases (Backman et al., 2011).





Figure 1: Selected Functionalities provided Provided by ChemmineR


Table of Contents

Getting Started

Installation

The R software for running ChemmineR can be downloaded here. The ChemmineR package itself is available at the Bioconductor repository. Due to its heavy development, it is strongly recommended to maintain a recent version of ChemmineR by updating or reinstalling it frequently. To install the package, it is strongly recommended to use the automated bioLite install command in R as shown here:

source("http://bioconductor.org/biocLite.R") # Sources the biocLite.R installation script.
biocLite("ChemmineR") # Installs the package.

Alternatively, one can download the package and then install it as shown below. Note: this is not the recommended approach for installing Bioconductor packages.

## OS X
install.packages("ChemmineR_x.x.x.tgz", repos=NULL) # Add 'type="source"' when installing from source.

## Linux
install.packages("ChemmineR_x.x.x.tar.gz", repos=NULL)

## Windows

install.packages("ChemmineR_x.x.x.zip", repos=NULL)

Note: x.x.x needs to be replaced by the current version number of the package.

Table of Contents

Version History

See Version History Page

Table of Contents

Loading the Package and Documentation


## Load the package
library("ChemmineR")

## List all functions and classes available in the package:
library(help="ChemmineR")

## Open the vignette pdf (manual) of the package
vignette("ChemmineR")

Five Minute Tutorial

The following code gives an interactive overview of the most important functionalities provided by ChemmineR. Copy and paste of the commands into the R console will demonstrate these utilities.


## Create Instances of SDFset class
## Sample data set contains first 100 compounds from PubChem SD file "Compound_00650001_00675000.sdf.gz"
## from: ftp://ftp.ncbi.nih.gov/pubchem/Compound/CURRENT-Full/SDF/

data(sdfsample); sdfset <- sdfsample
sdfset; view(sdfset[1:4])
sdfset[[1]]

## The SDFset object is created during the import of an SD file
sdfset <- read.SDFset("
http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")

## Miscellaneous accessor methods for SDFset container
header(sdfset[1:4])
atomblock(sdfset[1:4])
atomcount(sdfset[1:4])
bondblock(sdfset[1:4])
datablock(sdfset[1:4])

## Assigning compound IDs and keeping them unique
cid(sdfset); sdfid(sdfset)
unique_ids <- makeUnique(sdfid(sdfset))
cid(sdfset) <- unique_ids

## Converting the data blocks in SDFset to matrix
blockmatrix <- datablock2ma(datablocklist=datablock(sdfset)) # Converts data block to matrix 
numchar <- splitNumChar(blockmatrix=blockmatrix) # Splits to numeric and character matrix
numchar[[1]][1:4,]; numchar[[2]][1:4,]

## Compute atom frequency matrix, molecular weight and formula
propma <- data.frame(MF=MF(sdfset), MW=MW(sdfset), atomcountMA(sdfset))
propma[1:4, ]

## Assign matrix data to data block
datablock(sdfset) <- propma
view(sdfset[1:4])

## String Searching in SDFset
grepSDFset("650001", sdfset, field="datablock", mode="subset") # To return index, set mode="index")

## Export SDFset to SD file
# write.SDF(sdfset[1:4], file="sub.sdf", sig=TRUE)

## Plot molecule structure of one or many SDFs
plot(sdfset[1:4]) # plots to R graphics device
sdf.visualize(sdfset[1:4]) # viewing in web browser


## Structure similarity searching and clustering using atom pairs
apset <- sdf2ap(sdfset) # Generate atom pair descriptor database for searching
data(apset) # Loads same data set provided by library.
cmp.search(apset, apset[1], type=3, cutoff = 0.3) # Search apset database with single compound.
cmp.cluster(db=apset, cutoff = c(0.65, 0.5))[1:4,] # Binning clustering using variable similarity cutoffs.

## Structure similarity searching and clustering using PubChem fingerprints
data(sdfsample); sdfset <- sdfsample; cid(sdfset) <- sdfid(sdfset) # Refresh sample data set
fpset <- fp2bit(x=sdfset, type=2) #
Convert base 64 encoded fingerprints to binary matrix
fpSim(x=fpset[1,], y=fpset[2,]) #
Pairwise compound structure comparisons
fpSim(x=fpset[1,], y=fpset) # Structure similarity searching
simMA <- sapply(rownames(fpset), function(x) fpSim(x=fpset[x,], fpset)) # Compute similarity matrix
hc <- hclust(as.dist(simMA), method="single") # Hierarchical clustering with simMA as input
plot(as.dendrogram(hc), edgePar=list(col=4, lwd=2), horiz=TRUE)
# Plot hierarchical clustering tree

Overview of Classes and Functions

The following list gives an overview of the most important classes, methods and functions available in the ChemmineR package. The help documents of the package provide much more detailed information on each utility. The standard R help documents for these utilities can be accessed with this syntax: ?function_name (e.g. ?cid) and ?class_name-class (e.g. ?"SDFset-class").

  • Molecular Structure Data
    • Classes
      • SDFstr: intermediate string class to facilitate SD file import; not important for end user
      • SDF: container for single molecule imported from an SD file
      • SDFset: container for many SDF objects; most important structure container for end user 
    • Functions/Methods
      • Accessor methods for SDF/SDFset
        • Object slots: cid, header, atomblock, bondblock, datablock (sdfid, datablocktag)
        • Summary of SDFset: view
        • Matrix conversion of data block: datablock2ma, splitNumChar
        • String search in SDFset: grepSDFset
      • Coerce one class to another
        • See R help with ?"SDFset-class"
      • Utilities
        • Atom frequencies: atomcountMA, atomcount
        • Molecular weight: MW
        • Molecular formula: MF
      • Compound structure depictions
        • R graphics device: plot, plotStruc
        • Online: cmp.visualize
  • Structure Descriptor Data
    •  Classes
      • AP: container for atom pair descriptors of a single molecule
      • APset: container for many AP objects; most important structure descriptor container for end user
    • Functions/Methods
      • Create AP/APset instances
        • From SDFset: sdf2ap
        • From SD file: cmp.parse
        • Summary of AP/APset: view, db.explain
      • Accessor methods for AP/APset
        • Object slots: ap, cid
      • Coerce one class to another
        • See R help with ?"APset-class"
      • Structure Similarity comparisons and Searching
        • Compute pairwise similarities : cmp.similarity
        • Search APset database: cmp.search
        • Compute pairwise similarities : cmp.similarity
            
      • AP-based Structure Similarity Clustering
        • Single-linkage binning clustering: cmp.cluster
        • Visualize clustering result with MDS: cluster.visualize
        • Size distribution of clusters: cluster.sizestat

Import Compounds


## Import SD file and store as SDFset object
## Sample data set contains first 100 compounds from PubChem SD file "Compound_00650001_00675000.sdf.gz"
## from: ftp://ftp.ncbi.nih.gov/pubchem/Compound/CURRENT-Full/SDF/

sdfset <- read.SDFset("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")
data(sdfsample); sdfset <- sdfsample # The sample SDF set is provided by the library
valid <- validSDF(sdfset); which(!valid) # Identifies invalid SDFs in SDFset objects.
sdfset <- sdfset[valid] # Removes invalid SDFs, if there are any.

## Import SD file and store as SDFstr object
sdfstr <- read.SDFstr("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")

## Create SDFset from SDFstr class
read.SDFset(sdfstr)
as(sdfstr, "SDFset")

Export Compounds


## Write objects of classes SDFset/SDFstr/SDF to file
write.SDF(sdfset[1:4], file="sub.sdf")
    
## Writing customized SDFset to file containing ChemmineR signature, IDs from SDFset and no data block
write.SDF(sdfset[1:4], file="sub.sdf", sig=TRUE, cid=TRUE, db=NULL)
    
## Example for injecting a custom matrix/data frame into the data block of an SDFset and then writing it to an SD file
props <- data.frame(MF=MF(sdfset), MW=MW(sdfset), atomcountMA(sdfset))
datablock(sdfset) <- props
write.SDF(sdfset[1:4], file="sub.sdf", sig=TRUE, cid=TRUE)

## Indirect export via SDFstr object
sdf2str(sdf=sdfset[[1]], sig=TRUE, cid=TRUE) # Uses default components
sdf2str(sdf=sdfset[[1]], head=letters[1:4], db=NULL) # Uses custom components for header and data block

## Write SDF, SDFset or SDFstr Classes to File
write.SDF(sdfset[1:4], file="sub.sdf", sig=TRUE, cid=TRUE, db=NULL)
write.SDF(sdfstr[1:4], file="sub.sdf")
cat(unlist(as(sdfstr[1:4], "list")), file="sub.sdf", sep="\n")

Table of Contents


Working with SDF/SDFset Classes


## Inspecting content of SDF/SDFset objects
view(sdfset[1:4]) # Summary view of several molecules in SDFset object
length(sdfset) # Returns number of molecules stored in object
sdfset[[1]] # Returns single molecule from SDFset as SDF object
sdfset[[1]][[2]] # Returns atom block from first compound as matrix
sdfset[[1]][[2]][1:4,] # Returns first four rows of atom block from first compound
c(sdfset[1:4], sdfset[5:8]) # Concatenation of several SDFsets; is currently limited to two arguments!

## String searching in SDFsets
grepSDFset("650001", sdfset, field="datablock", mode="subset") # To return index, set mode="index")

## Compound IDs
sdfid(sdfset[1:4]) # Retrieves CMP IDs from Molecule Name field in header block.
cid(sdfset[1:4]) # Retrieves CMP IDs from ID slot in SDFset.
unique_ids <- makeUnique(sdfid(sdfset)) # Creates unique IDs by appending a counter to duplicates.
cid(sdfset) <- unique_ids # Assigns uniquified IDs to ID slot

## Subsetting by character, index and logical vectors
view(sdfset[c("650001", "650012")])
view(sdfset[4:1])
mylog <- cid(sdfset) %in% c("650001", "650012"); view(sdfset[mylog])

## Accessing SDF/SDFset components: header, atom, bond and data blocks
atomblock(sdf); sdf[[2]]; sdf[["atomblock"]] # all three methods return the same component
header(sdfset[1:4]); atomblock(sdfset[1:4]); bondblock(sdfset[1:4]); datablock(sdfset[1:4])
header(sdfset[[1]]); atomblock(sdfset[[1]]); bondblock(sdfset[[1]]); datablock(sdfset[[1]])

## Replacement Methods
sdfset[[1]][[2]][1,1] <- 999
atomblock(sdfset)[1] <- atomblock(sdfset)[2]

datablock(sdfset)[1] <- datablock(sdfset)[2]

## Assign matrix data to data block
datablock(sdfset) <- as.matrix(iris[1:100,])
view(sdfset[1:4])


## Class Coercions
## (a) From SDFstr to list, SDF and SDFset
as(sdfstr[1:2], "list") 
as(sdfstr[[1]], "SDF")
as(sdfstr[1:2], "SDFset")

## (b) From SDF to SDFstr, SDFset, list with SDF sub-components
sdfcomplist <- as(sdf, "list")
sdfcomplist <- as(sdfset[1:4], "list"); as(sdfcomplist[[1]], "SDF")
sdflist <- as(sdfset[1:4], "SDF"); as(sdflist, "SDFset")
as(sdfset[[1]], "SDFstr")
as(sdfset[[1]], "SDFset")

## (c) From SDFset to lists with components consisting of SDF or sub-components
as(sdfset[1:4], "SDF")
as(sdfset[1:4], "list")
as(sdfset[1:4], "SDFstr")

Molecular Property Functions (Physicochemical Descriptors)

Several methods and functions are available to compute basic compound descriptors, such as molecular formula (MF), molecular weight (MW) and atom frequencies. In all these functions, it is important to set addH=TRUE in order to include/add hydrogens that are often not specified in an SD file.

## Create atom frequency matrix
propma <- atomcountMA(sdfset, addH=FALSE)
boxplot(propma, main="Atom Frequency")
boxplot(rowSums(propma), main="All Atom Frequency")   

## Data frame provided by library containing atom names, atom symbols,
## standard atomic weights and group/period numbers
data(atomprop)
atomprop[1:4,]

  Number      Name Symbol Atomic_weight Group Period
1      1  hydrogen      H      1.007940     1      1
2      2    helium     He      4.002602    18      1
3      3   lithium     Li      6.941000     1      2
4      4 beryllium     Be      9.012182     2      2

## Compute MW and formula
MW(sdfset[1:4], addH=TRUE)

    CMP1     CMP2     CMP3     CMP4
456.4916 357.4069 370.4255 461.5346

MF(sdfset[1:4], addH=TRUE)

         CMP1          CMP2          CMP3          CMP4
 "C23H28N4O6"  "C18H23N5O3" "C18H18N4O3S" "C21H27N5O5S"

## Enumerate functional groups
groups(sdfset[1:4], groups="fctgroup", type="countMA")

     RNH2 R2NH R3N ROPO3 ROH RCHO RCOR RCOOH RCOOR ROR
CMP1    0    2   1     0   0    0    0     0     0   2
CMP2    0    2   2     0   1    0    0     0     0   0
CMP3    0    1   1     0   1    0    1     0     0   0
CMP4    0    1   3     0   0    0    0     0     0   2

## Combine MW, MF, charges, atom counts, functional group counts and ring counts in one data frame
propma <- data.frame(MF=MF(sdfset, addH=FALSE), MW=MW(sdfset, addH=FALSE),
                     Ncharges=sapply(bonds(sdfset, type="charge"), length),
                     atomcountMA(sdfset, addH=FALSE),
                     groups(sdfset, type="countMA"),
                     rings(sdfset, upper=6, type="count", arom=TRUE))

propma[1:4,]

              MF       MW Ncharges  C  H N O S F Cl RNH2 R2NH R3N ROPO3 ROH RCHO RCOR RCOOH RCOOR ROR RINGS AROMATIC
CMP1  C23H28N4O6 456.4916        0 23 28 4 6 0 0  0    0    2   1     0   0    0    0     0     0   2     4        2
CMP2  C18H23N5O3 357.4069        0 18 23 5 3 0 0  0    0    2   2     0   1    0    0     0     0   0     3        3
CMP3 C18H18N4O3S 370.4255        0 18 18 4 3 1 0  0    0    1   1     0   1    0    1     0     0   0     4        2
CMP4 C21H27N5O5S 461.5346        0 21 27 5 5 1 0  0    0    1   3     0   0    0    0     0     0   2     3        3

## Assign properties to data block
datablock(sdfset) <- propma # Works with all SDF components
test <- apply(propma[1:4,], 1, function(x) data.frame(col=colnames(propma), value=x))
sdf.visualize(sdfset[1:4], extra = test)

## Extracting data block elements by tag name
datablocktag(sdfset, tag="PUBCHEM_NIST_INCHI")
datablocktag(sdfset, tag="PUBCHEM_OPENEYE_CAN_SMILES")

## Convert entire data block to matrix
blockmatrix <- datablock2ma(datablocklist=datablock(sdfset)) # Converts data block to matrix 
numchar <- splitNumChar(blockmatrix=blockmatrix)
# Splits matrix to numeric matrix and character matrix
numchar[[1]][1:4,]; numchar[[2]][1:4,] # Splits matrix to numeric matrix and character matrix


Bond Matrices

Bond matrices provide an efficient data structure for many basic computations on small molecules. The function conMA creates this data structure from SDF and SDFset objects. The resulting matrix contains the atom labels in the row/column titles and the bond types in the data part. Their values are defined as follows: 0 is no connection, 1 is a single bond, 2 is a double bond and 3 is a triple bond.

## Create bond matrix for one or many molecules in an SDFset object
conMA(sdfset[1:2], exclude=c("H"))

## Return bond matrix for first molecule and plot its structure with atom numbering
conMA(sdfset[[82]], exclude="H")

     O_1 O_2 N_3 N_4 C_5 C_6 C_7 C_8 C_9 C_10
O_1    0   0   0   0   0   0   0   0   0    1
O_2    0   0   0   0   0   0   0   0   0    2
N_3    0   0   0   0   1   1   1   0   0    0
N_4    0   0   0   0   0   2   0   0   1    0
C_5    0   0   1   0   0   0   0   0   0    1
C_6    0   0   1   2   0   0   0   1   0    0
C_7    0   0   1   0   0   0   0   0   2    0
C_8    0   0   0   0   0   1   0   0   0    0
C_9    0   0   0   1   0   0   2   0   0    0
C_10   1   2   0   0   1   0   0   0   0    0

plot(sdfset[82], atomnum = TRUE, noHbonds=FALSE , no_print_atoms = "")

## Return number of non-H bonds for each atom of a single molecule
rowSums(conMA(sdfset[[82]], exclude=c("H")))


 O_1  O_2  N_3  N_4  C_5  C_6  C_7  C_8  C_9 C_10
   1    2    3    3    2    4    3    1    3    4

##
Return number of non-H bonds for all molecules in sdfset
sapply(cid(sdfset), function(x) rowSums(conMA(sdfset[[x]], exclude=c("H"))))

Table of Contents


Charges and Hydrogens

The function bonds returns information about the number of bonds, charges and missing hydrogens in SDF and SDFset objects. It is used by many other functions (e.g. MW, MF, atomcount, atomcuntMA and plot) to correct for missing hydrogens that are often not explicitly specified in SD files.

## Return data frame(s) with bonds and charges
bonds(sdfset[[1]], type="bonds")[1:20,]

   atom Nbondcount Nbondrule charge
1     C          4         4      0
2     C          4         4      0
3     C          4         4      0
4     C          3         4      0
5     C          4         4      0
6     C          3         4      0
7     N          3         3      0
8     C          4         4      0
9     C          4         4      0
10    C          2         4      0
11    C          3         4      0
12    N          2         3      0
13    C          2         4      0
14    N          2         3      0
15    C          4         4      0
16    C          4         4      0
17    C          4         4      0
18    C          3         4      0
19    C          3         4      0
20    O          2         2      0
...


## Returns charged atoms in each molecule
bonds(sdfset[1:2], type="charge")

$CMP1
NULL

$CMP2
NULL

## Returns the number of missing hydrogens in each molecule
bonds(sdfset[1:2], type="addNH")

CMP1 CMP2
   0    0


Table of Contents

Ring Perception and Aromaticity Assignment

The function rings identifies all possible rings in one or many molecules using the exhaustive ring perception algorithm from Hanser et al. (1996). In addition, the function can return all smallest possible rings as well as aromaticity information.

The following example returns all possible rings in a list. The argument upper allows to specify an upper length limit for rings. Choosing smaller length limits will reduce the search space resulting in shortened compute times. Note: each ring is represented by a character vector of atom symbols that are numbered by their position in the atom block of the corresponding SDF/SDFset object.

## Return ring information for one compound
rings(sdfset[1], upper=Inf, type="all", arom=FALSE, inner=FALSE)

$ring1
[1] "N_10" "O_6"  "C_32" "C_31" "C_30"

$ring2
[1] "C_12" "C_14" "C_15" "C_13" "C_11"

$ring3
[1] "C_23" "O_2"  "C_27" "C_28" "O_3"  "C_25"

$ring4
[1] "C_23" "C_21" "C_18" "C_22" "C_26" "C_25"

$ring5
 [1] "O_3"  "C_28" "C_27" "O_2"  "C_23" "C_21" "C_18" "C_22" "C_26" "C_25"

## For visual inspection, the corresponding compound structure can be plotted with the same atom numbers as the rings.
plot(sdfset[1], print=FALSE, atomnum=TRUE, no_print_atoms="H")




## Aromaticity information of rings can be returned in a logical vector by setting arom=TRUE
rings(sdfset[1], upper=Inf, type="all", arom=TRUE, inner=FALSE)

$RINGS
$RINGS$ring1
[1] "N_10" "O_6"  "C_32" "C_31" "C_30"

$RINGS$ring2
[1] "C_12" "C_14" "C_15" "C_13" "C_11"

$RINGS$ring3
[1] "C_23" "O_2"  "C_27" "C_28" "O_3"  "C_25"

$RINGS$ring4
[1] "C_23" "C_21" "C_18" "C_22" "C_26" "C_25"

$RINGS$ring5
 [1] "O_3"  "C_28" "C_27" "O_2"  "C_23" "C_21" "C_18" "C_22" "C_26" "C_25"


$AROMATIC
ring1 ring2 ring3 ring4 ring5
 TRUE FALSE FALSE  TRUE FALSE

## Return rings with no more than 6 atoms that are also aromatic
rings(sdfset[1], upper=6, type="arom", arom=TRUE, inner=FALSE)

$AROMATIC_RINGS
$AROMATIC_RINGS$ring1
[1] "N_10" "O_6"  "C_32" "C_31" "C_30"

$AROMATIC_RINGS$ring4
[1] "C_23" "C_21" "C_18" "C_22" "C_26" "C_25"

## Count shortest possible rings and their aromaticity assignments by setting type=count and inner=TRUE. The inner (smallest possible) rings are identified by first computing all possible rings and then selecting only the inner rings. For more details, consult the help documentation with ?rings.
rings(sdfset[1:4], upper=Inf, type="count", arom=TRUE, inner=TRUE)

     RINGS AROMATIC
CMP1     4        2
CMP2     3        3
CMP3     4        2
CMP4     3        3



Rendering Chemical Structure Images

R Graphics Device

A new plotting function for compound structures has been added to the package recently. This function uses the native R graphics device for generating compound depictions. At this point this function is still in an experimental developmental stage but should become stable soon. 

## Plot CMP Structures with R graphics device
plot(sdfset[1:4]) # Plots one to many molecules
plotStruc(sdfset[[1]]) # Only for single molecule



Figure 2: Structure Rendering with R's Graphics Device

## Customized plots
plot(sdfset[1:4], griddim=c(2,2), print_cid=letters[1:4], print=FALSE, noHbonds=FALSE)
plot(sdfset[1], atomnum = TRUE, noHbonds=F , no_print_atoms = "", atomcex=0.8, sub=paste("MW:", MW(sdfsample["CMP1"])))


Figure 3: Detailed Structure View

Table of Contents

Online with ChemMine Tools

Alternatively, one can visualize compound structures with a standard web browser using the online ChemMine Tools service. The service allows to display other information next to the structures using the extra argument of the sdf.visualize function. The following examples demonstrate, how one can plot and annotate structures by passing on extra data as vector of character strings, matrices or lists. 

## Plot structures using web service ChemMine Tools
sdf.visualize(sdfset[1:4]

## Add extra annotation as vector
sdf.visualize(sdfset[1:4], extra=month.name[1:4])

## Add extra annotation as matrix
extra <- apply(propma[1:4,], 1, function(x) data.frame(Property=colnames(propma), Value=x))
sdf.visualize(sdfset[1:4], extra=extra)

## Add extra annotation as list
sdf.visualize(sdfset[1:4], extra=bondblock(sdfset[1:4]))





Figure 4: Visualizing Structures and Tabular Data with sdf.visualize

Similarity Comparisons and Searching

AP/APset Classes for Storing Atom Pair Descriptors

The function sdf2ap computes atom pair descriptors for one or many compounds. It returns a searchable atom pair database stored in a container of class APset, which can be used for structural similarity searching and clustering. An APset object consists of one or many AP entries each storing the atom pairs of a single compound. Note: the deprecated cmp.parse function is still available which also generates atom pair descriptor databases, but directly from an SD file. Since the latter function is less flexible it may be discontinued in the future.

## Samples of SDFset/SDF classes
data(sdfsample)
sdfset <- sdfsample[1:50]
sdf <- sdfsample[[1]]
    
## Compute atom pair library
ap <- sdf2ap(sdf)
# apset <- sdf2ap(sdfset)
data(apset)
view(apset[1:4])
    
## Return main components of APset object
cid(apset[1:4]) # Compound IDs
ap(apset[1:4]) # Atom pair descriptors
    
## Return atom pairs in human readable format
db.explain(apset[1])
    
## Coerce APset to other objects
apset2descdb(apset) # Returns old list-style AP database
tmp <- as(apset, "list") # Returns list
as(tmp, "APset") # Converst list back to APset

## Generate atom pair database directly from SD file

## Note: this approach is less generic and may be discontinued in the future
apold <- cmp.parse("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")


## Construct
APset class from apold
aplist <- apold[[1]]; names(aplist) <- apold[[2]]
apset <- as(aplist, "APset")
view(apset[1:4])

Large SDF and Atom Pair Databases

When working with large data sets it is often desirable to save the SDFset and APset containers as binary R objects to files for later use. This way they can be loaded very quickly into a new R session without recreating them every time from scratch.    

## Save an load of SDFset
save(sdfset, file = "sdfset.rda", compress = TRUE)
load("sdfset.rda")

## Save and load of APset
save(apset, file = "apset.rda", compress = TRUE)
load("apset.rda")


Pairwise Compound Comparisons with Atom Pairs

The cmp.similarity function computes the atom pair similarity between two compounds using the Tanimoto coefficient as similarity measure. This coefficient is defined as c/(a+b+c), which is the proportion of the atom pairs shared among two compounds divided by their union. The variable c is the number of atom pairs common in both compounds, while a and b are the numbers of their unique atom pairs.

## Compute similarities among two compounds
cmp.similarity(apset[1], apset[2])
cmp.similarity(apset[1], apset[1])

## Run cmp.similarity in loop as custom similarity search function
sapply(cid(apset), function(x) cmp.similarity(apset[1], apset[x]))


Pairwise Compound Comparisons with PubChem Fingerprints

The fpSim function computes the Tanimoto coefficients for pairwise comparisons of binary fingerprints. For this data type, c is the number of "on-bits" common in both compounds, and a and b are the numbers of their unique "on-bits". Currently, the PubChem fingerprints need to be provided (here PubChem's SD files) and cannot be computed from scratch in ChemmineR. The PubChem fingerprint specifications are available here. They can be loaded into R with: data(pubchemFPencoding).

## Convert base 64 encoded fingerprints to character vector or binary matrix
fpset <- fp2bit(x=sdfset, type=1)
fpset <- fp2bit(x=sdfset, type=2)
    
## Pairwise compound structure comparisons
fpSim(x=fpset[1,], y=fpset[2,])

[1] 0.5344828

Similarity Searching with Atom Pairs

The cmp.search function searches an atom pair database for compounds that are similar to a query compound. The following example returns a data frame where the rows are sorted by the Tanimoto similarity score (best to worst). The first column contains the indices of the matching compounds in the database. The argument cutoff can be a similarity cutoff, meaning only compounds with a similarity value larger than this cutoff will be returned; or it can be an integer value restricting how many compounds will be returned. When supplying a cutoff of 0, the function will return the similarity values for every compound in the database.

cmp.search(apset, apset["650065"], type=1, cutoff = 0.3) # Returns index of matches if 'type=1'.

cmp.search(apset, apset["650065"], type=2, cutoff = 0.3)
# Returns matches as named vector with compound IDs if 'type=2'.

cmp.search(apset, apset["650065"], type=3, cutoff = 0.3)
# Returns matches as data frame if 'type=3'.

  index    cid    scores
1    61 650066 1.0000000
2    60 650065 1.0000000
3    67 650072 0.3389831
4    11 650011 0.3190608
5    15 650015 0.3184524
6    86 650092 0.3154270
7    64 650069 0.3010279
Table of Contents

Similarity Searching with PubChem Fingerprints

Similarly, the fpSim function provides search functionality for PubChem fingerprints.

fpSim(x=fpset["650065",], y=fpset)[1:6] # x is query and y is fingerprint database

   650065    650066    650035    650019    650012    650046
1.0000000 0.9944444 0.7422680 0.7420814 0.7216981 0.7129187



Visualize Similarity Search Results

The cmp.search function allows to visualize the chemical structures for the search results. Similar but more flexible chemical structure rendering functions are plot and sdf.visualize described above. By setting the visualize argument in cmp.search to TRUE, the matching compounds and their scores can be visualized with a standard web browser. Depending on the visualize.browse argument, an URL will be printed or a webpage will be opened showing the structures of the matching compounds along with their scores.

## R Graphics device
plot(sdfset[names(cmp.search(apset, apset[6], type=2, cutoff=4))])

## Online on Chemmine Tools

similarities <- cmp.search(apset, apset[1], type=3, cutoff = 10)
sdf.visualize(sdfset[similarities[,1]], extra=similarities[,3])

## Same result in one step
## Note works only with old AP object; this will be fixed asap!!
apold <- cmp.parse("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")
similarities <- cmp.search(apold, apold[[1]][[2]], cutoff = 10, quiet = TRUE, visualize = TRUE)



Figure 5: Structure Similarity Search Result

Clustering

Clustering Identical or Very Similar Compounds

Often it is of interest to identify very similar or identical compounds in a compound set. The cmp.duplicated function can be used to quickly identify very similar compounds in compound sets, which will be frequently, but not necessarily, identical compounds.

## Identify compounds with identical AP sets
cmp.duplicated(apset, type=1) # Returns AP duplicate information in logical vector
cmp.duplicated(apset, type=2) # Returns AP duplicate information as data frame

## Remove AP duplicates from SDFset and APset objects
apdups <- cmp.duplicated(apset, type=1)
sdfset[which(!apdups)]; apset[which(!apdups)]


Alternatively, one can identify duplicates via other descriptor types if they are provided in the data block of an imported SD file. For instance, one can use here fingerprints, InChI, SMILES or other molecular representations.

table(datablocktag(sdfset, tag="PUBCHEM_NIST_INCHI")) # Enumerate identical InChI strings
table(datablocktag(sdfset, tag="PUBCHEM_OPENEYE_CAN_SMILES")) # Enumerate identical SMILES strings
table(datablocktag(sdfset, tag="PUBCHEM_MOLECULAR_FORMULA")) # Enumerate identical molecular formulas

Binning Clustering

Compound libraries can be clustered into discrete similarity groups with the binning clustering function cmp.cluster. The function requires as input a descriptor database as well as a similarity threshold. The binning clustering result is returned in form of a data frame. Single linkage is used for cluster joining. The function calculates the required compound-to-compound distance information on the fly, while a memory-intensive distance matrix is only created upon user request via the save.distances argument (see below).

Because an optimum similarity threshold is often not known, the cmp.cluster function can calculate cluster results for multiple cutoffs in one step with almost the same speed as for a single cutoff. This can be achieved by providing several cutoffs under the cutoff argument. The clustering results for the different cutoffs will be stored in one data frame.

## Single-linkage binning clustering with one or multiple cutoffs
clusters <- cmp.cluster(db=apset, cutoff = c(0.65, 0.5, 0.4), quiet = TRUE) # Cutoffs can be changed under the 'cutoff' argument

## Return cluster size distributions for each cutoff
cluster.sizestat(clusters, cluster.result=1)
cluster.sizestat(clusters, cluster.result=2)
cluster.sizestat(clusters, cluster.result=3)

## Force calculation of distance matrix
clusters <- cmp.cluster(db=apset, cutoff = c(0.65, 0.5, 0.3), save.distances="distmat.rda") # Saves distance matrix to file "
distmat.rda" in current working directory.
load("distmat.rda") # Loads distance matrix into workspace

One may force the cmp.cluster function to calculate and store the distance matrix by supplying a file name to the save.distances argument. The generated distance matrix can be loaded and passed on to many other clustering methods available in R, such as the hierarchical clustering function hclust (see below).

If a distance matrix is available, it may also be supplied to cmp.cluster via the use.distances argument. This is useful when one has a pre-computed distance matrix either from a previous call to cmp.cluster or from other distance calculation subroutines.

Multi-Dimensional Scaling (MDS)

To visualize and compare clustering results, the cluster.visualize function can be used. The function performs Multi-Dimensional Scaling (MDS) and visualizes the results in form of a scatter plot. It requires as input an APset, a clustering result from cmp.cluster, and a cutoff for the minimum cluster size to consider in the plot. To help determining a proper cutoff size, the cluster.sizestat function is provided to generate cluster size statistics.

## MDS clustering and scatter plot
cluster.visualize(apset, clusters, size.cutoff=2, quiet = TRUE) # Color codes clusters with at least two members.

cluster.visualize(apset, clusters, size.cutoff=1, quiet = TRUE) # Plots all items

# Create a 3D scatter plot of MDS result
coord <- cluster.visualize(apset, clusters, size.cutoff=1, dimensions=3, quiet=TRUE)
library(scatterplot3d)
scatterplot3d(coord)

# Interactive 3D scatter plot with Open GL
# The rgl library needs to be installed for this.
library(rgl)
rgl.open(); offset <- 50; par3d(windowRect=c(offset, offset, 640+offset, 640+offset))
rm(offset); rgl.clear(); rgl.viewpoint(theta=45, phi=30, fov=60, zoom=1)
spheres3d(coord[,1], coord[,2], coord[,3], radius=0.03, color=coord[,4], alpha=1, shininess=20); aspect3d(1, 1, 1)
axes3d(col='black'); title3d("", "", "", "", "", col='black'); bg3d("white") #
To save a snapshot of the graph, one can use the command rgl.snapshot("test.png")

The data returned by the cluster.visualize can also be inspected with the fully interactive rggobi data visulalization system. The GGobi software and its dependencies can be obtained from the GGobi project site. The following commands demonstrate the import of the generated MDS data set into rggobi.

library(rggobi)
ggobi(coord)




Figure 6:
Clustering Results Visualized with the R Packages scatterplot3d and rggob

Clustering with Other Algorithms

ChemmineR allows the user to take advantage of the wide spectrum of clustering utilities available in R. An example on how to perform hierarchical clustering with the hclust function is given below.

Hierarchical Clustering

Using Atom Pairs
## Create atom pair distance matrix
dummy <- cmp.cluster(db=apset, cutoff=0, save.distances="distmat.rda")
load("distmat.rda")

# Hierarchical Clustering with hclust
hc <- hclust(as.dist(distmat), method="single")
hc[["labels"]] <- cid(apset) # Assign correct item labels
plot(as.dendrogram(hc), edgePar=list(col=4, lwd=2), horiz=T) # Plots hierarchical clustering tree.
Figure 7: Hierarchical Clustering Tree for Compound Similarities


## Plot dendrogram with heatmap (here similarity matrix)
library(gplots)
heatmap.2(1-distmat, Rowv=as.dendrogram(hc), Colv=as.dendrogram(hc), col=colorpanel(40, "darkblue", "yellow", "white"), density.info="none", trace="none")

Figure 8: Hierarchical Clustering Result with Heatmap



Using PubChem Fingerprints
## Convert base 64 encoded fingerprints to character vector or binary matrix
fpset <- fp2bit(x=sdfset, type=2)
    
## Compute fingerprint based Tanimoto similarity matrix
simMA <- sapply(rownames(fpset), function(x) fpSim(x=fpset[x,], fpset))
    
## Hierarchical clustering with simMA as input
hc <- hclust(as.dist(simMA), method="single")
    
## Plot hierarchical clustering tree
plot(as.dendrogram(hc), edgePar=list(col=4, lwd=2), horiz=TRUE)


Searching PubChem

These features require internet connectivity as the ChemMine Tools web service is used as an intermediate, to translate queries from plain HTTP POST to a PUG SOAP query.

Get Compounds from PubChem by Id

The function getIds accepts one or more numeric PubChem compound ids and downloads the corresponding compounds from PubChem Power User Gateway (PUG) returning results in an SDFset container.

## Fetch 2 compounds from PubChem
compounds <- getIds(c(111,123))
compounds

Similarity Search of PubChem with SMILES Query

The function searchString accepts one SMILES (Simplified Molecular Input Line Entry Specification) string and performs a >0.95 similarity PubChem fingerprint search, returning the hits in an SDFset container. 

## Search a SMILES string on PubChem
compounds <- searchString("CC(=O)OC1=CC=CC=C1C(=O)O")
compounds

Similarity Search of PubChem with SDF Query

The function searchSim performs a PubChem similarity search just like searchString, but accepts a query in an SDFset container. If the query contains more than one compound, only the first is searched.

## Search an SDFset container on PubChem
data(sdfsample); sdfset <- sdfsample[1]
compounds <- searchSim(sdfset)
compounds

Format Interconversions


The sdf2smiles and smiles2sdf functions provide format interconversion between SMILES strings (Simplified Molecular Input Line Entry Specification) and SDFset containers. Currently these functions are limited to a single compound at a time. These functions require internet connectivity, as they rely on the ChemMine Tools web service for conversion with the Open Babel Open Source Chemistry Toolbox.


## Convert an SDFset container to a SMILES character string
data(sdfsample); sdfset <- sdfsample[1]
smiles <- sdf2smiles(sdfset)
smiles

                                                  650001
"O=C(NC1CCCC1)CN(c1cc2OCCOc2cc1)C(=O)CCC(=O)Nc1noc(c1)C"
    
## Convert a SMILES character string to an SDFset container
sdf <- smiles2sdf("CC(=O)OC1=CC=CC=C1C(=O)O\tname")
view(sdf)


Biological Screen Analysis


This example uses an experimental software package, "bioassayR" that has not yet been publically released. The example currently only works from the UC Riverside biocluster system.

This library is designed for analyzing biological screen data, and comes loaded with all screens that target known proteins from PubChem Bioassay.

Users can access the data directly using SQL commands against the three built in tables (bioassay, proteins, sequences) or with one of the wrapper functions shown.

library(bioassayR)

## Show the first 10 rows in the "bioassay" database table using SQL
query(bioassay, "select * from bioassay limit 10")
# Activity key: 1=inactive, 2=active, 3=inconclusive, 4=unspecified


## Show the first 10 rows, joined with their target amino acid sequences using SQL
query(bioassay, "SELECT * FROM bioassay INNER JOIN (SELECT * FROM proteins INNER JOIN sequences USING (protein_target)) USING (aid) limit 10")

## Get a data frame of bioactivity data from a given assay

assay(bioassay, 348)

## Output the protein target for a given assay
protein(bioassay, 348)

## Get SDF file of all compounds from a given assay (#1000 in this example)
library(ChemmineR)
mySDFset <- getIds(as.numeric(assay(bioassay, 1000)$cid))


## Summarize data in database (VERY slow)
bioassay

Session Information


> sessionInfo()

R version 2.13.0 (2011-04-13)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base    

other attached packages:
[1] ChemmineR_2.4.4

loaded via a namespace (and not attached):
[1] RCurl_1.5-0  tools_2.13.0

Exercises


## Download and import the following SD file
## Sample data set contains first 100 compounds from PubChem SD file "Compound_00650001_00675000.sdf.gz"
## from: ftp://ftp.ncbi.nih.gov/pubchem/Compound/CURRENT-Full/SDF/

library(ChemmineR)
sdfset <- read.SDFset("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/Samples/sdfsample.sdf")

## Assign compound IDs from SD file to ID slot in SDFset
cid(sdfset) <- sdfid(sdfset)
view(sdfset[1:4])


## Write the data back to an SD file where the order of the SDF entries is reversed and the data block omitted
write.SDF(sdfset[100:1], file="sub.sdf", sig=TRUE, cid=TRUE, db=NULL)


## Write the first 10 compounds to separate SD files using a loop (e.g. for or sapply)
sapply(cid(sdfset[1:10]), function(x)
write.SDF(sdfset[x], file=paste(x, "sdf", sep="")))
for(i in cid(sdfset[1:10])) write.SDF(sdfset[i], file=paste(i, "sdf", sep=""))

##
Extract the numeric and character values from the data block of the SD file
blockmatrix <- datablock2ma(datablocklist=datablock(sdfset)
numchar <- splitNumChar(
blockmatrix=blockmatrix)

## Save the two data frames to external files for import into a spreadsheet program.
write.table(numchar[[1]], "numeric_val.xls", sep="\t", col.names = NA)
write.table(numchar[[2]], "character_val.xls", sep="\t", col.names = NA)

## Generate a box plot for columns 4 to 6 of the numeric data block and save it to a file
boxplot(numchar[[1]][,4:6])

## Generate a data frame containing of each compound its molecular formula, MW and atom frequencies
propma <- data.frame(MF=MF(sdfset), MW=MW(sdfset), atomcountMA(sdfset))
propma[1:4,]

## Inject the previous data frame into the data block of the SDFset and export it to a SD file
datablock(sdfset) <- propma
write.SDF(sdfset, file="sub.sdf")

## Append to the object propma microtiter plate location information and then repeat the inject/export step
## The plate locations can be created with these commands:
source("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/384_96_48_24conversion.txt")
propma2 <- data.frame(
my_plate_mappings[1:100,], propma)
datablock(sdfset) <- propma2
write.SDF(sdfset, file="sub.sdf")

## Visualize the first four compounds along with their tabular data with ChemMine Tools

extra <- apply(propma2[1:4,], 1, function(x) data.frame(Property=colnames(propma2), Value=x))
sdf.visualize(sdfset[1:4], extra = extra)

## Compute atom pair descriptors for sdfset
apset <- sdf2ap(sdfset)

## Cluster the compounds with cmp.cluster using cutoff values of
0.65, 0.5, 0.3
clusters <- cmp.cluster(db=apset, cutoff = c(0.65, 0.5, 0.3), save.distances="distmat.rda")

## Perform hierarchical clustering using the distance matrix from the previous step
load("distmat.rda")
hc <- hclust(as.dist(distmat), method="single")
hc[["labels"]] <- cid(apset) # Assign correct item labels
plot(as.dendrogram(hc), edgePar=list(col=4, lwd=2), horiz=T)

## First, compare the results in clusters and the hierarchical tree visually; then
## use the cutree function to identify discrete clusters in the tree and
## join them with the clusters from the binning clustering.
mycl <- cutree(hc, h=max(hc$height)/1.5)
cbind(clusters, hclust=mycl[clusters$ids])[1:10,]


FAQs

Q1: How many compounds can I cluster with cmp.cluster?
 
This depends on the amount of memory on your computer, the speed of your CPU and the cutoff parameters. As a rough time estimate: the clustering of 500 compounds takes only a few miniutes and the clustering of 10,000 compunds several hours. By default, the binning clustering function provided by ChemmineR does not store the distance matrix, and therefore it is very memory efficient.

Q2: Can I import compound structures as SMILES strings?

Batch import will be provided in the future. At this point, SMILES strings can be imported into ChemMineR indirectly by converting them into SDFs via ChemMine's online WorkBench. You can also import single compounds with the smiles2sdf() function (see section on Format Interconversion).


References

  1. T W Backman, Y Cao, and T Girke. ChemMine tools: an online service for analyzing and clustering small molecules. Nucleic Acids Res, 39 (Web Server issue): 486–491. HubMed
  2. R.E. Carhart, D.H. Smith, and R. Venkataraghavan. Atom pairs as molecular features in structure-activity studies: definition and applications. Journal of Chemical Information and Computer Sciences, 25(2):64 73, 1985.
  3. X. Chen and C.H. Reynolds. Performance of Similarity Measures in 2D Fragment-Based Similarity Searching: Comparison of Structural Descriptors and Similarity Coefficients. Journal of Chemical Information and Computer Sciences, 42(6):1407 1414, 2002.
  4. T. Girke, L.C. Cheng, and N. Raikhel. ChemMine. A Compound Mining Database for Chemical Genomics.  Plant Physiol, 138(2):573-577, 2005.
  5.  Cao Y, Charisi A, Cheng LC, Jiang T, Girke T (2008) ChemmineR: A Compound Mining Framework for R.  Bioinformatics, 24(15): 1733-1734, 2008. HubMed.
  6. Th. Hanser, Ph. Jauffret, and G. Kaufmann. A new algorithm for exhaustive ring perception in a molecular graph. Journal of Chemical Information and Computer Sciences, 36(6): 1146–1152. URL




This site was accessed tumblr analytics times (Detailed Access Stats)