- pandas - numpy - plotly - jinja2 - seaborn - panel - paths: - ./squares.py
Welcome! Please modify bounds or reset to add rectangles.
import js import json import pandas as pd import numpy as np import plotly import seaborn as sns import plotly.graph_objects as go import plotly.io as pio from pyodide import create_proxy from squares import Rect, Square, SquareCanvas, check_bounds pd.set_option("display.precision", 4) cm = sns.color_palette("light:b", as_cmap=True) list_square_radii_1 = [3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1] list_squares_1 = [Square(radius) for radius in list_square_radii_1] B = SquareCanvas(max_bound=8, contents=list_squares_1) fig = B.generate_plotly(render="object") graphJSON = json.dumps( fig, cls=plotly.utils.PlotlyJSONEncoder ) js.plot(graphJSON, "chart1") sess = js.sessionStorage sess.setItem('chart1', graphJSON) sess.setItem('chart-data', B.contents) canvas_size = js.document.getElementById("canvas-size") reset_button = js.document.getElementById("reset-canvas") def inner_text_update(tag_id, value): js.document.getElementById(tag_id).innerText = str(value) def panel_df(df): import panel as pn pn.extension('tabulator', css_files=[pn.io.resources.CSS_URLS['font-awesome']]) if isinstance(df, pd.io.formats.style.Styler): style = df df = df.data else: style = df.style pn.extension() df = style.format( {i: "{:.,1f}".format for i in df.columns.to_list()} ) df.apply(highlight_max) df_widget = pn.widgets.Tabulator( df, # group_by=['area'], # Missing JS? pagination='local', page_size=10 ) js.document.getElementById('coordinates-message').innerHTML = '' pn.Row( df_widget, ).servable(target='coordinates-message') def highlight_max(s): """ highlight the maximum in a Series yellow. """ is_max = s == s.max() return ['background-color: yellow' if v else '' for v in is_max] def redraw_chart(canvas_var, message_out, show_text=True): xfig = canvas_var.generate_plotly(render="object", show_text=show_text) graph_json = json.dumps( xfig, cls=plotly.utils.PlotlyJSONEncoder ) js.plot(graph_json, "chart1") sess.setItem('chart1', graph_json) sess.setItem('chart-data', canvas_var.contents) inner_text_update(tag_id='messages', value=message_out) df = canvas_var.contents_frame() df[['center_x', 'center_y']] = \ df.center.str.replace( "[", "" ).str.replace( "]", "" ).str.split(", ", expand=True).astype( float ) df.drop(columns=["center"], inplace=True) total = df.apply(np.sum) total[df.columns[0]] = 'totals' df = df.append(pd.DataFrame(total.values, index=total.keys()).T, ignore_index=True) df = df.style df = df.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False) df = df.background_gradient(cmap=cm) panel_df(df) def reset_chart(a): redraw_chart( SquareCanvas(max_bound=int(canvas_size.value)), "Canvas reset." ) reset_button.addEventListener("click", create_proxy(reset_chart)) def update_chart_size(a): contents = sess.getItem('chart-data')[1:-1] B = SquareCanvas(max_bound=int(canvas_size.value)) for sq_def in contents.split("],"): import re text = sq_def.split("::")[0] text = text.replace("[", "").replace("]", "").replace(" ", "") split_text = re.split(r'(?=\d)', text, 1) if split_text[0] == "Square": try: B.add_contents(Square(side=int(split_text[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return if split_text[0] == "Rect": try: lw = text.split("Rect")[1] split_lw = lw.split("x") B.add_contents(Rect(length=int(split_lw[0]), width=int(split_lw[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return message_out = "Canvas updated." redraw_chart(B, message_out) canvas_update = js.document.getElementById("canvas-size-update") canvas_update.addEventListener("click", create_proxy(update_chart_size)) width = js.document.getElementById("width") length = js.document.getElementById("length") add_rect = js.document.getElementById("add-rect") def add_rectangle(a): contents = sess.getItem('chart-data')[1:-1] B = SquareCanvas(max_bound=int(canvas_size.value)) for sq_def in contents.split("],"): import re text = sq_def.split("::")[0] text = text.replace("[", "").replace("]", "").replace(" ", "") split_text = re.split(r'(?=\d)', text, 1) if split_text[0] == "Square": try: B.add_contents(Square(side=int(split_text[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return if split_text[0] == "Rect": try: lw = text.split("Rect")[1] split_lw = lw.split("x") B.add_contents(Rect(length=int(split_lw[0]), width=int(split_lw[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return try: B.add_contents(Rect(length=int(length.value), width=int(width.value))) except IndexError: inner_text_update("messages", "Couldn't place rectangle... Expand canvas?") return message_out = "Canvas updated." redraw_chart(B, message_out) add_rect.addEventListener("click", create_proxy(add_rectangle)) toggle_coords = js.document.getElementById("center-toggle") sess.setItem('show_center_coordinates', 1) def toggle_coords_visibility(a): contents = sess.getItem('chart-data')[1:-1] B = SquareCanvas(max_bound=int(canvas_size.value)) for sq_def in contents.split("],"): import re text = sq_def.split("::")[0] text = text.replace("[", "").replace("]", "").replace(" ", "") split_text = re.split(r'(?=\d)', text, 1) if split_text[0] == "Square": try: B.add_contents(Square(side=int(split_text[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return if split_text[0] == "Rect": try: lw = text.split("Rect")[1] split_lw = lw.split("x") B.add_contents(Rect(length=int(split_lw[0]), width=int(split_lw[1]))) except IndexError: inner_text_update("messages", "Couldn't place all... Expand canvas?") return show_center = sess.getItem('show_center_coordinates') sess.removeItem('show_center_coordinates') sess.setItem('show_center_coordinates', '' if show_center == '1' else '1') message_out = "Canvas updated." redraw_chart(B, message_out, show_text=bool(sess.getItem('show_center_coordinates'))) toggle_coords.addEventListener("click", create_proxy(toggle_coords_visibility))