l4v1 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
l4v1-0.0.1/.gitignore ADDED
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
@@ -0,0 +1 @@
1
+ 3.12.2
l4v1-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
l4v1-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.3
2
+ Name: l4v1
3
+ Version: 0.0.1
4
+ Summary: Add your description here
5
+ Author-email: Miro Lavi <mirolavi@gmail.com>
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.8
8
+ Requires-Dist: plotly>=5.21.0
9
+ Requires-Dist: polars>=0.20.21
10
+ Description-Content-Type: text/markdown
11
+
12
+ # l4v1-analytics
l4v1-0.0.1/README.md ADDED
@@ -0,0 +1 @@
1
+ # l4v1-analytics
l4v1-0.0.1/TESTING.py ADDED
@@ -0,0 +1,25 @@
1
+ from l4v1.impact_analysis import impact_plot, impact_table
2
+ import polars as pl
3
+
4
+ df = pl.scan_parquet("data/supermarket_sales.parquet").with_columns(
5
+ pl.col(pl.Categorical).cast(pl.Utf8)
6
+ )
7
+
8
+ sales_week5 = df.filter(pl.col("Datetime").dt.week() == 5)
9
+ sales_week6 = df.filter(pl.col("Datetime").dt.week() == 6)
10
+
11
+ impact_table_df = impact_table(
12
+ df_primary=sales_week6,
13
+ df_comparison=sales_week5,
14
+ group_by_columns=["Branch", "Product line"],
15
+ volume_metric_name="Quantity",
16
+ outcome_metric_name="Total",
17
+ )
18
+
19
+ impact_plot(
20
+ impact_table=impact_table_df,
21
+ format_data_labels="{:,.0f}",
22
+ primary_total_label="Test1",
23
+ comparison_total_label="Test2",
24
+ title="Detailed Impact Analysis"
25
+ )
File without changes
@@ -0,0 +1,406 @@
1
+ import polars as pl
2
+ import polars.selectors as cs
3
+ import plotly.graph_objects as go
4
+ from typing import Any, Callable, Dict, List, Tuple, Union, Optional
5
+
6
+
7
+ def _group_dataframe(
8
+ lf: pl.LazyFrame,
9
+ group_by_columns: List[str],
10
+ metric_names: List[str],
11
+ ) -> pl.LazyFrame:
12
+ transformed_cols = [
13
+ pl.col(col_name).cast(pl.Utf8).alias(col_name) for col_name in group_by_columns
14
+ ]
15
+ agg_expressions = [pl.col(metric).sum().cast(pl.Float64) for metric in metric_names]
16
+ return lf.group_by(transformed_cols).agg(agg_expressions)
17
+
18
+
19
+ def _get_join_key_expression(group_by_columns: List[str]) -> pl.Expr:
20
+ group_keys = list()
21
+
22
+ for join_key in group_by_columns:
23
+ temp_expr = (
24
+ pl.when(pl.col(join_key).is_null())
25
+ .then(pl.col(f"{join_key}_comparison"))
26
+ .otherwise(join_key)
27
+ ).str.to_lowercase()
28
+
29
+ group_keys.append(temp_expr)
30
+
31
+ # Concatenate unique values returned by each expression
32
+ expr = pl.concat_str(*group_keys, separator="|").alias("group_keys")
33
+
34
+ return expr
35
+
36
+
37
+ def _get_impact_expressions(
38
+ volume_metric_name: str,
39
+ outcome_metric_name: str,
40
+ ) -> Tuple[pl.Expr, pl.Expr, pl.Expr, pl.Expr, pl.Expr]:
41
+ # Volume
42
+ volume_new = pl.col(volume_metric_name)
43
+ volume_comparison = pl.col(f"{volume_metric_name}_comparison")
44
+ volume_diff = volume_new - volume_comparison
45
+
46
+ # Outcome
47
+ outcome_new = pl.col(outcome_metric_name)
48
+ outcome_comparison = pl.col(f"{outcome_metric_name}_comparison")
49
+
50
+ # Rate
51
+ rate_new = outcome_new / volume_new
52
+ rate_comparison = outcome_comparison / volume_comparison
53
+ rate_avg_comparison = outcome_comparison.sum() / volume_comparison.sum()
54
+
55
+ # Impact Expressions
56
+ rate_impact = (rate_new - rate_comparison) * volume_new
57
+ volume_impact = volume_diff * rate_avg_comparison
58
+ mix_impact = (rate_comparison - rate_avg_comparison) * volume_diff
59
+
60
+ def impact_expression(expr: pl.Expr, name: str) -> pl.Expr:
61
+ expr = (
62
+ pl.when((outcome_comparison.is_null()) | (outcome_new.is_null()))
63
+ .then(pl.lit(0))
64
+ .otherwise(expr)
65
+ ).alias(f"{name}_impact")
66
+
67
+ return expr
68
+
69
+ rate_impact_expr = impact_expression(rate_impact, "rate")
70
+ volume_impact_expr = impact_expression(volume_impact, "volume")
71
+ mix_impact_expr = impact_expression(mix_impact, "mix")
72
+
73
+ new_impact = (
74
+ pl.when((outcome_comparison.is_null()) & (outcome_new.is_not_null()))
75
+ .then(outcome_new)
76
+ .otherwise(pl.lit(0))
77
+ .alias("new_impact")
78
+ )
79
+ old_impact = (
80
+ pl.when((outcome_new.is_null()) & (outcome_comparison.is_not_null()))
81
+ .then((outcome_comparison * -1))
82
+ .otherwise(pl.lit(0))
83
+ .alias("old_impact")
84
+ )
85
+
86
+ return (
87
+ rate_impact_expr,
88
+ volume_impact_expr,
89
+ mix_impact_expr,
90
+ new_impact,
91
+ old_impact,
92
+ )
93
+
94
+
95
+ def impact_table(
96
+ df_primary: Union[pl.LazyFrame, pl.DataFrame],
97
+ df_comparison: Union[pl.LazyFrame, pl.DataFrame],
98
+ group_by_columns: Union[str, List[str]],
99
+ volume_metric_name: str,
100
+ outcome_metric_name: str,
101
+ ) -> pl.DataFrame:
102
+ """
103
+ Generates a table with impact analysis results from primary and comparison data frames.
104
+
105
+ Parameters
106
+ ----------
107
+ df_primary : Union[pl.LazyFrame, pl.DataFrame]
108
+ The primary dataset to analyze.
109
+ df_comparison : Union[pl.LazyFrame, pl.DataFrame]
110
+ The dataset to compare against the primary dataset.
111
+ group_by_columns : Union[str, List[str]]
112
+ Column name(s) used to group data. Can be a single column name or a list of names.
113
+ volume_metric_name : str
114
+ The name of the column in the data frame that represents the volume metric.
115
+ outcome_metric_name : str
116
+ The name of the column in the data frame that represents the outcome metric.
117
+
118
+ Returns
119
+ -------
120
+ pl.DataFrame
121
+ A Polars DataFrame containing the results of the impact analysis.
122
+
123
+ Raises
124
+ ------
125
+ TypeError
126
+ If the input data frames are not Polars DataFrame or LazyFrame types.
127
+ ValueError
128
+ If any of the parameters are missing or if the 'group_by_columns' contains non-string types.
129
+ """
130
+ # Ensure polars df type and convert to lazy
131
+ if not all(
132
+ isinstance(item, (pl.LazyFrame, pl.DataFrame))
133
+ for item in (df_primary, df_comparison)
134
+ ):
135
+ raise TypeError(
136
+ "df_primary and df_comparison must be Polars LazyFrame or DataFrame"
137
+ )
138
+ if isinstance(df_primary, pl.DataFrame):
139
+ df_primary = df_primary.lazy()
140
+ if isinstance(df_comparison, pl.DataFrame):
141
+ df_comparison = df_comparison.lazy()
142
+
143
+ # Validate group_by_columns
144
+ if isinstance(group_by_columns, str):
145
+ group_by_columns = [group_by_columns]
146
+ elif isinstance(group_by_columns, list):
147
+ if not all(isinstance(col, str) for col in group_by_columns):
148
+ raise ValueError("All elements in group_by_columns must be strings.")
149
+ else:
150
+ raise TypeError(
151
+ "group_by_columns must be a list of strings or a single string."
152
+ )
153
+
154
+ # Check metric column names are string types
155
+ if not all(
156
+ isinstance(item, str) for item in (volume_metric_name, outcome_metric_name)
157
+ ):
158
+ raise TypeError("volume_metric_name and outcome_metric_name must be strings.")
159
+
160
+ df_primary, df_comparison = [
161
+ _group_dataframe(
162
+ df,
163
+ group_by_columns,
164
+ [volume_metric_name, outcome_metric_name],
165
+ )
166
+ for df in [df_primary, df_comparison]
167
+ ]
168
+
169
+ impact_expressions = _get_impact_expressions(
170
+ volume_metric_name, outcome_metric_name
171
+ )
172
+
173
+ impact_table = (
174
+ df_primary.join(
175
+ df_comparison, how="outer", on=group_by_columns, suffix="_comparison"
176
+ )
177
+ .select(
178
+ _get_join_key_expression(group_by_columns),
179
+ cs.numeric(),
180
+ *impact_expressions,
181
+ )
182
+ .with_columns(cs.numeric().fill_nan(0).fill_null(0))
183
+ .sort(by="group_keys")
184
+ )
185
+
186
+ return impact_table.collect()
187
+
188
+
189
+ def _parse_metric_column_names(impact_table: pl.LazyFrame) -> tuple:
190
+ metric_columns = impact_table.select(cs.ends_with("_comparison")).columns
191
+ volume_col = metric_columns[0]
192
+ outcome_col = metric_columns[1]
193
+
194
+ volume_col_stripped = (
195
+ volume_col.replace("_comparison", "")
196
+ if volume_col.endswith("_comparison")
197
+ else ValueError()
198
+ )
199
+ outcome_col_stripped = (
200
+ outcome_col.replace("_comparison", "")
201
+ if outcome_col.endswith("_comparison")
202
+ else ValueError()
203
+ )
204
+
205
+ return volume_col_stripped, outcome_col_stripped
206
+
207
+
208
+ def _create_data_label(
209
+ value: float, previous_value: float, format_func: Callable
210
+ ) -> str:
211
+ formatted_value = format_func(value)
212
+ if previous_value is not None:
213
+ growth = value - previous_value
214
+ sign = "+" if growth >= 0 else ""
215
+ formatted_growth = f"{sign}{format_func(growth)}"
216
+ return f"{formatted_value} ({formatted_growth})"
217
+ return formatted_value
218
+
219
+
220
+ def _prep_data_for_impact_plot(
221
+ impact_table: pl.DataFrame,
222
+ format_data_labels: Callable,
223
+ primary_total_label: str,
224
+ comparison_total_label: str,
225
+ ) -> Tuple[list, list, list, list]:
226
+ _, outcome_metric_name = _parse_metric_column_names(impact_table)
227
+ if format_data_labels is None:
228
+ format_data_labels = lambda value: f"{value:,.0f}"
229
+ primary_total_label = primary_total_label or outcome_metric_name
230
+ comparison_total_label = (
231
+ comparison_total_label or f"COMPARISON {outcome_metric_name}"
232
+ )
233
+
234
+ x_labels, y_values, data_labels, measure_list = [], [], [], []
235
+ outcome_comparison = impact_table.get_column(
236
+ f"{outcome_metric_name}_comparison"
237
+ ).sum()
238
+
239
+ x_labels.append(f"<b>{comparison_total_label}</b>".upper())
240
+ y_values.append(outcome_comparison)
241
+ data_labels.append(f"<b>{format_data_labels(outcome_comparison)}</b>")
242
+ measure_list.append("absolute")
243
+
244
+ cumulative_sum = outcome_comparison
245
+ previous_value = outcome_comparison
246
+
247
+ impact_types = ["rate", "volume", "mix", "old", "new"]
248
+ if (impact_table.get_column("old_impact").sum() == 0) & (
249
+ impact_table.get_column("new_impact").sum() == 0
250
+ ):
251
+ impact_types = ["rate", "volume", "mix"]
252
+
253
+ for impact_type in impact_types:
254
+ for key in impact_table.get_column("group_keys").unique().sort(descending=True):
255
+ impact_value = (
256
+ impact_table.filter(pl.col("group_keys") == key)
257
+ .get_column(f"{impact_type}_impact")
258
+ .sum()
259
+ )
260
+ # if impact_value != 0:
261
+ x_labels.append(f"{key} ({impact_type[0]}.)".lower())
262
+ y_values.append(impact_value)
263
+ data_labels.append(format_data_labels(impact_value))
264
+ measure_list.append("relative")
265
+ cumulative_sum += impact_value
266
+
267
+ x_labels.append(f"<b>{impact_type.capitalize()} Impact Subtotal</b>")
268
+ y_values.append(cumulative_sum)
269
+ data_labels.append(
270
+ _create_data_label(cumulative_sum, previous_value, format_data_labels)
271
+ )
272
+ measure_list.append("absolute")
273
+ previous_value = cumulative_sum
274
+
275
+ outcome_new = impact_table.get_column(outcome_metric_name).sum()
276
+ x_labels.append(f"<b>{primary_total_label}</b>".upper())
277
+ y_values.append(outcome_new)
278
+ data_labels.append(
279
+ f"<b>{_create_data_label(outcome_new, outcome_comparison, format_data_labels)}</b>"
280
+ )
281
+ measure_list.append("total")
282
+
283
+ return x_labels, y_values, data_labels, measure_list
284
+
285
+
286
+ def impact_plot(
287
+ impact_table: pl.DataFrame,
288
+ primary_total_label: Optional[str] = None,
289
+ comparison_total_label: Optional[str] = None,
290
+ format_data_labels: Optional[str] = "{:,.0f}",
291
+ title: Optional[str] = None,
292
+ color_increase: Optional[str] = "#00AF00",
293
+ color_decrease: Optional[str] = "#FF0000",
294
+ color_total: Optional[str] = "#F1F1F1",
295
+ text_font_size: Optional[int] = 8,
296
+ plot_height: Optional[int] = None,
297
+ plot_width: Optional[int] = 750,
298
+ plotly_template: Optional[str] = "plotly_white",
299
+ plotly_trace_settings: Optional[Dict[str, Any]] = None,
300
+ plotly_layout_settings: Optional[Dict[str, Any]] = None,
301
+ ) -> go.Figure:
302
+ """
303
+ Creates a waterfall plot visualizing the impact analysis results.
304
+
305
+ Parameters
306
+ ----------
307
+ impact_table : pl.DataFrame
308
+ The DataFrame containing impact analysis results, as returned by the `impact_table` function.
309
+ primary_total_label : str, optional
310
+ Label for the total of the primary data set in the plot. Defaults to the outcome metric name.
311
+ comparison_total_label : str, optional
312
+ Label for the total of the comparison data set in the plot. Defaults to "COMPARISON <outcome_metric_name>".
313
+ format_data_labels : str, optional
314
+ Format specification for the data labels. Defaults to "{:,.0f}". This should be a string
315
+ following Python's string formatting syntax, which allows custom numeric formatting, e.g.,
316
+ "{:.2f}" for floating-point numbers with two decimals, or "{:,.2f}" for numbers with commas
317
+ as thousands separators and two decimals.
318
+ title : str, optional
319
+ The title of the plot.
320
+ color_increase : str, optional
321
+ Color for positive changes. Can be specified as a hexadecimal code (e.g., "#00AF00") or
322
+ a named Plotly color (e.g., "green"). Defaults to green "#00AF00".
323
+ color_decrease : str, optional
324
+ Color for negative changes. Can be specified as a hexadecimal code (e.g., "#FF0000") or
325
+ a named Plotly color (e.g., "red"). Defaults to red "#FF0000".
326
+ color_total : str, optional
327
+ Color for total columns. Can be specified as a hexadecimal code (e.g., "#F1F1F1") or
328
+ a named Plotly color (e.g., "grey"). Defaults to light gray "#F1F1F1".
329
+ text_font_size : int, optional
330
+ Font size of the text in the plot. Defaults to 8.
331
+ plot_height : int, optional
332
+ Height of the plot in pixels. Calculated based on the number of labels if not provided.
333
+ plot_width : int, optional
334
+ Width of the plot in pixels. Defaults to 750.
335
+ plotly_template : str, optional
336
+ The Plotly template to use for the plot styling. Defaults to "plotly_white".
337
+ plotly_trace_settings : Dict[str, Any], optional
338
+ Additional trace settings for advanced customization using Plotly's trace options.
339
+ plotly_layout_settings : Dict[str, Any], optional
340
+ Additional layout settings for advanced customization using Plotly's layout options.
341
+
342
+ Returns
343
+ -------
344
+ go.Figure
345
+ A Plotly Figure object representing the impact analysis as a waterfall chart.
346
+
347
+ Raises
348
+ ------
349
+ TypeError
350
+ If `impact_table` is not a Polars DataFrame.
351
+ ValueError
352
+ If no columns with '_comparison' are found in `impact_table`.
353
+ """
354
+ if not isinstance(impact_table, pl.DataFrame):
355
+ raise TypeError("impact_table must be Polars DataFrame")
356
+
357
+ # Check for columns containing "_comparison" in the impact table
358
+ comparison_columns = [col for col in impact_table.columns if "_comparison" in col]
359
+ if not comparison_columns:
360
+ raise ValueError(
361
+ "No comparison column found in the impact_table. Use impact_table function and use it's returned dataframe for plotting."
362
+ )
363
+
364
+ # Convert format string to a formatting function
365
+ formatter = lambda x: format_data_labels.format(x)
366
+
367
+ # Prepare data for plotting
368
+ x_labels, y_values, data_labels, measure_list = _prep_data_for_impact_plot(
369
+ impact_table, formatter, primary_total_label, comparison_total_label
370
+ )
371
+
372
+ # Create the plot
373
+ fig = go.Figure(
374
+ go.Waterfall(
375
+ orientation="h",
376
+ measure=measure_list,
377
+ x=y_values,
378
+ y=x_labels,
379
+ text=data_labels,
380
+ textposition="auto",
381
+ textfont=dict(size=text_font_size),
382
+ increasing=dict(marker=dict(color=color_increase)),
383
+ decreasing=dict(marker=dict(color=color_decrease)),
384
+ totals=dict(
385
+ marker=dict(color=color_total, line=dict(color="black", width=1))
386
+ ),
387
+ )
388
+ )
389
+
390
+ # Update layout with basic settings
391
+ layout_params = {
392
+ "title": title,
393
+ "height": plot_height if plot_height else len(x_labels) * 25 + 100,
394
+ "width": plot_width,
395
+ "template": plotly_template,
396
+ }
397
+
398
+ # Apply advanced settings if provided
399
+ if plotly_trace_settings:
400
+ fig.update_traces(plotly_trace_settings)
401
+ if plotly_layout_settings:
402
+ fig.update_layout(**plotly_layout_settings)
403
+ else:
404
+ fig.update_layout(**layout_params)
405
+
406
+ return fig
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "l4v1"
3
+ version = "0.0.1"
4
+ description = "Add your description here"
5
+ authors = [
6
+ { name = "Miro Lavi", email = "mirolavi@gmail.com" }
7
+ ]
8
+ dependencies = [
9
+ "polars>=0.20.21",
10
+ "plotly>=5.21.0",
11
+ ]
12
+ readme = "README.md"
13
+ requires-python = ">= 3.8"
14
+
15
+ [build-system]
16
+ requires = ["hatchling"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [tool.rye]
20
+ managed = true
21
+ dev-dependencies = [
22
+ "jupyterlab>=4.1.6",
23
+ ]
24
+
25
+ [tool.hatch.metadata]
26
+ allow-direct-references = true
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/l4v1_analytics"]
@@ -0,0 +1,254 @@
1
+ # generated by rye
2
+ # use `rye lock` or `rye sync` to update this lockfile
3
+ #
4
+ # last locked with the following flags:
5
+ # pre: false
6
+ # features: []
7
+ # all-features: false
8
+ # with-sources: false
9
+
10
+ -e file:.
11
+ anyio==4.3.0
12
+ # via httpx
13
+ # via jupyter-server
14
+ argon2-cffi==23.1.0
15
+ # via jupyter-server
16
+ argon2-cffi-bindings==21.2.0
17
+ # via argon2-cffi
18
+ arrow==1.3.0
19
+ # via isoduration
20
+ asttokens==2.4.1
21
+ # via stack-data
22
+ async-lru==2.0.4
23
+ # via jupyterlab
24
+ attrs==23.2.0
25
+ # via jsonschema
26
+ # via referencing
27
+ babel==2.14.0
28
+ # via jupyterlab-server
29
+ beautifulsoup4==4.12.3
30
+ # via nbconvert
31
+ bleach==6.1.0
32
+ # via nbconvert
33
+ certifi==2024.2.2
34
+ # via httpcore
35
+ # via httpx
36
+ # via requests
37
+ cffi==1.16.0
38
+ # via argon2-cffi-bindings
39
+ charset-normalizer==3.3.2
40
+ # via requests
41
+ comm==0.2.2
42
+ # via ipykernel
43
+ debugpy==1.8.1
44
+ # via ipykernel
45
+ decorator==5.1.1
46
+ # via ipython
47
+ defusedxml==0.7.1
48
+ # via nbconvert
49
+ executing==2.0.1
50
+ # via stack-data
51
+ fastjsonschema==2.19.1
52
+ # via nbformat
53
+ fqdn==1.5.1
54
+ # via jsonschema
55
+ h11==0.14.0
56
+ # via httpcore
57
+ httpcore==1.0.5
58
+ # via httpx
59
+ httpx==0.27.0
60
+ # via jupyterlab
61
+ idna==3.7
62
+ # via anyio
63
+ # via httpx
64
+ # via jsonschema
65
+ # via requests
66
+ ipykernel==6.29.4
67
+ # via jupyterlab
68
+ ipython==8.23.0
69
+ # via ipykernel
70
+ isoduration==20.11.0
71
+ # via jsonschema
72
+ jedi==0.19.1
73
+ # via ipython
74
+ jinja2==3.1.3
75
+ # via jupyter-server
76
+ # via jupyterlab
77
+ # via jupyterlab-server
78
+ # via nbconvert
79
+ json5==0.9.25
80
+ # via jupyterlab-server
81
+ jsonpointer==2.4
82
+ # via jsonschema
83
+ jsonschema==4.21.1
84
+ # via jupyter-events
85
+ # via jupyterlab-server
86
+ # via nbformat
87
+ jsonschema-specifications==2023.12.1
88
+ # via jsonschema
89
+ jupyter-client==8.6.1
90
+ # via ipykernel
91
+ # via jupyter-server
92
+ # via nbclient
93
+ jupyter-core==5.7.2
94
+ # via ipykernel
95
+ # via jupyter-client
96
+ # via jupyter-server
97
+ # via jupyterlab
98
+ # via nbclient
99
+ # via nbconvert
100
+ # via nbformat
101
+ jupyter-events==0.10.0
102
+ # via jupyter-server
103
+ jupyter-lsp==2.2.5
104
+ # via jupyterlab
105
+ jupyter-server==2.14.0
106
+ # via jupyter-lsp
107
+ # via jupyterlab
108
+ # via jupyterlab-server
109
+ # via notebook-shim
110
+ jupyter-server-terminals==0.5.3
111
+ # via jupyter-server
112
+ jupyterlab==4.1.6
113
+ jupyterlab-pygments==0.3.0
114
+ # via nbconvert
115
+ jupyterlab-server==2.26.0
116
+ # via jupyterlab
117
+ markupsafe==2.1.5
118
+ # via jinja2
119
+ # via nbconvert
120
+ matplotlib-inline==0.1.7
121
+ # via ipykernel
122
+ # via ipython
123
+ mistune==3.0.2
124
+ # via nbconvert
125
+ nbclient==0.10.0
126
+ # via nbconvert
127
+ nbconvert==7.16.3
128
+ # via jupyter-server
129
+ nbformat==5.10.4
130
+ # via jupyter-server
131
+ # via nbclient
132
+ # via nbconvert
133
+ nest-asyncio==1.6.0
134
+ # via ipykernel
135
+ notebook-shim==0.2.4
136
+ # via jupyterlab
137
+ overrides==7.7.0
138
+ # via jupyter-server
139
+ packaging==24.0
140
+ # via ipykernel
141
+ # via jupyter-server
142
+ # via jupyterlab
143
+ # via jupyterlab-server
144
+ # via nbconvert
145
+ # via plotly
146
+ pandocfilters==1.5.1
147
+ # via nbconvert
148
+ parso==0.8.4
149
+ # via jedi
150
+ pexpect==4.9.0
151
+ # via ipython
152
+ platformdirs==4.2.0
153
+ # via jupyter-core
154
+ plotly==5.21.0
155
+ # via l4v1
156
+ polars==0.20.21
157
+ # via l4v1
158
+ prometheus-client==0.20.0
159
+ # via jupyter-server
160
+ prompt-toolkit==3.0.43
161
+ # via ipython
162
+ psutil==5.9.8
163
+ # via ipykernel
164
+ ptyprocess==0.7.0
165
+ # via pexpect
166
+ # via terminado
167
+ pure-eval==0.2.2
168
+ # via stack-data
169
+ pycparser==2.22
170
+ # via cffi
171
+ pygments==2.17.2
172
+ # via ipython
173
+ # via nbconvert
174
+ python-dateutil==2.9.0.post0
175
+ # via arrow
176
+ # via jupyter-client
177
+ python-json-logger==2.0.7
178
+ # via jupyter-events
179
+ pyyaml==6.0.1
180
+ # via jupyter-events
181
+ pyzmq==26.0.2
182
+ # via ipykernel
183
+ # via jupyter-client
184
+ # via jupyter-server
185
+ referencing==0.34.0
186
+ # via jsonschema
187
+ # via jsonschema-specifications
188
+ # via jupyter-events
189
+ requests==2.31.0
190
+ # via jupyterlab-server
191
+ rfc3339-validator==0.1.4
192
+ # via jsonschema
193
+ # via jupyter-events
194
+ rfc3986-validator==0.1.1
195
+ # via jsonschema
196
+ # via jupyter-events
197
+ rpds-py==0.18.0
198
+ # via jsonschema
199
+ # via referencing
200
+ send2trash==1.8.3
201
+ # via jupyter-server
202
+ six==1.16.0
203
+ # via asttokens
204
+ # via bleach
205
+ # via python-dateutil
206
+ # via rfc3339-validator
207
+ sniffio==1.3.1
208
+ # via anyio
209
+ # via httpx
210
+ soupsieve==2.5
211
+ # via beautifulsoup4
212
+ stack-data==0.6.3
213
+ # via ipython
214
+ tenacity==8.2.3
215
+ # via plotly
216
+ terminado==0.18.1
217
+ # via jupyter-server
218
+ # via jupyter-server-terminals
219
+ tinycss2==1.2.1
220
+ # via nbconvert
221
+ tornado==6.4
222
+ # via ipykernel
223
+ # via jupyter-client
224
+ # via jupyter-server
225
+ # via jupyterlab
226
+ # via terminado
227
+ traitlets==5.14.3
228
+ # via comm
229
+ # via ipykernel
230
+ # via ipython
231
+ # via jupyter-client
232
+ # via jupyter-core
233
+ # via jupyter-events
234
+ # via jupyter-server
235
+ # via jupyterlab
236
+ # via matplotlib-inline
237
+ # via nbclient
238
+ # via nbconvert
239
+ # via nbformat
240
+ types-python-dateutil==2.9.0.20240316
241
+ # via arrow
242
+ uri-template==1.3.0
243
+ # via jsonschema
244
+ urllib3==2.2.1
245
+ # via requests
246
+ wcwidth==0.2.13
247
+ # via prompt-toolkit
248
+ webcolors==1.13
249
+ # via jsonschema
250
+ webencodings==0.5.1
251
+ # via bleach
252
+ # via tinycss2
253
+ websocket-client==1.7.0
254
+ # via jupyter-server
@@ -0,0 +1,18 @@
1
+ # generated by rye
2
+ # use `rye lock` or `rye sync` to update this lockfile
3
+ #
4
+ # last locked with the following flags:
5
+ # pre: false
6
+ # features: []
7
+ # all-features: false
8
+ # with-sources: false
9
+
10
+ -e file:.
11
+ packaging==24.0
12
+ # via plotly
13
+ plotly==5.21.0
14
+ # via l4v1
15
+ polars==0.20.21
16
+ # via l4v1
17
+ tenacity==8.2.3
18
+ # via plotly
File without changes
@@ -0,0 +1,29 @@
1
+ from l4v1.price_volume_mix import pvm_plot, pvm_table
2
+ import polars as pl
3
+ import datetime as dt
4
+
5
+ df = pl.read_parquet("../data/supermarket_sales.parquet").with_columns(
6
+ pl.col(pl.Categorical).cast(pl.Utf8)
7
+ )
8
+
9
+ df1 = df.filter(pl.col("Datetime").dt.week() == 4)
10
+ df2 = df.filter(pl.col("Datetime").dt.week() == 5)
11
+
12
+ df1.columns
13
+
14
+ # Create the performance volume mix table
15
+ pvm_df = pvm_table(
16
+ df_primary=df1,
17
+ df_comparison=df2,
18
+ group_by_columns=["Customer type", "Product line"],
19
+ metrics={"volume": "Quantity", "outcome": "Total"},
20
+ )
21
+
22
+ pvm_df
23
+
24
+ pvm_plot(
25
+ pvm_table=pvm_df,
26
+ outcome_metric_name="Total",
27
+ primary_label="lala",
28
+ comparison_label="zaza",
29
+ )