1
0
mirror of https://github.com/pyscript/pyscript.git synced 2022-05-01 19:47:48 +03:00

Add Panel KMeans clustering example

This commit is contained in:
Philipp Rudiger
2022-04-09 17:15:03 +02:00
parent b7dc5e4076
commit dff11a8b51
3 changed files with 177 additions and 25 deletions

View File

@@ -65,7 +65,7 @@ def doc_json(model, target):
version = __version__,
))
def link_docs(pydoc, jsdoc):
def _link_docs(pydoc, jsdoc):
def jssync(event):
if (event.setter_id is not None):
return
@@ -76,9 +76,11 @@ def link_docs(pydoc, jsdoc):
jsdoc.on_change(pyodide.create_proxy(jssync), pyodide.to_js(False))
def pysync(event):
json_patch = process_document_events([event], use_buffers=False)[0]
jsdoc.apply_json_patch(JSON.parse(json_patch), {}, setter_id='js')
json_patch, buffers = process_document_events([event], use_buffers=True)
buffer_map = {}
for (ref, buffer) in buffers:
buffer_map[ref['id']] = buffer
jsdoc.apply_json_patch(JSON.parse(json_patch), pyodide.to_js(buffer_map), setter_id='js')
pydoc.on_change(pysync)
@@ -87,7 +89,7 @@ async def show(plot, target):
views = await Bokeh.embed.embed_item(JSON.parse(model_json))
print("Done embedding...")
jsdoc = views[0].model.document
link_docs(pydoc, jsdoc)
_link_docs(pydoc, jsdoc)
await show(row, 'myplot')
</py-script>

View File

@@ -1,4 +1,5 @@
<html><head>
<html>
<head>
<title>Panel Example</title>
<meta charset="iso-8859-1">
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.js"></script>
@@ -7,28 +8,21 @@
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@holoviz/panel@0.13.0-rc.5/dist/panel.min.js"></script>
<script type="text/javascript">
Bokeh.set_log_level("info");
</script>
<link rel="stylesheet" href="build/pyscript.css" />
<script defer src="build/pyscript.js"></script>
</head>
<body>
<py-env>
- bokeh
- numpy
</py-env>
<h1>Panel Example</h1>
<div id="myplot"></div>
<py-script>
</head>
<body>
<py-env>
- bokeh
- numpy
</py-env>
<h1>Panel Example</h1>
<div id="myplot"></div>
<py-script>
import asyncio
import micropip
import pyodide
await micropip.install(['panel==0.13.0rc8'])
await micropip.install(['panel==0.13.0rc9'])
import panel as pn
@@ -40,7 +34,6 @@ def callback(new):
row = pn.Row(slider, pn.bind(callback, slider))
await pn.io.pyodide.show(row, 'myplot')
</py-script>
</py-script>
</body>
</html>

View File

@@ -0,0 +1,157 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pyscript/Panel KMeans Demo</title>
<link rel="icon" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/icons/favicon.ico" type="">
<meta name="name" content="PyScript/Panel KMeans Demo">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" type="text/css" />
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/css/widgets.css" type="text/css" />
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/css/markdown.css" type="text/css" />
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/css/loading.css" type="text/css" />
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/css/dataframe.css" type="text/css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.9.3/dist/js/tabulator.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/panel.min.js"></script>
<script type="text/javascript">
Bokeh.set_log_level("info");
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/bundled/bootstraptemplate/bootstrap.css">
<link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0-rc.8/dist/bundled/defaulttheme/default.css">
<style>
#sidebar {
width: 350px;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="build/pyscript.css" />
<script defer src="build/pyscript.js"></script>
</head>
<body>
<py-env>
- bokeh
- numpy
- pandas
- scikit-learn
</py-env>
<div class="container-fluid d-flex flex-column vh-100 overflow-hidden" id="container">
<nav class="navbar navbar-expand-md navbar-dark sticky-top shadow" style="" id="header">
<button type="button" class="navbar-toggle collapsed" id="sidebarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="app-header">
<a class="title" href="/" >&nbsp;Panel</a>
<span class="title">&nbsp;-</span>
<a class="title" href="" >&nbsp;Pyscript KMeans Clustering Demo</a>
</div>
</nav>
<div class="row overflow-hidden" id="content">
<div class="sidenav" id="sidebar">
<ul class="nav flex-column">
<div class="bk-root" id="x-widget" data-root-id="1021"></div>
<div class="bk-root" id="y-widget" data-root-id="1026"></div>
<div class="bk-root" id="n-widget" data-root-id="1031"></div>
</ul>
</div>
<div class="col mh-100 float-left" id="main">
<div class="bk-root" id="intro" data-root-id="1008"></div>
<div class="bk-root" id="cluster-plot" data-root-id="1009"></div>
<div class="bk-root" id="table" data-root-id="1009"></div>
</div>
</div>
</div>
<py-script>
import asyncio
import micropip
from io import StringIO
from js import fetch
await micropip.install(['panel==0.13.0rc9', 'altair'])
import altair as alt
import panel as pn
import pandas as pd
from panel.io.pyodide import show
from sklearn.cluster import KMeans
pn.config.sizing_mode = 'stretch_width'
data = await fetch('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-28/penguins.csv')
penguins = pd.read_csv(StringIO(await data.text())).dropna()
cols = list(penguins.columns)[2:6]
x = pn.widgets.Select(name='x', options=cols, value='bill_depth_mm')
y = pn.widgets.Select(name='y', options=cols, value='bill_length_mm')
n_clusters = pn.widgets.IntSlider(name='n_clusters', start=1, end=5, value=3)
@pn.depends(x.param.value, y.param.value, n_clusters.param.value)
def get_clusters(x, y, n_clusters):
kmeans = KMeans(n_clusters=n_clusters)
est = kmeans.fit(penguins[cols].values)
df = penguins.copy()
df['labels'] = est.labels_.astype('str')
centers = df.groupby('labels').mean()
table.value = df
return (
alt.Chart(df)
.mark_point(size=100)
.encode(
x=alt.X(x, scale=alt.Scale(zero=False)),
y=alt.Y(y, scale=alt.Scale(zero=False)),
shape='labels',
color='species'
).properties(width=800) +
alt.Chart(centers)
.mark_point(size=200, shape='cross', color='black')
.encode(x=x+':Q', y=y+':Q')
)
table = pn.widgets.Tabulator(penguins, pagination='remote', page_size=10)
intro = """
This app provides an example of **building a simple dashboard using
Panel**.\n\nIt demonstrates how to take the output of **k-means
clustering on the Penguins dataset** using scikit-learn, parameterizing
the number of clusters and the variables to plot.\n\nThe entire
clustering and plotting pipeline is expressed as a **single reactive
function** that responsively returns an updated plot when one of the
widgets changes.\n\n The **`x` marks the center** of the cluster.
"""
await show(x, 'x-widget')
await show(y, 'y-widget')
await show(n_clusters, 'n-widget')
await show(intro, 'intro')
await show(get_clusters, 'cluster-plot')
await show(table, 'table')
</py-script>
<script>
$(document).ready(function () {
$('#sidebarCollapse').on('click', function () {
$('#sidebar').toggleClass('active')
$(this).toggleClass('active')
var interval = setInterval(function () { window.dispatchEvent(new Event('resize')); }, 10);
setTimeout(function () { clearInterval(interval) }, 210)
});
});
</script>
</body>
</html>