goad-toolkit 0.2.3__tar.gz → 0.2.5__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.
Files changed (103) hide show
  1. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/PKG-INFO +1 -1
  2. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/02-pipelines.md +26 -25
  3. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/03-plot-composition.md +10 -0
  4. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/04-five-families.md +2 -1
  5. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/05-distributions.md +52 -7
  6. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/08-api-reference.md +32 -3
  7. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/pyproject.toml +1 -1
  8. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/analytics.py +74 -33
  9. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/datatransforms.py +47 -0
  10. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/distributions.py +16 -0
  11. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/visualizer.py +124 -0
  12. goad_toolkit-0.2.5/tests/test_datatransforms.py +167 -0
  13. goad_toolkit-0.2.5/tests/test_distributions.py +195 -0
  14. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/tests/test_visualizer.py +51 -0
  15. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/uv.lock +1 -1
  16. goad_toolkit-0.2.3/tests/test_datatransforms.py +0 -66
  17. goad_toolkit-0.2.3/tests/test_distributions.py +0 -72
  18. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/settings.local.json +0 -0
  19. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/.gitignore +0 -0
  20. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/.python-version +0 -0
  21. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/CHANGELOG.md +0 -0
  22. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/MCP_SERVER.md +0 -0
  23. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/README.md +0 -0
  24. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/demo/linear.py +0 -0
  25. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/01-goal-oriented-analysis.md +0 -0
  26. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/02-pipelines.md +0 -0
  27. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/03-plot-composition.md +0 -0
  28. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/04-five-families.md +0 -0
  29. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/05-distributions.md +0 -0
  30. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/06-models-and-residuals.md +0 -0
  31. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/07-visual-critique.md +0 -0
  32. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/08-api-reference.md +0 -0
  33. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/09-analysis-method.md +0 -0
  34. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/10-teaching-path.md +0 -0
  35. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/docs/README.md +0 -0
  36. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/goad_mcp.py +0 -0
  37. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/img/distribution_fit.png +0 -0
  38. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/img/goaded.png +0 -0
  39. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/img/linear_results.png +0 -0
  40. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/img/residuals.png +0 -0
  41. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/img/zscores.png +0 -0
  42. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/pyproject.toml +0 -0
  43. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/__init__.py +0 -0
  44. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/analytics.py +0 -0
  45. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/cli.py +0 -0
  46. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/config.py +0 -0
  47. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/dataprocessor.py +0 -0
  48. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/datatransforms.py +0 -0
  49. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/distributions.py +0 -0
  50. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/filehandler.py +0 -0
  51. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/models.py +0 -0
  52. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/src/goad_toolkit/visualizer.py +0 -0
  53. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/tests/test_cli.py +0 -0
  54. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/tests/test_distributions.py +0 -0
  55. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/tests/test_filehandler.py +0 -0
  56. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/tests/test_visualizer.py +0 -0
  57. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.claude/worktrees/quizzical-solomon-b62511/uv.lock +0 -0
  58. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.gitignore +0 -0
  59. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.python-version +0 -0
  60. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/.gitignore +0 -0
  61. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/autonomous/save-195516.log +0 -0
  62. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/autonomous/save-195720.log +0 -0
  63. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/autonomous/save-195933.log +0 -0
  64. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/autonomous/save-200831.log +0 -0
  65. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/autonomous/save-201034.log +0 -0
  66. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/hook-errors.log +0 -0
  67. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/logs/memory-2026-08-10.log +0 -0
  68. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/now.md +0 -0
  69. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/capture-alive +0 -0
  70. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/capture-alive.d/90574e63-97cd-4c11-87e5-23b656c56fd9 +0 -0
  71. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/case-divergence +0 -0
  72. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/last-ndc.ts +0 -0
  73. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/last-save-ts +0 -0
  74. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/last-save.json +0 -0
  75. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/now-day +0 -0
  76. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/post-tool-ran +0 -0
  77. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/save-session.pid +0 -0
  78. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/tmp/session-slug +0 -0
  79. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/.remember/today-2026-08-10.md +0 -0
  80. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/CHANGELOG.md +0 -0
  81. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/MCP_SERVER.md +0 -0
  82. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/README.md +0 -0
  83. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/demo/linear.py +0 -0
  84. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/01-goal-oriented-analysis.md +0 -0
  85. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/06-models-and-residuals.md +0 -0
  86. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/07-visual-critique.md +0 -0
  87. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/09-analysis-method.md +0 -0
  88. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/10-teaching-path.md +0 -0
  89. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/docs/README.md +0 -0
  90. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/goad_mcp.py +0 -0
  91. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/img/distribution_fit.png +0 -0
  92. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/img/goaded.png +0 -0
  93. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/img/linear_results.png +0 -0
  94. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/img/residuals.png +0 -0
  95. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/img/zscores.png +0 -0
  96. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/__init__.py +0 -0
  97. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/cli.py +0 -0
  98. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/config.py +0 -0
  99. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/dataprocessor.py +0 -0
  100. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/filehandler.py +0 -0
  101. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/src/goad_toolkit/models.py +0 -0
  102. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/tests/test_cli.py +0 -0
  103. {goad_toolkit-0.2.3 → goad_toolkit-0.2.5}/tests/test_filehandler.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: goad-toolkit
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: An extensible toolkit for Goal Oriented Analysis of Data
5
5
  Project-URL: Github, https://github.com/raoulg/goad_toolkit
6
6
  Author-email: raoul grouls <Raoul.Grouls@han.nl>
@@ -59,6 +59,7 @@ input frame is safe, and the steps stay cheap.
59
59
  | `RollingAvg` | rolling mean, drops the leading NaNs | `column`, `window`, `rename` |
60
60
  | `ZScaler` | standardise to mean 0, std 1 | `column`, `rename` |
61
61
  | `TimeFeatures` | derive calendar columns from a timestamp | `column`, `features` |
62
+ | `RegexFeature` | count / flag / extract a pattern in a text column | `column`, `pattern`, `feature`, `mode` |
62
63
 
63
64
  `rename=True` writes to a new column (`deaths_shifted`, `deaths_zscore`, …) instead of
64
65
  overwriting. Prefer it. An overwritten column is a step you cannot debug, and the whole
@@ -104,39 +105,39 @@ Two rules for your `transform`:
104
105
  - **Name your parameters explicitly** in the signature. `def transform(self, data, column,
105
106
  window)` documents itself; `**kwargs` does not, and the validation cannot help you.
106
107
 
107
- ## 2.5 A transform for feature enrichment
108
+ ## 2.5 `RegexFeature`: feature enrichment from text
108
109
 
109
- The single most useful custom transform for text data, and a good template:
110
+ The single most useful transform for text data, and the reason `TransformBase` is worth
111
+ subclassing at all. It ships:
110
112
 
111
113
  ```python
112
- class RegexFeature(TransformBase):
113
- """Add a feature extracted from a text column with a regular expression."""
114
-
115
- def transform(
116
- self,
117
- data: pd.DataFrame,
118
- column: str,
119
- pattern: str,
120
- feature: str,
121
- mode: str = "count",
122
- ) -> pd.DataFrame:
123
- text = data[column].fillna("")
124
- if mode == "count":
125
- data[feature] = text.str.count(pattern)
126
- elif mode == "has":
127
- data[feature] = text.str.contains(pattern, regex=True)
128
- elif mode == "extract":
129
- data[feature] = text.str.extract(pattern, expand=False)
130
- else:
131
- raise ValueError(f"mode must be count/has/extract, got {mode!r}")
132
- return data
133
- ```
114
+ from goad_toolkit.datatransforms import RegexFeature
134
115
 
135
- ```python
136
116
  pipeline.add(RegexFeature, name="url_flag",
137
117
  column="message", pattern=r"https?://\S+", feature="has_url", mode="has")
138
118
  ```
139
119
 
120
+ Three modes, each writing one new column named by `feature`:
121
+
122
+ | `mode` | writes | use for |
123
+ |---|---|---|
124
+ | `"count"` | how many times the pattern occurs (int) | how many URLs, how many question marks |
125
+ | `"has"` | whether it occurs at all (bool) | flags you will group or filter on |
126
+ | `"extract"` | the first capture group, NaN where nothing matched | pulling a value *out* of the text |
127
+
128
+ `"extract"` needs exactly one capture group in `pattern`, and it is the mode worth being
129
+ careful with. `count` and `has` fail visibly when a pattern is wrong — a column of all zeros
130
+ or all `False` is hard to miss. Extraction fails *silently*, filling with NaN, so it reports
131
+ its own coverage through `loguru`:
132
+
133
+ ```
134
+ mentions: extracted 'addressed_to' from 92,415/627,172 rows (14.7%); 534,757 rows had no match
135
+ ```
136
+
137
+ That number is the point. A pattern that matches 15% of rows may be exactly right — on IRC,
138
+ most messages do not address anyone — or it may be silently broken. The log line makes you
139
+ decide which, instead of finding out four notebooks later.
140
+
140
141
  Note the two different `name`s: `Pipeline.add(name=...)` names the *step*, and
141
142
  `TransformBase.__init__` consumes it. So the new-column parameter has to be called something
142
143
  else — `feature` here. Any transform that wants to name an output column hits this.
@@ -156,6 +156,8 @@ step 3.
156
156
  | `HistogramPlot` | `sns.histplot`, `stat="density"` | density so a pdf can be overlaid |
157
157
  | `DistPlot` | a scipy distribution's pdf or pmf | estimates its own x-range from `ppf` |
158
158
  | `PlotFits` | histogram + fitted pdf, one panel per fit | see [Distributions](05-distributions.md) |
159
+ | `QQPlot` | sample quantiles vs. a distribution's theoretical quantiles | the tails, not the bulk — see [Distributions §5.5](05-distributions.md) |
160
+ | `ECDFPlot` | one or two empirical CDFs, bin-free | the right tool for comparing two samples |
159
161
 
160
162
  `HistogramPlot` defaults to `sqrt(n)` bins capped at 50. That default is a starting point,
161
163
  not an answer — bin count changes what a histogram appears to say, and choosing it is part of
@@ -166,6 +168,14 @@ falling back to `pmf` for discrete families. Left to itself it picks an x-range
166
168
  0.1st to the 99.9th percentile, which is right for most things and wrong for anything with a
167
169
  very heavy tail — pass `x_range` explicitly there.
168
170
 
171
+ `QQPlot` takes a sample and a *frozen* distribution and plots sorted data against the
172
+ distribution's quantiles at matching plotting positions, with a y=x reference line —
173
+ where `PlotFits`' histogram is dominated by the bulk of the data, this is where a tail
174
+ mismatch actually shows up.
175
+
176
+ `ECDFPlot` plots one sample, or two with `compare=`, as step functions of the empirical CDF —
177
+ no bin width to choose, so nothing about the shape is a plotting decision.
178
+
169
179
  ## 3.7 Writing your own plot
170
180
 
171
181
  Two questions decide the shape:
@@ -116,7 +116,8 @@ fitted pdf drawn over the histogram to see where it agrees and where it does not
116
116
  sample sizes are near-unreadable. Normalise, or use ECDFs, or do a two-sample test.
117
117
 
118
118
  **In GOAD:** `HistogramPlot` (density-scaled, so a pdf overlays correctly), `DistPlot` for a
119
- parametric curve, and `DistributionFitter` + `PlotFits` for the full ranked comparison. See
119
+ parametric curve, `DistributionFitter` + `PlotFits` for the full ranked comparison, and
120
+ `QQPlot` / `ECDFPlot` for the tail diagnostics a histogram cannot show. See
120
121
  [Distributions](05-distributions.md).
121
122
 
122
123
  ---
@@ -25,7 +25,7 @@ kind of process you are looking at.
25
25
  needs: the scipy object, whether it is discrete, and how many parameters it takes.
26
26
 
27
27
  Shipped: `norm`, `uniform`, `lognorm`, `poisson`, `exponential`, `skewnorm`, `gamma`,
28
- `weibull`.
28
+ `weibull`, `bernoulli`, `binomial`, `nbinom`, `beta`.
29
29
 
30
30
  ```python
31
31
  from goad_toolkit.distributions import DistributionRegistry
@@ -36,10 +36,16 @@ registry.get_names()
36
36
  registry.register_distribution("pareto", stats.pareto, is_discrete=False, num_params=3)
37
37
  ```
38
38
 
39
- Registering a family is the extension point that matters most in practice, because the
40
- shipped set is missing things real data needs — `pareto` and `zipf` for rank-frequency data,
41
- `bernoulli` and `binom` for yes/no outcomes, `nbinom` for over-dispersed counts, `beta` for a
42
- distribution over a probability.
39
+ `pareto` is deliberately not in the shipped set, even though the chat corpus is exactly the
40
+ kind of data it fits — word frequency and burst lengths are rank-frequency data, the
41
+ textbook case for a power law. Registering it yourself, as above, is the extensibility
42
+ exercise: a fit run without it will call the same data "lognormal" and look convincing, and
43
+ registering `pareto` is what exposes that the winner depends on what you thought to try.
44
+ `zipf` is the same story for discrete rank data and ships the same way.
45
+
46
+ Registering a family is the extension point that matters whenever the shipped set is still
47
+ missing something real data needs — a power-law family among them, `zipf` for discrete
48
+ rank data, or anything scipy has that GOAD has not wrapped.
43
49
 
44
50
  Two things to know before you rely on it:
45
51
 
@@ -154,8 +160,7 @@ What to look at, in order:
154
160
 
155
161
  1. **The tails.** This is where families differ and where the fit matters, and it is also
156
162
  where a histogram has the fewest observations and is least readable. If your question is
157
- about extreme values, a histogram will not settle it — use a qq-plot or an ECDF on a log
158
- scale.
163
+ about extreme values, a histogram will not settle it — use `QQPlot` or `ECDFPlot`, below.
159
164
  2. **Systematic deviation, not point-by-point wobble.** A curve that is above the histogram
160
165
  on the left and below it on the right is a wrong-shape signal. Individual bars being off
161
166
  is sampling noise.
@@ -163,6 +168,43 @@ What to look at, in order:
163
168
  log-likelihoods have not been distinguished by your data, and picking one is a choice you
164
169
  should make on mechanism, not on the fourth decimal place.
165
170
 
171
+ ### `QQPlot`, `ECDFPlot`, and `fit_table`
172
+
173
+ ```python
174
+ from goad_toolkit.visualizer import QQPlot, ECDFPlot, PlotSettings
175
+
176
+ QQPlot(PlotSettings(title="Residuals vs. normal")).plot(
177
+ data=data["residual"], distribution=best.frozen_dist,
178
+ )
179
+ ```
180
+
181
+ `QQPlot` sorts the sample and plots it against the fitted (frozen) distribution's quantiles
182
+ at matching plotting positions, with a y=x reference line. A fit that looked fine in
183
+ `PlotFits`' histogram can still bend away from that line in the tails — which is the point:
184
+ the histogram is dominated by the bulk, the qq-plot is not.
185
+
186
+ ```python
187
+ ECDFPlot(PlotSettings()).plot(
188
+ data=group_a["value"], compare=group_b["value"],
189
+ label="group a", compare_label="group b",
190
+ )
191
+ ```
192
+
193
+ `ECDFPlot` draws one empirical CDF, or two with `compare=` for a direct two-sample
194
+ comparison — no bin width to choose, so the shape on screen is entirely the data's, not a
195
+ plotting decision.
196
+
197
+ ```python
198
+ from goad_toolkit.analytics import fit_table
199
+
200
+ fit_table(results)
201
+ ```
202
+
203
+ `fit_table` turns a list of `fit()` results into the dataframe a student should hand in
204
+ instead of a screenshot of a picture: distribution, fitted params, log-likelihood, KS
205
+ statistic and p-value, and which criteria (if any) it won — ranked by log-likelihood, with
206
+ `FailedFit` rows sorted last and their message kept instead of a blank row.
207
+
166
208
  ## 5.6 Outliers, properly
167
209
 
168
210
  The sequence that avoids the usual mistake:
@@ -195,6 +237,9 @@ data is.
195
237
  | lognormal | *products* of many factors | message length, income, response time, file size |
196
238
  | exponential | waiting time between independent events | time between messages, within a burst |
197
239
  | Poisson | counts of independent rare events in a fixed window | messages per hour, arrivals per day |
240
+ | negative binomial | over-dispersed counts — a Poisson whose rate itself varies | messages per day across people, not within a steady process |
241
+ | Bernoulli | a single yes/no trial | did this message get a reply, is this author still active |
242
+ | binomial | a fixed number of independent yes/no trials | replies within N messages, conversions per N views |
198
243
  | power law / Pareto | preferential attachment, "rich get richer" | word frequency by rank, followers, city size |
199
244
  | gamma / Weibull | sums of exponentials; time-to-failure with changing hazard | durations, lifetimes |
200
245
  | beta | a distribution *over a probability* | uncertainty about a rate, A/B test posteriors |
@@ -84,6 +84,7 @@ class TransformBase(ABC):
84
84
  | `RollingAvg` | `column: str, window: int, rename: bool = False` |
85
85
  | `ZScaler` | `column: str, rename: bool = False` |
86
86
  | `TimeFeatures` | `column: str, features: Optional[List[str]] = None` |
87
+ | `RegexFeature` | `column: str, pattern: str, feature: str, mode: str = "count"` |
87
88
 
88
89
  `rename=True` writes to `{column}_shifted` / `_diff` / `_rolling_avg` / `_zscore` instead of
89
90
  overwriting.
@@ -92,6 +93,12 @@ overwriting.
92
93
  `TimeFeatures.DEFAULT` — used when `features` is omitted — is `("day_name", "isoweek",
93
94
  "year_week")`. A feature named the same as `column` overwrites it.
94
95
 
96
+ `RegexFeature.mode` is one of `"count"` (int), `"has"` (bool) or `"extract"` (the first
97
+ capture group, NaN where nothing matched); anything else raises `ValueError`. `extract`
98
+ requires exactly one capture group in `pattern` and logs its match rate through `loguru`.
99
+ The output column is `feature`, not `name` — `Pipeline.add(name=...)` already claims `name`
100
+ for the step.
101
+
95
102
  ```python
96
103
  class Pipeline:
97
104
  def add(self, transform_class: Type[T], name: Optional[str] = None, **kwargs) -> "Pipeline"
@@ -139,8 +146,11 @@ class DistributionRegistry:
139
146
  ```
140
147
 
141
148
  Registered by default: `norm`, `uniform`, `lognorm`, `poisson`, `exponential`, `skewnorm`,
142
- `gamma`, `weibull`. Every instance starts from that set, so a registration is scoped to the
143
- registry you made it on — hand that registry to `DistributionFitter(registry)` to use it.
149
+ `gamma`, `weibull`, `bernoulli`, `binomial`, `nbinom`, `beta`. Every instance starts from that
150
+ set, so a registration is scoped to the registry you made it on — hand that registry to
151
+ `DistributionFitter(registry)` to use it. `pareto` is not in the default set — lesson 4 has
152
+ the student register it, since a default fit missing the one family the data actually needs
153
+ is the point of that exercise.
144
154
 
145
155
  ---
146
156
 
@@ -192,10 +202,21 @@ class DistributionFitter:
192
202
 
193
203
  @staticmethod
194
204
  def best(results: list[Result], criterion: str = "combined") -> list[Result]
205
+
206
+ def fit_table(results: list[Result]) -> pd.DataFrame
195
207
  ```
196
208
 
197
209
  `criterion` is one of `"likelihood"`, `"ks"`, `"combined"`. Failures are returned as
198
- `FailedFit` values rather than raised.
210
+ `FailedFit` values rather than raised. `log_likelihood` is computed with `logpdf` for
211
+ continuous families and `logpmf` for discrete ones. The two criteria are marked
212
+ independently: a `criterion="combined"` fit where every KS p-value comes back exactly 0
213
+ (routine for discrete families on a large, tied sample) still gets a `best_likelihood`
214
+ winner — it just has no `best_ks` winner.
215
+
216
+ `fit_table` turns a list of results into one row per distribution — `distribution`, `params`,
217
+ `log_likelihood`, `ks_stat`, `ks_pvalue`, `best_likelihood`, `best_ks`, `message` — ranked by
218
+ `log_likelihood` descending, with `FailedFit` rows (their `message` kept, metrics `NaN`)
219
+ sorted last.
199
220
 
200
221
  ---
201
222
 
@@ -273,6 +294,8 @@ class BasePlot(ABC):
273
294
  | `HistogramPlot` | `data: np.ndarray, bins=None, kde=False, color="skyblue", alpha=0.7, **kwargs` |
274
295
  | `DistPlot` | `distribution, x_range=None, samples=1000, color="crimson", linewidth=2, label=None, **kwargs` |
275
296
  | `ACFPlot` | `data, nlags=40, alpha=0.05, color="steelblue", band_color="gray", **kwargs` |
297
+ | `QQPlot` | `data, distribution, color="steelblue", line_color="black", alpha=0.6, **kwargs` |
298
+ | `ECDFPlot` | `data, compare=None, label="data", compare_label="compare", color="steelblue", compare_color="crimson", **kwargs` |
276
299
 
277
300
  ```python
278
301
  class PlotFits(BasePlot):
@@ -329,6 +352,12 @@ of `likelihood`, `ks`, `combined`; `--method` is passed to `scipy.stats.fit`.
329
352
  - `ACFPlot` raises `ValueError` if the data contains NaNs, rather than passing them through.
330
353
  `statsmodels.tsa.stattools.acf` does not raise on missing values — it silently returns an
331
354
  all-NaN result — so a decomposition's residual needs `.dropna()` before it reaches `ACFPlot`.
355
+ - `binomial` and `nbinom` fit two shape parameters (`n`, `p`) from the sample mean and
356
+ variance alone. If `n` is not known independently, it is not identifiable from the data —
357
+ many `(n, p)` pairs with the same `n·p` fit about as well, so a fitted `n` should be treated
358
+ as "consistent with the mean", not as a recovered count of trials. When you know `n` from
359
+ the process (a fixed number of messages, a fixed number of views), trust that `n`, not the
360
+ fitted one.
332
361
 
333
362
  ---
334
363
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "goad-toolkit"
3
- version = "0.2.3"
3
+ version = "0.2.5"
4
4
  description = "An extensible toolkit for Goal Oriented Analysis of Data"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -2,6 +2,7 @@ from dataclasses import dataclass
2
2
  from typing import Any, List, Optional, Tuple, Union
3
3
 
4
4
  import numpy as np
5
+ import pandas as pd
5
6
  from loguru import logger
6
7
  from scipy import stats
7
8
 
@@ -105,7 +106,11 @@ class DistributionFitter:
105
106
  # Create bounds based on parameter count
106
107
  if dist_obj.num_params == 1:
107
108
  if dist_obj.is_discrete:
108
- mean_lower_bound = max(0.1, float(data_mean / 10))
109
+ # A single-parameter discrete family's shape parameter is not always
110
+ # a count-scale rate (poisson's lambda) — it can be a probability
111
+ # (bernoulli's p), which is routinely well under 0.1, so the floor
112
+ # here stays near zero rather than at 0.1.
113
+ mean_lower_bound = max(1e-3, float(data_mean / 10))
109
114
  mean_upper_bound = float(data_mean * 10)
110
115
  return [(mean_lower_bound, mean_upper_bound)]
111
116
  else:
@@ -134,15 +139,17 @@ class DistributionFitter:
134
139
 
135
140
  def _calculate_loglikelihood(self, data: np.ndarray, dist_obj, params) -> float:
136
141
  """Calculate log-likelihood of data given distribution and parameters.
137
- For every datapoint, calculate the log probability density function (PDF)
138
- We sum all the log PDFs to get the log-likelihood of the data.
139
- If there are a lot of datapoints with very low probability, the log-likelihood
140
- will be very negative (or -inf if probability is 0).
142
+ For every datapoint, calculate the log density (continuous families, via
143
+ logpdf) or the log mass (discrete families, via logpmf). We sum them to get
144
+ the log-likelihood of the data. If there are a lot of datapoints with very
145
+ low probability, the log-likelihood will be very negative (or -inf if
146
+ probability is 0).
141
147
 
142
148
  We will prefer distributions with higher log-likelihood values.
143
149
  """
144
150
  try:
145
- return np.sum(dist_obj.dist.logpdf(data, *params))
151
+ log_density = dist_obj.dist.logpmf if dist_obj.is_discrete else dist_obj.dist.logpdf
152
+ return np.sum(log_density(data, *params))
146
153
  except Exception as e:
147
154
  logger.warning(f"Log-likelihood calculation failed: {str(e)}")
148
155
  return -np.inf
@@ -239,33 +246,24 @@ class DistributionFitter:
239
246
  best_ks_value = fit_ks
240
247
  best_ks_fit = fit
241
248
 
242
- # Only mark if we found best fits
243
- if best_likelihood_fit is not None and best_ks_fit is not None:
244
- # Mark based on criterion
245
- if criterion == "likelihood":
246
- # Mark only likelihood best
247
- for fit in fits:
248
- if isinstance(fit, FitResult):
249
- fit.best_likelihood = (
250
- fit.distribution == best_likelihood_fit.distribution
251
- )
252
-
253
- elif criterion == "ks":
254
- # Mark only KS best
255
- for fit in fits:
256
- if isinstance(fit, FitResult):
257
- fit.best_ks = fit.distribution == best_ks_fit.distribution
258
-
259
- elif criterion == "combined":
260
- # Mark both
261
- for fit in fits:
262
- if isinstance(fit, FitResult):
263
- fit.best_likelihood = (
264
- fit.distribution == best_likelihood_fit.distribution
265
- )
266
- fit.best_ks = fit.distribution == best_ks_fit.distribution
267
- else:
268
- raise ValueError(f"Unknown criterion '{criterion}'")
249
+ if criterion not in ("likelihood", "ks", "combined"):
250
+ raise ValueError(f"Unknown criterion '{criterion}'")
251
+
252
+ # Each criterion is marked independently: a KS test that never clears the
253
+ # p > 0 threshold (routine for discrete families on a large sample, where
254
+ # ties push the p-value to numerical zero) must not suppress a perfectly
255
+ # good best_likelihood winner, and vice versa.
256
+ if criterion in ("likelihood", "combined") and best_likelihood_fit is not None:
257
+ for fit in fits:
258
+ if isinstance(fit, FitResult):
259
+ fit.best_likelihood = (
260
+ fit.distribution == best_likelihood_fit.distribution
261
+ )
262
+
263
+ if criterion in ("ks", "combined") and best_ks_fit is not None:
264
+ for fit in fits:
265
+ if isinstance(fit, FitResult):
266
+ fit.best_ks = fit.distribution == best_ks_fit.distribution
269
267
 
270
268
  # Return the original list
271
269
  return fits
@@ -327,3 +325,46 @@ class DistributionFitter:
327
325
  ]
328
326
  else:
329
327
  raise ValueError(f"Unknown criterion '{criterion}'")
328
+
329
+
330
+ def fit_table(results: List[Result]) -> pd.DataFrame:
331
+ """Turn a list of fit results into a ranked dataframe: what a student hands in.
332
+
333
+ One row per distribution: name, fitted params, log-likelihood, KS statistic and
334
+ KS p-value, plus which criteria (if any) it won. Ranked by log-likelihood,
335
+ descending; `FailedFit` entries carry their failure message in `message` and
336
+ sort last, since a missing likelihood is not a small likelihood.
337
+ """
338
+ rows = []
339
+ for result in results:
340
+ if isinstance(result, FitResult):
341
+ rows.append(
342
+ {
343
+ "distribution": result.distribution,
344
+ "params": result.params,
345
+ "log_likelihood": result.log_likelihood,
346
+ "ks_stat": result.kstest.statistic if result.kstest else float("nan"),
347
+ "ks_pvalue": result.kstest.p_value if result.kstest else float("nan"),
348
+ "best_likelihood": bool(result.best_likelihood),
349
+ "best_ks": bool(result.best_ks),
350
+ "message": result.message,
351
+ }
352
+ )
353
+ else:
354
+ rows.append(
355
+ {
356
+ "distribution": result.distribution,
357
+ "params": None,
358
+ "log_likelihood": float("nan"),
359
+ "ks_stat": float("nan"),
360
+ "ks_pvalue": float("nan"),
361
+ "best_likelihood": False,
362
+ "best_ks": False,
363
+ "message": result.message,
364
+ }
365
+ )
366
+
367
+ table = pd.DataFrame(rows)
368
+ return table.sort_values(
369
+ "log_likelihood", ascending=False, na_position="last"
370
+ ).reset_index(drop=True)
@@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
2
2
  from typing import Any, Dict, List, Optional, Type, TypeVar
3
3
 
4
4
  import pandas as pd
5
+ from loguru import logger
5
6
  from tqdm import tqdm
6
7
 
7
8
  T = TypeVar("T", bound="TransformBase")
@@ -161,6 +162,52 @@ class TimeFeatures(TransformBase):
161
162
  return data
162
163
 
163
164
 
165
+ class RegexFeature(TransformBase):
166
+ """Add a feature extracted from a text column with a regular expression.
167
+
168
+ Three modes, all writing a single new column named by `feature`:
169
+
170
+ - `"count"` — how many times the pattern occurs per row (int);
171
+ - `"has"` — whether it occurs at all (bool);
172
+ - `"extract"` — the first capture group's text, or NaN where nothing matched.
173
+ `pattern` must contain exactly one capture group in this mode.
174
+
175
+ The new column is `feature`, not `name`: `Pipeline.add(name=...)` already claims
176
+ `name` for the step, and `TransformBase.__init__` consumes it. Any transform that
177
+ names an output column has to spell that parameter something else.
178
+
179
+ `mode="extract"` reports its own coverage through `loguru`. `count` and `has` fail
180
+ visibly when a pattern is wrong — a column of all zeros or all False. Extraction
181
+ fails silently, filling with NaN, so it says out loud how much it matched.
182
+ """
183
+
184
+ def transform(
185
+ self,
186
+ data: pd.DataFrame,
187
+ column: str,
188
+ pattern: str,
189
+ feature: str,
190
+ mode: str = "count",
191
+ ) -> pd.DataFrame:
192
+ text = data[column].fillna("")
193
+ if mode == "count":
194
+ data[feature] = text.str.count(pattern)
195
+ elif mode == "has":
196
+ data[feature] = text.str.contains(pattern, regex=True)
197
+ elif mode == "extract":
198
+ data[feature] = text.str.extract(pattern, expand=False)
199
+ matched = data[feature].notna().sum()
200
+ total = len(data)
201
+ share = f"{matched / total:.1%}" if total else "n/a"
202
+ logger.info(
203
+ f"{self.name}: extracted '{feature}' from {matched:,}/{total:,} rows "
204
+ f"({share}); {total - matched:,} rows had no match"
205
+ )
206
+ else:
207
+ raise ValueError(f"mode must be count/has/extract, got {mode!r}")
208
+ return data
209
+
210
+
164
211
  class Pipeline:
165
212
  """Pipeline for chaining data transformations."""
166
213
 
@@ -54,6 +54,22 @@ class DistributionRegistry:
54
54
  self.register_distribution(
55
55
  "weibull", stats.weibull_min, is_discrete=False, num_params=3
56
56
  )
57
+ self.register_distribution(
58
+ "bernoulli", stats.bernoulli, is_discrete=True, num_params=1
59
+ )
60
+ self.register_distribution(
61
+ "binomial", stats.binom, is_discrete=True, num_params=2
62
+ )
63
+ self.register_distribution(
64
+ "nbinom", stats.nbinom, is_discrete=True, num_params=2
65
+ )
66
+ self.register_distribution("beta", stats.beta, is_discrete=False, num_params=4)
67
+ # pareto is deliberately not shipped here: lesson 4 has the student
68
+ # register it themselves as the extensibility exercise, and a fit that
69
+ # silently has pareto available from the start would remove the point
70
+ # of that exercise. Register it yourself when you need it:
71
+ # registry.register_distribution("pareto", stats.pareto,
72
+ # is_discrete=False, num_params=3)
57
73
 
58
74
  def __repr__(self) -> str:
59
75
  """Detailed representation of the registry."""
@@ -505,6 +505,130 @@ class DistPlot(BasePlot):
505
505
  return x
506
506
 
507
507
 
508
+ class QQPlot(BasePlot):
509
+ """Quantile-quantile plot: is this fit believable, not just which one wins.
510
+
511
+ A histogram with a pdf overlaid (PlotFits, DistPlot) is dominated by the bulk
512
+ of the data, which is exactly where distributions look most alike. A qq-plot
513
+ puts sorted data against the fitted distribution's theoretical quantiles, so a
514
+ systematic deviation in a tail — where families actually differ — shows up as
515
+ points bending away from the reference line instead of as a few stray bars.
516
+ """
517
+
518
+ def build(
519
+ self,
520
+ data: np.ndarray,
521
+ distribution: Any,
522
+ color: str = "steelblue",
523
+ line_color: str = "black",
524
+ alpha: float = 0.6,
525
+ **kwargs,
526
+ ) -> Tuple[Any, Any]:
527
+ """
528
+ Plot sample quantiles against a distribution's theoretical quantiles.
529
+
530
+ Parameters:
531
+ -----------
532
+ data : np.ndarray
533
+ Sample to plot
534
+ distribution : scipy.stats distribution
535
+ Fitted (frozen) distribution to compare against; must have a ppf method
536
+ color : str
537
+ Colour of the quantile points
538
+ line_color : str
539
+ Colour of the y=x reference line
540
+ alpha : float
541
+ Transparency of the quantile points
542
+ **kwargs : Additional keyword arguments passed to ax.scatter
543
+
544
+ Returns:
545
+ --------
546
+ fig, ax : The created figure and axes
547
+ """
548
+ if self.ax is None:
549
+ raise ValueError("No axes available for plotting")
550
+
551
+ sample = np.sort(np.asarray(data))
552
+ n = len(sample)
553
+ if n == 0:
554
+ raise ValueError("QQPlot got no data to plot")
555
+
556
+ # Filliben-style plotting positions: (i - 0.5) / n avoids ppf(0) / ppf(1),
557
+ # which are -inf/inf for most families.
558
+ probabilities = (np.arange(1, n + 1) - 0.5) / n
559
+ theoretical = distribution.ppf(probabilities)
560
+
561
+ self.ax.scatter(theoretical, sample, color=color, alpha=alpha, **kwargs)
562
+
563
+ lo = min(np.min(theoretical), np.min(sample))
564
+ hi = max(np.max(theoretical), np.max(sample))
565
+ self.ax.plot([lo, hi], [lo, hi], color=line_color, linewidth=1, linestyle="--")
566
+
567
+ return self.fig, self.ax
568
+
569
+
570
+ class ECDFPlot(BasePlot):
571
+ """Empirical CDF: bin-free, and the right tool for comparing two samples.
572
+
573
+ A histogram's shape depends on its bin width; an ECDF has no such knob, uses
574
+ every point, and puts two samples on directly comparable axes without either
575
+ one's binning choice hiding or manufacturing a difference.
576
+ """
577
+
578
+ def build(
579
+ self,
580
+ data: np.ndarray,
581
+ compare: Optional[np.ndarray] = None,
582
+ label: str = "data",
583
+ compare_label: str = "compare",
584
+ color: str = "steelblue",
585
+ compare_color: str = "crimson",
586
+ **kwargs,
587
+ ) -> Tuple[Any, Any]:
588
+ """
589
+ Plot the empirical CDF of `data`, and optionally a second sample over it.
590
+
591
+ Parameters:
592
+ -----------
593
+ data : np.ndarray
594
+ Sample to plot
595
+ compare : Optional[np.ndarray]
596
+ A second sample to overlay, for a direct two-sample comparison
597
+ label : str
598
+ Legend label for `data`
599
+ compare_label : str
600
+ Legend label for `compare`
601
+ color : str
602
+ Colour of the `data` step curve
603
+ compare_color : str
604
+ Colour of the `compare` step curve
605
+ **kwargs : Additional keyword arguments passed to ax.step
606
+
607
+ Returns:
608
+ --------
609
+ fig, ax : The created figure and axes
610
+ """
611
+ if self.ax is None:
612
+ raise ValueError("No axes available for plotting")
613
+ ax = self.ax
614
+
615
+ self._draw(ax, np.asarray(data), color=color, label=label, **kwargs)
616
+ if compare is not None:
617
+ self._draw(ax, np.asarray(compare), color=compare_color, label=compare_label, **kwargs)
618
+
619
+ if compare is not None or label:
620
+ ax.legend()
621
+
622
+ return self.fig, self.ax
623
+
624
+ def _draw(self, ax: Axes, values: np.ndarray, color: str, label: Optional[str], **kwargs) -> None:
625
+ if len(values) == 0:
626
+ raise ValueError("ECDFPlot got no data to plot")
627
+ sorted_values = np.sort(values)
628
+ y = np.arange(1, len(sorted_values) + 1) / len(sorted_values)
629
+ ax.step(sorted_values, y, where="post", color=color, label=label, **kwargs)
630
+
631
+
508
632
  @dataclass
509
633
  class FitPlotSettings:
510
634
  """Settings for distribution fit plots."""