Ошибка типа: update_graph () отсутствует 1 обязательный позиционный аргумент: 'date_value' - PullRequest
1 голос
/ 13 января 2020

У меня есть простая база данных, как на картинке ниже:

enter image description here

, и запрос выглядит так:

SELECT 
       [Date]
      ,[eNodeBName]
      ,[Downlinkbandwidth]
      ,[DownlinkEARFCN]
      ,[CellName]
      ,[LocalCellId]
      ,[PhysicalcellID]
      ,[LRRCConnReqAtt]
      ,[RRCSetupSuccessRate]
      ,[InterFreqSuccessRate4G]
      ,[IntraRATHOSucccessRate]
      ,[IntraFreqSuccessRate4G]
      ,[CellDLMaxThroughputMbps]
      ,[CellDownlinkAverageThroughputMbps]
  FROM [myDB].[dbo].[input]

Теперь мне нужно создать интерактивную диаграмму, которая зависит от входных данных, таких как указатель даты и выпадающий список.

Поскольку это образец GUI, который я создал для диаграммы, выведите эти входные данные, как показано на рисунке ниже:

enter image description here

Теперь я создаю диаграмму на основе названия столбцов, как показано на рисунке ниже:

enter image description here

, так как это связанный запрос, как показано ниже:

SELECT 
       [Date]
      ,[CellName]
      ,[LRRCConnReqAtt]
      ,[RRCSetupSuccessRate]
      ,[InterFreqSuccessRate4G]
      ,[IntraRATHOSucccessRate]
      ,[IntraFreqSuccessRate4G]
      ,[CellDLMaxThroughputMbps]
      ,[CellDownlinkAverageThroughputMbps]
  FROM [myDB].[dbo].[input]

Так что теперь ось X должна быть столбцом Date, а ось y связана с приведенными ниже. столбцы KPI столбцы:

SELECT 
       [LRRCConnReqAtt]
      ,[RRCSetupSuccessRate]
      ,[InterFreqSuccessRate4G]
      ,[IntraRATHOSucccessRate]
      ,[IntraFreqSuccessRate4G]
      ,[CellDLMaxThroughputMbps]
      ,[CellDownlinkAverageThroughputMbps]
  FROM [myDB].[dbo].[input]

Итак, теперь у нас есть уникальный столбец, содержащий уникальные значения, называется CellName, это имя ячейки, я хочу создать простую диаграмму для этого уникального значения на основе даты columnn и столбец KPI.

Так, например, я хочу показать график для определенного CellName = 2002334 для KPI * 1 039 * по данным с 27 декабря по 9 января. Поэтому мне нужна диаграмма, как показано на рисунке ниже, и это пример диаграммы, созданной в Excel.

enter image description here

и это мой код:

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from sqlalchemy import create_engine
import datetime
from datetime import datetime as dt
from dash.dependencies import Input, Output

# connect db
engine = create_engine('mssql+pyodbc://WWX542337CDCD\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()

start = datetime.datetime(2019, 12, 2)
end = datetime.datetime(2019, 12, 15)

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

lte_kpis = pd.read_sql('SELECT * FROM [myDB].[dbo].[input]',
                       engine)

lte_kpis_raw = pd.read_sql('SELECT LRRCConnReqAtt, RRCSetupSuccessRate, InterFreqSuccessRate4G, IntraRATHOSucccessRate, IntraFreqSuccessRate4G,CellDLMaxThroughputMbps, CellDownlinkAverageThroughputMbps FROM [myDB].[dbo].[input]',
                           engine)

scale_1 = ['LRRCConnReqAtt']
scale_2 = ['RRCSetupSuccessRate', 'InterFreqSuccessRate4G', 'IntraRATHOSucccessRate', 'IntraFreqSuccessRate4G']
scale_3 = ['CellDLMaxThroughputMbps', 'CellDownlinkAverageThroughputMbps']

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

availble_cell = lte_kpis['CellName'].unique()

# availble_cell = lte_kpis.unique(lte_kpis[['Date', 'Site Name', 'Cell CI', 'Cell LAC']].values.ravel('K'))

app.layout = html.Div([
    dcc.Dropdown(
        id='cell-name-xaxis-column',
        options=[{'label': i, 'value': i} for i in availble_cell],
        value='2205516'
    ),

    dcc.Dropdown(
        id='myColumns',
        options=[{'label': col, 'value': col} for col in lte_kpis_raw.columns],
        multi=True,
        value='LRRCConnReqAtt'
    ),

    dcc.DatePickerRange(
        id='my-date-picker-range',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2030, 9, 19),
        initial_visible_month=dt(2019, 10, 5),
        start_date=dt(2019, 10, 1),
        end_date=dt(2020, 1, 1)
    ),
    html.Div(id='output-container-date-picker-range'),

    dcc.Graph(
        style={'height': 300},
        id='my-graph'
    )

])


@app.callback(
    Output('my-graph', 'figure'),
    [Input('cell-name-xaxis-column', 'value'),
     Input('myColumns', 'value')])
def update_graph(xaxis_column_name, yaxis_column_name, date_value):
    dff = lte_kpis[lte_kpis['Date'] == date_value]

    return {
        'data': [dict(
            x=dff[dff['Date'] == xaxis_column_name]['Value'],
            y=dff[dff['Date'] == yaxis_column_name]['Value'],
            text=dff[dff['Date'] == yaxis_column_name]['CellName'],
            mode='line',
            line={
                'size': 15,
                'opacity': 0.5
            }
        )],
    }


if __name__ == '__main__':
    app.run_server(debug=True)

Обратите внимание, что я хочу разместить более одного KPI на одном графике с разными графиками ....

Поскольку значения шкалы в этих KPI немного отличаются, поэтому я попытался создать три типа объектов со значениями масштаба имен столбцов, как показано ниже:

scale_1 = ['LRRCConnReqAtt']
scale_2 = ['RRCSetupSuccessRate', 'InterFreqSuccessRate4G', 'IntraRATHOSucccessRate', 'IntraFreqSuccessRate4G']
scale_3 = ['CellDLMaxThroughputMbps', 'CellDownlinkAverageThroughputMbps']

, и это ошибка, которую я обнаружил:

TypeError: update_graph() missing 1 required positional argument: 'date_value'

Traceback (most recent call last)
File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\dash\dash.py", line 1337, in add_context

        def wrap_func(func):
            @wraps(func)
            def add_context(*args, **kwargs):
                # don't touch the comment on the next line - used by debugger
                output_value = func(*args, **kwargs)  # %% callback invoked %%
                if multi:
                    if not isinstance(output_value, (list, tuple)):
                        raise exceptions.InvalidCallbackReturnValue(
                            "The callback {} is a multi-output.\n"
                            "Expected the output type to be a list"
TypeError: update_graph() missing 1 required positional argument: 'date_value'
Traceback (most recent call last):
  File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\dash\dash.py", line 1337, in add_context
    output_value = func(*args, **kwargs)  # %% callback invoked %%
TypeError: update_graph() missing 1 required positional argument: 'date_value'

Отредактировано:

Я пытался использовать по-другому @Callback но я нашел KeyError, связанный с ошибкой ниже

KeyError: '2205516'

Traceback (most recent call last)
File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\pandas\core\indexes\base.py", line 2897, in get_loc
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc

File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc

File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item

File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

During handling of the above exception, another exception occurred:
File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '2205516'
Traceback (most recent call last):
  File "C:\Users\mwx825326\PycharmProjects\MyReference\venv\Lib\site-packages\pandas\core\indexes\base.py", line 2897, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '2205516'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '2205516'

, и это новый обратный вызов

@app.callback(
    Output(component_id='my-graph', component_property='figure'),
    [Input(component_id='cell-name-xaxis-column', component_property='value'),
     Input(component_id='myColumns', component_property='value')])
def update_graph(xaxis_column_name_value, myColumns_value):
    from pandas.conftest import cls
    figure = {
        'data' : [
            go.Scatter(
                x = lte_kpis[lte_kpis['CellName'] == cls][xaxis_column_name_value],
                y = lte_kpis[lte_kpis['CellName'] == cls][myColumns_value],
                mode = 'line',
                line = {'size' : 15},
                name = cls
            )for cls in lte_kpis['CellName'].unique()
        ],
        'layout':
            go.layout(
                height = 350,
                hovermode = 'closest',
                title = go.layout.Title(text = 'Dash InterActive Data Visualization', xref = 'paper', x = 0)
            )
    }
    return figure

Любая помощь приветствуется.

...