Exemplo n.º 1
0
def test_valid_chart_w_invalid_treemap_chart():
    assert not chart_utils.valid_chart("treemap", treemap_value=None)
    assert not chart_utils.valid_chart(
        "treemap", treemap_value="a", treemap_label=None)
    assert chart_utils.valid_chart("treemap",
                                   treemap_value="x",
                                   treemap_label="open")
Exemplo n.º 2
0
def test_valid_chart_w_invalid_candlestick_chart():
    assert not chart_utils.valid_chart("candlestick", cs_x=None)
    assert chart_utils.valid_chart(
        "candlestick",
        cs_x="x",
        cs_open="open",
        cs_close="close",
        cs_high="high",
        cs_low="low",
    )
Exemplo n.º 3
0
def test_valid_chart():
    assert not chart_utils.valid_chart(
        chart_type="line", x="a", y="b", agg="rolling")
    assert not chart_utils.valid_chart(
        chart_type="line", x="a", y="b", agg="rolling", window=10)
    assert not chart_utils.valid_chart(
        chart_type="line", x="a", y="b", agg="rolling", rolling_comp="sum")
    assert chart_utils.valid_chart(chart_type="line",
                                   x="a",
                                   y="b",
                                   agg="rolling",
                                   window=10,
                                   rolling_comp="sum")
Exemplo n.º 4
0
def test_valid_chart():
    assert not chart_utils.valid_chart(
        chart_type='line', x='a', y='b', agg='rolling')
    assert not chart_utils.valid_chart(
        chart_type='line', x='a', y='b', agg='rolling', window=10)
    assert not chart_utils.valid_chart(
        chart_type='line', x='a', y='b', agg='rolling', rolling_comp='sum')
    assert chart_utils.valid_chart(chart_type='line',
                                   x='a',
                                   y='b',
                                   agg='rolling',
                                   window=10,
                                   rolling_comp='sum')
Exemplo n.º 5
0
def build_figure_data(data_id,
                      chart_type=None,
                      query=None,
                      x=None,
                      y=None,
                      z=None,
                      group=None,
                      agg=None,
                      window=None,
                      rolling_comp=None,
                      **kwargs):
    """
    Builds chart figure data for loading into dash:`dash_core_components.Graph <dash-core-components/graph>` components

    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :param chart_type: type of chart (line, bar, pie, scatter...)
    :type chart_type: str
    :param query: pandas dataframe query string
    :type query: str, optional
    :param x: column to use for the X-Axis
    :type x: str
    :param y: columns to use for the Y-Axes
    :type y: list of str
    :param z: column to use for the Z-Axis
    :type z: str, optional
    :param group: column(s) to use for grouping
    :type group: list of str or str, optional
    :param agg: specific aggregation that can be applied to y or z axes.  Possible values are: count, first, last mean,
                median, min, max, std, var, mad, prod, sum.  This is included in label of axis it is being applied to.
    :type agg: str, optional
    :param window: number of days to include in rolling aggregations
    :type window: int, optional
    :param rolling_comp: computation to use in rolling aggregations
    :type rolling_comp: str, optional
    :param kwargs: optional keyword arguments, here in case invalid arguements are passed to this function
    :type kwargs: dict
    :return: dictionary of series data, min/max ranges of columns used in chart
    :rtype: dict
    """
    try:
        if not valid_chart(**dict(x=x, y=y, z=z, chart_type=chart_type)):
            return None

        data = DATA[data_id] if (query
                                 or '') == '' else DATA[data_id].query(query)
        chart_kwargs = dict(group_col=group,
                            agg=agg,
                            allow_duplicates=chart_type == 'scatter',
                            rolling_win=window,
                            rolling_comp=rolling_comp)
        if chart_type in ZAXIS_CHARTS:
            chart_kwargs['z'] = z
            del chart_kwargs['group_col']
        data = build_chart_data(data, x, y, **chart_kwargs)
        return data
    except BaseException as e:
        return dict(error=str(e), traceback=str(traceback.format_exc()))
Exemplo n.º 6
0
def test_valid_chart_w_invalid_map_chart():
    assert not chart_utils.valid_chart(
        "maps", map_type="choropleth", loc_mode="geojson-id", geojson=None)
Exemplo n.º 7
0
def heatmap_builder(data_id, **inputs):
    """
    Builder function for :plotly:`plotly.graph_objects.Heatmap <plotly.graph_objects.Heatmap>`

    :param data_id: integer string identifier for a D-Tale process's data
    :type data_id: str
    :param inputs: Optional keyword arguments containing the following information:
        - x: column to be used as x-axis of chart
        - y: column to be used as y-axis of chart
        - z: column to use for the Z-Axis
        - agg: points to a specific function that can be applied to :func: pandas.core.groupby.DataFrameGroupBy
    :type inputs: dict
    :return: heatmap
    :rtype: :plotly:`plotly.graph_objects.Heatmap <plotly.graph_objects.Heatmap>`
    """

    try:
        if not valid_chart(**inputs):
            return None
        raw_data = global_state.get_data(data_id)
        wrapper = chart_wrapper(data_id, raw_data, inputs)
        hm_kwargs = dict(hoverongaps=False,
                         colorscale='Greens',
                         showscale=True,
                         hoverinfo='x+y+z')
        x, y, z, agg = (inputs.get(p) for p in ['x', 'y', 'z', 'agg'])
        y = y[0]
        data = retrieve_chart_data(raw_data, x, y, z)
        x_title = update_label_for_freq(x)
        y_title = update_label_for_freq(y)
        z_title = z
        data = data.sort_values([x, y])
        check_all_nan(data)
        dupe_cols = [x, y]
        if agg is not None:
            z_title = '{} ({})'.format(z_title, AGGS[agg])
            if agg == 'corr':
                data = data.dropna()
                data = data.set_index([x, y]).unstack().corr()
                data = data.stack().reset_index(0, drop=True)
                y_title = x_title
                dupe_cols = [
                    '{}{}'.format(col, i)
                    for i, col in enumerate(data.index.names)
                ]
                [x, y] = dupe_cols
                data.index.names = dupe_cols
                data = data.reset_index()
                data.loc[data[x] == data[y], z] = np.nan
                hm_kwargs = dict_merge(
                    hm_kwargs,
                    dict(colorscale=[[0, 'red'], [0.5, 'yellow'],
                                     [1.0, 'green']],
                         zmin=-1,
                         zmax=1))
            else:
                data = build_agg_data(data, x, y, inputs, agg, z=z)
        if not len(data):
            raise Exception('No data returned for this computation!')
        check_exceptions(
            data[dupe_cols],
            agg != 'corr',
            data_limit=40000,
            limit_msg=
            'Heatmap exceeds {} cells, cannot render. Please apply filter...')
        dtypes = {
            c: classify_type(dtype)
            for c, dtype in get_dtypes(data).items()
        }
        data_f, _ = chart_formatters(data)
        data = data_f.format_df(data)
        data = data.sort_values([x, y])
        data = data.set_index([x, y])
        data = data.unstack(0)[z]

        x_data = weekday_tick_handler(data.columns, x)
        y_data = weekday_tick_handler(data.index.values, y)
        heat_data = data.values

        x_axis = dict_merge({
            'title': x_title,
            'tickangle': -20
        }, build_spaced_ticks(x_data))
        if dtypes.get(x) == 'I':
            x_axis['tickformat'] = '.0f'

        y_axis = dict_merge({
            'title': y_title,
            'tickangle': -20
        }, build_spaced_ticks(y_data))
        if dtypes.get(y) == 'I':
            y_axis['tickformat'] = '.0f'

        hovertemplate = ''.join([
            x_title, ': %{customdata[0]}<br>', y_title,
            ': %{customdata[1]}<br>', z_title, ': %{z}<extra></extra>'
        ])
        hm_kwargs = dict_merge(
            hm_kwargs,
            dict(z=heat_data,
                 colorbar={'title': z_title},
                 hoverinfo='x+y+z',
                 hovertemplate=hovertemplate,
                 customdata=[[[xd, yd] for xd in x_data] for yd in y_data]))
        return wrapper(
            dcc.Graph(id='heatmap-graph-{}'.format(y),
                      style={
                          'margin-right': 'auto',
                          'margin-left': 'auto',
                          'height': 600
                      },
                      figure=dict(data=[go.Heatmap(**hm_kwargs)],
                                  layout=build_layout(
                                      dict_merge(
                                          dict(xaxis=x_axis,
                                               yaxis=y_axis,
                                               xaxis_zeroline=False,
                                               yaxis_zeroline=False),
                                          build_title(x, y, z=z, agg=agg))))))
    except BaseException as e:
        return build_error(str(e), str(traceback.format_exc()))