From 473dbb8b4482bd3b2ee4d735d1baeb48f575cbaa Mon Sep 17 00:00:00 2001 From: RyanAugust Date: Thu, 28 May 2026 18:30:54 +0000 Subject: [PATCH] pre-commit cleanup of whitespace --- .pre-commit-config.yaml | 6 ++++++ LICENSE | 42 +++++++++++++++++++-------------------- README.md | 4 ++-- pyproject.toml | 4 ++-- src/tippingpoint/curve.py | 22 ++++++++++---------- tests/test_bayesian.py | 8 ++++---- tests/test_curve.py | 8 ++++---- 7 files changed, 50 insertions(+), 44 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..c78abf7 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 # Use the latest stable version + hooks: + - id: trailing-whitespace + diff --git a/LICENSE b/LICENSE index 7083002..74db2cb 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -GNU GENERAL PUBLIC LICENSE +GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright © 2007 Free Software Foundation, Inc. @@ -46,7 +46,7 @@ To “convey” a work means any kind of propagation that enables other parties An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. -1. Source Code. +1. Source Code. The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. @@ -59,24 +59,24 @@ The Corresponding Source need not include anything that users can regenerate aut The Corresponding Source for a work in source code form is that same work. -2. Basic Permissions. +2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. -3. Protecting Users' Legal Rights From Anti-Circumvention Law. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. -4. Conveying Verbatim Copies. +4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. -5. Conveying Modified Source Versions. +5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. @@ -89,7 +89,7 @@ d) If the work has interactive user interfaces, each must display Appropriate Le A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. -6. Conveying Non-Source Forms. +6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. @@ -114,7 +114,7 @@ The requirement to provide Installation Information does not include a requireme Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. -7. Additional Terms. +7. Additional Terms. “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. @@ -139,7 +139,7 @@ If you add terms to a covered work in accord with this section, you must place, Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. -8. Termination. +8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. @@ -148,17 +148,17 @@ Moreover, your license from a particular copyright holder is reinstated permanen Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. -9. Acceptance Not Required for Having Copies. +9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. -10. Automatic Licensing of Downstream Recipients. +10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. -11. Patents. +11. Patents. A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. @@ -175,13 +175,13 @@ A patent license is “discriminatory” if it does not include within the scope Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. -12. No Surrender of Others' Freedom. +12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. -13. Use with the GNU Affero General Public License. +13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. -14. Revised Versions of this License. +14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. @@ -190,13 +190,13 @@ If the Program specifies that a proxy can decide which future versions of the GN Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. -15. Disclaimer of Warranty. +15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. -16. Limitation of Liability. +16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. -17. Interpretation of Sections 15 and 16. +17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -207,7 +207,7 @@ If you develop a new program, and you want it to be of the greatest possible use To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. - + Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. @@ -220,8 +220,8 @@ Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: - Copyright (C) -This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) +This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. diff --git a/README.md b/README.md index 1f6f2aa..ce9e552 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ [![PyPI Downloads](https://img.shields.io/pypi/dm/tippingpt.svg?label=PyPI%20downloads)]( https://pypi.org/project/tippingpt/) -A lightweight, high-performance marketing intelligence module that uses machine learning and calculus to determine the exact inflection points of a media response curve. +A lightweight, high-performance marketing intelligence module that uses machine learning and calculus to determine the exact inflection points of a media response curve. Growth marketers and media buyers constantly ask two questions: *"When are we out of the inefficient learning phase?"* and *"When should we stop scaling spend?"* By fitting historical performance data to a continuous mathematical curve, this tool identifies the **Minimal Marginal Cost Point** (where efficiency peaks) and the **Point of Diminishing Returns** (where scaling is no longer profitable), defining your exact **Optimal Scaling Zone**. ## 🧠 Methodology -This project leverages the mathematical foundations of modern Marketing Mix Modeling (MMM)—specifically the techniques popularized by [Google’s Meridian](https://github.com/google/meridian). +This project leverages the mathematical foundations of modern Marketing Mix Modeling (MMM)—specifically the techniques popularized by [Google’s Meridian](https://github.com/google/meridian). Instead of basic linear or logarithmic approximations, this module natively models media saturation using the **Hill Function**. diff --git a/pyproject.toml b/pyproject.toml index f9a294a..fb976a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ keywords = [ "tipping point", "marketing", "utility", - "cli" + "cli" ] classifiers = [ @@ -16,7 +16,7 @@ classifiers = [ "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Operating System :: OS Independent", - "Development Status :: 3 - Alpha", + "Development Status :: 3 - Alpha", ] authors = [ { name = "Ryan Duecker", email = "ryanduecker@gmail.com" }, diff --git a/src/tippingpoint/curve.py b/src/tippingpoint/curve.py index bc928ba..7ce549d 100644 --- a/src/tippingpoint/curve.py +++ b/src/tippingpoint/curve.py @@ -65,7 +65,7 @@ def log_posterior(params): np.std(y) * 0.1 ]) current_log_post = log_posterior(current_params) - + samples = [] # Adaptive step size (simplified) step_size = current_params * 0.05 @@ -73,14 +73,14 @@ def log_posterior(params): for i in range(n_samples + burn_in): proposal = current_params + np.random.normal(0, step_size) proposal_log_post = log_posterior(proposal) - + if proposal_log_post > current_log_post or np.random.rand() < np.exp(proposal_log_post - current_log_post): current_params = proposal current_log_post = proposal_log_post - + if i >= burn_in: samples.append(current_params.copy()) - + # Small adaptation during burn-in if i < burn_in and i % 100 == 0 and i > 0: # This is a very crude adaptation @@ -95,12 +95,12 @@ def log_posterior(params): 'K': posterior[:, 2], 'sigma': posterior[:, 3] } - + # Point estimates (posterior mean) beta_mean = np.mean(samples_dict['beta']) alpha_mean = np.mean(samples_dict['alpha']) K_mean = np.mean(samples_dict['K']) - + print(f"[{channel_name}] Bayesian fit complete. Samples: {len(posterior)}") return cls(beta_mean, alpha_mean, K_mean, channel_name, posterior_samples=samples_dict) @@ -218,13 +218,13 @@ def plot_response_curve(self, target_mroas=1.0, current_spend=None, show_interva plot_limit = max(plot_limit, current_spend * 1.2 if current_spend else 0) x_vals = np.linspace(0, plot_limit, 500) - + if show_intervals and self.posterior_samples: y_returns_dist = self.predict_incremental_return(x_vals, use_samples=True) y_return = np.mean(y_returns_dist, axis=0) y_return_low = np.percentile(y_returns_dist, 5, axis=0) y_return_high = np.percentile(y_returns_dist, 95, axis=0) - + y_mroas_dist = self.predict_marginal_return(x_vals, use_samples=True) y_mroas = np.mean(y_mroas_dist, axis=0) y_mroas_low = np.percentile(y_mroas_dist, 5, axis=0) @@ -238,18 +238,18 @@ def plot_response_curve(self, target_mroas=1.0, current_spend=None, show_interva ax1.plot(x_vals, y_return, color='#2CA02C', linewidth=3, label="Incremental Return") if show_intervals and self.posterior_samples: ax1.fill_between(x_vals, y_return_low, y_return_high, color='#2CA02C', alpha=0.2, label="90% Credible Interval") - + ax1.set_xlabel('Spend ($)', fontsize=12, fontweight='bold') ax1.set_ylabel('Incremental Return', color='#2CA02C', fontsize=12, fontweight='bold') ax1.tick_params(axis='y', labelcolor='#2CA02C') ax1.grid(True, linestyle='--', alpha=0.5) - + # Secondary Axis: Marginal Return ax2 = ax1.twinx() ax2.plot(x_vals, y_mroas, color='#1F77B4', linestyle='--', linewidth=2, label="Marginal ROAS") if show_intervals and self.posterior_samples: ax2.fill_between(x_vals, y_mroas_low, y_mroas_high, color='#1F77B4', alpha=0.1) - + ax2.set_ylabel('Marginal ROAS (mROAS)', color='#1F77B4', fontsize=12, fontweight='bold') ax2.tick_params(axis='y', labelcolor='#1F77B4') ax2.axhline(target_mroas, color='gray', linestyle=':', label="Target mROAS Floor") diff --git a/tests/test_bayesian.py b/tests/test_bayesian.py index d405eb4..d964110 100644 --- a/tests/test_bayesian.py +++ b/tests/test_bayesian.py @@ -17,7 +17,7 @@ def synthetic_data(): def test_fit_bayesian_basic(synthetic_data): x, y = synthetic_data model = MarketingReturnCurve.fit_bayesian(x, y, n_samples=500, burn_in=100, chains=2) - + assert model.beta > 0 assert model.alpha > 0 assert model.K > 0 @@ -33,7 +33,7 @@ def test_fit_bayesian_with_priors(synthetic_data): 'K': (np.log(20000), 0.1) } model = MarketingReturnCurve.fit_bayesian(x, y, priors=priors, n_samples=200, burn_in=50, chains=1) - + # Check if results are close to true values due to tight priors assert 90000 < model.beta < 110000 assert 1.3 < model.alpha < 1.7 @@ -42,11 +42,11 @@ def test_fit_bayesian_with_priors(synthetic_data): def test_predict_with_samples(synthetic_data): x, y = synthetic_data model = MarketingReturnCurve.fit_bayesian(x, y, n_samples=100, burn_in=50, chains=1) - + # Incremental return preds = model.predict_incremental_return([1000, 2000], use_samples=True) assert preds.shape == (100, 2) - + # Marginal return m_preds = model.predict_marginal_return([1000, 2000], use_samples=True) assert m_preds.shape == (100, 2) diff --git a/tests/test_curve.py b/tests/test_curve.py index 519f7a3..ee58e61 100644 --- a/tests/test_curve.py +++ b/tests/test_curve.py @@ -12,7 +12,7 @@ def setup_method(self): """Setup a baseline S-Curve for use in multiple tests.""" # Parameters: Max Return=10000, Shape=2.0 (S-Curve), Half-Saturation=500 self.s_curve = MarketingReturnCurve(beta=10000.0, alpha=2.0, half_saturation_k=500.0, channel_name="Test_S_Curve") - + # Parameters: Shape=0.8 (C-Curve, no warm-up phase) self.c_curve = MarketingReturnCurve(beta=10000.0, alpha=0.8, half_saturation_k=500.0, channel_name="Test_C_Curve") @@ -45,7 +45,7 @@ def test_minimal_marginal_cost_point_s_curve(self): """Test f''(x) = 0 for an S-Curve (alpha > 1).""" expected_inflection = 500.0 * np.sqrt(1.0 / 3.0) # For alpha = 2.0, inflection = K * sqrt((2-1)/(2+1)) = 500 * sqrt(1/3) ≈ 288.675 actual_inflection = self.s_curve.get_minimal_marginal_cost_point() - + assert actual_inflection == pytest.approx(expected_inflection, rel=1e-3) def test_minimal_marginal_cost_point_c_curve(self): @@ -56,7 +56,7 @@ def test_diminishing_returns_point_valid(self): """Test finding the target spend level for a reachable mROAS.""" target_mroas = 5.0 spend_cap = self.s_curve.get_diminishing_returns_point(target_mroas) - + assert spend_cap is not None actual_mroas_at_cap = self.s_curve.predict_marginal_return(spend_cap) assert actual_mroas_at_cap == pytest.approx(target_mroas, rel=1e-3) @@ -75,7 +75,7 @@ def test_tinygrad_optimization_engine(self): returns = (50000 * spends**1.5) / (4000**1.5 + spends**1.5) # Fake responses following roughly an S curve # Run with very few epochs just to verify the math/graph builds and executes properly model = MarketingReturnCurve.from_historical_data( spend_array=spends, return_array=returns, epochs=10, lr=0.1)# Fast execution for test suite - + assert isinstance(model, MarketingReturnCurve) assert model.beta > 0 assert model.alpha > 0