【问题标题】:using data generator inside dash/plotly callbacks在破折号/绘图回调中使用数据生成器
【发布时间】:2020-10-27 03:06:18
【问题描述】:

我正在尝试在破折号应用的回调中使用数据生成器。这个想法是绘制一些正在数据生成器函数中更新的值。生成器是使用 yield 创建的,我的问题是如何在 dash 应用程序中以正确的方式使用生成器。以下是一些可能有助于澄清问题的信息:

# generator
def generator():
    while True
        # do some calculations
        yield output 

以及有关应用程序本身的一些信息:

app = dash.Dash(__name__)
app.layout = html.Div(
    [
        html.H1(children='Trial'),
        dcc.Graph(id='live-graph_1', style={'float': 'left','margin': 'auto'}),
        dcc.Graph(id='live-graph_2', style={'float': 'left','margin': 'auto'}),
        dcc.Graph(id='live-graph_3', style={'float': 'left','margin': 'auto'}),
        dcc.Interval(
            id='graph-update',
            interval=2*1000),
    ]
)

#############
## callback
#############
@app.callback([Output('live-graph_1', 'figure'),
               Output('live-graph_2', 'figure'),
               Output('live-graph_3', 'figure')],
              [Input('graph-update', 'n_intervals')])
def update_data(input_data):
   
   # step 1
   ###########################################
   # use data generator to produce new data;
   # which is not a simple loading or importing
   # function.
   ###########################################
   new_data = next(generator)

   # step 2
   # create three figures using new_data

   # step 3
   return fig1, fig2, fig3

应该提醒生成器已经过测试,并且 next(generator) 正在为每个调用生成正确的值;此外,dash 应用程序在没有生成器的情况下也能完美运行,但组合会导致以下错误:

Callback error updating live-graph_1.figure, live-graph_2.figure, live-graph_3.figure
StopIteration
new_data = next(generator)

我非常感谢您对此事的任何帮助。

【问题讨论】:

    标签: callback generator intervals yield plotly-dash


    【解决方案1】:

    StopIteration 异常表示that there are no further items produced by the iterator。根据您看到的错误,因此该错误似乎与 Dash 应用程序无关,而是与您的迭代器的实现有关(它耗尽了数据)。

    【讨论】:

    • 感谢您的评论,确实,new_data = next(generator) 可以很好地摆脱破折号,并为每个next 生成新的数据集;但是,在破折号内会引发这样的错误。我认为问题可以追溯到回调中 next 的使用。
    • 我之前没有听说过在回调上下文中应用 next 有任何问题。但是,当您将生成器创建为全局变量时(不建议这样做,请参见例如dash.plotly.com/sharing-data-between-callbacks),您可能会看到奇怪的行为 - 特别是如果您有多个客户端,因为它们都将共享同一个生成器对象。
    • 这是真的,因为生成器不是静态的。那么,是否可以在生成器本身内部使用 dash 应用程序?
    • 我认为这是不可能的。您能否详细说明您要使用生成器实现的目标?
    • 其实generator是一个神经网络模型,对一些图像进行一些预测。简而言之,读取图像(如视频帧),然后调用神经网络进行预测,然后在 dash 应用程序中使用图像及其预测来提供一种实时可视化。每个next(generator) 都给出了一个数据结构(如 c 中的数据结构),其中提供了对新图像的预测。 Dash 被用于处理视频帧及其预测。
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多