Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
yakutovicha committed Apr 13, 2019
2 parents f6296f8 + 76974ca commit 291a9b1
Show file tree
Hide file tree
Showing 16 changed files with 1,452 additions and 33 deletions.
206 changes: 206 additions & 0 deletions aiida_datatypes.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from os import path\n",
"from aiida import load_dbenv, is_dbenv_loaded\n",
"from aiida.backends import settings\n",
"if not is_dbenv_loaded():\n",
" load_dbenv(profile=settings.AIIDADB_PROFILE)\n",
"from aiida.orm import DataFactory"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from aiidalab_widgets_base import aiidalab_display"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ParameterData"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# visualize ParameterData\n",
"ParameterData = DataFactory('parameter')\n",
"p = ParameterData(dict={\n",
" 'Parameter' :'super long string '*4,\n",
" 'parameter 2' :'value 2',\n",
" 'parameter 3' : 1,\n",
" 'parameter 4' : 2,\n",
"})\n",
"aiidalab_display(p.store(), downloadable=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# create molecule\n",
"from ase.build import molecule\n",
"m = molecule('H2O')\n",
"m.center(vacuum=2.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CifData"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# visualize CifData\n",
"CifData = DataFactory('cif')\n",
"s = CifData(ase=m)\n",
"aiidalab_display(s.store(), downloadable=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## StructureData"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# visualize StructureData\n",
"StructureData = DataFactory('structure')\n",
"s = StructureData(ase=m)\n",
"aiidalab_display(s.store(), downloadable=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## BandsData"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"BandsData = DataFactory('array.bands')\n",
"bs = BandsData()\n",
"kpoints = np.array([[0. , 0. , 0. ], # array shape is 12 * 3\n",
" [0.1 , 0. , 0.1 ],\n",
" [0.2 , 0. , 0.2 ],\n",
" [0.3 , 0. , 0.3 ],\n",
" [0.4 , 0. , 0.4 ],\n",
" [0.5 , 0. , 0.5 ],\n",
" [0.5 , 0. , 0.5 ],\n",
" [0.525 , 0.05 , 0.525 ],\n",
" [0.55 , 0.1 , 0.55 ],\n",
" [0.575 , 0.15 , 0.575 ],\n",
" [0.6 , 0.2 , 0.6 ],\n",
" [0.625 , 0.25 , 0.625 ]])\n",
"\n",
"bands = np.array([\n",
" [-5.64024889, 6.66929678, 6.66929678, 6.66929678, 8.91047649], # array shape is 12 * 5, where 12 is the size of the kpoints mesh\n",
" [-5.46976726, 5.76113772, 5.97844699, 5.97844699, 8.48186734], # and 5 is the number of states\n",
" [-4.93870761, 4.06179965, 4.97235487, 4.97235488, 7.68276008],\n",
" [-4.05318686, 2.21579935, 4.18048674, 4.18048675, 7.04145185],\n",
" [-2.83974972, 0.37738276, 3.69024464, 3.69024465, 6.75053465],\n",
" [-1.34041116, -1.34041115, 3.52500177, 3.52500178, 6.92381041],\n",
" [-1.34041116, -1.34041115, 3.52500177, 3.52500178, 6.92381041],\n",
" [-1.34599146, -1.31663872, 3.34867603, 3.54390139, 6.93928289],\n",
" [-1.36769345, -1.24523403, 2.94149041, 3.6004033 , 6.98809593],\n",
" [-1.42050683, -1.12604118, 2.48497007, 3.69389815, 7.07537154],\n",
" [-1.52788845, -0.95900776, 2.09104321, 3.82330632, 7.20537566],\n",
" [-1.71354964, -0.74425095, 1.82242466, 3.98697455, 7.37979746]])\n",
"bs.set_kpoints(kpoints)\n",
"bs.set_bands(bands)\n",
"labels = [(0, u'GAMMA'),\n",
" (5, u'X'),\n",
" (6, u'Z'),\n",
" (11, u'U')]\n",
"bs.labels = labels"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aiidalab_display(bs.store()) # to visualize the bands"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## FolderData"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"FolderData = DataFactory('folder')\n",
"fd = FolderData()\n",
"with fd.folder.open(path.join('path','test1.txt'), 'w') as fobj:\n",
" fobj.write('content of test1 file')\n",
"with fd.folder.open(path.join('path','test2.txt'), 'w') as fobj:\n",
" fobj.write('content of test2\\nfile')\n",
"with fd.folder.open(path.join('path','test_long.txt'), 'w') as fobj:\n",
" fobj.write('content of test_long file'*1000)\n",
"aiidalab_display(fd.store(), downloadable=True)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.15rc1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
12 changes: 10 additions & 2 deletions aiidalab_widgets_base/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
# pylint: disable=unused-import
from aiida import load_dbenv, is_dbenv_loaded
from aiida.backends import settings
if not is_dbenv_loaded():
load_dbenv(profile=settings.AIIDADB_PROFILE)

from .structures import StructureUploadWidget # noqa
from .structures_multi import MultiStructureUploadWidget # noqa
from .codes import CodeDropdown # noqa
from .codes import CodeDropdown, AiiDACodeSetup, extract_aiidacodesetup_arguments # noqa
from .computers import SshComputerSetup, extract_sshcomputersetup_arguments # noqa
from .computers import AiidaComputerSetup, extract_aiidacomputer_arguments # noqa
from .display import aiidalab_display # noqa

__version__ = "0.2.0a1"
__version__ = "0.3.0b1"
145 changes: 145 additions & 0 deletions aiidalab_widgets_base/aiida_visualizers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
from __future__ import print_function
import os

import ipywidgets as ipw

class ParameterDataVisualizer(ipw.HTML):
"""Visualizer class for ParameterData object"""
def __init__(self, parameter, downloadable=True, **kwargs):
super(ParameterDataVisualizer, self).__init__(**kwargs)
import pandas as pd
# Here we are defining properties of 'df' class (specified while exporting pandas table into html).
# Since the exported object is nothing more than HTML table, all 'standard' HTML table settings
# can be applied to it as well.
# For more information on how to controle the table appearance please visit:
# https://css-tricks.com/complete-guide-table-element/
self.value = '''
<style>
.df { border: none; }
.df tbody tr:nth-child(odd) { background-color: #e5e7e9; }
.df tbody tr:nth-child(odd):hover { background-color: #f5b7b1; }
.df tbody tr:nth-child(even):hover { background-color: #f5b7b1; }
.df tbody td { min-width: 300px; text-align: center; border: none }
.df th { text-align: center; border: none; border-bottom: 1px solid black;}
</style>
'''
pd.set_option('max_colwidth', 40)
df = pd.DataFrame([(key, value) for key, value
in sorted(parameter.get_dict().items())
], columns=['Key', 'Value'])
self.value += df.to_html(classes='df', index=False) # specify that exported table belongs to 'df' class
# this is used to setup table's appearance using CSS
if downloadable:
import base64
payload = base64.b64encode(df.to_csv(index=False).encode()).decode()
fname = '{}.csv'.format(parameter.pk)
to_add = """Download table in csv format: <a download="{filename}"
href="data:text/csv;base64,{payload}" target="_blank">{title}</a>"""
self.value += to_add.format(filename=fname, payload=payload,title=fname)

class StructureDataVisualizer(ipw.VBox):
"""Visualizer class for StructureData object"""
def __init__(self, structure, downloadable=True, **kwargs):
import nglview
self._structure = structure
viewer = nglview.NGLWidget()
viewer.add_component(nglview.ASEStructure(self._structure.get_ase())) # adds ball+stick
viewer.add_unitcell()
children = [viewer]
if downloadable:
self.file_format = ipw.Dropdown(
options=['xyz', 'cif'],
description="File format:",
)
self.download_btn = ipw.Button(description="Download")
self.download_btn.on_click(self.download)
children.append(ipw.HBox([self.file_format, self.download_btn]))
super(StructureDataVisualizer, self).__init__(children, **kwargs)

def download(self, b=None):
import base64
from tempfile import TemporaryFile
from IPython.display import Javascript
with TemporaryFile() as fobj:
self._structure.get_ase().write(fobj, format=self.file_format.value)
fobj.seek(0)
b64 = base64.b64encode(fobj.read())
payload = b64.decode()
js = Javascript(
"""
var link = document.createElement('a');
link.href = "data:;base64,{payload}"
link.download = "{filename}"
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
""".format(payload=payload,filename=str(self._structure.id)+'.'+self.file_format.value)
)
display(js)

class FolderDataVisualizer(ipw.VBox):
"""Visualizer class for FolderData object"""
def __init__(self, folder, downloadable=True, **kwargs):
self._folder = folder
self.files = ipw.Dropdown(
options=self._folder.get_folder_list(),
description="Select file:",
)
self.text = ipw.Textarea(
value="",
description='File content:',
layout={'width':"900px", 'height':'300px'},
disabled=False
)
self.change_file_view()
self.files.observe(self.change_file_view, names='value')
children = [self.files, self.text]
if downloadable:
self.download_btn = ipw.Button(description="Download")
self.download_btn.on_click(self.download)
children.append(self.download_btn)
super(FolderDataVisualizer, self).__init__(children, **kwargs)

def change_file_view(self, b=None):
with open(self._folder.get_abs_path(self.files.value), "rb") as fobj:
self.text.value = fobj.read()

def download(self, b=None):
import base64
from IPython.display import Javascript
with open(self._folder.get_abs_path(self.files.value), "rb") as fobj:
b64 = base64.b64encode(fobj.read())
payload = b64.decode()
js = Javascript(
"""
var link = document.createElement('a');
link.href = "data:;base64,{payload}"
link.download = "{filename}"
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
""".format(payload=payload,filename=self.files.value)
)
display(js)

class BandsDataVisualizer(ipw.VBox):
"""Visualizer class for BandsData object"""
def __init__(self, bands, **kwargs):
from bokeh.plotting import figure
from bokeh.io import show, output_notebook
output_notebook(hide_banner=True)
out = ipw.Output()
with out:
plot_info = bands._get_bandplot_data(cartesian=True, join_symbol="|")
y = plot_info['y'].transpose().tolist()
x = [plot_info['x'] for i in range(len(y))]
labels = plot_info['labels']
p = figure(y_axis_label='Dispersion ({})'.format(bands.units))
p.multi_line(x, y, line_width=2)
p.xaxis.ticker = [l[0] for l in labels]
p.xaxis.major_label_overrides = {int(l[0]) if l[0].is_integer() else l[0]:l[1] for l in labels}
# int(l[0]) if l[0].is_integer() else l[0]
# This trick was suggested here: https://github.com/bokeh/bokeh/issues/8166#issuecomment-426124290
show(p)
children = [out]
super(BandsDataVisualizer, self).__init__(children, **kwargs)
Loading

0 comments on commit 291a9b1

Please sign in to comment.