code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def bar_mean(data_frame, x, y):
"""Creates a custom bar chart with aggregated data (mean)."""
df_agg = data_frame.groupby(x).agg({y: "mean"}).reset_index()
fig = px.bar(df_agg, x=x, y=y, labels={"tip": "Average Tip ($)"})
fig.update_traces(width=0.6)
return fig | Creates a custom bar chart with aggregated data (mean). | bar_mean | python | mckinsey/vizro | vizro-core/examples/tutorial/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/tutorial/app.py | Apache-2.0 |
def make_chart_card(page: Union[vm.Page, IncompletePage]) -> vm.Card:
"""Makes a card with svg icon, linked to the right page if page is complete.
Args:
page: page to make card for
Returns: card with svg icon, linked to the right page if page is complete.
"""
# There's one SVG per chart t... | Makes a card with svg icon, linked to the right page if page is complete.
Args:
page: page to make card for
Returns: card with svg icon, linked to the right page if page is complete.
| make_chart_card | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/app.py | Apache-2.0 |
def make_homepage_container(chart_group: ChartGroup) -> vm.Container:
"""Makes a container with cards for each completed and incomplete chart in chart_group.
Args:
chart_group: group of charts to make container for.
Returns: container with cards for each chart in chart_group.
"""
# Pages ... | Makes a container with cards for each completed and incomplete chart in chart_group.
Args:
chart_group: group of charts to make container for.
Returns: container with cards for each chart in chart_group.
| make_homepage_container | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/app.py | Apache-2.0 |
def make_navlink(chart_group: ChartGroup) -> vm.NavLink:
"""Makes a navlink with icon and links to every complete page within chart_group.
Args:
chart_group: chart_group to make a navlink for.
Returns: navlink for chart_group.
"""
# Pages are sorted in alphabetical order within each chart... | Makes a navlink with icon and links to every complete page within chart_group.
Args:
chart_group: chart_group to make a navlink for.
Returns: navlink for chart_group.
| make_navlink | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/app.py | Apache-2.0 |
def butterfly(data_frame: pd.DataFrame, **kwargs) -> go.Figure:
"""Creates a butterfly chart based on px.bar.
A butterfly chart is a type of bar chart where two sets of bars are displayed back-to-back, often used to compare
two sets of data.
Args:
data_frame: DataFrame for the chart. Can be lo... | Creates a butterfly chart based on px.bar.
A butterfly chart is a type of bar chart where two sets of bars are displayed back-to-back, often used to compare
two sets of data.
Args:
data_frame: DataFrame for the chart. Can be long form or wide form.
See https://plotly.com/python/wide-fo... | butterfly | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def sankey(data_frame: pd.DataFrame, source: str, target: str, value: str, labels: list[str]) -> go.Figure:
"""Creates a Sankey chart based on go.Sankey.
A Sankey chart is a type of flow diagram where the width of the arrows is proportional to the flow rate.
It is used to visualize the flow of resources or... | Creates a Sankey chart based on go.Sankey.
A Sankey chart is a type of flow diagram where the width of the arrows is proportional to the flow rate.
It is used to visualize the flow of resources or data between different stages or categories.
For detailed information on additional parameters and customizat... | sankey | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def column_and_line(
data_frame: pd.DataFrame,
x: Union[str, pd.Series, list[str], list[pd.Series]],
y_column: Union[str, pd.Series, list[str], list[pd.Series]],
y_line: Union[str, pd.Series, list[str], list[pd.Series]],
) -> go.Figure:
"""Creates a combined column and line chart based on px.bar and... | Creates a combined column and line chart based on px.bar and px.line.
This function generates a chart with a bar graph for one variable (y-axis 1) and a line graph for another variable
(y-axis 2), sharing the same x-axis. The y-axes for the bar and line graphs are synchronized and overlaid.
Args:
... | column_and_line | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def categorical_column(data_frame: pd.DataFrame, **kwargs) -> go.Figure:
"""Creates categorical bar chart based on px.bar.
Args:
data_frame: DataFrame for the chart. Can be long form or wide form.
See https://plotly.com/python/wide-form/.
**kwargs: Keyword arguments to pass into px.... | Creates categorical bar chart based on px.bar.
Args:
data_frame: DataFrame for the chart. Can be long form or wide form.
See https://plotly.com/python/wide-form/.
**kwargs: Keyword arguments to pass into px.bar (e.g. x, y, labels).
See https://plotly.com/python-api-reference... | categorical_column | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def waterfall(data_frame: pd.DataFrame, x: str, y: str, measure: list[str]) -> go.Figure:
"""Creates a waterfall chart based on go.Waterfall.
A Waterfall chart visually breaks down the cumulative effect of sequential positive and negative values,
showing how each value contributes to the total.
For ad... | Creates a waterfall chart based on go.Waterfall.
A Waterfall chart visually breaks down the cumulative effect of sequential positive and negative values,
showing how each value contributes to the total.
For additional parameters and customization options, see the Plotly documentation:
https://plotly.c... | waterfall | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def radar(data_frame: pd.DataFrame, **kwargs) -> go.Figure:
"""Creates a radar chart based on px.line_polar.
A radar chart is a type of data visualization in which there are three or more
variables represented on axes that originate from the same central point.
Args:
data_frame: DataFrame for ... | Creates a radar chart based on px.line_polar.
A radar chart is a type of data visualization in which there are three or more
variables represented on axes that originate from the same central point.
Args:
data_frame: DataFrame for the chart.
**kwargs: Keyword arguments to pass into px.line... | radar | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def dumbbell(data_frame: pd.DataFrame, **kwargs) -> go.Figure:
"""Creates a dumbbell chart based on px.scatter.
A dumbbell plot is a type of dot plot where the points, displaying different groups, are connected with a straight
line. They are ideal for illustrating differences or gaps between two points.
... | Creates a dumbbell chart based on px.scatter.
A dumbbell plot is a type of dot plot where the points, displaying different groups, are connected with a straight
line. They are ideal for illustrating differences or gaps between two points.
Inspired by: https://community.plotly.com/t/how-to-make-dumbbell-pl... | dumbbell | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def diverging_stacked_bar(data_frame: pd.DataFrame, **kwargs) -> go.Figure:
"""Creates a diverging stacked bar chart based on px.bar.
This type of chart is a variant of the standard stacked bar chart, with bars aligned on a central baseline to
show both positive and negative values. Each bar is segmented t... | Creates a diverging stacked bar chart based on px.bar.
This type of chart is a variant of the standard stacked bar chart, with bars aligned on a central baseline to
show both positive and negative values. Each bar is segmented to represent different categories.
This function is not suitable for diverging ... | diverging_stacked_bar | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def lollipop(data_frame: pd.DataFrame, **kwargs):
"""Creates a lollipop based on px.scatter.
A lollipop chart is a variation of a bar chart where each data point is represented by a line and a dot at the end
to mark the value.
Inspired by: https://towardsdatascience.com/lollipop-dumbbell-charts-with-p... | Creates a lollipop based on px.scatter.
A lollipop chart is a variation of a bar chart where each data point is represented by a line and a dot at the end
to mark the value.
Inspired by: https://towardsdatascience.com/lollipop-dumbbell-charts-with-plotly-696039d5f85
Args:
data_frame: DataFram... | lollipop | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_charts.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_charts.py | Apache-2.0 |
def build(self):
"""Returns the code clipboard component inside an accordion."""
markdown_code = "\n".join([f"```{self.language}", self.code, "```"])
pycafe_link = dbc.Button(
[
"Edit code live on PyCafe",
html.Span("open_in_new", className="material-... | Returns the code clipboard component inside an accordion. | build | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_components.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_components.py | Apache-2.0 |
def build(self):
"""Returns a markdown component with an optional classname."""
return dcc.Markdown(
id=self.id, children=self.text, dangerously_allow_html=False, className=self.classname, link_target="_blank"
) | Returns a markdown component with an optional classname. | build | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/custom_components.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/custom_components.py | Apache-2.0 |
def butterfly_factory(group: str):
"""Reusable function to create the page content for the butterfly chart with a unique ID."""
return vm.Page(
id=f"{group}-butterfly",
path=f"{group}/butterfly",
title="Butterfly",
layout=vm.Grid(grid=PAGE_GRID),
components=[
... | Reusable function to create the page content for the butterfly chart with a unique ID. | butterfly_factory | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/pages/_factories.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/pages/_factories.py | Apache-2.0 |
def connected_scatter_factory(group: str):
"""Reusable function to create the page content for the column chart with a unique ID."""
return vm.Page(
id=f"{group}-connected-scatter",
path=f"{group}/connected-scatter",
title="Connected scatter",
layout=vm.Grid(grid=PAGE_GRID),
... | Reusable function to create the page content for the column chart with a unique ID. | connected_scatter_factory | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/pages/_factories.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/pages/_factories.py | Apache-2.0 |
def column_and_line_factory(group: str):
"""Reusable function to create the page content for the column+line chart with a unique ID."""
return vm.Page(
id=f"{group}-column-and-line",
path=f"{group}/column-and-line",
title="Column and line",
layout=vm.Grid(grid=PAGE_GRID),
... | Reusable function to create the page content for the column+line chart with a unique ID. | column_and_line_factory | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/pages/_factories.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/pages/_factories.py | Apache-2.0 |
def lollipop_factory(group: str):
"""Reusable function to create the page content for the lollipop chart with a unique ID."""
return vm.Page(
id=f"{group}-lollipop",
path=f"{group}/lollipop",
title="Lollipop",
layout=vm.Grid(grid=PAGE_GRID),
components=[
vm.Ca... | Reusable function to create the page content for the lollipop chart with a unique ID. | lollipop_factory | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/pages/_factories.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/pages/_factories.py | Apache-2.0 |
def _format_and_lint(code_string: str, line_length: int) -> str:
"""Inspired by vizro.models._base._format_and_lint. The only difference is that this does isort too."""
# Tracking https://github.com/astral-sh/ruff/issues/659 for proper Python API
# Good example: https://github.com/astral-sh/ruff/issues/8401... | Inspired by vizro.models._base._format_and_lint. The only difference is that this does isort too. | _format_and_lint | python | mckinsey/vizro | vizro-core/examples/visual-vocabulary/pages/_pages_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/visual-vocabulary/pages/_pages_utils.py | Apache-2.0 |
def __init__(self, **kwargs):
"""Initializes Dash app, stored in `self.dash`.
Args:
**kwargs : Passed through to `Dash.__init__`, e.g. `assets_folder`, `url_base_pathname`. See
[Dash documentation](https://dash.plotly.com/reference#dash.dash) for possible arguments.
... | Initializes Dash app, stored in `self.dash`.
Args:
**kwargs : Passed through to `Dash.__init__`, e.g. `assets_folder`, `url_base_pathname`. See
[Dash documentation](https://dash.plotly.com/reference#dash.dash) for possible arguments.
| __init__ | python | mckinsey/vizro | vizro-core/src/vizro/_vizro.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_vizro.py | Apache-2.0 |
def build(self, dashboard: Dashboard):
"""Builds the `dashboard`.
Args:
dashboard (Dashboard): [`Dashboard`][vizro.models.Dashboard] object.
Returns:
self: Vizro app
"""
# Set global chart template to vizro_light or vizro_dark.
# The choice betw... | Builds the `dashboard`.
Args:
dashboard (Dashboard): [`Dashboard`][vizro.models.Dashboard] object.
Returns:
self: Vizro app
| build | python | mckinsey/vizro | vizro-core/src/vizro/_vizro.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_vizro.py | Apache-2.0 |
def run(self, *args, **kwargs): # if type annotated, mkdocstring stops seeing the class
"""Runs the dashboard.
Args:
*args : Passed through to `dash.run`.
**kwargs : Passed through to `dash.run`.
"""
data_manager._frozen_state = True
model_manager._froz... | Runs the dashboard.
Args:
*args : Passed through to `dash.run`.
**kwargs : Passed through to `dash.run`.
| run | python | mckinsey/vizro | vizro-core/src/vizro/_vizro.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_vizro.py | Apache-2.0 |
def _pre_build():
"""Runs pre_build method on all models in the model_manager."""
# Note that a pre_build method can itself add a model (e.g. an Action) to the model manager, and so we need to
# iterate through set(model_manager) rather than model_manager itself or we loop through something that... | Runs pre_build method on all models in the model_manager. | _pre_build | python | mckinsey/vizro | vizro-core/src/vizro/_vizro.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_vizro.py | Apache-2.0 |
def _reset():
"""Private method that clears all state in the `Vizro` app.
This deliberately does not clear the data manager cache - see comments in data_manager._clear for
explanation.
"""
data_manager._clear()
model_manager._clear()
dash._callback.GLOBAL_CALLBAC... | Private method that clears all state in the `Vizro` app.
This deliberately does not clear the data manager cache - see comments in data_manager._clear for
explanation.
| _reset | python | mckinsey/vizro | vizro-core/src/vizro/_vizro.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_vizro.py | Apache-2.0 |
def outputs(self) -> Union[list[_IdOrIdProperty], dict[str, _IdOrIdProperty]]: # type: ignore[override]
"""Must be defined by concrete action, even if there's no output.
This should return a dictionary of the form `{"key": "dropdown.value"}`, where the key corresponds to the key
in the diction... | Must be defined by concrete action, even if there's no output.
This should return a dictionary of the form `{"key": "dropdown.value"}`, where the key corresponds to the key
in the dictionary returned by the action `function`, and the value `"dropdown.value"` is converted into
`Output("dropdown"... | outputs | python | mckinsey/vizro | vizro-core/src/vizro/actions/_abstract_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_abstract_action.py | Apache-2.0 |
def _apply_filter_controls(
data_frame: pd.DataFrame, ctds_filter: list[CallbackTriggerDict], target: ModelID
) -> pd.DataFrame:
"""Applies filters from a vm.Filter model in the controls.
Args:
data_frame: unfiltered DataFrame.
ctds_filter: list of CallbackTriggerDict for filters.
t... | Applies filters from a vm.Filter model in the controls.
Args:
data_frame: unfiltered DataFrame.
ctds_filter: list of CallbackTriggerDict for filters.
target: id of targeted Figure.
Returns: filtered DataFrame.
| _apply_filter_controls | python | mckinsey/vizro | vizro-core/src/vizro/actions/_actions_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_actions_utils.py | Apache-2.0 |
def _apply_filter_interaction(
data_frame: pd.DataFrame, ctds_filter_interaction: list[dict[str, CallbackTriggerDict]], target: ModelID
) -> pd.DataFrame:
"""Applies filters from a filter_interaction.
This will be removed in future when filter interactions are implemented using controls.
Args:
... | Applies filters from a filter_interaction.
This will be removed in future when filter interactions are implemented using controls.
Args:
data_frame: unfiltered DataFrame.
ctds_filter_interaction: structure containing CallbackTriggerDict for filter interactions.
target: id of targeted F... | _apply_filter_interaction | python | mckinsey/vizro | vizro-core/src/vizro/actions/_actions_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_actions_utils.py | Apache-2.0 |
def _get_target_dot_separated_strings(dot_separated_strings: list[str], target: ModelID, data_frame: bool) -> list[str]:
"""Filters list of dot separated strings to get just those relevant for a single target.
Args:
dot_separated_strings: list of dot separated strings that can be targeted by a vm.Param... | Filters list of dot separated strings to get just those relevant for a single target.
Args:
dot_separated_strings: list of dot separated strings that can be targeted by a vm.Parameter,
e.g. ["target_name.data_frame.arg", "target_name.x"]
target: id of targeted Figure.
data_frame... | _get_target_dot_separated_strings | python | mckinsey/vizro | vizro-core/src/vizro/actions/_actions_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_actions_utils.py | Apache-2.0 |
def _get_parametrized_config(
ctds_parameter: list[CallbackTriggerDict], target: ModelID, data_frame: bool
) -> dict[str, Any]:
"""Convert parameters into a keyword-argument dictionary.
Args:
ctds_parameter: list of CallbackTriggerDicts for vm.Parameter.
target: id of targeted figure.
... | Convert parameters into a keyword-argument dictionary.
Args:
ctds_parameter: list of CallbackTriggerDicts for vm.Parameter.
target: id of targeted figure.
data_frame: whether to return only DataFrame parameters starting "data_frame." or only non-DataFrame parameters.
Returns: keyword-a... | _get_parametrized_config | python | mckinsey/vizro | vizro-core/src/vizro/actions/_actions_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_actions_utils.py | Apache-2.0 |
def function(self, _controls: _Controls) -> dict[ModelID, Any]:
"""Applies _controls to charts on page once filter is applied.
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
"""
# This is identical to _on_page_load.
# TOD... | Applies _controls to charts on page once filter is applied.
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
| function | python | mckinsey/vizro | vizro-core/src/vizro/actions/_filter_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_filter_action.py | Apache-2.0 |
def _get_triggered_model(self) -> FigureWithFilterInteractionType: # type: ignore[return]
"""Gets the model that triggers the action with "action_id"."""
# In future we should have a better way of doing this:
# - maybe through the model manager
# - pass trigger into callback as a buil... | Gets the model that triggers the action with "action_id". | _get_triggered_model | python | mckinsey/vizro | vizro-core/src/vizro/actions/_filter_interaction.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_filter_interaction.py | Apache-2.0 |
def function(self, _controls: _Controls) -> dict[ModelID, Any]:
"""Applies _controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
"""
# TODO-AV2 A 1: _controls is not cu... | Applies _controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
| function | python | mckinsey/vizro | vizro-core/src/vizro/actions/_filter_interaction.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_filter_interaction.py | Apache-2.0 |
def function(self, _controls: _Controls) -> dict[ModelID, Any]:
"""Applies controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
"""
# TODO-AV2 A 1: _controls is not cu... | Applies controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
| function | python | mckinsey/vizro | vizro-core/src/vizro/actions/_on_page_load.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_on_page_load.py | Apache-2.0 |
def function(self, _controls: _Controls) -> dict[ModelID, Any]:
"""Applies _controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
"""
# This is identical to _on_page_lo... | Applies _controls to charts on page once the page is opened (or refreshed).
Returns:
Dict mapping target chart ids to modified figures e.g. {"my_scatter": Figure(...)}.
| function | python | mckinsey/vizro | vizro-core/src/vizro/actions/_parameter_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_parameter_action.py | Apache-2.0 |
def _build_actions_models():
"""Builds a callback for each `Action` model and returns required components for these callbacks.
Returns:
List of required components for each `Action` in the `Dashboard` e.g. list[dcc.Download]
"""
return html.Div(
[action.build() ... | Builds a callback for each `Action` model and returns required components for these callbacks.
Returns:
List of required components for each `Action` in the `Dashboard` e.g. list[dcc.Download]
| _build_actions_models | python | mckinsey/vizro | vizro-core/src/vizro/actions/_action_loop/_action_loop.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_action_loop/_action_loop.py | Apache-2.0 |
def _build_action_loop_callbacks() -> None:
"""Creates all required dash callbacks for the action loop."""
# actions_chain and actions are not iterated over multiple times so conversion to list is not technically needed,
# but it prevents future bugs and matches _get_action_loop_components.
actions_chai... | Creates all required dash callbacks for the action loop. | _build_action_loop_callbacks | python | mckinsey/vizro | vizro-core/src/vizro/actions/_action_loop/_build_action_loop_callbacks.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_action_loop/_build_action_loop_callbacks.py | Apache-2.0 |
def _get_action_loop_components() -> html.Div:
"""Gets all required components for the action loop.
Returns:
List of dcc or html components.
"""
# actions_chain and actions are iterated over multiple times so must be realized into a list.
actions_chains: list[ActionsChain] = list(model_man... | Gets all required components for the action loop.
Returns:
List of dcc or html components.
| _get_action_loop_components | python | mckinsey/vizro | vizro-core/src/vizro/actions/_action_loop/_get_action_loop_components.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/actions/_action_loop/_get_action_loop_components.py | Apache-2.0 |
def kpi_card(
data_frame: pd.DataFrame,
value_column: str,
*,
value_format: str = "{value}",
agg_func: str = "sum",
title: Optional[str] = None,
icon: Optional[str] = None,
) -> dbc.Card:
"""Creates a styled KPI (Key Performance Indicator) card displaying a value.
**Warning:** Note ... | Creates a styled KPI (Key Performance Indicator) card displaying a value.
**Warning:** Note that the format string provided to `value_format` is being evaluated, so ensure that only trusted
user input is provided to prevent potential security risks.
Args:
data_frame: DataFrame containing the data.... | kpi_card | python | mckinsey/vizro | vizro-core/src/vizro/figures/_kpi_cards.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/figures/_kpi_cards.py | Apache-2.0 |
def kpi_card_reference( # noqa: PLR0913
data_frame: pd.DataFrame,
value_column: str,
reference_column: str,
*,
value_format: str = "{value}",
reference_format: str = "{delta_relative:+.1%} vs. reference ({reference})",
agg_func: str = "sum",
title: Optional[str] = None,
icon: Option... | Creates a styled KPI (Key Performance Indicator) card displaying a value in comparison to a reference value.
**Warning:** Note that the format string provided to `value_format` and `reference_format` is being evaluated,
so ensure that only trusted user input is provided to prevent potential security risks.
... | kpi_card_reference | python | mckinsey/vizro | vizro-core/src/vizro/figures/_kpi_cards.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/figures/_kpi_cards.py | Apache-2.0 |
def catalog_from_project(
project_path: Union[str, Path], env: Optional[str] = None, extra_params: Optional[dict[str, Any]] = None
) -> CatalogProtocol:
"""Return the Kedro Data Catalog associated to a Kedro project.
Args:
project_path: Path to the Kedro project root directory.
env: Kedro c... | Return the Kedro Data Catalog associated to a Kedro project.
Args:
project_path: Path to the Kedro project root directory.
env: Kedro configuration environment to be used. Defaults to "local".
extra_params: Optional dictionary containing extra project parameters
for underlying K... | catalog_from_project | python | mckinsey/vizro | vizro-core/src/vizro/integrations/kedro/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/integrations/kedro/_data_manager.py | Apache-2.0 |
def pipelines_from_project(project_path: Union[str, Path]) -> dict[str, Pipeline]:
"""Return the Kedro Pipelines associated to a Kedro project.
Args:
project_path: Path to the Kedro project root directory.
Returns:
A dictionary mapping pipeline names to Kedro Pipelines.
Examples:
... | Return the Kedro Pipelines associated to a Kedro project.
Args:
project_path: Path to the Kedro project root directory.
Returns:
A dictionary mapping pipeline names to Kedro Pipelines.
Examples:
>>> from vizro.integrations import kedro as kedro_integration
>>> pipelines =... | pipelines_from_project | python | mckinsey/vizro | vizro-core/src/vizro/integrations/kedro/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/integrations/kedro/_data_manager.py | Apache-2.0 |
def datasets_from_catalog(catalog: CatalogProtocol, *, pipeline: Pipeline = None) -> dict[str, pd_DataFrameCallable]:
"""Return the Kedro Dataset loading functions associated to a Kedro Data Catalog.
Args:
catalog: Path to the Kedro project root directory.
pipeline: Optional Kedro pipeline. If ... | Return the Kedro Dataset loading functions associated to a Kedro Data Catalog.
Args:
catalog: Path to the Kedro project root directory.
pipeline: Optional Kedro pipeline. If specified, the factory-based Kedro datasets it defines are returned.
Returns:
A dictionary mapping dataset name... | datasets_from_catalog | python | mckinsey/vizro | vizro-core/src/vizro/integrations/kedro/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/integrations/kedro/_data_manager.py | Apache-2.0 |
def __setitem__(self, name: DataSourceName, data: Union[pd.DataFrame, pd_DataFrameCallable]):
"""Adds `data` to the `DataManager` with key `name`."""
if callable(data):
# __qualname__ is required by flask-caching (even if we specify our own make_name) but
# not defined for partia... | Adds `data` to the `DataManager` with key `name`. | __setitem__ | python | mckinsey/vizro | vizro-core/src/vizro/managers/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_data_manager.py | Apache-2.0 |
def __getitem__(self, name: DataSourceName) -> Union[_DynamicData, _StaticData]:
"""Returns the `_DynamicData` or `_StaticData` object associated with `name`."""
try:
return self.__data[name]
except KeyError as exc:
raise KeyError(f"Data source {name} does not exist.") fr... | Returns the `_DynamicData` or `_StaticData` object associated with `name`. | __getitem__ | python | mckinsey/vizro | vizro-core/src/vizro/managers/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_data_manager.py | Apache-2.0 |
def _multi_load(self, multi_name_load_kwargs: list[tuple[DataSourceName, dict[str, Any]]]) -> list[pd.DataFrame]:
"""Loads multiple data sources as efficiently as possible.
Deduplicates a list of (data source name, load keyword argument dictionary) tuples so that each one corresponds
to only a ... | Loads multiple data sources as efficiently as possible.
Deduplicates a list of (data source name, load keyword argument dictionary) tuples so that each one corresponds
to only a single load() call. In the worst case scenario where there are no repeated tuples then performance of
this function i... | _multi_load | python | mckinsey/vizro | vizro-core/src/vizro/managers/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_data_manager.py | Apache-2.0 |
def _cache_has_app(self) -> bool:
"""Detects whether self.cache.init_app has been called (as it is in Vizro) to attach a Flask app to the cache.
Note that even NullCache needs to have an app attached before it can be "used". The only time the cache would
not have an app attached is if the user ... | Detects whether self.cache.init_app has been called (as it is in Vizro) to attach a Flask app to the cache.
Note that even NullCache needs to have an app attached before it can be "used". The only time the cache would
not have an app attached is if the user tries to interact with the cache before Vizro... | _cache_has_app | python | mckinsey/vizro | vizro-core/src/vizro/managers/_data_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_data_manager.py | Apache-2.0 |
def __iter__(self) -> Generator[ModelID, None, None]:
"""Iterates through all models.
Note this yields model IDs rather key/value pairs to match the interface for a dictionary.
"""
# TODO: should this yield models rather than model IDs? Should model_manager be more like set with a speci... | Iterates through all models.
Note this yields model IDs rather key/value pairs to match the interface for a dictionary.
| __iter__ | python | mckinsey/vizro | vizro-core/src/vizro/managers/_model_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_model_manager.py | Apache-2.0 |
def _get_models(
self,
model_type: Optional[Union[type[Model], tuple[type[Model], ...], type[FIGURE_MODELS]]] = None,
root_model: Optional[VizroBaseModel] = None,
) -> Generator[Model, None, None]:
"""Iterates through all models of type `model_type` (including subclasses).
I... | Iterates through all models of type `model_type` (including subclasses).
If `model_type` is specified, return only models matching that type. Otherwise, include all types.
If `root_model` is specified, return only models that are descendants of the given `root_model`.
| _get_models | python | mckinsey/vizro | vizro-core/src/vizro/managers/_model_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_model_manager.py | Apache-2.0 |
def __get_model_children(self, model: Model) -> Generator[Model, None, None]:
"""Iterates through children of `model`.
Currently, this method looks only through certain fields (components, tabs, controls, actions, selector) and
their children so might miss some children models.
"""
... | Iterates through children of `model`.
Currently, this method looks only through certain fields (components, tabs, controls, actions, selector) and
their children so might miss some children models.
| __get_model_children | python | mckinsey/vizro | vizro-core/src/vizro/managers/_model_manager.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/managers/_model_manager.py | Apache-2.0 |
def _get_layout_discriminator(layout: Any) -> Optional[str]:
"""Helper function for callable discriminator used for LayoutType."""
# It is not immediately possible to introduce a discriminated union as a field type without it breaking existing
# YAML/dictionary configuration in which `type` is not specified... | Helper function for callable discriminator used for LayoutType. | _get_layout_discriminator | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def _get_action_discriminator(action: Any) -> Optional[str]:
"""Helper function for callable discriminator used for ActionType."""
# It is not immediately possible to introduce a discriminated union as a field type without it breaking existing
# YAML/dictionary configuration in which `type` is not specified... | Helper function for callable discriminator used for ActionType. | _get_action_discriminator | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def validate_captured_callable(cls, value, info: ValidationInfo):
"""Reusable validator for the `figure` argument of Figure like models."""
# Bypass validation so that legacy vm.Action(function=filter_interaction(...)) and
# vm.Action(function=export_data(...)) work.
from vizro.actions import export_dat... | Reusable validator for the `figure` argument of Figure like models. | validate_captured_callable | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def __init__(self, function, /, *args, **kwargs):
"""Creates a new `CapturedCallable` object that will be able to re-run `function`.
Partially binds *args and **kwargs to the function call.
Raises:
ValueError if `function` contains positional-only or variadic positional parameters ... | Creates a new `CapturedCallable` object that will be able to re-run `function`.
Partially binds *args and **kwargs to the function call.
Raises:
ValueError if `function` contains positional-only or variadic positional parameters (*args).
| __init__ | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""Run the `function` with the initially bound arguments overridden by `**kwargs`.
*args are possible here, but cannot be used to override arguments bound in `__init__` - just to
provide additional arguments. You can still override arguments that were origin... | Run the `function` with the initially bound arguments overridden by `**kwargs`.
*args are possible here, but cannot be used to override arguments bound in `__init__` - just to
provide additional arguments. You can still override arguments that were originally given
as positional using their arg... | __call__ | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def _parse_json(
cls,
captured_callable_config: Union[_SupportsCapturedCallable, CapturedCallable, dict[str, Any]],
json_schema_extra: JsonSchemaExtraType,
) -> Union[CapturedCallable, _SupportsCapturedCallable]:
"""Parses captured_callable_config specification from JSON/YAML.
... | Parses captured_callable_config specification from JSON/YAML.
If captured_callable_config is already _SupportCapturedCallable or CapturedCallable then it just passes through
untouched.
This uses the hydra syntax for _target_ but none of the other bits and we don't actually use hydra
to... | _parse_json | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def _extract_from_attribute(
cls, captured_callable: Union[_SupportsCapturedCallable, CapturedCallable]
) -> CapturedCallable:
"""Extracts CapturedCallable from _SupportCapturedCallable (e.g. _DashboardReadyFigure).
If captured_callable is already CapturedCallable then it just passes throug... | Extracts CapturedCallable from _SupportCapturedCallable (e.g. _DashboardReadyFigure).
If captured_callable is already CapturedCallable then it just passes through untouched.
| _extract_from_attribute | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def _check_type(
cls, captured_callable: CapturedCallable, json_schema_extra: JsonSchemaExtraType
) -> CapturedCallable:
"""Checks captured_callable is right type and mode."""
from vizro.actions import export_data, filter_interaction
# Bypass validation so that legacy {"function": {... | Checks captured_callable is right type and mode. | _check_type | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def __repr_clean__(self):
"""Alternative __repr__ method with cleaned module paths."""
args = ", ".join(f"{key}={value!r}" for key, value in self._arguments.items())
original_module_path = f"{self._function.__module__}"
return f"{_clean_module_string(original_module_path)}{self._function... | Alternative __repr__ method with cleaned module paths. | __repr_clean__ | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def _pio_templates_default():
"""Sets pio.templates.default to "vizro_dark" and then reverts it.
This is to ensure that in a Jupyter Notebook captured charts look the same as when they're in the dashboard. When
the context manager exits the global theme is reverted just to keep things clean (e.g. if you re... | Sets pio.templates.default to "vizro_dark" and then reverts it.
This is to ensure that in a Jupyter Notebook captured charts look the same as when they're in the dashboard. When
the context manager exits the global theme is reverted just to keep things clean (e.g. if you really wanted to,
you could compare... | _pio_templates_default | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def __call__(self, func, /):
"""Produces a CapturedCallable or _DashboardReadyFigure.
mode="action" and mode="table" give a CapturedCallable, while mode="graph" gives a _DashboardReadyFigure that
contains a CapturedCallable. In both cases, the CapturedCallable is based on func and the provided
... | Produces a CapturedCallable or _DashboardReadyFigure.
mode="action" and mode="table" give a CapturedCallable, while mode="graph" gives a _DashboardReadyFigure that
contains a CapturedCallable. In both cases, the CapturedCallable is based on func and the provided
*args and **kwargs.
| __call__ | python | mckinsey/vizro | vizro-core/src/vizro/models/types.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/types.py | Apache-2.0 |
def add_type(cls, field_name: str, new_type: type[Any]):
"""Adds a new type to an existing field based on a discriminated union.
Args:
field_name: Field that new type will be added to
new_type: New type to add to discriminated union
"""
field = cls.model_fields[... | Adds a new type to an existing field based on a discriminated union.
Args:
field_name: Field that new type will be added to
new_type: New type to add to discriminated union
| add_type | python | mckinsey/vizro | vizro-core/src/vizro/models/_base.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_base.py | Apache-2.0 |
def _to_python(
self, extra_imports: Optional[set[str]] = None, extra_callable_defs: Optional[set[str]] = None
) -> str:
"""Converts a Vizro model to the Python code that would create it.
Args:
extra_imports: Extra imports to add to the Python code. Provide as a set of complete ... | Converts a Vizro model to the Python code that would create it.
Args:
extra_imports: Extra imports to add to the Python code. Provide as a set of complete import strings.
extra_callable_defs: Extra callable definitions to add to the Python code. Provide as a set of complete
... | _to_python | python | mckinsey/vizro | vizro-core/src/vizro/models/_base.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_base.py | Apache-2.0 |
def _all_hidden(components: list[Component]):
"""Returns True if all `components` are either None and/or have hidden=True and/or className contains `d-none`."""
return all(
component is None
or getattr(component, "hidden", False)
or "d-none" in getattr(component, "className", "d-inline")... | Returns True if all `components` are either None and/or have hidden=True and/or className contains `d-none`. | _all_hidden | python | mckinsey/vizro | vizro-core/src/vizro/models/_dashboard.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_dashboard.py | Apache-2.0 |
def build(self):
"""Creates empty flex container to later position components in."""
bs_wrap = "flex-wrap" if self.wrap else "flex-nowrap"
component_container = html.Div(
[],
style={"gap": self.gap},
className=f"d-flex flex-{self.direction} {bs_wrap}",
... | Creates empty flex container to later position components in. | build | python | mckinsey/vizro | vizro-core/src/vizro/models/_flex.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_flex.py | Apache-2.0 |
def _convert_to_combined_grid_coord(matrix: ma.MaskedArray) -> ColRowGridLines:
"""Converts `matrix` coordinates from user `grid` to one combined grid area spanned by component i.
Required for validation of grid areas spanned by components.
User-provided grid: [[0, 1], [0, 2]]
Matrix coordinates for ... | Converts `matrix` coordinates from user `grid` to one combined grid area spanned by component i.
Required for validation of grid areas spanned by components.
User-provided grid: [[0, 1], [0, 2]]
Matrix coordinates for component i=0: [(0, 0), (1, 0)]
Grid coordinates for component i=0: ColRowGridLines... | _convert_to_combined_grid_coord | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def _convert_to_single_grid_coord(matrix: ma.MaskedArray) -> list[ColRowGridLines]:
"""Converts `matrix` coordinates from user `grid` to list of grid areas spanned by each placement of component i.
Required for validation of grid areas spanned by spaces, where the combined area does not need to be rectangular.... | Converts `matrix` coordinates from user `grid` to list of grid areas spanned by each placement of component i.
Required for validation of grid areas spanned by spaces, where the combined area does not need to be rectangular.
User-provided grid: [[0, 1], [0, 2]]
Matrix coordinates for component i=0: [(0, ... | _convert_to_single_grid_coord | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def _do_rectangles_overlap(r1: ColRowGridLines, r2: ColRowGridLines) -> bool:
"""Checks if rectangles `r1` and `r2` overlap in areas.
1. Computes the min and max of r1 and r2 on both axes.
2. Computes the boundaries of the intersection rectangle (x1=left, x2=right, y1=top, y2=bottom)
3. Checks if the i... | Checks if rectangles `r1` and `r2` overlap in areas.
1. Computes the min and max of r1 and r2 on both axes.
2. Computes the boundaries of the intersection rectangle (x1=left, x2=right, y1=top, y2=bottom)
3. Checks if the intersection is valid and has a positive non-zero area (x1 < x2 and y1 < y2)
See:... | _do_rectangles_overlap | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def _validate_grid_areas(grid_areas: list[ColRowGridLines]) -> None:
"""Validates `grid_areas` spanned by screen components in `Grid`."""
for i, r1 in enumerate(grid_areas):
for r2 in grid_areas[i + 1 :]:
if _do_rectangles_overlap(r1, r2):
raise ValueError("Grid areas must be... | Validates `grid_areas` spanned by screen components in `Grid`. | _validate_grid_areas | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def _get_grid_lines(grid: list[list[int]]) -> tuple[list[ColRowGridLines], list[ColRowGridLines]]:
"""Gets list of ColRowGridLines for components and spaces on screen for validation and placement."""
component_grid_lines = []
unique_grid_idx = _get_unique_grid_component_ids(grid)
for component_idx in un... | Gets list of ColRowGridLines for components and spaces on screen for validation and placement. | _get_grid_lines | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def build(self):
"""Creates empty container with inline style to later position components in."""
components_content = [
html.Div(
id=f"{self.id}_{component_idx}",
style={
"gridColumn": f"{grid_coord.col_start}/{grid_coord.col_end}",
... | Creates empty container with inline style to later position components in. | build | python | mckinsey/vizro | vizro-core/src/vizro/models/_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_grid.py | Apache-2.0 |
def _build_inner_layout(layout, components):
"""Builds inner layout and adds components to grid or flex. Used inside `Page`, `Container` and `Form`."""
from vizro.models import Grid
components_container = layout.build()
if isinstance(layout, Grid):
for idx, component in enumerate(components):
... | Builds inner layout and adds components to grid or flex. Used inside `Page`, `Container` and `Form`. | _build_inner_layout | python | mckinsey/vizro | vizro-core/src/vizro/models/_models_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_models_utils.py | Apache-2.0 |
def model_post_init(self, context: Any) -> None:
"""Adds the model instance to the model manager."""
try:
super().model_post_init(context)
except DuplicateIDError as exc:
raise ValueError(
f"Page with id={self.id} already exists. Page id is automatically s... | Adds the model instance to the model manager. | model_post_init | python | mckinsey/vizro | vizro-core/src/vizro/models/_page.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_page.py | Apache-2.0 |
def _get_control_states(self, control_type: ControlType) -> list[State]:
"""Gets list of `States` for selected `control_type` that appear on page where this Action is defined."""
# Possibly the code that specifies the state associated with a control will move to an inputs property
# of the filte... | Gets list of `States` for selected `control_type` that appear on page where this Action is defined. | _get_control_states | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def _get_filter_interaction_states(self) -> list[dict[str, State]]:
"""Gets list of `States` for selected chart interaction `filter_interaction`."""
from vizro.actions import filter_interaction
page = model_manager._get_model_page(self)
return [
action._get_triggered_model()... | Gets list of `States` for selected chart interaction `filter_interaction`. | _get_filter_interaction_states | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def _transform_dependency(dependency: _IdOrIdProperty, type: Literal["output", "input"]) -> _IdProperty:
"""Transform a component dependency into its mapped property value.
This method handles two formats of component dependencies:
1. Explicit format: "component-id.component-property" (e.g. "gr... | Transform a component dependency into its mapped property value.
This method handles two formats of component dependencies:
1. Explicit format: "component-id.component-property" (e.g. "graph-1.figure")
- Returns the mapped value if it exists in the component's _action_outputs/_action_inputs
... | _transform_dependency | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def _transformed_inputs(self) -> Union[list[State], dict[str, Union[State, ControlsStates]]]:
"""Creates Dash States given the user-specified runtime arguments and built in ones.
Return type is list only for legacy actions. Otherwise, it will always be a dictionary (unlike
for _transformed_outp... | Creates Dash States given the user-specified runtime arguments and built in ones.
Return type is list only for legacy actions. Otherwise, it will always be a dictionary (unlike
for _transformed_outputs, where new behavior can still give a list). Keys are the parameter names. For
user-specified ... | _transformed_inputs | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def _transformed_outputs(self) -> Union[list[Output], dict[str, Output]]:
"""Creates Dash Output objects from string specifications in self.outputs.
Converts self.outputs (list of strings or dictionary of strings where each string is in the format
'<component_id>.<property>' or '<component_id>'... | Creates Dash Output objects from string specifications in self.outputs.
Converts self.outputs (list of strings or dictionary of strings where each string is in the format
'<component_id>.<property>' or '<component_id>') and converts into Dash Output objects.
For example, ['my_graph.figure'] bec... | _transformed_outputs | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def build(self) -> html.Div:
"""Builds a callback for the Action model and returns required components for the callback.
Returns:
Div containing a list of required components (e.g. dcc.Download) for the Action model
"""
# TODO: after sorting out model manager and pre-build ... | Builds a callback for the Action model and returns required components for the callback.
Returns:
Div containing a list of required components (e.g. dcc.Download) for the Action model
| build | python | mckinsey/vizro | vizro-core/src/vizro/models/_action/_action.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_action/_action.py | Apache-2.0 |
def _filter_interaction(
self, data_frame: pd.DataFrame, target: str, ctd_filter_interaction: dict[str, CallbackTriggerDict]
) -> pd.DataFrame:
"""Function to be carried out for `filter_interaction`."""
# data_frame is the DF of the target, ie the data to be filtered, hence we cannot get the... | Function to be carried out for `filter_interaction`. | _filter_interaction | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/ag_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/ag_grid.py | Apache-2.0 |
def _build_container(self):
"""Returns a collapsible container based on the `collapsed` state.
If `collapsed` is `None`, returns a non-collapsible container.
Otherwise, returns a collapsible container with visibility controlled by the `collapsed` flag.
"""
if self.collapsed is N... | Returns a collapsible container based on the `collapsed` state.
If `collapsed` is `None`, returns a non-collapsible container.
Otherwise, returns a collapsible container with visibility controlled by the `collapsed` flag.
| _build_container | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/container.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/container.py | Apache-2.0 |
def _build_container_title(self):
"""Builds and returns the container title, including an optional icon and tooltip if collapsed."""
description = self.description.build().children if self.description is not None else [None]
title_content = [
html.Div(
[html.Span(id=... | Builds and returns the container title, including an optional icon and tooltip if collapsed. | _build_container_title | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/container.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/container.py | Apache-2.0 |
def _optimise_fig_layout_for_dashboard(fig):
"""Post layout updates to visually enhance charts used inside dashboard."""
# Determine if a title is present
has_title = bool(fig.layout.title.text)
# TODO: Check whether we should increase margins for all chart types in template_dashboard_o... | Post layout updates to visually enhance charts used inside dashboard. | _optimise_fig_layout_for_dashboard | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/graph.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/graph.py | Apache-2.0 |
def _get_list_of_labels(full_options: OptionsType) -> Union[list[StrictBool], list[float], list[str], list[date]]:
"""Returns a list of labels from the selector options provided."""
if all(isinstance(option, dict) for option in full_options):
return [option["label"] for option in full_options] # type: ... | Returns a list of labels from the selector options provided. | _get_list_of_labels | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/dropdown.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py | Apache-2.0 |
def _calculate_option_height(full_options: OptionsType) -> int:
"""Calculates the height of the dropdown options based on the longest option."""
# 30 characters is roughly the number of "A" characters you can fit comfortably on a line in the dropdown.
# "A" is representative of a slightly wider than average... | Calculates the height of the dropdown options based on the longest option. | _calculate_option_height | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/dropdown.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py | Apache-2.0 |
def _add_select_all_option(full_options: OptionsType) -> OptionsType:
"""Adds a 'Select All' option to the list of options."""
# TODO: Move option to dictionary conversion within `get_options_and_default` function as here: https://github.com/mckinsey/vizro/pull/961#discussion_r1923356781
options_dict = [
... | Adds a 'Select All' option to the list of options. | _add_select_all_option | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/dropdown.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/dropdown.py | Apache-2.0 |
def get_options_and_default(options: OptionsType, multi: bool = False) -> tuple[OptionsType, SingleValueType]:
"""Gets list of full options and default value based on user input type of `options`."""
if multi:
if all(isinstance(option, dict) for option in options):
options = [{"label": ALL_O... | Gets list of full options and default value based on user input type of `options`. | get_options_and_default | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def is_value_contained(value: Union[SingleValueType, MultiValueType], options: OptionsType):
"""Checks if value is contained in a list."""
if isinstance(value, list):
return all(item in options for item in value)
else:
return value in options | Checks if value is contained in a list. | is_value_contained | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def validate_options_dict(cls, data: Any) -> Any:
"""Reusable validator for the "options" argument of categorical selectors."""
if "options" not in data or not isinstance(data["options"], list):
return data
for entry in data["options"]:
if isinstance(entry, dict) and not set(entry.keys()) =... | Reusable validator for the "options" argument of categorical selectors. | validate_options_dict | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def validate_value(value, info: ValidationInfo):
"""Reusable validator for the "value" argument of categorical selectors."""
if "options" not in info.data or not info.data["options"]:
return value
possible_values = (
[entry["value"] for entry in info.data["options"]]
if isinstance(i... | Reusable validator for the "value" argument of categorical selectors. | validate_value | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def validate_max(max, info: ValidationInfo):
"""Validates that the `max` is not below the `min` for a range-based input."""
if max is None:
return max
if info.data["min"] is not None and max < info.data["min"]:
raise ValueError("Maximum value of selector is required to be larger than minimu... | Validates that the `max` is not below the `min` for a range-based input. | validate_max | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def validate_range_value(value, info: ValidationInfo):
"""Validates a value or range of values to ensure they lie within specified bounds (min/max)."""
EXPECTED_VALUE_LENGTH = 2
if value is None:
return value
lvalue, hvalue = (
(value[0], value[1])
if isinstance(value, list) and... | Validates a value or range of values to ensure they lie within specified bounds (min/max). | validate_range_value | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def validate_step(step, info: ValidationInfo):
"""Reusable validator for the "step" argument for sliders."""
if step is None:
return step
if info.data["max"] is not None and step > (info.data["max"] - info.data["min"]):
raise ValueError(
"The step value of the slider must be les... | Reusable validator for the "step" argument for sliders. | validate_step | python | mckinsey/vizro | vizro-core/src/vizro/models/_components/form/_form_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_components/form/_form_utils.py | Apache-2.0 |
def _get_proposed_targets(self):
"""Get all valid figure model targets for this control based on its location in the page hierarchy."""
page = model_manager._get_model_page(self)
page_containers = model_manager._get_models(model_type=Container, root_model=page)
# Find the control's pare... | Get all valid figure model targets for this control based on its location in the page hierarchy. | _get_proposed_targets | python | mckinsey/vizro | vizro-core/src/vizro/models/_controls/filter.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_controls/filter.py | Apache-2.0 |
def _get_control_parent(control: ControlType) -> Optional[VizroBaseModel]:
"""Get the parent model of a control."""
# Return None if the control is not part of any page.
if (page := model_manager._get_model_page(model=control)) is None:
return None
# Return the Page if the control is its direct... | Get the parent model of a control. | _get_control_parent | python | mckinsey/vizro | vizro-core/src/vizro/models/_controls/_controls_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_controls/_controls_utils.py | Apache-2.0 |
def _create_nav_links(self, pages: list[ModelID]):
"""Creates a `NavLink` for each provided page."""
from vizro.models import Page
nav_links = []
for page_id in pages:
page = cast(Page, model_manager[page_id])
nav_links.append(
dbc.NavLink(
... | Creates a `NavLink` for each provided page. | _create_nav_links | python | mckinsey/vizro | vizro-core/src/vizro/models/_navigation/accordion.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_navigation/accordion.py | Apache-2.0 |
def _validate_pages(pages: NavPagesType) -> NavPagesType:
"""Reusable validator to check if provided Page IDs exist as registered pages."""
from vizro.models import Page
pages_as_list = list(itertools.chain(*pages.values())) if isinstance(pages, dict) else pages
# Ideally we would use dashboard.pages i... | Reusable validator to check if provided Page IDs exist as registered pages. | _validate_pages | python | mckinsey/vizro | vizro-core/src/vizro/models/_navigation/_navigation_utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/models/_navigation/_navigation_utils.py | Apache-2.0 |
def dash_ag_grid(data_frame: pd.DataFrame, **kwargs: Any) -> dag.AgGrid:
"""Implementation of `dash_ag_grid.AgGrid` with sensible defaults to be used in [`AgGrid`][vizro.models.AgGrid].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be p... | Implementation of `dash_ag_grid.AgGrid` with sensible defaults to be used in [`AgGrid`][vizro.models.AgGrid].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_ag_grid.AgGrid` component.
Returns:
A `dash_ag_g... | dash_ag_grid | python | mckinsey/vizro | vizro-core/src/vizro/tables/_dash_ag_grid.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/tables/_dash_ag_grid.py | Apache-2.0 |
def dash_data_table(data_frame: pd.DataFrame, **kwargs: Any) -> dash_table.DataTable:
"""Standard `dash.dash_table.DataTable` with sensible defaults to be used in [`Table`][vizro.models.Table].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments... | Standard `dash.dash_table.DataTable` with sensible defaults to be used in [`Table`][vizro.models.Table].
Args:
data_frame: DataFrame containing the data to be displayed.
kwargs: Additional keyword arguments to be passed to the `dash_table.DataTable` component.
Returns:
A `dash.dash_tab... | dash_data_table | python | mckinsey/vizro | vizro-core/src/vizro/tables/_dash_table.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/tables/_dash_table.py | Apache-2.0 |
def _extract_last_two_occurrences(variable: str, css_content: str) -> tuple[Optional[str], Optional[str]]:
"""Extracts the last two occurrences of a variable from the CSS content.
Within the `vizro-bootstrap.min.css` file, variables appear multiple times: initially from the default Bootstrap
values, follow... | Extracts the last two occurrences of a variable from the CSS content.
Within the `vizro-bootstrap.min.css` file, variables appear multiple times: initially from the default Bootstrap
values, followed by the dark theme, and lastly the light theme. We are interested in the final two occurrences,
as these rep... | _extract_last_two_occurrences | python | mckinsey/vizro | vizro-core/src/vizro/_themes/generate_plotly_templates.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/src/vizro/_themes/generate_plotly_templates.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.