Skip to content

Commit

Permalink
Workaround for issue in which play box doesn't appear in Voila. Set a…
Browse files Browse the repository at this point in the history
…rrows to default. Reverted to gamma point (could change in future). Fixed links to source code.
  • Loading branch information
Taylor-96 committed May 12, 2024
1 parent ce637b5 commit dbb464f
Show file tree
Hide file tree
Showing 4 changed files with 167 additions and 31 deletions.
40 changes: 35 additions & 5 deletions notebook/lattice-vibration/NGLTrajectoryClass.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
import os
import logging

import matplotlib.pyplot as plt
import ipywidgets as widgets
Expand All @@ -8,7 +9,9 @@
from ase.io.trajectory import Trajectory
from sympy import *
from NGLUtilsClass import NGLWidgets

from ipywidgets import Output
import sys
sys.stdout = open('/dev/stdout', 'w')

class NGLTrajectory(NGLWidgets):
def __init__(self, trajectory):
Expand Down Expand Up @@ -71,11 +74,13 @@ def __init__(self, trajectory):
self.x = 0
self.y = 0
self.ka = 0
#target_k=np.pi/2
self.ka_array = np.linspace(-2 * np.pi, 2 * np.pi, 101)
self.idx = 50 # idx corresponding to ka=0
self.optic = False

self.init_delay = 20



def addArrows(self, *args):
'''
Expand Down Expand Up @@ -428,6 +433,7 @@ def initialize_dispersion_plot(self, *args):

# Selected frequency point
(self.point,) = self.ax.plot([], [], ".", c="crimson", markersize=15)
self.point.set_data((np.pi/2, 1)) # default to non-trivial k-point

self.ax.set_xlabel("k")
self.ax.set_ylabel("$\omega$")
Expand Down Expand Up @@ -458,6 +464,15 @@ def band_dispersion(self, *args):
self.lines_op.set_data(([], []))
self.lines_ac_out.set_data(([], []))
self.lines_op_out.set_data(([], []))

# set default k point for monatomic chain
self.x=np.pi/2
self.idx = (np.abs(self.ka_array - self.x)).argmin()
self.ka = self.ka_array[self.idx]

w = self.w[self.idx]
self.point.set_data((self.ka, w))


elif self.button_chain.value == "diatomic":
# Reduce figure width to "half" the size, since x axis is half as big now.
Expand All @@ -480,6 +495,13 @@ def band_dispersion(self, *args):
# Remove monoatomic chain lines
self.lines.set_data(([], []))
self.lines_out.set_data(([], []))

# set default k point for diatomic chain
self.x=np.pi/2
self.idx = (np.abs(self.ka_array - self.x)).argmin()
self.ka = self.ka_array[self.idx]
w= self.w_ac[self.idx]
self.point.set_data((self.ka, w))

# First BZ limit
self.ax.plot([-np.pi, -np.pi], [0, 2.2], "k--", linewidth=1)
Expand All @@ -490,16 +512,24 @@ def band_dispersion(self, *args):
# 2.2 works well for initial height
self.ax.set_ybound(0, 2.2)

self.point.set_data((0, 0))
# set default point on dispersion
self.fig.canvas.mpl_connect("button_press_event", self.onclick)
plt.ion()

def onclick(self, event):
if event==None:

self.x=0.0
self.y=0.0
else:
self.x = event.xdata
self.y = event.ydata


"""
Determine frequency and k point upon click on band dispersion figure
"""
self.x = event.xdata
self.y = event.ydata


# Get the idx of the closest k in the array
self.idx = (np.abs(self.ka_array - self.x)).argmin()
Expand Down
2 changes: 1 addition & 1 deletion notebook/lattice-vibration/NGLUtilsClass.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def __init__(self, trajectory) -> None:
r"Arrow amplitude", layout=self.layout_description
)
self.slider_amp_arrow = widgets.FloatSlider(
value=2.0,
value=0.5,
min=0.1,
max=5.01,
step=0.1,
Expand Down
142 changes: 122 additions & 20 deletions notebook/lattice-vibration/Phonon_1D.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
"\n",
"<i class=\"fa fa-home fa-2x\"></i><a href=\"../index.ipynb\" style=\"font-size: 20px\"> Go back to index</a>\n",
"\n",
"**Source code:** https://github.com/osscar-org/quantum-mechanics/blob/master/notebook/statistical-mechanics/ising_model.ipynb\n",
"**Source code:** https://github.com/osscar-org/quantum-mechanics/blob/master/notebook/lattice-vibration/Phonon_1D.ipynb\n",
"\n",
"<hr style=\"height:1px;border:none;color:#cccccc;background-color:#cccccc;\" />\n",
"\n",
"## **Tasks and exercises**\n",
"\n",
"1. Visualize the lattice vibration at $k=0$ and $k=\\frac{\\pi}{a}$, what characteristics do you observe ? \n",
"1. Visualize the lattice vibration at $k=0$ and $k=\\frac{\\pi}{a}$. What characteristics do you observe ? \n",
" <details>\n",
" <summary style=\"color: red\">Solution</summary>\n",
" The atom indexed $n$ has a displacement given by $u=\\exp(i(n\\cdot ka-\\omega t))$.\n",
Expand All @@ -41,18 +41,18 @@
"3. Visualize the phonon dispersion for a diatomic chain. What is the difference between the acoustic and optical branch at $k=0$ and $k=\\pm\\frac{\\pi}{2a}$ ? How do the atoms displacements relate to frequency ?\n",
" <details>\n",
" <summary style=\"color: red\">Solution</summary>\n",
" At $k=0$, in the acoustic branch, as in the monoatomic chain, the atoms do not move. Instead, in the optical branch the two atoms are moving out-of-phase. The latter one has therefore a high frequency.\n",
" At $k=0$, in the acoustic branch, as in the monoatomic chain, the atoms do not move. Instead, in the optical branch the two atoms are moving out-of-phase. The latter therefore has a high frequency.\n",
" \n",
" At $k=\\pm\\frac{\\pi}{2a}$, in the acoustic branch the light atoms stand still whearas the heavier atoms move. In the optical branch, the opposite is observed. Since frequency is proportional to $\\sqrt{1/M}$, the frequency is higher when lighter atoms move. \n",
" At $k=\\pm\\frac{\\pi}{2a}$, in the acoustic branch, the light atoms stand still whearas the heavier atoms move. In the optical branch, the opposite is observed. Since frequency is proportional to $\\sqrt{1/M}$, the frequency is higher when lighter atoms move. \n",
" </details>\n",
" \n",
" \n",
"4. Adjust the mass ratio of the molecules. What happens when the ratio is high ? When the ratio is close to unity ? How does the band dispersion evolve ?\n",
"4. Adjust the mass ratio of the molecules. What happens when the ratio is high ? How about when the ratio is close to unity ? How does the band dispersion change ?\n",
" <details>\n",
" <summary style=\"color: red\">Solution</summary>\n",
" As the ratio grows, the forbidden frequencies gap grows as well. At $k=\\pm\\frac{\\pi}{2a}$, the gap is proportional to $\\sqrt{1/M_{gray}}-\\sqrt{1/M_{red}}$.\n",
" As the ratio grows, the gap of forbidden frequencies grows as well. At $k=\\pm\\frac{\\pi}{2a}$, the gap is proportional to $\\sqrt{1/M_{gray}}-\\sqrt{1/M_{red}}$.\n",
" \n",
" Furthermore, at $k=0$, we have $\\frac{u_{red}}{u_{gray}}=\\frac{-M_{gray}}{M_{red}}$, and thus the heavier atom amplitude decreases as it gets heavier.\n",
" Furthermore, at $k=0$, we have $\\frac{u_{red}}{u_{gray}}=\\frac{-M_{gray}}{M_{red}}$, and thus the oscillation amplitude of the heavier atom decreases as it gets heavier.\n",
" </details>\n",
" \n",
" \n",
Expand All @@ -70,7 +70,7 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -80,17 +80,18 @@
"matplotlib.rcParams['figure.facecolor']='w'\n",
"from ase.io.trajectory import Trajectory\n",
"from ase import Atoms\n",
"import time\n",
"\n",
"from NGLTrajectoryClass import NGLTrajectory\n",
"\n",
"import ipywidgets as widgets\n",
"from ipywidgets import jslink,HBox, VBox, HTMLMath,Label,IntSlider, Tab,Play, Layout\n",
"from ipywidgets import jslink,HBox, VBox, HTMLMath,Label,IntSlider, Tab,Play, Layout, AppLayout\n",
"from IPython.display import display"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -108,6 +109,10 @@
" }, false);\n",
"\"\"\")\n",
"\n",
"\n",
"view = handler.view \n",
"# view.on_displayed(loop)\n",
"\n",
"widgets=[\n",
" handler.slider_C,\n",
" handler.slider_M,\n",
Expand All @@ -118,8 +123,9 @@
" handler.widgetList.append(widget)\n",
"\n",
"handler.slider_atom_radius.value=0.1\n",
"handler.slider_arrow_radius.value=0.1\n",
"handler.tick_box_arrows.value=False\n",
"handler.slider_arrow_radius.value=0.05\n",
"handler.tick_box_arrows.value=True\n",
"handler.addArrows() # add arrows by default\n",
"handler.set_player_parameters(delay=handler.init_delay)\n",
"handler.set_view_parameters(clipDist=1,quality='low')\n",
"\n",
Expand All @@ -131,12 +137,15 @@
"handler.compute_dispersion()\n",
"handler.compute_dispersion_relation()\n",
"\n",
"handler.compute_trajectory_1D()\n",
"handler.band_dispersion()\n",
"\n",
"\n",
"handler.set_view_dimensions()\n",
"handler.view.stage.set_parameters(mouse_preset=\"pymol\")\n",
"\n",
"handler.compute_trajectory_1D()\n",
"\n",
"\n",
"\n",
"chain= HBox([handler.button_chain_description,handler.button_chain])\n",
"mass_ratio=handler.output_ratio\n",
Expand Down Expand Up @@ -206,9 +215,26 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 7,
"metadata": {},
"outputs": [],
"outputs": [
{
"data": {
"text/html": [
"<style>\n",
".box_style{\n",
" border : 2px solid red;\n",
"}\n",
"</style>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%%html\n",
"<style>\n",
Expand All @@ -220,11 +246,87 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"execution_count": 8,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d7b84f9985bc41639601a74613eceb9e",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(Tab(children=(HBox(children=(VBox(children=(HBox(children=(HTMLMath(value='Atomic chain type', …"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "1ab3a0ba628041beab40ecd5efee8549",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"HBox(children=(NGLWidget(max_frame=50),), layout=Layout(align_items='center', display='flex', flex_flow='colum…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"ename": "TypeError",
"evalue": "loop() takes 1 positional argument but 2 were given",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[8], line 18\u001b[0m\n\u001b[1;32m 14\u001b[0m view\u001b[38;5;241m.\u001b[39m_run_on_another_thread(do)\n\u001b[1;32m 17\u001b[0m hv_thread\u001b[38;5;241m=\u001b[39mhandler\u001b[38;5;241m.\u001b[39mview\u001b[38;5;241m.\u001b[39m_run_on_another_thread(init_view)\n\u001b[0;32m---> 18\u001b[0m \u001b[43mloop\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m,\u001b[49m\u001b[43mview\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[0;31mTypeError\u001b[0m: loop() takes 1 positional argument but 2 were given"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception in thread Thread-10 (init_view):\n",
"Traceback (most recent call last):\n",
" File \"/usr/lib/python3.10/threading.py\", line 1016, in _bootstrap_inner\n",
" self.run()\n",
" File \"/home/taylor/venvs/nb_testing/lib/python3.10/site-packages/ipykernel/ipkernel.py\", line 766, in run_closure\n",
" _threading_Thread_run(self)\n",
" File \"/usr/lib/python3.10/threading.py\", line 953, in run\n",
" self._target(*self._args, **self._kwargs)\n",
" File \"/tmp/ipykernel_27490/1732612826.py\", line 14, in init_view\n",
"NameError: name 'do' is not defined\n"
]
}
],
"source": [
"display(actions,HBox([handler.view],layout=layout).add_class(\"box_style\"))\n"
"display(actions,HBox([handler.view],layout=layout).add_class(\"box_style\"))\n",
"stop = False\n",
"def loop(view):\n",
" def do():\n",
" while True and not stop:\n",
" if view.frame == view.max_frame:\n",
" view.frame = 0\n",
" view.frame = view.frame + 1\n",
" time.sleep(0.2)\n",
" view._run_on_another_thread(do)\n",
" \n",
"def init_view():\n",
" time.sleep(5)\n",
" handler.onclick(None)\n",
"\n",
"\n",
"hv_thread=handler.view._run_on_another_thread(init_view)\n",
"# time.sleep(5)\n",
"# loop(view)\n"
]
},
{
Expand Down Expand Up @@ -297,7 +399,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
"version": "3.10.12"
}
},
"nbformat": 4,
Expand Down
14 changes: 9 additions & 5 deletions notebook/lattice-vibration/theory/theory_phonon_1d.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"# **Background theory**: Introduction to phonons\n",
"<i class=\"fa fa-book fa-2x\"></i><a href=\"../Phonon_1D.ipynb\" style=\"font-size: 20px\"> Go back to the interactive notebook</a>\n",
"\n",
"**Source code:** https://github.com/osscar-org/quantum-mechanics/tree/develop/notebook/lattice-vibration/theory/theory_phonon_1d.ipynb\n",
"**Source code:** https://github.com/osscar-org/quantum-mechanics/tree/master/notebook/lattice-vibration/theory/theory_phonon_1d.ipynb\n",
"\n",
"<hr style=\"height:1px;border:none;color:#cccccc;background-color:#cccccc;\" />"
]
Expand All @@ -19,7 +19,11 @@
"outputs": [
{
"data": {
"application/javascript": "MathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n});\n",
"application/javascript": [
"MathJax.Hub.Config({\n",
" TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n",
"});\n"
],
"text/plain": [
"<IPython.core.display.Javascript object>"
]
Expand Down Expand Up @@ -142,7 +146,7 @@
"celltoolbar": "Aucun(e)",
"hide_input": false,
"kernelspec": {
"display_name": "Python 3.8.10 ('base')",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
Expand All @@ -156,7 +160,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
"version": "3.10.12"
},
"vscode": {
"interpreter": {
Expand All @@ -165,5 +169,5 @@
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}

0 comments on commit dbb464f

Please sign in to comment.