23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168 | class OutputPriceElasticity(ModelOutputItem):
def __init__(
self,
price_values: PriceElasticityTrackers | list[PriceElasticityTrackers] = None,
encodings: Encodings | None = None,
combine_granularities_flag: bool = False,
final_df: pd.DataFrame | list[pd.DataFrame] = None,
is_animation_call: bool = False,
):
super().__init__(final_df, [price_values, encodings])
self.final_df = final_df
self.is_animation_call = is_animation_call
if self.final_df is None:
self.price_values = [
RecursiveNamespace.parse(inter) if isinstance(inter, Mapping) else inter
for inter in (price_values if isinstance(price_values, list) else [price_values])
]
self.encodings = encodings
self.combine_granularities_flag = combine_granularities_flag
def get_price_elasticity_df(self, price_values: PriceElasticityTrackers):
# return pandas dataframe
# indexes are price indices (x-axis of price elasticity curve)
# columns is a multiindex (
# granularities string concatenated together,
# [price elasticity multiplier + 'steps' for animation frames])
index = pd.Index(to_numpy(price_values.price)[0, :, 0], name="spend")
granularity_names, level_names = get_granularity_names(self.encodings, price_values.input)
price_names = to_signal_names(price_values.signal_names)
columns = pd.MultiIndex.from_tuples(
[
(*names, signal, vehicle)
for names in granularity_names
for signal in ("impact", "slope")
for vehicle in price_names
],
names=(*level_names, "value", "signal"),
)
me_df = pd.DataFrame(
np.stack([price_values.impact, price_values.slope], axis=2)
.transpose(1, 0, 2, 3)
.reshape(index.shape[0], -1),
index=index,
columns=columns,
)
step_cols = pd.MultiIndex.from_tuples(
[(*names, "step", signal) for names in granularity_names for signal in price_names],
names=(*level_names, "value", "signal"),
)
return pd.concat(
[
me_df,
pd.DataFrame(
np.full((len(me_df.index), len(step_cols)), to_numpy(price_values.step), dtype=np.int32),
index=me_df.index,
columns=step_cols,
),
],
axis=1,
)
@cached_property
def df(self) -> pd.DataFrame:
"""Get price elasticity dataframe"""
if self.final_df is not None:
return self.final_df
price_elasticity_dfs = []
for step_price_values in self.price_values:
step_price_elasticity_df = self.get_price_elasticity_df(step_price_values)
price_elasticity_dfs.append(
combine_granularities(step_price_elasticity_df)
if self.combine_granularities_flag
else step_price_elasticity_df
)
price_elasticity_dfs = price_elasticity_dfs[0] if len(self.price_values) == 1 else price_elasticity_dfs
return price_elasticity_dfs
def visualize(
self,
price_devs: dict[str, int] | None = None,
wibbles: list[str] | dict[str, int] | None = None,
wibble_encodings: dict[str, int] | None = None,
group_by_granularity: bool = True,
show_both=False,
height: int = 800,
**kwargs,
) -> dict[str, go.Figure]:
"""Visualize price elasticity
Args:
price_devs (dict[str, int]): price_dev level values
wibbles (list[str] | None, optional): Names of all the wibbles/keys. Defaults to None.
wibble_encodings (dict[str, int]): Wibble encodings
group_by_granularity (bool, optional): Flag to indicate whether to group and view the plots by granularity.
Defaults to True.
show_both (bool, optional): Flag to indicate whether to group plots both by granularity level and
price_dev level. Defaults to False.
height (int, optional): The height of the line or the scatter plot. Defaults to 800.
show_plots (bool, optional): Flag to indicate whether to show the plots. Defaults to True.
Returns:
dict[str, go.Figure]: Prepared line or scatter plots of mixed effects dataframe of granularity names and/or
signal names.
"""
all_plots = {}
animation_frame = "step" if self.is_animation_call else None
price_elasticity_df = self.df
if price_devs is None:
first_df = price_elasticity_df[0] if isinstance(price_elasticity_df, list) else price_elasticity_df
price_devs = {v: i for i, v in enumerate(first_df.columns.unique("signal"))}
if isinstance(price_elasticity_df, list):
if self.is_animation_call:
price_elasticity_df = pd.concat(price_elasticity_df, axis=0)
else:
price_elasticity_df = pd.concat(price_elasticity_df, axis=1)
if wibbles is None:
if wibble_encodings:
wibbles = list(wibble_encodings.keys())
else:
wibbles = price_elasticity_df.columns.unique("granularity").tolist()
if group_by_granularity:
all_plots = make_plots(
price_elasticity_df,
wibbles,
"granularity",
list(price_devs.keys()),
animation_frame,
height,
**kwargs,
)
if not group_by_granularity or show_both:
all_plots |= make_plots(
price_elasticity_df,
list(price_devs.keys()),
"signal",
wibbles,
animation_frame,
height,
**kwargs,
)
return all_plots
|