{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "RDKit WARNING: [11:02:29] Enabling RDKit 2020.03.1dev1 jupyter extensions\n"
     ]
    }
   ],
   "source": [
    "from rdkit import Chem\n",
    "from rdkit.Chem import Draw\n",
    "from rdkit.Chem.Draw import IPythonConsole\n",
    "from rdkit.Chem.Scaffolds import rdScaffoldNetwork"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 15992 characters]\n",
      "text/plain": [
       "<rdkit.Chem.rdchem.Mol at 0x7f7be08cf170>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Flucloxacillin\n",
    "m = Chem.MolFromSmiles('Cc1onc(-c2c(F)cccc2Cl)c1C(=O)N[C@@H]1C(=O)N2[C@@H](C(=O)O)C(C)(C)S[C@H]12')\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<rdkit.Chem.Scaffolds.rdScaffoldNetwork.NetworkEdge_VECT object at 0x7f7be08cfa30>\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 60320 characters]\n",
      "text/plain": [
       "<PIL.PngImagePlugin.PngImageFile image mode=RGB size=800x600 at 0x7F7BE08DF2E8>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "params = rdScaffoldNetwork.ScaffoldNetworkParams()\n",
    "params.includeGenericScaffolds = True\n",
    "params.includeScaffoldsWithoutAttachments = False\n",
    "net = rdScaffoldNetwork.CreateScaffoldNetwork([m],params)\n",
    "print(net.edges)\n",
    "nodemols = [Chem.MolFromSmiles(x) for x in net.nodes]\n",
    "Draw.MolsToGridImage(nodemols,legends=[str(x) for x in range(len(nodemols))],molsPerRow=4)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800px\"\n",
       "            height=\"600px\"\n",
       "            src=\"basic.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f7bde743908>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyvis.network import Network\n",
    "from urllib import parse\n",
    "g = Network(notebook=True,height='600px',width='800px')\n",
    "for i,smi in enumerate(net.nodes):\n",
    "    qsmi = parse.quote(smi)\n",
    "    imgurl = f\"https://mol-renderer2-dev.t5ix.io/to_img/mol.png?smiles={qsmi}&w=200&h=150\"\n",
    "    g.add_node(i,shape=\"image\",label=' ',\n",
    "               image =imgurl, title=f'<img src=\"{imgurl}\"/>')\n",
    "for e in net.edges:\n",
    "    g.add_edge(e.beginIdx,e.endIdx,label=str(e.type))\n",
    "g.show(\"basic.html\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## More complex example with multiple molecules"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 89960 characters]\n",
      "text/plain": [
       "<PIL.PngImagePlugin.PngImageFile image mode=RGB size=800x800 at 0x7F7BDE743E48>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Flucloxacillin\n",
    "flu = Chem.MolFromSmiles('Cc1onc(-c2c(F)cccc2Cl)c1C(=O)N[C@@H]1C(=O)N2[C@@H](C(=O)O)C(C)(C)S[C@H]12')\n",
    "# ampicillin\n",
    "amp = Chem.MolFromSmiles('CC1(C)S[C@@H]2[C@H](NC(=O)[C@H](N)c3ccccc3)C(=O)N2[C@H]1C(=O)O')\n",
    "# penicillin\n",
    "pen = Chem.MolFromSmiles('CC1(C)SC2C(NC(=O)Cc3ccccc3)C(=O)N2C1C(=O)O.[Na]')\n",
    "# oxacillin\n",
    "ox = Chem.MolFromSmiles('Cc1onc(-c2ccccc2)c1C(=O)N[C@@H]1C(=O)N2[C@@H](C(=O)O)C(C)(C)S[C@H]12')\n",
    "params = rdScaffoldNetwork.ScaffoldNetworkParams()\n",
    "params.includeGenericScaffolds = True\n",
    "params.includeScaffoldsWithoutAttachments = False\n",
    "net = rdScaffoldNetwork.CreateScaffoldNetwork([flu,amp,pen,ox],params)\n",
    "nodemols = [Chem.MolFromSmiles(x) for x in net.nodes]\n",
    "Draw.MolsToGridImage(nodemols,legends=[str(x) for x in range(len(nodemols))],molsPerRow=4)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800px\"\n",
       "            height=\"600px\"\n",
       "            src=\"multiple.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f7bde6e7550>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from collections import Counter\n",
    "maxCount = max(net.counts)\n",
    "g = Network(notebook=True,height='600px',width='800px')\n",
    "for i,smi in enumerate(net.nodes):\n",
    "    qsmi = parse.quote(smi)\n",
    "    imgurl = f\"https://mol-renderer2-dev.t5ix.io/to_img/mol.png?smiles={qsmi}&w=200&h=150\"\n",
    "    g.add_node(i,shape=\"image\",label=' ',\n",
    "               image =imgurl, title=f'<img src=\"{imgurl}\"/>', size=30*net.counts[i]/maxCount)\n",
    "for e in net.edges:\n",
    "    g.add_edge(e.beginIdx,e.endIdx,label=str(e.type))\n",
    "g.show(\"multiple.html\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800px\"\n",
       "            height=\"600px\"\n",
       "            src=\"simple.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f7bde743b38>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyvis.network import Network\n",
    "from urllib import parse\n",
    "\n",
    "m = Chem.MolFromSmiles('c1ccccc1CC1NC(=O)CCC1')\n",
    "\n",
    "params = rdScaffoldNetwork.ScaffoldNetworkParams()\n",
    "net = rdScaffoldNetwork.CreateScaffoldNetwork([m],params)\n",
    "nodemols = [Chem.MolFromSmiles(x) for x in net.nodes]\n",
    "from collections import Counter\n",
    "maxCount = max(net.counts)\n",
    "g = Network(notebook=True,height='600px',width='800px')\n",
    "for i,smi in enumerate(net.nodes):\n",
    "    qsmi = parse.quote(smi)\n",
    "    imgurl = f\"https://mol-renderer2-dev.t5ix.io/to_img/mol.png?smiles={qsmi}&w=200&h=150\"\n",
    "    g.add_node(i,shape=\"image\",label=' ',\n",
    "               image =imgurl, title=f'<img src=\"{imgurl}\"/>', size=30*net.counts[i]/maxCount)\n",
    "for e in net.edges:\n",
    "    g.add_edge(e.beginIdx,e.endIdx,label=str(e.type))\n",
    "g.show(\"simple.html\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type('fo')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mergeAttachPointsToAtoms(mol,propName='attachPt'):\n",
    "    if type(mol) == type('foo'):\n",
    "        mol = Chem.MolFromSmiles(mol)\n",
    "        returnSmiles = True\n",
    "    else:\n",
    "        returnSmiles = False\n",
    "    rwm = Chem.RWMol(mol)\n",
    "    # start by tagging all the neighbors:\n",
    "    toRemove = []\n",
    "    for at in rwm.GetAtoms():\n",
    "        if at.GetAtomicNum()==0 and at.GetDegree()==1:\n",
    "            nbr = at.GetNeighbors()[0]\n",
    "            if at.GetIsotope():\n",
    "                iso = str(at.GetIsotope())\n",
    "            else:\n",
    "                iso = ''\n",
    "            nbr.SetProp('attachPt',f'[{iso}*]')\n",
    "            if nbr.GetIsAromatic() and nbr.GetAtomicNum() != 6:\n",
    "                nbr.SetNoImplicit(True)\n",
    "                nbr.SetNumExplicitHs(1)\n",
    "            toRemove.append(at.GetIdx())\n",
    "    # now remove the atoms\n",
    "    for idx in sorted(toRemove,reverse=True):\n",
    "        rwm.RemoveAtom(idx)\n",
    "    if not returnSmiles:\n",
    "        return rwm.GetMol()\n",
    "    else:\n",
    "        return Chem.MolToCXSmiles(rwm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "O=C1CCCC(NC(=O)c2ccccc2)N1\n",
      "c1ccccc1 |atomProp:2.attachPt.[*]|\n",
      "O=CNC1CCCC(=O)N1 |atomProp:1.attachPt.[*]|\n",
      "O=C1CCCCN1 |atomProp:5.attachPt.[*]|\n",
      "NC(=O)c1ccccc1 |atomProp:0.attachPt.[*]|\n",
      "NC=O |atomProp:0.attachPt.[*]:1.attachPt.[*]|\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800px\"\n",
       "            height=\"600px\"\n",
       "            src=\"simple2.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f7be08bdd30>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyvis.network import Network\n",
    "from urllib import parse\n",
    "\n",
    "m = Chem.MolFromSmiles('c1ccccc1C(=O)NC1NC(=O)CCC1')\n",
    "params = rdScaffoldNetwork.ScaffoldNetworkParams()\n",
    "params.keepOnlyFirstFragment=False\n",
    "params.includeGenericScaffolds=False\n",
    "params.includeScaffoldsWithoutAttachments=False\n",
    "net = rdScaffoldNetwork.CreateScaffoldNetwork([m],params)\n",
    "nodemols = [Chem.MolFromSmiles(x) for x in net.nodes]\n",
    "from collections import Counter\n",
    "maxCount = max(net.counts)\n",
    "g = Network(notebook=True,height='600px',width='800px')\n",
    "for i,smi in enumerate(net.nodes):\n",
    "    smi = mergeAttachPointsToAtoms(smi)\n",
    "    print(smi)\n",
    "    qsmi = parse.quote(smi)\n",
    "    imgurl = f\"https://mol-renderer2-dev.t5ix.io/to_img/mol.png?smiles={qsmi}&w=200&h=150\"\n",
    "    g.add_node(i,shape=\"image\",label=' ',\n",
    "               image =imgurl, title=f'<img src=\"{imgurl}\"/>', size=30*net.counts[i]/maxCount)\n",
    "for e in net.edges:\n",
    "    g.add_edge(e.beginIdx,e.endIdx,label=str(e.type))\n",
    "g.show(\"simple2.html\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "O=C1CCCC(NC(=O)c2ccccc2)N1\n",
      "O=Cc1ccccc1 |atomProp:1.attachPt.[1*]|\n",
      "NC1CCCC(=O)N1 |atomProp:0.attachPt.[5*]|\n",
      "NC(=O)c1ccccc1 |atomProp:0.attachPt.[5*]|\n",
      "O=C1CCCCN1 |atomProp:5.attachPt.[13*]|\n",
      "O=CNC1CCCC(=O)N1 |atomProp:1.attachPt.[6*]|\n",
      "c1ccccc1 |atomProp:2.attachPt.[16*]|\n",
      "NC=O |atomProp:0.attachPt.[5*]:1.attachPt.[6*]|\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800px\"\n",
       "            height=\"600px\"\n",
       "            src=\"simple3.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f7bdc266f28>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pyvis.network import Network\n",
    "from urllib import parse\n",
    "\n",
    "m = Chem.MolFromSmiles('c1ccccc1C(=O)NC1NC(=O)CCC1')\n",
    "params = rdScaffoldNetwork.BRICSScaffoldParams()\n",
    "params.keepOnlyFirstFragment=False\n",
    "params.includeGenericScaffolds=False\n",
    "params.includeScaffoldsWithoutAttachments=False\n",
    "net = rdScaffoldNetwork.CreateScaffoldNetwork([m],params)\n",
    "nodemols = [Chem.MolFromSmiles(x) for x in net.nodes]\n",
    "from collections import Counter\n",
    "maxCount = max(net.counts)\n",
    "g = Network(notebook=True,height='600px',width='800px')\n",
    "\n",
    "# do a viz where we only show nodes with at least 5 atoms:\n",
    "keepNodes = set()\n",
    "for i,smi in enumerate(net.nodes):\n",
    "    if(Chem.MolFromSmiles(smi,sanitize=False).GetNumAtoms()<=4):\n",
    "        continue\n",
    "    smi = mergeAttachPointsToAtoms(smi)\n",
    "    print(smi)\n",
    "    keepNodes.add(i)\n",
    "    qsmi = parse.quote(smi)\n",
    "    imgurl = f\"https://mol-renderer2-dev.t5ix.io/to_img/mol.png?smiles={qsmi}&w=200&h=150\"\n",
    "    g.add_node(i,shape=\"image\",label=' ',\n",
    "               image =imgurl, title=f'<img src=\"{imgurl}\"/>', size=30*net.counts[i]/maxCount)\n",
    "for e in net.edges:\n",
    "    if e.beginIdx in keepNodes and e.endIdx in keepNodes:\n",
    "        g.add_edge(e.beginIdx,e.endIdx,label=str(e.type))\n",
    "g.show(\"simple3.html\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(10, 20)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(net.nodes),len(net.edges)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
