animate 3d surface

This commit is contained in:
TerenceLiu 2022-09-23 02:11:02 +08:00
parent 8750868cab
commit 300f81fba8
6 changed files with 51393 additions and 104 deletions

View File

@ -12,100 +12,39 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": null,
"id": "0a5c51d2-8b18-4143-b6f1-73a909ccb623",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "9059357c5be5412c9c92e436a2a6499d",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(VBox(children=(Text(value='x**3 - x**(1/2)', description='Expression:', style=Te…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b60f5896d3394f3195c55eaf4fe3fe23",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d21a3883fd054ad7849e00eed23780ac",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"outputs": [],
"source": [
"gd1 = gradient_descent_1d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": null,
"id": "15c6e757-cde3-422b-be7e-3f55b7752142",
"metadata": {},
"outputs": [],
"source": [
"gd2 = gradient_descent_2d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "081eff94-4d25-4455-8ff1-86b4518a052c",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "6fa72562a120492da5df506e493ccb0a",
"model_id": "b22d5c450acf419db39a6d9106ef7c2c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(VBox(children=(Text(value='(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2', description…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "69599d86bf5a49ca82788ca5fc19b4d3",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "36f1d55d6496429888a95493e534b62f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
"Dropdown(description='Number:', index=1, options=(('One', '(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** (1/2)'), ('Tw…"
]
},
"metadata": {},
@ -113,13 +52,66 @@
}
],
"source": [
"gd2 = gradient_descent_2d(environ=\"jupyterlab\")"
"gd2 = gradient_descent_2d_custom(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "c0445fd1-de19-4b5c-adb7-f285ebe38bb7",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "988a5acf153946928f4513f428759f9c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"interactive(children=(Select(description='country', options=('USA', 'Russia'), value='USA'), Output()), _dom_c…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import ipywidgets as widgets\n",
"from IPython.display import display\n",
"\n",
"geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}\n",
"geoWs = {key: widgets.Select(options=geo[key]) for key in geo}\n",
"\n",
"def get_current_state():\n",
" return {'country': i.children[0].value,\n",
" 'city': i.children[1].value}\n",
"\n",
"def print_city(country=\"Russia\"):\n",
" if country==\"Russia\":\n",
" hello = widgets.Text(value=\"a\", discription=\"hello\")\n",
" display(hello)\n",
" print(hello.value)\n",
"\n",
"def select_country(country):\n",
" new_i = widgets.interactive(print_city, country=countryW, city=geoWs[country['new']])\n",
" children = new_i.children\n",
"\n",
"countryW = widgets.Select(options=list(geo.keys()))\n",
"init = countryW.value\n",
"cityW = geoWs[init]\n",
"\n",
"countryW.observe(select_country, 'value')\n",
"\n",
"i = widgets.interactive(print_city, country=countryW, city=cityW)\n",
"\n",
"display(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "081eff94-4d25-4455-8ff1-86b4518a052c",
"id": "9d58d792-f358-4bc1-9684-87fa1184c746",
"metadata": {},
"outputs": [],
"source": []

File diff suppressed because one or more lines are too long

View File

@ -100,7 +100,7 @@ class gradient_descent_1d(object):
fig.show()
class gradient_descent_2d(object):
class gradient_descent_2d_custom(object):
def __init__(self, environ:str="jupyterlab"):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
@ -133,6 +133,121 @@ class gradient_descent_2d(object):
self.button_plot.on_click(self.plot)
display(self.plot_output)
def compute(self, *args):
with self.compute_output:
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
xn = x0
x1 = symbols("x1")
x2 = symbols("x2")
expr = sympify(self.wg_expr.value)
self.xn_list, self.df_list = [], []
for n in tqdm(range(0, self.wg_max_iter.value)):
gradient = np.array([diff(expr, x1).subs(x1, xn[0]).subs(x2, xn[1]),
diff(expr, x2).subs(x1, xn[0]).subs(x2, xn[1])], dtype=float)
self.xn_list.append(xn)
self.df_list.append(gradient)
if np.linalg.norm(gradient, ord=2) < self.wg_epsilon.value:
clear_output(wait=True)
print("Found solution of {} after".format(expr), n, "iterations")
print("x* = [{}, {}]".format(xn[0], xn[1]))
return None
xn = xn - self.wg_lr.value * gradient
clear_output(wait=True)
display("Exceeded maximum iterations. No solution found.")
return None
def plot(self, *args):
with self.plot_output:
clear_output(wait=True)
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
x1 = symbols("x1")
x2 = symbols("x2")
expr = sympify(self.wg_expr.value)
xx1 = np.arange(np.array(self.xn_list)[:, 0].min()*0.5, np.array(self.xn_list)[:, 0].max()*1.5, 0.05)
xx2 = np.arange(np.array(self.xn_list)[:, 1].min()*0.5, np.array(self.xn_list)[:, 1].max()*1.5, 0.05)
xx1, xx2 = np.meshgrid(xx1, xx2)
f = lambdify((x1, x2), expr, "numpy")
fx = f(xx1, xx2)
f_xn = f(np.array(self.xn_list)[:, 0], np.array(self.xn_list)[:, 1])
frames, steps = [], []
for k in range(len(f_xn)):
#frame = go.Frame(data=[go.Surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.8)])
#fig.add_trace(go.Scatter3d(x=np.array(self.xn_list)[:k, 0], y=np.array(self.xn_list)[:k, 1], z=f_xn))
frame = go.Frame(dict(data=[go.Scatter3d(x=np.array(self.xn_list)[:k,0], y=np.array(self.xn_list)[:k,1], z=f_xn)], name=f'frame{k+1}'), traces=[1])
frames.append(frame)
step = dict(
method="update",
args=[{"visible": [True]},
{"title": "Slider switched to step: " + str(k+1)}], # layout attribute
)
steps.append(step)
sliders = [dict(steps= [dict(method= 'animate',
args= [[f'frame{k+1}'],
dict(mode= 'immediate',
frame= dict( duration=0, redraw= True ),
transition=dict( duration=0)
)
],
#label='Date : {}'.format(date_range[k])
) for k in range(0,len(frames))],
transition= dict(duration=0),
x=0,
y=0,
currentvalue=dict(font=dict(size=12), visible=True, xanchor= 'center'),
len=1.0)
]
trace1 = go.Surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.8)
trace2 = go.Scatter3d(x=None, y=None, z=None)
fig = go.Figure(data=[trace1, trace2], frames=frames)
#fig.add_surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.9)
#fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))
#fig.update(frames=frames)
fig.update_layout(updatemenus=[dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None, dict(fromcurrent=True)]), \
dict(label="Pause", method="animate", args=[[None], dict(fromcurrent=True, mode='immediate', transition= {'duration': 0}, frame=dict(redraw=True, duration=0))])])],
margin=dict(l=0, r=0, b=0, t=0), sliders=sliders)
fig.show()
class gradient_descent_2d(object):
def __init__(self, environ:str="jupyterlab"):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
self.wg_expr = widgets.Dropdown(options=[("(sin(x1) - 2) + (sin(x2) - 2) ** 2", "(sin(x1) - 2) + (sin(x2) - 2) ** 2"),
("(sin(x1) - 2) ** (1/2) + (sin(x2) - 2) ** 2", "(sin(x1) - 2) ** (1/2) + (sin(x2) - 2) ** 2"),
("(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2", "(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2")],
value="(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2", descrption="Expression")
self.wg_x0 = widgets.Text(value="5,5",
description="Startpoint:")
self.wg_lr = widgets.FloatText(value="1e-1",
description="step size:")
self.wg_epsilon = widgets.FloatText(value="1e-5",
description="criterion:")
self.wg_max_iter = widgets.IntText(value="1000",
description="max iteration")
self.button_compute = widgets.Button(description="Compute")
self.button_plot = widgets.Button(description="Plot")
self.compute_output = widgets.Output()
self.plot_output = widgets.Output()
self.params_lvbox = widgets.VBox([self.wg_x0, self.wg_lr])
self.params_rvbox = widgets.VBox([self.wg_epsilon, self.wg_max_iter])
self.exp_box = widgets.HBox([self.wg_expr])
self.params_box = widgets.HBox([self.params_lvbox, self.params_rvbox], description="Parameters")
self.button_box = widgets.HBox([self.button_compute, self.button_plot], description="operations")
self.config = widgets.VBox([self.exp_box, self.params_box, self.button_box])
self.initialization()
def initialization(self):
display(self.config)
self.button_compute.on_click(self.compute)
display(self.compute_output)
self.button_plot.on_click(self.plot)
display(self.plot_output)
def compute(self, *args):
with self.compute_output:
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
@ -211,7 +326,3 @@ class gradient_descent_2d(object):
dict(label="Pause", method="animate", args=[[None], dict(fromcurrent=True, mode='immediate', transition= {'duration': 0}, frame=dict(redraw=True, duration=0))])])],
margin=dict(l=0, r=0, b=0, t=0), sliders=sliders)
fig.show()

View File

@ -100,7 +100,7 @@ class gradient_descent_1d(object):
fig.show()
class gradient_descent_2d(object):
class gradient_descent_2d_custom(object):
def __init__(self, environ:str="jupyterlab"):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
@ -133,6 +133,121 @@ class gradient_descent_2d(object):
self.button_plot.on_click(self.plot)
display(self.plot_output)
def compute(self, *args):
with self.compute_output:
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
xn = x0
x1 = symbols("x1")
x2 = symbols("x2")
expr = sympify(self.wg_expr.value)
self.xn_list, self.df_list = [], []
for n in tqdm(range(0, self.wg_max_iter.value)):
gradient = np.array([diff(expr, x1).subs(x1, xn[0]).subs(x2, xn[1]),
diff(expr, x2).subs(x1, xn[0]).subs(x2, xn[1])], dtype=float)
self.xn_list.append(xn)
self.df_list.append(gradient)
if np.linalg.norm(gradient, ord=2) < self.wg_epsilon.value:
clear_output(wait=True)
print("Found solution of {} after".format(expr), n, "iterations")
print("x* = [{}, {}]".format(xn[0], xn[1]))
return None
xn = xn - self.wg_lr.value * gradient
clear_output(wait=True)
display("Exceeded maximum iterations. No solution found.")
return None
def plot(self, *args):
with self.plot_output:
clear_output(wait=True)
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
x1 = symbols("x1")
x2 = symbols("x2")
expr = sympify(self.wg_expr.value)
xx1 = np.arange(np.array(self.xn_list)[:, 0].min()*0.5, np.array(self.xn_list)[:, 0].max()*1.5, 0.05)
xx2 = np.arange(np.array(self.xn_list)[:, 1].min()*0.5, np.array(self.xn_list)[:, 1].max()*1.5, 0.05)
xx1, xx2 = np.meshgrid(xx1, xx2)
f = lambdify((x1, x2), expr, "numpy")
fx = f(xx1, xx2)
f_xn = f(np.array(self.xn_list)[:, 0], np.array(self.xn_list)[:, 1])
frames, steps = [], []
for k in range(len(f_xn)):
#frame = go.Frame(data=[go.Surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.8)])
#fig.add_trace(go.Scatter3d(x=np.array(self.xn_list)[:k, 0], y=np.array(self.xn_list)[:k, 1], z=f_xn))
frame = go.Frame(dict(data=[go.Scatter3d(x=np.array(self.xn_list)[:k,0], y=np.array(self.xn_list)[:k,1], z=f_xn)], name=f'frame{k+1}'), traces=[1])
frames.append(frame)
step = dict(
method="update",
args=[{"visible": [True]},
{"title": "Slider switched to step: " + str(k+1)}], # layout attribute
)
steps.append(step)
sliders = [dict(steps= [dict(method= 'animate',
args= [[f'frame{k+1}'],
dict(mode= 'immediate',
frame= dict( duration=0, redraw= True ),
transition=dict( duration=0)
)
],
#label='Date : {}'.format(date_range[k])
) for k in range(0,len(frames))],
transition= dict(duration=0),
x=0,
y=0,
currentvalue=dict(font=dict(size=12), visible=True, xanchor= 'center'),
len=1.0)
]
trace1 = go.Surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.8)
trace2 = go.Scatter3d(x=None, y=None, z=None)
fig = go.Figure(data=[trace1, trace2], frames=frames)
#fig.add_surface(x=xx1, y=xx2, z=fx, showscale=True, opacity=0.9)
#fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))
#fig.update(frames=frames)
fig.update_layout(updatemenus=[dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None, dict(fromcurrent=True)]), \
dict(label="Pause", method="animate", args=[[None], dict(fromcurrent=True, mode='immediate', transition= {'duration': 0}, frame=dict(redraw=True, duration=0))])])],
margin=dict(l=0, r=0, b=0, t=0), sliders=sliders)
fig.show()
class gradient_descent_2d(object):
def __init__(self, environ:str="jupyterlab"):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
self.wg_expr = widgets.Dropdown(options=[("(sin(x1) - 2) + (sin(x2) - 2) ** 2", "(sin(x1) - 2) + (sin(x2) - 2) ** 2"),
("(sin(x1) - 2) ** (1/2) + (sin(x2) - 2) ** 2", "(sin(x1) - 2) ** (1/2) + (sin(x2) - 2) ** 2"),
("(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2", "(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2")],
value="(sin(x1) - 2) ** 2 + (sin(x2) - 2) ** 2", descrption="Expression")
self.wg_x0 = widgets.Text(value="5,5",
description="Startpoint:")
self.wg_lr = widgets.FloatText(value="1e-1",
description="step size:")
self.wg_epsilon = widgets.FloatText(value="1e-5",
description="criterion:")
self.wg_max_iter = widgets.IntText(value="1000",
description="max iteration")
self.button_compute = widgets.Button(description="Compute")
self.button_plot = widgets.Button(description="Plot")
self.compute_output = widgets.Output()
self.plot_output = widgets.Output()
self.params_lvbox = widgets.VBox([self.wg_x0, self.wg_lr])
self.params_rvbox = widgets.VBox([self.wg_epsilon, self.wg_max_iter])
self.exp_box = widgets.HBox([self.wg_expr])
self.params_box = widgets.HBox([self.params_lvbox, self.params_rvbox], description="Parameters")
self.button_box = widgets.HBox([self.button_compute, self.button_plot], description="operations")
self.config = widgets.VBox([self.exp_box, self.params_box, self.button_box])
self.initialization()
def initialization(self):
display(self.config)
self.button_compute.on_click(self.compute)
display(self.compute_output)
self.button_plot.on_click(self.plot)
display(self.plot_output)
def compute(self, *args):
with self.compute_output:
x0 = np.array(self.wg_x0.value.split(","), dtype=float)
@ -211,7 +326,3 @@ class gradient_descent_2d(object):
dict(label="Pause", method="animate", args=[[None], dict(fromcurrent=True, mode='immediate', transition= {'duration': 0}, frame=dict(redraw=True, duration=0))])])],
margin=dict(l=0, r=0, b=0, t=0), sliders=sliders)
fig.show()

403
algorithm/test.ipynb Normal file
View File

@ -0,0 +1,403 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import ipywidgets\n",
"import ipyvuetify as v\n",
"from threading import Timer\n",
"\n",
"lorum_ipsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "579f46256ca142a39554456f29e644a8",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Layout(children=[Btn(children=['button'])], class_='pa-2')"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count = 0\n",
"\n",
"def on_click(widget, event, data):\n",
" global count\n",
" count += 1\n",
" button1.children=['button ' + str(count)]\n",
"\n",
"button1 = v.Btn(children=['button'])\n",
"button1.on_event('click', on_click)\n",
"\n",
"v.Layout(class_='pa-2', children=[button1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v.Layout(children=[\n",
" v.Btn(color='primary', class_='ma-2', children=['primary']),\n",
" v.Btn(color='error', class_='ma-2', children=['error']),\n",
" v.Btn(color='pink lighten-4', class_='ma-2', children=['custom']),\n",
" v.Btn(color='#654321', dark=True, class_='ma-2', children=['hex']),\n",
" v.Btn(color='#654321', disabled=True, class_='ma-2', children=['disabled']),\n",
"\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v.Layout(children=[\n",
" v.Btn(color='primary', text=True, class_='ma-2', children=['flat']),\n",
" v.Btn(color='primary', text=True, disabled=True, class_='ma-2', children=['flat']),\n",
" v.Btn(color='primary', rounded=True, class_='ma-2', children=['rounded']),\n",
" v.Btn(color='primary', rounded=True, class_='ma-2', disabled=True, children=['rounded']),\n",
" v.Btn(color='primary', depressed=True, class_='ma-2', children=['depressed']),\n",
" v.Btn(color='primary', icon=True, class_='ma-2', children=[v.Icon(children=['mdi-thumb-up'])]),\n",
" v.Btn(color='primary', outline=True, class_='ma-2', children=['outline']),\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v.Layout(children=[\n",
" v.Btn(color='primary', small=True, class_='ma-2', children=['small']),\n",
" v.Btn(color='primary', class_='ma-2', children=['normal']),\n",
" v.Btn(color='primary', class_='ma-2', large=True, children=['large']),\n",
" v.Btn(color='primary', class_='ma-2', small=True, fab=True, children=[v.Icon(children=['mdi-pencil'])]),\n",
" v.Btn(color='primary', class_='ma-2', fab=True, children=[v.Icon(children=['mdi-pencil'])]),\n",
" v.Btn(color='primary', class_='ma-2', fab=True, large=True, children=[v.Icon(children=['mdi-pencil'])]),\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def toggleLoading():\n",
" button2.loading = not button2.loading\n",
" button2.disabled = button2.loading\n",
"\n",
"def on_loader_click(*args):\n",
" toggleLoading()\n",
" Timer(2.0, toggleLoading).start()\n",
" \n",
"button2 = v.Btn(loading=False, class_='ma-2', children=['loader'])\n",
"button2.on_event('click', on_loader_click)\n",
"\n",
"v.Layout(children=[button2])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"toggle_single = v.BtnToggle(v_model=2, class_='mr-3', children=[\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-align-left'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-align-center'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-align-right'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-align-justify'])]),\n",
"])\n",
"\n",
"toggle_multi = v.BtnToggle(v_model=[0,2], multiple=True, children=[\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-bold'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-italic'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-underline'])]),\n",
" v.Btn(text=True, children=[v.Icon(children=['mdi-format-color-fill'])]),\n",
"])\n",
"\n",
"v.Layout(children=[\n",
" toggle_single,\n",
" toggle_multi,\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v.Layout(children=[\n",
" v.Btn(color='primary', class_='ma-2', children=[\n",
" v.Icon(left=True, children=['mdi-fingerprint']),\n",
" 'Icon left'\n",
" ]),\n",
" v.Btn(color='primary', class_='ma-2', children=[\n",
" 'Icon right',\n",
" v.Icon(right=True, children=['mdi-fingerprint']),\n",
" ]),\n",
" v.Tooltip(bottom=True, v_slots=[{\n",
" 'name': 'activator',\n",
" 'variable': 'tooltip',\n",
" 'children': v.Btn(v_on='tooltip.on', color='primary', class_='ma-2', children=[\n",
" 'tooltip' \n",
" ]),\n",
" }], children=[\n",
" 'Insert tooltip text here'\n",
" ]) \n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def on_menu_click(widget, event, data):\n",
" if len(layout.children) == 1:\n",
" layout.children = layout.children + [info]\n",
" info.children=[f'Item {items.index(widget)+1} clicked']\n",
" \n",
"\n",
"items = [v.ListItem(children=[\n",
" v.ListItemTitle(children=[\n",
" f'Click me {i}'])]) \n",
" for i in range(1, 5)]\n",
"\n",
"for item in items:\n",
" item.on_event('click', on_menu_click)\n",
"\n",
"menu = v.Menu(offset_y=True,\n",
" v_slots=[{\n",
" 'name': 'activator',\n",
" 'variable': 'menuData',\n",
" 'children': v.Btn(v_on='menuData.on', class_='ma-2', color='primary', children=[\n",
" 'menu', \n",
" v.Icon(right=True, children=[\n",
" 'mdi-menu-down'\n",
" ])\n",
" ]),\n",
" }]\n",
" , \n",
" children=[\n",
" v.List(children=items)\n",
" ]\n",
")\n",
"\n",
"info = v.Chip(class_='ma-2')\n",
"\n",
"layout = v.Layout(children=[\n",
" menu\n",
"])\n",
"layout"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dialog = v.Dialog(width='500',\n",
" v_slots=[{\n",
" 'name': 'activator',\n",
" 'variable': 'x',\n",
" 'children': v.Btn(v_on='x.on', color='success', dark=True, children=[\n",
" 'Open dialog'\n",
" ]),\n",
" }], \n",
" children=[\n",
" v.Card(children=[\n",
" v.CardTitle(class_='headline gray lighten-2', primary_title=True, children=[\n",
" \"Lorem ipsum\"\n",
" ]),\n",
" v.CardText(children=[\n",
" lorum_ipsum,\n",
" v.TextField(label='Label', placeholder='Placeholder')\n",
" ]),\n",
" ])\n",
"])\n",
"\n",
"v.Layout(children=[dialog])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"slider = v.Slider(v_model=25)\n",
"slider2 = v.Slider(thumb_label=True, v_model=25)\n",
"slider3 = v.Slider(thumb_label='always', v_model=25)\n",
"\n",
"ipywidgets.jslink((slider, 'v_model'), (slider2, 'v_model'))\n",
"ipywidgets.jslink((slider, 'v_model'), (slider3, 'v_model'))\n",
"\n",
"v.Container(children=[\n",
" slider,\n",
" slider2,\n",
" slider3\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"select1=v.Select(label=\"Choose option\", items=['Option a', 'Option b', 'Option c'])\n",
"v.Layout(children=[select1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tab_list = [v.Tab(children=['Tab ' + str(i)]) for i in range(1,4)]\n",
"content_list = [v.TabItem(children=[lorum_ipsum]) for i in range(1,4)] \n",
"tabs = v.Tabs(\n",
" v_model=1, \n",
" children=tab_list + content_list)\n",
"tabs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def on_click(widget, event, data):\n",
" vnd.v_model = not vnd.v_model\n",
"\n",
"drawer_button = v.Btn(color='primary', children=['Close drawer'])\n",
"drawer_button.on_event('click', on_click)\n",
"\n",
"vnd = v.NavigationDrawer(v_model=False, absolute=True, right=True, children=[\n",
" drawer_button\n",
"])\n",
"\n",
"show_drawer = v.Btn(color='primary', children=['Toggle drawer'])\n",
"show_drawer.on_event('click', on_click)\n",
"\n",
"v.Layout(children=[vnd, show_drawer]) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"vepc1 = v.ExpansionPanel(children=[\n",
" v.ExpansionPanelHeader(children=['item1']),\n",
" v.ExpansionPanelContent(children=['First Text'])])\n",
"\n",
"vepc2 = v.ExpansionPanel(children=[\n",
" v.ExpansionPanelHeader(children=['item2']),\n",
" v.ExpansionPanelContent(children=['Second Text'])])\n",
"\n",
"vep = v.ExpansionPanels(children=[vepc1, vepc2])\n",
"vl = v.Layout(class_='pa-4', children=[vep])\n",
"vl"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v.Banner(single_line=True,\n",
" v_slots=[{\n",
" 'name': 'icon',\n",
" 'children': v.Icon(children=['mdi-thumb-up'])\n",
" }, {\n",
" 'name': 'actions',\n",
" 'children': v.Btn(text=True, color='deep-purple accent-4', children=['Action'])\n",
" }], \n",
" children=['One line message text string with two actions on tablet / Desktop'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"activated = v.Chip(children=['_'])\n",
"\n",
"items = [{\n",
" 'id': 1,\n",
" 'name': 'Applications :',\n",
" 'children': [\n",
" { 'id': 2, 'name': 'Calendar' },\n",
" { 'id': 3, 'name': 'Chrome' },\n",
" { 'id': 4, 'name': 'Webstorm', 'children': [\n",
" { 'id': 5, 'name': 'Test'}]},\n",
" ],\n",
"}]\n",
"\n",
"def on_activated(widget, event, data):\n",
" activated.children = [f'{data}']\n",
"\n",
"treeview = v.Treeview(items=items, selectable=True, activatable=True, v_model=[2])\n",
"treeview.on_event('update:active', on_activated)\n",
"\n",
"v.Container(row=True, children=[\n",
" v.Flex(xs12=True, children=[treeview]),\n",
" v.Flex(xs12=True, children=[activated])])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@ -1,5 +1,5 @@
1. 动画可以随时暂停 - 进度条 [0] ## plotly Silder
2. 下拉栏 - 典型函数 + custom function ## ipywidgets.SlectionSlider
3. 判断 n+1 和 n 是否为同一个函数,若相同则在同一个画布上画图
[d/x] 1. 动画可以随时暂停 - 进度条 [0] ## plotly Silder
[h/x] 2. 下拉栏 - 典型函数 + custom function ## ipywidgets.SlectionSlider
[] 3. 判断 n+1 和 n 是否为同一个函数,若相同则在同一个画布上画图
4. **自定义方向+步长**
5. 输入点坐标求得 gradient -> tangent plane -> 法线