SAR visualization with RDKit ver2.

Somedays ago I posted SARviz test code using RDKit.
It was based on command line type. So, I think it is easy to use for applying SDF etc but not familiar for chemist.
Because almost of chemist, don’t like black command screen….;-)
Next step, I tried to make very simple web-app using sarviz.py.
I used flask for web framework and JSME for molecular editor.( Point!! I want to make app, only using open source tools !!!)
Structure of app folder is following.
– chemolib folder stored library for calculate molprop. and make image.
– dataprep folder strored sklearn predictive model as pkl format.
– static folder stored static files. js and tempfig( figure generated sarviz function. ) => static and templates folder is needed to run app.( flask manner.)

sarviz_web/
├── README.md
├── __init__.py
├── app.py
├── chemolib
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   └── sarviz.cpython-34.pyc
│   └── sarviz.py
├── dataprep
│   └── svcmodel.pkl
├── static
│   ├── js
│   │   ├── jquery-2.2.2.min.js
│   │   └── jsme
│   │       ├── 0C2FB4F99F888620E6F186FB989A1E5F.cache.js
| ~~~~~~~~~~~~~~cut too long ~~~~~~~~~~~~~~~
│   └── tempfig
│       └── activemol_dummy.png
└── templates
    ├── query.html
    ├── result.html
    ├── template.html
    └── top.html

App.py is main code of this app.
But not so complicated.

# this is test app for SARviz.
# Author iwatobipen
# Licence FREE and please enjoy chemoinfromatics

from flask import Flask
from flask import render_template, url_for
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired
from chemolib import sarviz
import pickle
from rdkit import Chem

class Smiles( Form ):
    smi = StringField( "- mol to smiles", validators=[ DataRequired() ] )

def create_app():
    app = Flask( __name__ )
    Bootstrap( app )
    return app

app = create_app()

@app.route( "/top/" )
def top():
    return render_template( "top.html" )

@app.route( "/predict/", methods = ( "GET", "POST" ) )
def predict():
    actcls = { -1: "non-active", 1: "active" }
    form = Smiles( csrf_enabled=False )
    if form.validate_on_submit():
        smi = form.smi.data
        try:
            mol = Chem.MolFromSmiles( smi )

        except:
            mol = Chem.MolFromSmiles( "c1ccccc1" )
        # get molwt, mollogp, tpsa
        molprop = sarviz.molprop_calc( mol )
        # predict active / nonactive as integer and save image.
        res, fname = sarviz.mapperfunc( mol )
        res = int( res[0] )
        return render_template( "result.html", res = actcls[res], fname=fname, molprop = molprop )
    else:
        return render_template( "query.html", form = form, fname="dummy.png" )

if __name__ == "__main__":
    app.run( debug = True )

And one of key function is sarviz.py.
I used uuid to avoid crash of names.
I added some function to calculate molecular property.
Property will be provided for user as table format.

# this is core function of SAR visualizetion.

from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
from rdkit.Chem import Descriptors
from rdkit.Chem.Draw import SimilarityMaps
from sklearn.svm import SVC
from matplotlib import cm
import numpy as np
import pickle
import uuid

modelf = open( "./dataprep/svcmodel.pkl", "rb" )
model = pickle.load( modelf )

def calc_fp_arr( mol ):
    fp = AllChem.GetMorganFingerprintAsBitVect( mol, 2 )
    arr = np.zeros((1,))
    DataStructs.ConvertToNumpyArray( fp, arr )
    return arr

def getProba( fp, probabilityfunc ):
    # probability function returns 2 x 1 matrix.
    return probabilityfunc( fp )[0][1]
#save fig random or unique name!!! avoid chaching
def mapperfunc( mol ):
    fig, weight = SimilarityMaps.GetSimilarityMapForModel( mol,
                                                           SimilarityMaps.GetMorganFingerprint,
                                                            lambda x:getProba( x, model.predict_proba ),
                                                            colorMap=cm.bwr )
    cls_result = model.predict( calc_fp_arr(mol) )
    fname = uuid.uuid1().hex+".png"
    fig.savefig( "static/tempfig/"+fname, bbox_inches = "tight" )
    return cls_result, fname

def molprop_calc( mol ):
    mw = round( Descriptors.MolWt( mol ), 2 )
    mollogp = round( Descriptors.MolLogP( mol ), 2 )
    tpsa = round( Descriptors.TPSA( mol ), 2  )
    return [ mw, mollogp, tpsa ]

Finally I made template. It was difficult task for me, because I’m not good at html… ;-/
Following code shows only results.html. I uploaded all code to my github repo.
Using Flask-Boot strap for good visualisation.

{% extends "template.html" %}

{% block header %}
{% endblock %}

{% block content %}
<div class="container">
<div class="row">
<div class="col-md-5">
      <img src="{{ url_for( 'static', filename='tempfig/'+fname) }}" height="300" width="300" alt="IMAGE"></br></div>
<div class="col-md-3">
<table class="table table-hover">
<thead>
<tr>
<th> Pram</th>
<th> Val</th>
</tr>
</thead>
<tbody>
<tr>
<td>MW</td>
<td>{{ molprop[0] }}</td>
</tr>
<tr>
<td>MolLogP</td>
<td>{{ molprop[1] }}</td>
</tr>
<tr>
<td>TPSA</td>
<td>{{ molprop[2] }}</td>
</tr>
<tr>
<td>Predicted</td>
<td>{{ res }}</td>
</tr>
<tr>
<td>#</td>
<td><a href="/predict/"> predict again </a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}

OK, All done.
Let’s run app.
From terminal tipe.
python app.py
Then access localhost:5000/predict.
User get query input page.
Screen Shot 2016-03-27 at 8.04.16 AM

I embed javascript function to get smiles from JMSE. When user mouse over the button, smiles will be got automatically.

Then push button, prediction will start and image will be generated.
Screen Shot 2016-03-27 at 8.04.29 AM

This accuracy of this app depend on performance of sklern model.
I’ll introduce in this point in mishima.syk8. 😉
Readers who are interested in mishima.syk, I recommend check following URL.
The event will be held on 28.Mar.2016.
http://connpass.com/event/29258/

And my code was uploaded to my repo.
https://github.com/iwatobipen/sarviz_flask

広告

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中