t7morgen
vis
7d18a20
raw
history blame
7.67 kB
import gradio as gr
import py3Dmol
from Bio.PDB import *
import numpy as np
from Bio.PDB import PDBParser
import pandas as pd
import os, sys
#sys.path.append(os.getcwd())
print('importing...')
from run_gfn import run_gfn2
print('done')
# JavaScript functions
resid_hover = """function(atom,viewer) {{
if(!atom.label) {{
atom.label = viewer.addLabel('{0}:'+atom.atom+atom.serial,
{{position: atom, backgroundColor: 'mintcream', fontColor:'black'}});
}}
}}"""
hover_func = """
function(atom,viewer) {
if(!atom.label) {
atom.label = viewer.addLabel(atom.interaction,
{position: atom, backgroundColor: 'black', fontColor:'white'});
}
}"""
unhover_func = """
function(atom,viewer) {
if(atom.label) {
viewer.removeLabel(atom.label);
delete atom.label;
}
}"""
def get_qm_atom_features(gfn2_output, checked_features):
qm_atom_features = {}
qm_atom_features['atom type'] = gfn2_output["fetchatomicprops"]["atmlist"]
for checked_feature in checked_features:
if checked_feature == 'Charge':
qm_atom_features['Charge'] = gfn2_output["fetchatomicprops"]["charges"]
if checked_feature == 'Polarizability':
qm_atom_features['Polarizability'] = gfn2_output["fetchatomicprops"]["polarisabilities"]
return qm_atom_features
def get_qm_mol_features(gfn2_output, checked_features):
qm_mol_features = {}
qm_mol_features['Total Energy'] = gfn2_output["etotal"]
qm_mol_features['Total Polarizability'] = gfn2_output["totalpol"]
return qm_mol_features
def export_csv(d):
d.to_csv("qm_atom_features.csv")
return gr.File.update(value="qm_atom_features.csv", visible=True)
def get_basic_visualization(input_f,input_format):
view = py3Dmol.view(width=600, height=400)
view.setBackgroundColor('white')
view.addModel(input_f, input_format)
view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': 'turquoise'}}})
#view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}},'cartoon': {'color': '#4c4e9e', 'alpha':"0.6"}})
view.zoomTo()
output = view._make_html().replace("'", '"')
print('output of html', output)
x = f"""<!DOCTYPE html><html> {output} </html>""" # do not use ' in this input
visualization_html = f"""<iframe style="width: 100%; height:420px" data-ui="true" name="result" allow="midi; geolocation; microphone; camera;
display-capture; encrypted-media;" sandbox="allow-modals allow-forms
allow-scripts allow-same-origin allow-popups
allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>"""
return visualization_html
def add_spheres_feature_view(view, feature,xyz, viewnum, sizefactor, spec_color):
for i in range(len(feature)):
if feature[i]<0:
color="red"
else:
color=spec_color
view.addSphere({'center':{
'x':xyz[i][0],
'y':xyz[i][1],
'z':xyz[i][2]},
'radius':abs(feature[i])*sizefactor,'color':color,'alpha':1.00}, viewer=viewnum)
return view
def add_densities(view, dens, color, viewnum):
view.addVolumetricData(dens, "cube", {'isoval': 0.01, 'color': color, 'opacity': 1.0}, viewer=viewnum)
return view
def get_feature_visualization(input_f,input_format, features, xyz):
view = py3Dmol.view(width=600, height=400, viewergrid=(2,2))
view.setBackgroundColor('white')
view.addModel(input_f, input_format, viewer=(0,0))
view.addModel(input_f, input_format, viewer=(0,1))
view.addModel(input_f, input_format, viewer=(1,0))
view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}}}, viewer=(0,0))
view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}}}, viewer=(0,1))
view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}}}, viewer=(1,0))
#view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}}}, viewer=(0,1))
add_spheres_feature_view(view, features["fetchatomicprops"]["charges"], xyz, (0,1), 20, 'blue')
add_spheres_feature_view(view, features["fetchatomicprops"]["polarisabilities"], xyz, (1,0), 0.2, 'orange')
add_densities(view, open('dummy_struct_dens.cub', "r").read(), 'green', (1,1))
#view.setStyle({'stick': {'colorscheme': {'prop': 'resi', 'C': '#cccccc'}},'cartoon': {'color': '#4c4e9e', 'alpha':"0.6"}})
view.zoomTo(viewer=(0,0))
output = view._make_html().replace("'", '"')
x = f"""<!DOCTYPE html><html> {output} </html>""" # do not use ' in this input
visualization_html = f"""<iframe style="width: 100%; height:420px" name="result" allow="midi; geolocation; microphone; camera;
display-capture; encrypted-media;" sandbox="allow-modals allow-forms
allow-scripts allow-same-origin allow-popups
allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>"""
return visualization_html
def predict(checked_features, input_file, temperature):
input_f = open(input_file.name, "r").read()
input_format = input_file.name.split('.')[-1]
with open('dummy_struct.'+input_format, "w") as oF:
oF.write(input_f)
input_f2 = open('dummy_struct.'+input_format, "r").read()
gfn2_input = ["filename","geom=dummy_struct."+input_format, 'calcdens=1']
gfn2_output = run_gfn2(gfn2_input)
qm_atom_features = get_qm_atom_features(gfn2_output, checked_features)
qm_mol_features = get_qm_mol_features(gfn2_output, checked_features)
#basic_visualization_html = get_basic_visualization(input_f,input_format)
feature_visualization_html = get_feature_visualization(input_f,input_format, gfn2_output, gfn2_output['xyz'])
return feature_visualization_html, pd.DataFrame(qm_atom_features)#, pd.DataFrame(qm_mol_features, index=[0])
with gr.Blocks() as demo:
gr.Markdown("# QM property calculation")
#text_input = gr.Textbox()
#text_output = gr.Textbox()
#text_button = gr.Button("Flip")
with gr.Row():
input_file = gr.File(label="Structure file for input")
charge = gr.Textbox(placeholder="Total charge", label="Give the total charge of the input molecule. (Default=0)")
checked_features = gr.CheckboxGroup(["Charge", "Polarizability", "Koopman IP", "Electronic Density"], label="QM features", info="Which features shall be calculated?")
temperature = gr.Slider(value=300,minimum=0, maximum=1000, label="Temperature for Thermodynamics evaluation in K", step=5)
#with gr.Row():
# helix = gr.ColorPicker(label="helix")
# sheet = gr.ColorPicker(label="sheet")
# loop = gr.ColorPicker(label="loop")
single_btn = gr.Button(label="Run")
with gr.Row():
basic_html = gr.HTML()
gr.HighlightedText(value=[("Positive Charge","blue"),("Negative charge","red"),("Polarizability","orange"), ("Electronic Densities", "Green")], color_map={"red":"red", "blue":"blue", "orange":"orange", "Green":"green"})
#with gr.Row():
# basic_html = gr.HTML()
with gr.Row():
Dbutton = gr.Button("Download calculated atom features")
csv = gr.File(interactive=False, visible=False)
with gr.Row():
df_atom_features = gr.Dataframe()
#df_mol_features = gr.Dataframe()
single_btn.click(fn=predict, inputs=[checked_features, input_file, temperature], outputs=[basic_html, df_atom_features])
Dbutton.click(export_csv, df_atom_features, csv)
demo.launch(server_name="0.0.0.0", server_port=7860)