pythonpyvizholovizpanel-pyviz

Use button to trigger action in Panel with Parameterized Class and when button action is finished have another dependency updated (Holoviz)


I am building a dashboard with Panel Holoviz using a Parameterized Class .

In this Class I would like a button that, when pushed starts training a model, and when the model is finished training, it needs to show a graph based on that model.

How do I build such dependencies in Panel using a Class?


Solution

  • The example below shows how when the button is pushed, it triggers 'button', which triggers method train_model(), which when finished, triggers method update_graph().
    The key lies in the lambda x: x.param.trigger('button') and @param.depends('button', watch=True):

    import numpy as np
    import pandas as pd
    import holoviews as hv
    import param
    import panel as pn
    hv.extension('bokeh')
    
    class ActionExample(param.Parameterized):
           
        # create a button that when pushed triggers 'button'
        button = param.Action(lambda x: x.param.trigger('button'), label='Start training model!')
          
        model_trained = None
        
        # method keeps on watching whether button is triggered
        @param.depends('button', watch=True)
        def train_model(self):
            self.model_df = pd.DataFrame(np.random.normal(size=[50, 2]), columns=['col1', 'col2'])
            self.model_trained = True
    
        # method is watching whether model_trained is updated
        @param.depends('model_trained', watch=True)
        def update_graph(self):
            if self.model_trained:
                return hv.Points(self.model_df)
            else:
                return "Model not trained yet"
    
    action_example = ActionExample()
    
    pn.Row(action_example.param, action_example.update_graph)
    

    Helpful documentation on the Action button:
    https://panel.pyviz.org/gallery/param/action_button.html#gallery-action-button

    Other helpful example of Action param:
    https://github.com/pyviz/panel/issues/239

    BEFORE pushing button:

    button not pushed yet no graph shown


    AFTER pushing button:

    button triggers method and dependent method