Package: simple-pydash
SimplePyDashSimplePyDashis a versatile, browser-based dashboard designed for real-time data plotting. With a focus on simplicity, it allows Python developers to easily visualize data streams without complex setup or dependencies.Although originally developed to facilitate real-time plotting of OpenAI Gym environments for observing agent behavior, the versatility of SimplePyDash extends its utility beyond this use case, making it an excellent tool for many other data visualization scenarios.Under the hood, SimplePyDash leverages theFastAPIweb framework and usesWebSocketfor bidirectional communication.RequirementsRunningpip install simple-pydashwill install all the requirements. Otherwise you can dopip install fastapi uvicorn[standard] numpy Pillow plotly sty jinja2 matplotlib.For running the OpenAI Gym example, you additionally need to have  thegymlibrary. This is not a requirement for usingsimple-pydash:pip install gymInstallationTo install SimplePyDash, you caneither:Install directly from the repository:pip install git+https://github.com/ValerioB88/browser-dashboard.gitORClone/fork the repository, and install in editable mode (recommended if you plan to modify the code):pip install -e {path_to_cloned_folder}ORfrom PyPl:pip install simple-pydash(this won't include the examples, which you can download from GitHub).ExamplesThe best way to get started is to explore the examples provided.examples/openai_gym.pydemonstrates plotting a gym environment (requires thegymlibrary), whileexamples/generic.pyis a more general use case.To run an example, navigate to the repository folder and execute the Python module:cd {path_to_repo_folder}
python -m examples.gymThe script will try to use the first available port starting at8000. Open your browser and visitlocalhost:8000(or another port if indicated in the console output).If you are running the script on a server, port forwarding will be necessary. Open a new terminal on your local machine and type:ssh -L {portnum}:localhost:{portnum} {username}@{machinename}For example:ssh -L 8000:localhost:8000 val@titan.itThen, open your browser and visitlocalhost:8000to view the dashboard.Quick StartSimplePyDash organizes your dashboard into columns (2 by default). TheCustomAPIobject takes amodel_objand a series ofDashboardComponents. The user-definedmodel_objis a simple iterator performing the computations (e.g., running a neural network and returning an action).DashboardComponentsare widgets that can be displayed in the browser.SimplePyDash includes several default widgets, includingHeatMap,LinePlot,StaticImage,TextInfo, andRenderGymEnv. Theplotwidgets, such asHeatMapandLinePlot, are based on thePlotlygraphics library, allowing for easy addition of Plotly graphs to your widget list.Here's a basic instance of aCustomAPIobject (seeexamples/generic.pyfor the full example):server=CustomAPI(model_obj=DummyModel,dash_comps=[GeneralTextInfo(location_col_idx=0,use_scroll=False),MatplotlibPlot(location_col_idx=0,width=500),AppendScatterPlot(get_new_data_fun=lambdam:np.random.randn(2,2).tolist(),location_col_idx=0,mode="markers",width=500,height=350,),HeatMap(get_new_data_fun=lambdam:m.rnd_matrix,clr_min=-1,clr_max=1,location_col_idx=1,height=420,),AppendScatterPlot(legends=["Rnd","Rnd2",],get_new_data_fun=lambdam:m.rnd_lines.tolist(),location_col_idx=1,width=500,height=350,),],model_params=dict(num_lines=3),)We'll talk about themodel_objin a second. For now consider thedash_comps(DashComponents). We provide 5 components: a Text Box, a matplotlib Barplot, a HeatMap, a Scatter plot and a Line plot. Notice that the using matplotlib is discouraged in favour of Plotly, but here we show that it's possible to integrate matplotlib plots within your dashboard.SimplePyDashautomatically arranges these 5 components in 2 columns, as specified by the fact that theirlocation_col_idxis 0 and 1:If thelocation_col_idxof theHeatMapwas=2, this would automatically create 3 columns:Notice that the order in which the widgets are placed in a column corresponds to the order they are passed todash_comps.EachDashComponentwill have a defaultwidthandheight. However, you can modify one or both of them to make the widget bigger or smaller. This will not resize the whole column. When using more than 2 columns,SimplePyDashwill automatically span the whole page, otheewise it will center the columns in the middle of the page. You can control this behaviour by passingwide_page=True/FalsetoCustomAPI.ModelTheModelmust be an infinite iterator that performs computations for the data you want to plot. Take theDummyModelused inexamples/generic.py:classDummyModel(Model):tot_steps=0def__init__(self,num_lines,**kwargs):self.num_lines=num_linessuper().__init__(**kwargs)def__iter__(self):whileTrue:self.rnd_matrix=np.random.randn(10,10)self.rnd_lines=np.random.randint(-3,3,(self.num_lines,1))self.tot_steps+=1yieldNonedefstop(self):passIn a real life scenario, this class would perform the computation that you want to plot. For example, it might contain a neural netwok, one or several RL agents, etc. For an example with OpenAI Gym Environment, checkexamples/openai_gym.py.Plotly ComponentsHeatMapandAppendScatterPlotare Plotly components.AppendScatterPlotcan be used both for scatter and line plots: just pass the argumentmode='markers'for a scatter plot andmode='lines'for a line plot (this is following Plotly convention). these are Plotly figures which are passed to the web browser. Implementing a new plotting component just a bit more effort than creating a new Plotly plot: each component needs to implement arenderfunction which specifies what to do with the figure at each iteration. ForHeatMapandAppendScatterPlot, therenderfunction calls a user-providedget_new_data_funwhich takes some data and use them to update the Plotly figure. In this way theAppendScatterPlotandHeatMapare general and can be used for any model.  However, you can create your ownPlotlyComponentthat simple plots some data specific to your own model. This is easy, sincerenderhas access to the whole model object, so that you can do something likeself.fig.data[0].z = model.agents[0].energy_level. .CanvasTheCanvasmodule returns an image for rendering animations made of individual images in the browser. This could be an OpenAI rendering (usingRenderGymEnvmodule) or any other image (e.g., a matplotlib figure, a static image, etc.).To extendCanvas, simply create a new class that overrides therendermethod. For instance, theRenderGymEnvclass is defined as follows:classRenderGymEnv(Canvas):defrender(self,model):canvas=model.env.render()canvas=Image.fromarray(canvas)returnPIL2base64(canvas)TheCanvasmodule expects the render output to be abase64string. A PIL image can be converted to this format usingPIL2base64. If you have a matplotlib figure, usefig2PILfollowed byPIL2base64. We do not reccomend using matplotlib figures as the aren't as fast as Plotly plots, but the option is there for you.Settings and PerformanceUpon running SimplePyDash, you will find aSettingsdropdown menu in the navigation bar in your web browser. Here, you can specify the desired FPS . Note that while WebSocket will attempt to maintain the specified rate, it's not guaranteed to always match it.By default, SimplePyDash runs one iteration of theModelobject, computes the result for each dashboard component, and renders the result in the browser. To boost performance, you can perform multipleModeliterations and computations before rendering to the browser. Adjust theNum. Model Iters x Gfx Updatevalue in the Settings to do so. This could result in a massive speed up.Some modern browsers such as Edge use an "Efficiency mode" which will slow down websocket transfer even for tabs that are in the foreground! If you see a sudden slowdown after the first 10 seconds or so, and the slowdown disappears if you interact with the page in any way (random pressing around), it means that the browser is doing performing "optimisations" on your tab. You can prevent this, but it depends on your browser. For example, in Edge, go to Settings->Systems and performance->Never put these sites to sleep and addlocalhost:8000.What performance should I expect?Performance will depend on a variety of factors. As a guideline, with 1 iteration per graphic update, I get a FPS of a least 8 with theexamples/generic.py(which, recall, uses a Matplotlib plot which is not efficient). I get 14 FPS withexamples/openai_gym.py. Of course, increasing the iterations per update will significantly increase that.