Skip to content

Instantly share code, notes, and snippets.

@mbohun
Created July 17, 2012 03:48
Show Gist options
  • Save mbohun/3126926 to your computer and use it in GitHub Desktop.
Save mbohun/3126926 to your computer and use it in GitHub Desktop.
Martin Bohun's SMILES tokenizer (re-formatted by JSLint)
var smiles_tokenize = (function () {
"use strict";
var PTE = [
"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na",
"Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti",
"V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge",
"As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo",
"Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te",
"I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm",
"Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf",
"Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb",
"Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U",
"Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No",
"Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn",
"Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo"
],
special = [ //aromatic: C, N, O, P, S, As, Se, and *
"(", ")", "[", "]", "=", "#", "@", "*", "%", "1", "2", "3", "4",
"5", "6", "7", "8", "9", ".", "/", "\\", "+", "-", "c", "n",
"o"
],
table = PTE.sort().reverse().concat(special),
match_symbol = function (smiles, offset, tokens) {
var i, symbol;
for (i = 0; i < table.length; i += 1) {
symbol = table[i];
if (symbol === smiles.substr(offset, symbol.length)) {
tokens.push(symbol);
return symbol.length;
}
}
return 0;
};
return function (smiles) {
var tok = [],
i = 0,
match = 0;
while (i < smiles.length) {
match = match_symbol(smiles, i, tok);
if (match > 0) {
i = i + match;
} else {
print("smiles_tokenize error - no match[" + i + "]:"
+ smiles.substr(i, 1));
i = i + 1;
}
}
return tok;
};
}()),
smiles,
i,
read_file;
// spidermonkey (1.8.5) requires the explicit this.hasOwnProperty
print("read():" + this.hasOwnProperty("read"));
print("readFile():" + this.hasOwnProperty("readFile"));
if (this.hasOwnProperty("read")) {
read_file = read;
}
if (this.hasOwnProperty("readFile")) {
read_file = readFile;
}
// what if read_file is udnefined?
// print(typeof read_file);
smiles = read_file("data.smi").trim().split("\n");
for (i = 0; i < smiles.length; i += 1) {
print("smiles[" + i + "]:" + smiles[i]
+ " " + smiles_tokenize(smiles[i]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment