Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Nov 15, 2024
1 parent 5f161aa commit cfdf4fc
Show file tree
Hide file tree
Showing 11 changed files with 143 additions and 110 deletions.
57 changes: 34 additions & 23 deletions vizro-core/examples/scratch_dev/_poc_dynamic_controls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import dash
import plotly.express as px

from dash import Dash, html, dcc, Output, callback, clientside_callback, Input, State, set_props
import dash_mantine_components as dmc

import plotly.express as px
from dash import Dash, Input, Output, State, callback, clientside_callback, dcc, html

CONTROL_SELECTOR = dcc.RangeSlider

Expand Down Expand Up @@ -90,18 +88,18 @@ def categorical_filter_build(options=None):
kwargs["multi"] = MULTI

return CONTROL_SELECTOR(
id=f'filter',
id="filter",
options=options or pre_build_options,
value=pre_build_categorical_value,
persistence=True,
persistence_type="session",
**kwargs
**kwargs,
)


def numerical_filter_build(min_value=None, max_value=None):
return CONTROL_SELECTOR(
id=f'filter',
id="filter",
min=min_value or pre_build_min,
max=max_value or pre_build_max,
value=pre_build_numerical_value,
Expand All @@ -117,7 +115,7 @@ def _get_initial_page_build_object():
if CONTROL_SELECTOR == dcc.Dropdown:
# A hack explained in on_page_load To-do:"Limitations" section below in this page.
return dmc.DateRangePicker(
id='filter',
id="filter",
value=pre_build_categorical_value,
persistence=True,
persistence_type="session",
Expand All @@ -133,27 +131,28 @@ def _get_initial_page_build_object():
[
dcc.Store(id="on_page_load_trigger_another_page"),
html.H2("Another page"),

# # This does NOT work because id="filter" doesn't exist but is used as OPL callback State.
# dcc.Loading(id="filter_container"),

# # Possible solution is to alter filter.options from on_page_load. This would work, but it's not optimal.
# dcc.Dropdown(id="filter", options=options, value=options, multi=True, persistence=True),

# # Outer container can be changed with dcc.Loading.
html.Div(
_get_initial_page_build_object(),
id="filter_container",
),

# # Does not work because OPL filter input is missing, but it's used for filtering figures data_frame.
# html.Div(
# html.Div(id="filter"),
# id="filter_container",
# ),

html.Br(),
dcc.RadioItems(id="parameter", options=["sepal_width", "sepal_length"], value="sepal_width", persistence=True, persistence_type="session"),
dcc.RadioItems(
id="parameter",
options=["sepal_width", "sepal_length"],
value="sepal_width",
persistence=True,
persistence_type="session",
),
dcc.Loading(dcc.Graph(id="graph1")),
dcc.Loading(dcc.Graph(id="graph2")),
]
Expand Down Expand Up @@ -206,11 +205,10 @@ def get_data(species):
],
inputs=[
Input("global_on_page_load_another_page_action_trigger", "data"),
State("filter", "value"),
State("parameter", "value"),
],
prevent_initial_call=True
prevent_initial_call=True,
)
def on_page_load(data, persisted_filter_value, x):
# Ideally, OPL flow should look like this:
Expand Down Expand Up @@ -263,9 +261,13 @@ def on_page_load(data, persisted_filter_value, x):
if CONTROL_SELECTOR in SELECTOR_TYPE["categorical"]:
categorical_filter_options = sorted(df["species"].unique().tolist())
if MULTI:
categorical_filter_value = [value for value in persisted_filter_value if value in categorical_filter_options]
categorical_filter_value = [
value for value in persisted_filter_value if value in categorical_filter_options
]
else:
categorical_filter_value = persisted_filter_value if persisted_filter_value in categorical_filter_options else None
categorical_filter_value = (
persisted_filter_value if persisted_filter_value in categorical_filter_options else None
)
new_filter_obj = categorical_filter_build(options=categorical_filter_options)

# --- Filtering data: ---
Expand Down Expand Up @@ -298,19 +300,28 @@ def on_page_load(data, persisted_filter_value, x):
numerical_filter_min = float(df["sepal_length"].min())
numerical_filter_max = float(df["sepal_length"].max())
if MULTI:
numerical_filter_value = [max(numerical_filter_min, persisted_filter_value[0]), min(numerical_filter_max, persisted_filter_value[1])]
numerical_filter_value = [
max(numerical_filter_min, persisted_filter_value[0]),
min(numerical_filter_max, persisted_filter_value[1]),
]
else:
numerical_filter_value = persisted_filter_value if numerical_filter_min < persisted_filter_value < numerical_filter_max else numerical_filter_min
numerical_filter_value = (
persisted_filter_value
if numerical_filter_min < persisted_filter_value < numerical_filter_max
else numerical_filter_min
)
new_filter_obj = numerical_filter_build(min_value=numerical_filter_min, max_value=numerical_filter_max)
# set_props(component_id="numerical_filter_container", props={"children": new_filter_obj})

# --- Filtering data: ---
if MULTI:
df = df[(df["sepal_length"] >= numerical_filter_value[0]) & (df["sepal_length"] <= numerical_filter_value[1])]
df = df[
(df["sepal_length"] >= numerical_filter_value[0]) & (df["sepal_length"] <= numerical_filter_value[1])
]
else:
df = df[(df["sepal_length"] == numerical_filter_value)]

print("")
print()
return graph1_call(df), graph2_call(df, x), new_filter_obj


Expand Down Expand Up @@ -394,4 +405,4 @@ def on_page_load(data, persisted_filter_value, x):
# IMPORTANT: also consider parametrised data case.

if __name__ == "__main__":
app.run(debug=True, dev_tools_hot_reload=False)
app.run(debug=True, dev_tools_hot_reload=False)
95 changes: 54 additions & 41 deletions vizro-core/examples/scratch_dev/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Dev app to try things out."""

import time
import yaml

Expand Down Expand Up @@ -27,24 +28,35 @@
def load_from_file(filter_column=None, parametrized_species=None):
# Load the full iris dataset
df = px.data.iris()
df['date_column'] = pd.date_range(start=pd.to_datetime("2024-01-01"), periods=len(df), freq='D')
df["date_column"] = pd.date_range(start=pd.to_datetime("2024-01-01"), periods=len(df), freq="D")

if parametrized_species:
return df[df["species"].isin(parametrized_species)]

with open('data.yaml', 'r') as file:
with open("data.yaml", "r") as file:
data = yaml.safe_load(file)
data = data or {}

filter_column = filter_column or FILTER_COLUMN
if filter_column == "species":
final_df = pd.concat(objs=[
df[df[filter_column] == 'setosa'].head(data.get("setosa", 0)),
df[df[filter_column] == 'versicolor'].head(data.get("versicolor", 0)),
df[df[filter_column] == 'virginica'].head(data.get("virginica", 0)),
], ignore_index=True)
final_df = pd.concat(
objs=[
df[df[filter_column] == "setosa"].head(data.get("setosa", 0)),
df[df[filter_column] == "versicolor"].head(data.get("versicolor", 0)),
df[df[filter_column] == "virginica"].head(data.get("virginica", 0)),
],
ignore_index=True,
)
elif filter_column == "sepal_length":
final_df = df[df[filter_column].between(data.get("min"), data.get("max",), inclusive="both")]
final_df = df[
df[filter_column].between(
data.get("min"),
data.get(
"max",
),
inclusive="both",
)
]
elif filter_column == "date_column":
date_min = pd.to_datetime(data.get("date_min"))
date_max = pd.to_datetime(data.get("date_max"))
Expand Down Expand Up @@ -82,16 +94,18 @@ def load_from_file(filter_column=None, parametrized_species=None):
vm.Graph(
id="p1-G-2",
figure=px.scatter(data_frame=px.data.iris(), **SCATTER_CHART_CONF),
)
),
],
controls=[
vm.Filter(id="p1-F-1", column="species", targets=["p1-G-1"], selector=vm.Dropdown(title="Dynamic filter")),
vm.Filter(id="p1-F-2", column="species", targets=["p1-G-2"], selector=vm.Dropdown(title="Static filter")),
vm.Parameter(
targets=["p1-G-1.x", "p1-G-2.x"],
selector=vm.RadioItems(options=["species", "sepal_width"], value="species", title="Simple X-axis parameter")
)
]
selector=vm.RadioItems(
options=["species", "sepal_width"], value="species", title="Simple X-axis parameter"
),
),
],
)


Expand All @@ -110,9 +124,11 @@ def load_from_file(filter_column=None, parametrized_species=None):
vm.Filter(id="p2-F-4", column="species", selector=vm.RadioItems()),
vm.Parameter(
targets=["p2-G-1.x"],
selector=vm.RadioItems(options=["species", "sepal_width"], value="species", title="Simple X-axis parameter")
)
]
selector=vm.RadioItems(
options=["species", "sepal_width"], value="species", title="Simple X-axis parameter"
),
),
],
)


Expand All @@ -129,9 +145,11 @@ def load_from_file(filter_column=None, parametrized_species=None):
vm.Filter(id="p3-F-2", column="sepal_length", selector=vm.RangeSlider()),
vm.Parameter(
targets=["p3-G-1.x"],
selector=vm.RadioItems(options=["species", "sepal_width"], value="species", title="Simple X-axis parameter")
)
]
selector=vm.RadioItems(
options=["species", "sepal_width"], value="species", title="Simple X-axis parameter"
),
),
],
)

page_4 = vm.Page(
Expand All @@ -147,9 +165,11 @@ def load_from_file(filter_column=None, parametrized_species=None):
vm.Filter(id="p4-F-2", column="date_column", selector=vm.DatePicker()),
vm.Parameter(
targets=["p4-G-1.x"],
selector=vm.RadioItems(options=["species", "sepal_width"], value="species", title="Simple X-axis parameter")
)
]
selector=vm.RadioItems(
options=["species", "sepal_width"], value="species", title="Simple X-axis parameter"
),
),
],
)

page_5 = vm.Page(
Expand All @@ -170,73 +190,66 @@ def load_from_file(filter_column=None, parametrized_species=None):
# "p5-F-1.",
],
selector=vm.Dropdown(
options=["setosa", "versicolor", "virginica"],
multi=True,
title="Parametrized species"
)
options=["setosa", "versicolor", "virginica"], multi=True, title="Parametrized species"
),
),
vm.Parameter(
targets=[
"p5-G-1.x",
# TODO: Uncomment the following target and see the magic :D
# "p5-F-1.",
],
selector=vm.RadioItems(options=["species", "sepal_width"], value="species", title="Simple X-axis parameter")
selector=vm.RadioItems(
options=["species", "sepal_width"], value="species", title="Simple X-axis parameter"
),
),
]
],
)


page_6 = vm.Page(
title="Page to test things out",
components=[
vm.Graph(
id="graph_dynamic",
figure=px.bar(data_frame="load_from_file", **BAR_CHART_CONF)
),
vm.Graph(id="graph_dynamic", figure=px.bar(data_frame="load_from_file", **BAR_CHART_CONF)),
vm.Graph(
id="graph_static",
figure=px.scatter(data_frame=px.data.iris(), **SCATTER_CHART_CONF),
)
),
],
controls=[
vm.Filter(
id="filter_container_id",
column=FILTER_COLUMN,
targets=["graph_dynamic"],
# targets=["graph_static"],

# selector=vm.Dropdown(id="filter_id"),
# selector=vm.Dropdown(id="filter_id", value=["setosa"]),

# selector=vm.Checklist(id="filter_id"),
# selector=vm.Checklist(id="filter_id", value=["setosa"]),

# TODO-BUG: vm.Dropdown(multi=False) Doesn't work if value is cleared. The persistence storage become
# "null" and our placeholder component dmc.DateRangePicker can't process null value. It expects a value or
# a list of values.
# SOLUTION -> Create the "Universal Vizro placeholder component".
# TEMPORARY SOLUTION -> set clearable=False for the dynamic Dropdown(multi=False)
# selector=vm.Dropdown(id="filter_id", multi=False), ->
# selector=vm.Dropdown(id="filter_id", multi=False, value="setosa"),

# selector=vm.RadioItems(id="filter_id"),
# selector=vm.RadioItems(id="filter_id", value="setosa"),

# selector=vm.Slider(id="filter_id"),
# selector=vm.Slider(id="filter_id", value=5),

# selector=vm.RangeSlider(id="filter_id"),
# selector=vm.RangeSlider(id="filter_id", value=[5, 7]),
),
),
vm.Parameter(
id="parameter_x",
targets=["graph_dynamic.x",],
targets=[
"graph_dynamic.x",
],
selector=vm.Dropdown(
options=["species", "sepal_width"],
value="species",
multi=False,
)
),
),
],
)
Expand Down
2 changes: 1 addition & 1 deletion vizro-core/examples/scratch_dev/data.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ max: 7
# Choose from:
# 2020-01-01 to 2020-05-29
date_min: 2024-01-01
date_max: 2024-05-29
date_max: 2024-05-29
10 changes: 6 additions & 4 deletions vizro-core/src/vizro/actions/_actions_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from vizro.models.types import MultiValueType, SelectorType, SingleValueType

if TYPE_CHECKING:
from vizro.models import Action, VizroBaseModel, Filter
from vizro.models import Action, VizroBaseModel

ValidatedNoneValueType = Union[SingleValueType, MultiValueType, None, list[None]]

Expand Down Expand Up @@ -162,6 +162,7 @@ def _update_nested_figure_properties(
current_property[keys[-1]] = value
return figure_config


def _get_parametrized_config(
ctd_parameter: list[CallbackTriggerDict], target: ModelID, data_frame: bool
) -> dict[str, Any]:
Expand Down Expand Up @@ -275,7 +276,9 @@ def _get_modified_page_figures(
# Also, it was a good decision to return action output as key: value pairs for the predefined actions.
_get_unfiltered_data_targets = list(set(figure_targets + control_targets_targets))

figure_targets_unfiltered_data: dict[ModelID, pd.DataFrame] = _get_unfiltered_data(ctds_parameter, _get_unfiltered_data_targets)
figure_targets_unfiltered_data: dict[ModelID, pd.DataFrame] = _get_unfiltered_data(
ctds_parameter, _get_unfiltered_data_targets
)

for target, unfiltered_data in figure_targets_unfiltered_data.items():
if target in figure_targets:
Expand All @@ -292,8 +295,7 @@ def _get_modified_page_figures(
current_value = []

outputs[target] = model_manager[target](
target_to_data_frame=figure_targets_unfiltered_data,
current_value=current_value
target_to_data_frame=figure_targets_unfiltered_data, current_value=current_value
)

return outputs
Loading

0 comments on commit cfdf4fc

Please sign in to comment.