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 _register_data(all_df_metadata: AllDfMetadata) -> vm.Dashboard:
"""Register the dashboard data in data manager."""
from vizro.managers import data_manager
for name, metadata in all_df_metadata.all_df_metadata.items():
data_manager[name] = metadata.df | Register the dashboard data in data manager. | _register_data | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
def _extract_overall_imports_and_code(
custom_charts_code: list[list[dict[str, str]]], custom_charts_imports: list[list[dict[str, str]]]
) -> tuple[set[str], set[str]]:
"""Extract custom functions and imports from the custom charts code.
Args:
custom_charts_code: A list of lists of dictionaries, wh... | Extract custom functions and imports from the custom charts code.
Args:
custom_charts_code: A list of lists of dictionaries, where each dictionary
contains the custom chart code for a component.
The outer list represents pages, the inner list represents
components on a p... | _extract_overall_imports_and_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
def _create_prompt_template(additional_info: str) -> ChatPromptTemplate:
"""Create the ChatPromptTemplate from the base prompt and additional info."""
return ChatPromptTemplate.from_messages(
[
("system", BASE_PROMPT.format(df_info="{df_info}", additional_info=additional_info)),
... | Create the ChatPromptTemplate from the base prompt and additional info. | _create_prompt_template | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _create_message_content(
query: str, df_info: Any, validation_error: Optional[str] = None, retry: bool = False
) -> dict:
"""Create the message content for the LLM model."""
message_content = {"message": [HumanMessage(content=query)], "df_info": df_info}
if retry:
message_content["validatio... | Create the message content for the LLM model. | _create_message_content | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _get_pydantic_model(
query: str,
llm_model: BaseChatModel,
response_model: BaseModel,
df_info: Optional[Any] = None, # TODO: this should potentially not be part of this function.
max_retry: int = 2,
) -> BaseModel:
# TODO: fix typing similar to instructor library, ie the return type should ... | Get the pydantic output from the LLM model with retry logic. | _get_pydantic_model | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _continue_to_pages(state: GraphState) -> list[Send]:
"""Map-reduce logic to build pages in parallel."""
all_df_metadata = state.all_df_metadata
return [
Send(node="_build_page", arg={"page_plan": v, "all_df_metadata": all_df_metadata})
for v in state.dashboard_plan.pages
] | Map-reduce logic to build pages in parallel. | _continue_to_pages | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_graph/dashboard_creation.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_graph/dashboard_creation.py | Apache-2.0 |
def create(self, model: BaseChatModel, all_df_metadata: AllDfMetadata) -> ComponentResult:
"""Create the component based on its type.
Args:
model: The llm used.
all_df_metadata: Metadata for all available dataframes.
Returns:
ComponentResult containing:
... | Create the component based on its type.
Args:
model: The llm used.
all_df_metadata: Metadata for all available dataframes.
Returns:
ComponentResult containing:
- component: The created component (vm.Card, vm.AgGrid, or vm.Graph)
- code: Optio... | create | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/components.py | Apache-2.0 |
def validate_date_picker_column(cls, data: Any):
"""Validate the column for date picker."""
column = data.get("column")
selector = data.get("selector")
if selector and hasattr(selector, "type") and selector.type == "date_picker":
if not pd.api.types.is_datetime64_any_dtype(df... | Validate the column for date picker. | validate_date_picker_column | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/controls.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/controls.py | Apache-2.0 |
def _get_df_info(df: pd.DataFrame) -> tuple[dict[str, str], pd.DataFrame]:
"""Get the dataframe schema and sample."""
formatted_pairs = dict(df.dtypes.astype(str))
df_sample = df.sample(5, replace=True, random_state=19)
return formatted_pairs, df_sample | Get the dataframe schema and sample. | _get_df_info | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/df_info.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/df_info.py | Apache-2.0 |
def _validate_component_id_unique(components_list):
"""Validate the component id is unique."""
component_ids = [comp.component_id for comp in components_list]
duplicates = [id for id, count in Counter(component_ids).items() if count > 1]
if duplicates:
raise ValueError(f"Component ids must be un... | Validate the component id is unique. | _validate_component_id_unique | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/page.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/page.py | Apache-2.0 |
def _strip_markdown(code_string: str) -> str:
"""Remove any code block wrappers (markdown or triple quotes)."""
wrappers = [("```python\n", "```"), ("```py\n", "```"), ("```\n", "```"), ('"""', '"""'), ("'''", "'''")]
for start, end in wrappers:
if code_string.startswith(start) and code_string.ends... | Remove any code block wrappers (markdown or triple quotes). | _strip_markdown | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def _exec_code(code: str, namespace: dict) -> dict:
"""Execute code and return the local dictionary."""
# Need the global namespace for the imports to work for executed code
# Tried just handling it in local scope, ie getting the import statement into ldict, but it didn't work
# TODO: ideally in future ... | Execute code and return the local dictionary. | _exec_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def validator_code(v, info: ValidationInfo):
"""Test the execution of the chart code."""
imports = "\n".join(info.data.get("imports", []))
code_to_validate = imports + "\n\n" + v
try:
_safeguard_check(code_to_validate)
except Exception as e:
raise ValueErr... | Test the execution of the chart code. | validator_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def get_fig_object(self, data_frame: Union[pd.DataFrame, str], chart_name: Optional[str] = None, vizro=True):
"""Execute code to obtain the plotly go.Figure object. Be sure to check code to be executed before running.
Args:
data_frame: Dataframe or string representation of the dataframe.
... | Execute code to obtain the plotly go.Figure object. Be sure to check code to be executed before running.
Args:
data_frame: Dataframe or string representation of the dataframe.
chart_name: Name of the chart function. Defaults to `None`,
in which case it remains as `custom... | get_fig_object | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def __new__(cls, data_frame: pd.DataFrame, chart_plan: type[BaseChartPlan] = ChartPlan) -> type[BaseChartPlan]:
"""Creates a chart plan model with additional validation.
Args:
data_frame: DataFrame to use for validation
chart_plan: Chart plan model to run extended validation aga... | Creates a chart plan model with additional validation.
Args:
data_frame: DataFrame to use for validation
chart_plan: Chart plan model to run extended validation against. Defaults to ChartPlan.
Returns:
Chart plan model with additional validation
| __new__ | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def _check_data_handling(node: ast.stmt):
"""Check usage of unsafe data file loading and saving."""
code = ast.unparse(node)
redlisted_data_handling = [method for method in REDLISTED_DATA_HANDLING if method in code]
if redlisted_data_handling:
methods_str = ", ".join(redlisted_data_handling)
... | Check usage of unsafe data file loading and saving. | _check_data_handling | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _check_class_method_usage(node: ast.stmt):
"""Check usage of unsafe builtin in code."""
code = ast.unparse(node)
redlisted_builtins = [funct for funct in REDLISTED_CLASS_METHODS if funct in code]
if redlisted_builtins:
functions_str = ", ".join(redlisted_builtins)
raise Exception(
... | Check usage of unsafe builtin in code. | _check_class_method_usage | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _check_builtin_function_usage(node: ast.stmt):
"""Check usage of unsafe builtin functions."""
code = ast.unparse(node)
builtin_list = [name for name, obj in vars(builtins).items()]
non_whitelisted_builtins = [
builtin
for builtin in builtin_list
if re.search(r"\b" + re.escap... | Check usage of unsafe builtin functions. | _check_builtin_function_usage | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _safeguard_check(code: str):
"""Perform safeguard checks to avoid execution of malicious code."""
try:
tree = ast.parse(code)
except (SyntaxError, UnicodeDecodeError):
raise ValueError(f"Generated code is not valid: {code}")
except OverflowError:
raise ValueError(f"Generated ... | Perform safeguard checks to avoid execution of malicious code. | _safeguard_check | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _get_df_info(df: pd.DataFrame, n_sample: int = 5) -> tuple[str, str]:
"""Get the dataframe schema and head info as string."""
formatted_pairs = [f"{col_name}: {dtype}" for col_name, dtype in df.dtypes.items()]
schema_string = "\n".join(formatted_pairs)
return schema_string, df.sample(n_sample, repla... | Get the dataframe schema and head info as string. | _get_df_info | python | mckinsey/vizro | vizro-ai/src/vizro_ai/utils/helper.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/utils/helper.py | Apache-2.0 |
def logic( # noqa: PLR0912, PLR0913, PLR0915
dashboard,
model_name,
dash_duo,
prompt_tier,
prompt_name,
prompt_text,
config: dict,
):
"""Calculates all separate scores. Creates csv report.
Attributes:
dashboard: VizroAI generated dashboard
model_name: GenAI model na... | Calculates all separate scores. Creates csv report.
Attributes:
dashboard: VizroAI generated dashboard
model_name: GenAI model name
dash_duo: dash_duo fixture
prompt_tier: complexity of the prompt
prompt_name: short prompt description
prompt_text: prompt text
... | logic | python | mckinsey/vizro | vizro-ai/tests/e2e/test_dashboard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/e2e/test_dashboard.py | Apache-2.0 |
def test_chart_plan_factory_validation_failure(sample_df):
"""Test factory validation fails with invalid code."""
ValidatedModel = ChartPlanFactory(data_frame=sample_df, chart_plan=BaseChartPlan)
with pytest.raises(ValueError, match="The chart code must be wrapped in a function named"):
ValidatedMo... | Test factory validation fails with invalid code. | test_chart_plan_factory_validation_failure | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def test_chart_plan_factory_preserves_fields(sample_df, valid_chart_code):
"""Test factory preserves all fields from base class."""
ValidatedModel = ChartPlanFactory(data_frame=sample_df, chart_plan=ChartPlan)
instance = ValidatedModel(
chart_type="scatter",
imports=["import plotly.express ... | Test factory preserves all fields from base class. | test_chart_plan_factory_preserves_fields | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def test_base_chart_plan_no_explanatory_fields(valid_chart_code):
"""Test BaseChartPlan doesn't have explanatory fields."""
instance = BaseChartPlan(chart_type="scatter", imports=["import plotly.express as px"], chart_code=valid_chart_code)
with pytest.raises(AttributeError):
_ = instance.chart_ins... | Test BaseChartPlan doesn't have explanatory fields. | test_base_chart_plan_no_explanatory_fields | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def make_subheading(label, link):
"""Creates a subheading with a link to the docs."""
slug = label.replace(" ", "")
heading = html.H3(
html.Span(
[
label,
html.A(
html.I(className="bi bi-book h4 ms-2"),
href=f"{DBC_D... | Creates a subheading with a link to the docs. | make_subheading | python | mckinsey/vizro | vizro-core/examples/bootstrap/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/bootstrap/app.py | Apache-2.0 |
def scatter_with_line(data_frame, x, y, hline=None, title=None):
"""Custom scatter chart based on px."""
fig = px.scatter(data_frame=data_frame, x=x, y=y, title=title)
fig.add_hline(y=hline, line_color="orange")
return fig | Custom scatter chart based on px. | scatter_with_line | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def waterfall(data_frame, measure, x, y, text, title=None):
"""Custom waterfall chart based on go."""
fig = go.Figure()
fig.add_traces(
go.Waterfall(
measure=data_frame[measure],
x=data_frame[x],
y=data_frame[y],
text=data_frame[text],
decr... | Custom waterfall chart based on go. | waterfall | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def my_custom_table(data_frame=None, chosen_columns: Optional[list[str]] = None):
"""Custom table with added logic to filter on chosen columns."""
columns = [{"name": i, "id": i} for i in chosen_columns]
defaults = {
"style_as_list_view": True,
"style_data": {"border_bottom": "1px solid var(... | Custom table with added logic to filter on chosen columns. | my_custom_table | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def build(self):
"""Extend existing component by calling the super build and update properties."""
range_slider_build_obj = super().build()
range_slider_build_obj[self.id].allowCross = False
range_slider_build_obj[self.id].tooltip = {"always_visible": True, "placement": "bottom"}
... | Extend existing component by calling the super build and update properties. | build | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def multiple_cards(data_frame: pd.DataFrame, n_rows: Optional[int] = 1) -> html.Div:
"""Creates a list with a variable number of `vm.Card` components from the provided data_frame.
Args:
data_frame: Data frame containing the data.
n_rows: Number of rows to use from the data_frame. Defaults to 1.... | Creates a list with a variable number of `vm.Card` components from the provided data_frame.
Args:
data_frame: Data frame containing the data.
n_rows: Number of rows to use from the data_frame. Defaults to 1.
Returns:
html.Div with a list of dbc.Card objects generated from the data.
... | multiple_cards | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
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 waterfall_factory(group: str):
"""Reusable function to create the page content for the column chart with a unique ID."""
return vm.Page(
id=f"{group}-waterfall",
path=f"{group}/waterfall",
title="Waterfall",
layout=vm.Grid(grid=PAGE_GRID),
components=[
vm.... | Reusable function to create the page content for the column chart with a unique ID. | waterfall_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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.