Compare commits

..

14 Commits

9 changed files with 437 additions and 982 deletions

View File

@ -1,215 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "b705b060",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Steepest Descent Method\n",
"\n",
"Instructor: Dr.Yuhui Deng\n",
"\n",
"![level_gradient](figure/level_gradient.png)"
]
},
{
"cell_type": "markdown",
"id": "f576c3bd",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## Problem Description\n",
"\n",
"Problem: \n",
"\n",
"$\\begin{align*} \n",
"min(fx) \\\\\n",
"s.t. \\ x \\in \\mathbb{R}^n\n",
"\\end{align*}$\n",
"where\n",
"\n",
"* $f: \\mathbb{R}^n \\rightarrow \\mathbb{R}$\n",
"* No constraints are placed on the variables $X$\n"
]
},
{
"cell_type": "markdown",
"id": "c6e94df1",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# One Dimential Function\n",
"\n",
"$$min \\ f(x)=x^2 - 4x + 7$$\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "af1d5646-4b13-4039-9f76-8042bc9dbda3",
"metadata": {},
"outputs": [],
"source": [
"from optimization.gd_new import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8ce3dbbd-a698-448b-a2c6-772286c745d5",
"metadata": {},
"outputs": [],
"source": [
"gd1 = gd_1d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1765810-6cd8-4e1a-aaa6-7691a7b2a42e",
"metadata": {},
"outputs": [],
"source": [
"gd2 = gd_2d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "06b73a46-f6d5-420d-a668-abaf2c6127a3",
"metadata": {},
"outputs": [],
"source": [
"expr = sympify(gd2.wg_expr.value)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e7504cf8-514c-444a-bd62-91a13b067cf6",
"metadata": {},
"outputs": [],
"source": [
"expr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff3f9fa9-9071-45c5-a939-d5f0bbe7b37e",
"metadata": {},
"outputs": [],
"source": [
"from sympy import *\n",
"from sympy.abc import x\n",
"expr = \"(x - 2)**2 + 3\"\n",
"ex = sympify(expr)\n",
"solve(ex, x)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "61e0d2b8-41c8-4790-8b25-2df6ba4c3625",
"metadata": {},
"outputs": [],
"source": [
"from optimization.common import *"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cc84e26c-7135-427b-9a5b-c39b6b495fe5",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "e2a6bc45f7354f529c8475f034416135",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(Text(value='-2 * x * sin(-(pi/4) * x)+10', description='Expression:', style=Text…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c2c3118f55d241e68649a094a6bb3836",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "cdc830df33fe4705b448245a1d64c335",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"a = func_1d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "98061d97-555e-486a-a07d-1b8c37cd2471",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Slideshow",
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 421 KiB

View File

@ -1,118 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "af1d5646-4b13-4039-9f76-8042bc9dbda3",
"metadata": {},
"outputs": [],
"source": [
"from optimization.gd_new import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8ce3dbbd-a698-448b-a2c6-772286c745d5",
"metadata": {},
"outputs": [],
"source": [
"gd1 = gd_1d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1765810-6cd8-4e1a-aaa6-7691a7b2a42e",
"metadata": {},
"outputs": [],
"source": [
"gd2 = gd_2d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "06b73a46-f6d5-420d-a668-abaf2c6127a3",
"metadata": {},
"outputs": [],
"source": [
"expr = sympify(gd2.wg_expr.value)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e7504cf8-514c-444a-bd62-91a13b067cf6",
"metadata": {},
"outputs": [],
"source": [
"expr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ff3f9fa9-9071-45c5-a939-d5f0bbe7b37e",
"metadata": {},
"outputs": [],
"source": [
"from sympy import *\n",
"from sympy.abc import x\n",
"expr = \"(x - 2)**2 + 3\"\n",
"ex = sympify(expr)\n",
"solve(ex, x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61e0d2b8-41c8-4790-8b25-2df6ba4c3625",
"metadata": {},
"outputs": [],
"source": [
"from optimization.common import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cc84e26c-7135-427b-9a5b-c39b6b495fe5",
"metadata": {},
"outputs": [],
"source": [
"a = func_1d()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "98061d97-555e-486a-a07d-1b8c37cd2471",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Slideshow",
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -1,227 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "011c5f34-be40-4f0b-8146-73f66ba18672",
"metadata": {},
"outputs": [],
"source": [
"from optimization.common import *\n",
"from optimization.gradient import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "302d9c60",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"funcPlot1d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a4827f0c",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "776f68cc5732452382ee39d4ac337bba",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(VBox(children=(Text(value='sin(x) + sin((10.0 / 3.0) * x)', description='Express…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "0032d539590641b484466da05a125e19",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "cdc7760b287b4a7881f0c2288ddcb0af",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<optimization.gradient.gd_1d at 0x1a753d29748>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd_1d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7c589589",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"funcPlot2d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "f28bd167",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "3ad25604b04c4023a838429d3ceccbaa",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(Dropdown(options=(('(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d913b214c8a54e1897eb161fdc41d04f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "39765310aa524308a29842b1770f7f3c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "6d9886e39bd44ab39269fb3cd8e27af0",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<optimization.gradient.gd2d at 0x1a752773f88>"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd2d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5651fc9-3fcd-4e91-8d3c-04897da1ea02",
"metadata": {},
"outputs": [],
"source": [
"gd2d_compete(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f0c08039-6581-4b40-9e08-df40f8395e2b",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Slideshow",
"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": 5
}

View File

@ -28,7 +28,7 @@ def array_mesh(data, n):
array_mesh.append(data[i:i+n])
return np.vstack(array_mesh)
class gd_1d(object):
class gd1d(object):
def __init__(self, environ:str="jupyterlab"):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
self.wg_expr = widgets.Text(value="sin(x) + sin((10.0 / 3.0) * x)",
@ -150,7 +150,7 @@ class gd2d(object):
def initialization_default(self, environ):
pio.renderers.default = environ # 'notebook' or 'colab' or 'jupyterlab'
self.wg_expr = widgets.Dropdown(options=[("(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)", "(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)"), ("x1 - x2 + 2*x1*x2 + 2*x1**2 + x2**2", "x1 - x2 + 2*x1*x2 + 2*x1**2 + x2**2")], value="(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)", descrption="Expression")
self.wg_expr = widgets.Dropdown(options=[("(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)", "(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)"), ("x1 - x2 + 2*x1*x2 + 2*x1**2 + x2**2", "x1 - x2 + 2*x1*x2 + 2*x1**2 + x2**2"), ("(4-x1)**2 + x2**2", "(4-x1)**2 + x2**2"), ("x1**2 + (10*x2)**2", "x1**2 + (10*x2)**2")], value="(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)", descrption="Expression")
self.wg_x0 = widgets.Text(value="0,2", description="Startpoint:")
self.wg_lr = widgets.FloatText(value="1e-1", description="step size:")
self.wg_epsilon = widgets.FloatText(value="1e-5", description="criterion:")
@ -211,10 +211,11 @@ class gd2d(object):
x1 = symbols("x1")
x2 = symbols("x2")
expr = sympify(self.wg_expr.value)
xx1 = np.arange(0, 5, 0.25)
xx2 = np.arange(0, 5, 0.25)
#xx1 = np.arange(np.array(self.xn_list)[:, 0].min() * 0.5, np.array(self.xn_list)[:, 0].max() * 1.5, 0.1)
#xx2 = np.arange(np.array(self.xn_list)[:, 1].min() * 0.5, np.array(self.xn_list)[:, 1].max() * 1.5, 0.1)
expression_list = ["(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)", "(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x2**2 * E**(-x2)"]
if self.wg_expr.value in expression_list:
xx1, xx2 = np.arange(0, 5, 0.25), np.arange(0, 5, 0.25)
elif self.wg_expr.value == "(4-x1)**2 + x2**2":
xx1, xx2 = np.arange(-4, 12, 0.25), np.arange(-8, 8, 0.25)
xx1_tangent = np.arange(np.array(self.xn_list)[:, 0].min(), np.array(self.xn_list)[:, 0].max(), 0.1)
xx2_tangent = np.arange(np.array(self.xn_list)[:, 1].min(), np.array(self.xn_list)[:, 1].max(), 0.1)
xx1_o, xx2_o = xx1, xx2
@ -229,14 +230,22 @@ class gd2d(object):
partial_x2 = lambdify((x1, x2), diff(expr, x2), "numpy")
self.partial_x1, self.partial_x2 = partial_x1, partial_x2
plane = partial_x1(np.array(self.xn_list)[:, 0], np.array(self.xn_list)[:, 1]) * (x1 - np.array(self.xn_list)[:, 0]) + partial_x2(np.array(self.xn_list)[:, 0], np.array(self.xn_list)[:, 1]) * (x2 - np.array(self.xn_list)[:, 1]) + f_xn
self.plane = plane
z = [lambdify((x1, x2), plane[i], "numpy")(xx1_tangent, xx2_tangent) for i in range(0, len(plane))]
self.z = z
try:
if z[-1] == 0:
z[-1] = np.zeros(z[0].shape)
except:
pass
## projection
z_offset = (np.min(fx)) * np.ones(fx.shape)
proj_z = lambda x, y, z: z
colorsurfz = proj_z(xx1, xx2, fx)
self.z = z
self.xx1_tangent, self.xx2_tangent = xx1_tangent, xx2_tangent
self.f_xn = f_xn
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'surface'}, {'type': 'surface'}]])
fig.add_trace(go.Surface(contours = {"x": {"show": True}, "y":{"show": True}, "z":{"show": True}}, x=xx1, y=xx2, z=fx), row=1, col=1)
fig.add_trace(go.Scatter3d(x=None, y=None, z=None, marker=dict(size=5)), row=1, col=1)
@ -245,11 +254,11 @@ class gd2d(object):
fig.add_trace(go.Scatter3d(x=None, y=None, z=None, marker=dict(size=5)), row=1, col=2)
fig.add_trace(go.Scatter3d(x=None, y=None, z=None, marker=dict(size=5)), row=1, col=2)
frames = [go.Frame(data=[go.Surface(visible=True, showscale=False, opacity=0.8),
go.Scatter3d(x=np.array(self.xn_list)[:k,0], y=np.array(self.xn_list)[:k,1], z=f_xn, marker=dict(size=5), line={"color":"blue", "width":3, 'dash': 'dash'}),
go.Scatter3d(x=np.array(self.xn_list)[:k+1,0], y=np.array(self.xn_list)[:k+1,1], z=f_xn, marker=dict(size=5), line={"color":"red", "width":3, 'dash': 'dash'}),
go.Surface(visible=False, x=xx1_tangent, y=xx2_tangent, z=z[k]),
go.Surface(visible=True, showscale=False, opacity=0.8),
go.Scatter3d(x=np.array(self.xn_list)[:k, 0], y=np.array(self.xn_list)[:k, 1], z=f_xn, line={"color":"blue", "width":3, 'dash': 'dash'}),
go.Scatter3d(x=np.array(self.xn_list)[:k, 0].flatten(), y=np.array(self.xn_list)[:k, 1].flatten(), z=z_offset.flatten(), marker=dict(size=5), line={"color":"green", "width":3, 'dash': 'dash'})],
go.Scatter3d(x=np.array(self.xn_list)[:k+1, 0], y=np.array(self.xn_list)[:k+1, 1], z=f_xn, line={"color":"red", "width":3, 'dash': 'dash'}),
go.Scatter3d(x=np.array(self.xn_list)[:k+1, 0].flatten(), y=np.array(self.xn_list)[:k, 1].flatten(), z=z_offset.flatten(), marker=dict(size=5), line={"color":"green", "width":3, 'dash': 'dash'})],
traces=[0, 1, 2, 3, 4, 5]) for k in range(len(f_xn))]
fig.frames = frames
self.fig_frames = frames
@ -337,6 +346,30 @@ class gd2d_compete(object):
display(self.compute_output)
self.button_plot.on_click(self.plot)
display(self.plot_output)
def compute_default(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 compute(self, *args):
with self.compute_output:
@ -349,16 +382,28 @@ class gd2d_compete(object):
self.xn_p1_list.append(x0)
direction_p0 = np.array(self.wg_direction_p0.value.split(","), dtype=float)
direction_p1 = np.array(self.wg_direction_p1.value.split(","), dtype=float)
self.timer = self.timer + 1
# calcualte next point position
x0_p0 = self.xn_p0_list[self.timer-1] + self.wg_lr.value * direction_p0
x0_p1 = self.xn_p1_list[self.timer-1] + self.wg_lr.value * direction_p1
self.xn_p0_list.append(x0_p0)
self.xn_p1_list.append(x0_p1)
self.xn_p1_list.append(x0_p1)
f = lambdify((x1, x2), expr, "numpy")
f_xn = f(np.array([x0_p0, x0_p1])[:, 0], np.array([x0_p0, x0_p1])[:, 1])
self.expr = expr
self.x0_p0 = x0_p0
self.x0_p1 = x0_p1
gradient_p0 = np.array([diff(expr, x1).subs(x1, x0_p0[0]).subs(x2, x0_p0[1]),
diff(expr, x2).subs(x1, x0_p0[0]).subs(x2, x0_p0[1])], dtype=float)
gradient_p1 = np.array([diff(expr, x1).subs(x1, x0_p1[0]).subs(x2, x0_p1[1]),
diff(expr, x2).subs(x1, x0_p1[0]).subs(x2, x0_p1[1])], dtype=float)
clear_output(wait=True)
print("a1({}): {}, a2({}): {}".format(self.timer, np.append(x0_p0, f_xn[0]), self.timer,np.append(x0_p1, f_xn[1])))
print("coordinate a1({}): {}, a2({}): {}".format(self.timer, np.append(x0_p0, f_xn[0]), self.timer,np.append(x0_p1, f_xn[1])))
print("gradient: a1({}): {}, a2({}): {}".format(self.timer, gradient_p0, self.timer,gradient_p1))
def plot(self, *args):
with self.plot_output:

View File

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

View File

@ -1,3 +1,7 @@
tqdm
numpy
scipy
sympy
plotly
ipywidgets
matplotlib
ipywidgets

374
sec4.2.ipynb Normal file
View File

@ -0,0 +1,374 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "011c5f34-be40-4f0b-8146-73f66ba18672",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from algorithm.optimization.common import *\n",
"from algorithm.optimization.gradient import *\n",
"from IPython.display import IFrame"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7a1ba495-73ac-4710-bab7-edb429ab9628",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"\n",
" <iframe\n",
" width=\"1080\"\n",
" height=\"800\"\n",
" src=\"https://ufal.mff.cuni.cz/~straka/courses/npfl129/2223/demos/mnist_web.html\"\n",
" frameborder=\"0\"\n",
" allowfullscreen\n",
" \n",
" ></iframe>\n",
" "
],
"text/plain": [
"<IPython.lib.display.IFrame at 0x7ff78cb8c7c0>"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"IFrame(\"https://ufal.mff.cuni.cz/~straka/courses/npfl129/2223/demos/mnist_web.html\", width=1080, height=800)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a4827f0c",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "09273efb924743fe9166063fedbbdb01",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(VBox(children=(Text(value='sin(x) + sin((10.0 / 3.0) * x)', description='Express…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8fb9b9acda4645d68c9edce4f9f90327",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8967e9daa8514d2bb5c1357d3eed43ef",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<algorithm.optimization.gradient.gd1d at 0x7ff78cb8c700>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd1d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "bb36631d-cc88-4a66-b057-33b4355eb757",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "5e92624f2062434ca3acdb4ad697d220",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(Dropdown(options=(('(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a44ccfbc22e14a8e8c0448d2dd59910d",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bf12052c62284e63bd556f279581d5dc",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<algorithm.optimization.gradient.gd2d_compete at 0x7ff78813e770>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd2d_compete(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f28bd167",
"metadata": {
"slideshow": {
"slide_type": "subslide"
},
"tags": []
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b79aad48bb9f4cfa992dcea0aa720e67",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(Dropdown(options=(('(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a86144f7d0334c4cba8712372558d6bf",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "9808dc0661a745249011c3b46041d295",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "aaa14c821855466999a584708a88eae5",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<algorithm.optimization.gradient.gd2d at 0x7ff78c663910>"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd2d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "d5651fc9-3fcd-4e91-8d3c-04897da1ea02",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "4fd3c62cc07f4d1096f71b945c85da49",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HBox(children=(Dropdown(options=(('(1 - 8 * x1 + 7 * x1**2 - (7/3) * x1**3 + (1/4) * x1**4) * x…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "594ba59306d044f5a0465bbd16b66572",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "4395055562f84b6ba2f06b9f7212f761",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "94f9b8e9a80547f39f225c74dcbccadd",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"<algorithm.optimization.gradient.gd2d at 0x7ff78813f850>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gd2d(environ=\"jupyterlab\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "318a7308-55ea-43f4-bdee-df614a22f40d",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Slideshow",
"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.10.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}