| File: | blib/lib/Database/BI/Insights.pm |
| Coverage: | 95.5% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Database::BI::Insights; | |||||
| 2 | ||||||
| 3 | 10 10 10 | 2960 23 99 | use strict; | |||
| 4 | 10 10 10 | 12 8 331 | use warnings; | |||
| 5 | ||||||
| 6 | our $VERSION = '0.025.0'; | |||||
| 7 | ||||||
| 8 | 10 10 10 | 15 8 235 | use Database::BI::Util qw(urlencode); | |||
| 9 | 10 10 10 | 16 9 254 | use List::Util qw(sum min max); | |||
| 10 | 10 10 10 | 13 9 133 | use Scalar::Util qw(looks_like_number); | |||
| 11 | 10 10 10 | 16 6 10177 | use Readonly; | |||
| 12 | ||||||
| 13 | # --------------------------------------------------------------------------- | |||||
| 14 | # Constants | |||||
| 15 | # --------------------------------------------------------------------------- | |||||
| 16 | ||||||
| 17 | # IQR fence multiplier (Tukey, 1977). | |||||
| 18 | Readonly my $IQR_FENCE => 1.5; | |||||
| 19 | ||||||
| 20 | # Minimum distinct periods required for period-over-period and seasonality. | |||||
| 21 | Readonly my $MIN_PERIODS_POP => 2; | |||||
| 22 | Readonly my $MIN_PERIODS_SEASON => 8; | |||||
| 23 | ||||||
| 24 | # Minimum rows in a group to attempt outlier detection. | |||||
| 25 | Readonly my $MIN_ROWS_OUTLIER => 4; | |||||
| 26 | ||||||
| 27 | # Autocorrelation threshold above which we call a pattern "seasonal". | |||||
| 28 | Readonly my $SEASON_R_THRESHOLD => 0.6; | |||||
| 29 | ||||||
| 30 | # Maximum outliers reported per column (keeps the panel readable). | |||||
| 31 | Readonly my $MAX_OUTLIERS_PER_COL => 5; | |||||
| 32 | ||||||
| 33 | # Maximum top-mover rows reported. | |||||
| 34 | Readonly my $MAX_TOP_MOVERS => 5; | |||||
| 35 | ||||||
| 36 | # --------------------------------------------------------------------------- | |||||
| 37 | # Public API | |||||
| 38 | # --------------------------------------------------------------------------- | |||||
| 39 | ||||||
| 40 | # compute( records => \@rows, columns => \@cols, spec_key => $l, base_url => $url ) | |||||
| 41 | # -> \@insights | |||||
| 42 | # | |||||
| 43 | # Each insight hashref has: | |||||
| 44 | # kind -- 'outlier' | 'top_mover' | 'period_delta' | 'seasonality' | |||||
| 45 | # headline -- one short sentence | |||||
| 46 | # detail -- one sentence giving the numbers | |||||
| 47 | # view_url -- absolute-path URL (without host) linking to the view that shows it | |||||
| 48 | # (always present; the spec says "an insight you cannot click through is a bug") | |||||
| 49 | # method -- key into %METHOD_NOTES documenting the algorithm used | |||||
| 50 | # | |||||
| 51 | # Arguments: | |||||
| 52 | # records -- arrayref of row hashrefs (pre-filtered, post-calc) | |||||
| 53 | # columns -- arrayref of column names in order | |||||
| 54 | # spec_key -- the l= value (e.g. "table:sales" or "path:/data/x.csv") | |||||
| 55 | # base_url -- base request URL to build view_url from (e.g. "/stats?l=table:sales") | |||||
| 56 | # | |||||
| 57 | # NOTE: This sub is pure arithmetic -- no LLM, no external calls. | |||||
| 58 | sub compute { | |||||
| 59 | 77 | 29149 | my (%args) = @_; | |||
| 60 | 77 | 127 | my $records = $args{records} // []; | |||
| 61 | 77 | 86 | my $columns = $args{columns} // []; | |||
| 62 | 77 | 104 | my $spec_key = $args{spec_key} // ''; | |||
| 63 | 77 | 137 | my $base_url = $args{base_url} // "/insights?l=$spec_key"; | |||
| 64 | ||||||
| 65 | 77 | 173 | return [] unless @$records && @$columns; | |||
| 66 | ||||||
| 67 | 72 | 44 | my @insights; | |||
| 68 | ||||||
| 69 | # Identify date columns (ISO-8601 YYYY-MM-DD) and numeric columns. | |||||
| 70 | 72 | 53 | my (@date_cols, @numeric_cols); | |||
| 71 | 72 | 66 | for my $col (@$columns) { | |||
| 72 | 239 2387 2387 | 138 1481 1079 | my @vals = grep { defined $_ && length $_ } map { $_->{$col} } @$records; | |||
| 73 | 239 | 212 | next unless @vals; | |||
| 74 | 238 | 161 | if (_is_date_col(\@vals)) { | |||
| 75 | 44 | 49 | push @date_cols, $col; | |||
| 76 | } elsif (_is_numeric_col(\@vals)) { | |||||
| 77 | 89 | 96 | push @numeric_cols, $col; | |||
| 78 | } | |||||
| 79 | } | |||||
| 80 | ||||||
| 81 | # Outlier detection: for each numeric column scan all distinct category | |||||
| 82 | # groups formed by each non-numeric, non-date column. When the dataset | |||||
| 83 | # has no categorical column, treat all rows as one group. | |||||
| 84 | my @cat_cols = grep { | |||||
| 85 | 72 239 | 72 110 | my $c = $_; | |||
| 86 | 239 543 | 104 300 | !grep { $_ eq $c } (@date_cols, @numeric_cols) | |||
| 87 | } @$columns; | |||||
| 88 | ||||||
| 89 | 72 | 53 | for my $num_col (@numeric_cols) { | |||
| 90 | 89 | 101 | my @found = _find_outliers($records, $num_col, \@cat_cols, $spec_key, $base_url); | |||
| 91 | 89 | 74 | push @insights, @found; | |||
| 92 | } | |||||
| 93 | ||||||
| 94 | # Period-over-period and top movers: need a date column + at least one | |||||
| 95 | # numeric column. | |||||
| 96 | 72 | 123 | if (@date_cols && @numeric_cols) { | |||
| 97 | 44 | 33 | my $date_col = $date_cols[0]; # use the first date column found | |||
| 98 | 44 | 34 | for my $num_col (@numeric_cols) { | |||
| 99 | 64 | 101 | push @insights, | |||
| 100 | _period_over_period($records, $date_col, $num_col, $spec_key, $base_url); | |||||
| 101 | 64 | 135 | push @insights, | |||
| 102 | _top_movers($records, $date_col, $num_col, \@cat_cols, $spec_key, $base_url); | |||||
| 103 | 64 | 154 | push @insights, | |||
| 104 | _seasonality($records, $date_col, $num_col, $spec_key, $base_url); | |||||
| 105 | } | |||||
| 106 | } | |||||
| 107 | ||||||
| 108 | 72 | 184 | return \@insights; | |||
| 109 | } | |||||
| 110 | ||||||
| 111 | # method_note($method_key) -> $string | |||||
| 112 | # | |||||
| 113 | # Returns a one-sentence human-readable description of the algorithm behind | |||||
| 114 | # a given insight method key. Used by the template's tooltip/footnote. | |||||
| 115 | sub method_note { | |||||
| 116 | 15 | 6548 | my $key = shift; | |||
| 117 | 15 | 25 | my %notes = ( | |||
| 118 | iqr_fence => 'Outlier: value beyond 1.5 x IQR from Q1 or Q3 (Tukey fence).', | |||||
| 119 | pop_delta => 'Period-over-period: sum for the most-recent period vs. the prior period.', | |||||
| 120 | top_mover => 'Top mover: dimension member with the largest period-over-period absolute change.', | |||||
| 121 | autocorr => 'Seasonality: lag-1 autocorrelation on period sums; r >= 0.6 flagged.', | |||||
| 122 | ); | |||||
| 123 | 15 | 32 | return $notes{$key} // $key; | |||
| 124 | } | |||||
| 125 | ||||||
| 126 | # --------------------------------------------------------------------------- | |||||
| 127 | # Private helpers | |||||
| 128 | # --------------------------------------------------------------------------- | |||||
| 129 | ||||||
| 130 | # _looks_like_date($v) -> bool | |||||
| 131 | # | |||||
| 132 | # Returns true when $v matches any common date format. Checked BEFORE numeric | |||||
| 133 | # classification so that slash-dates (e.g. 12/22/2025 from US bank exports), | |||||
| 134 | # EU slash-dates (22/12/2025), and dash-Mon dates (22-Oct-2026) are never | |||||
| 135 | # stripped of their punctuation and misread as large integers like 12222025. | |||||
| 136 | sub _looks_like_date { | |||||
| 137 | 1465 | 5444 | my $v = shift; | |||
| 138 | 1465 | 1012 | return 0 unless defined $v && length $v; | |||
| 139 | 1461 | 834 | return 1 if $v =~ /\A\d{4}-\d{2}-\d{2}\z/; # ISO-8601 | |||
| 140 | 992 | 486 | return 1 if $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/; # M/D/YYYY or D/M/YYYY | |||
| 141 | 966 | 463 | return 1 if $v =~ /\A\d{1,2}-[A-Za-z]{3}-\d{4}\z/; # DD-Mon-YYYY | |||
| 142 | 954 | 604 | return 0; | |||
| 143 | } | |||||
| 144 | ||||||
| 145 | sub _is_date_col { | |||||
| 146 | 246 | 1976 | my $vals = shift; | |||
| 147 | 246 | 181 | my $n = @$vals > 20 ? 20 : scalar @$vals; | |||
| 148 | 246 | 117 | my $ok = 0; | |||
| 149 | 246 246 | 178 133 | for my $v (@{$vals}[0 .. $n - 1]) { | |||
| 150 | 692 | 324 | return 0 unless _looks_like_date($v); | |||
| 151 | 496 | 209 | $ok++; | |||
| 152 | } | |||||
| 153 | 50 | 73 | return $ok ? 1 : 0; | |||
| 154 | } | |||||
| 155 | ||||||
| 156 | sub _is_numeric_col { | |||||
| 157 | 203 | 910 | my $vals = shift; | |||
| 158 | 203 | 129 | return 0 unless @$vals; | |||
| 159 | 201 | 148 | my $ok = 0; | |||
| 160 | 201 | 132 | my $n = @$vals > 20 ? 20 : scalar @$vals; | |||
| 161 | 201 201 | 117 124 | for my $v (@{$vals}[0 .. $n - 1]) { | |||
| 162 | 749 | 323 | return 0 if _looks_like_date($v); # date values are not numeric measures | |||
| 163 | 747 | 338 | my $num = _to_num($v); | |||
| 164 | 747 | 512 | return 0 unless defined $num; | |||
| 165 | 640 | 249 | $ok++; | |||
| 166 | } | |||||
| 167 | 92 | 137 | return $ok ? 1 : 0; | |||
| 168 | } | |||||
| 169 | ||||||
| 170 | sub _to_num { | |||||
| 171 | 5073 | 6700 | return Database::BI::Util::parse_number($_[0]); | |||
| 172 | } | |||||
| 173 | ||||||
| 174 | # _quartiles(\@sorted_nums) -> ($q1, $median, $q3) | |||||
| 175 | # | |||||
| 176 | # Uses the "inclusive" method: for n values, Q1 is the median of the lower | |||||
| 177 | # half (not including the overall median when n is odd), Q3 the median of the | |||||
| 178 | # upper half. This matches R's type=2 and Excel's QUARTILE.INC. | |||||
| 179 | sub _quartiles { | |||||
| 180 | 75 | 1666 | my $s = shift; # already sorted | |||
| 181 | 75 | 35 | my $n = scalar @$s; | |||
| 182 | 75 | 67 | return (undef, undef, undef) unless $n >= 4; | |||
| 183 | ||||||
| 184 | 72 | 56 | my $mid = int($n / 2); | |||
| 185 | 72 72 | 51 58 | my @lo = @{$s}[0 .. $mid - 1]; | |||
| 186 | 72 72 | 89 58 | my @hi = @{$s}[($n % 2 ? $mid + 1 : $mid) .. $n - 1]; | |||
| 187 | ||||||
| 188 | 72 | 57 | my $q1 = _median(\@lo); | |||
| 189 | 72 | 45 | my $q2 = _median($s); | |||
| 190 | 72 | 46 | my $q3 = _median(\@hi); | |||
| 191 | 72 | 113 | return ($q1, $q2, $q3); | |||
| 192 | } | |||||
| 193 | ||||||
| 194 | sub _median { | |||||
| 195 | 223 | 958 | my $s = shift; | |||
| 196 | 223 | 91 | my $n = scalar @$s; | |||
| 197 | 223 | 105 | return undef unless $n; | |||
| 198 | 221 | 108 | my $m = int($n / 2); | |||
| 199 | 221 | 158 | return $n % 2 ? $s->[$m] : ($s->[$m - 1] + $s->[$m]) / 2; | |||
| 200 | } | |||||
| 201 | ||||||
| 202 | # _find_outliers($records, $num_col, \@cat_cols, $spec_key, $base_url) -> @insights | |||||
| 203 | # | |||||
| 204 | # For each categorical group (or all rows when @cat_cols is empty), apply the | |||||
| 205 | # Tukey IQR fence to the numeric column. Report up to MAX_OUTLIERS_PER_COL | |||||
| 206 | # values that fall outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR]. | |||||
| 207 | sub _find_outliers { | |||||
| 208 | 111 | 15889 | my ($records, $num_col, $cat_cols, $spec_key, $base_url) = @_; | |||
| 209 | ||||||
| 210 | 111 | 116 | my @insights; | |||
| 211 | ||||||
| 212 | # Group records by category key (empty string when no cat_cols). | |||||
| 213 | 111 | 63 | my (%groups, %group_example); | |||
| 214 | 111 | 82 | for my $row (@$records) { | |||
| 215 | 1099 1312 | 446 806 | my $key = join("\x00", map { $row->{$_} // '' } @$cat_cols); | |||
| 216 | 1099 | 526 | my $val = _to_num($row->{$num_col}); | |||
| 217 | 1099 1090 | 530 589 | push @{ $groups{$key} }, $val if defined $val; | |||
| 218 | 1099 | 666 | $group_example{$key} //= $row; | |||
| 219 | } | |||||
| 220 | ||||||
| 221 | 111 | 149 | for my $key (sort keys %groups) { | |||
| 222 | 311 311 | 288 209 | my @nums = @{ $groups{$key} }; | |||
| 223 | 311 | 256 | next if @nums < $MIN_ROWS_OUTLIER; | |||
| 224 | ||||||
| 225 | 66 1857 | 157 640 | my @sorted = sort { $a <=> $b } @nums; | |||
| 226 | 66 | 49 | my ($q1, undef, $q3) = _quartiles(\@sorted); | |||
| 227 | 66 | 90 | next unless defined $q1 && defined $q3; | |||
| 228 | ||||||
| 229 | 66 | 37 | my $iqr = $q3 - $q1; | |||
| 230 | 66 | 49 | my $lo_fence = $q1 - $IQR_FENCE * $iqr; | |||
| 231 | 66 | 103 | my $hi_fence = $q3 + $IQR_FENCE * $iqr; | |||
| 232 | ||||||
| 233 | # Find outlier rows. | |||||
| 234 | 66 | 86 | my @outlier_rows; | |||
| 235 | 66 | 46 | for my $row (@$records) { | |||
| 236 | 1687 1457 | 649 784 | my $gkey = join("\x00", map { $row->{$_} // '' } @$cat_cols); | |||
| 237 | 1687 | 762 | next unless $gkey eq $key; | |||
| 238 | 826 | 326 | my $val = _to_num($row->{$num_col}); | |||
| 239 | 826 | 381 | next unless defined $val; | |||
| 240 | 826 | 567 | next unless $val < $lo_fence || $val > $hi_fence; | |||
| 241 | 72 | 70 | push @outlier_rows, { val => $val, row => $row }; | |||
| 242 | } | |||||
| 243 | 66 | 45 | next unless @outlier_rows; | |||
| 244 | ||||||
| 245 | # Sort by distance from nearest fence, descending. | |||||
| 246 | @outlier_rows = sort { | |||||
| 247 | 57 | 41 | _fence_distance($b->{val}, $lo_fence, $hi_fence) <=> | |||
| 248 | 24 | 10 | _fence_distance($a->{val}, $lo_fence, $hi_fence) | |||
| 249 | } @outlier_rows; | |||||
| 250 | ||||||
| 251 | 57 | 46 | splice @outlier_rows, $MAX_OUTLIERS_PER_COL if @outlier_rows > $MAX_OUTLIERS_PER_COL; | |||
| 252 | ||||||
| 253 | # Build one insight per outlier. | |||||
| 254 | 57 | 85 | for my $o (@outlier_rows) { | |||
| 255 | 68 | 37 | my $val = $o->{val}; | |||
| 256 | 68 | 33 | my $row = $o->{row}; | |||
| 257 | ||||||
| 258 | # Build a human-readable group label. | |||||
| 259 | 68 | 32 | my $group_label = ''; | |||
| 260 | 68 | 42 | if (@$cat_cols) { | |||
| 261 | 48 | 19 | my @parts; | |||
| 262 | 48 | 24 | for my $c (@$cat_cols) { | |||
| 263 | 49 | 54 | push @parts, "$c=" . ($row->{$c} // ''); | |||
| 264 | } | |||||
| 265 | 48 | 37 | $group_label = join(', ', @parts); | |||
| 266 | } | |||||
| 267 | ||||||
| 268 | 68 | 43 | my $dir = $val > $hi_fence ? 'high' : 'low'; | |||
| 269 | 68 | 78 | my $headline = $group_label | |||
| 270 | ? "Unusual $num_col in $group_label: " . _fmt_num($val) . " is unusually $dir" | |||||
| 271 | : "Unusual $num_col value: " . _fmt_num($val) . " is unusually $dir"; | |||||
| 272 | ||||||
| 273 | 68 | 44 | my $detail = sprintf( | |||
| 274 | "Expected range %s \x{2013} %s (IQR fence on %d values)", | |||||
| 275 | _fmt_num($lo_fence), _fmt_num($hi_fence), scalar @nums | |||||
| 276 | ); | |||||
| 277 | ||||||
| 278 | # Build view_url: link to /bar for cat_cols, /stats otherwise. | |||||
| 279 | 68 | 47 | my $view_url; | |||
| 280 | 68 | 43 | if (@$cat_cols) { | |||
| 281 | 48 | 43 | my $cat = urlencode($cat_cols->[0]); | |||
| 282 | 48 | 22 | my $val_enc = urlencode($num_col); | |||
| 283 | 48 48 | 28 24 | $view_url = "/bar?l=${\urlencode($spec_key)}&cat=$cat&val=$val_enc&sort=value"; | |||
| 284 | } else { | |||||
| 285 | 20 | 19 | $view_url = "/stats?l=" . urlencode($spec_key); | |||
| 286 | } | |||||
| 287 | ||||||
| 288 | # Build drill_url: data table filtered to category group so the | |||||
| 289 | # outlier row is visible in context of its peers. The hl_col / | |||||
| 290 | # hl_op / hl_val params tell dashboard.html.tt to highlight and | |||||
| 291 | # scroll to the specific outlier row(s) within those 75+ peers. | |||||
| 292 | 68 | 43 | my $drill_url; | |||
| 293 | 68 | 40 | if (@$cat_cols) { | |||
| 294 | 48 | 41 | my $base = _spec_to_data_url($spec_key); | |||
| 295 | 48 | 34 | if ($base) { | |||
| 296 | 47 | 34 | my $cat_enc = urlencode($cat_cols->[0]); | |||
| 297 | 47 | 59 | my $gval = (split /\x00/, $key)[0] // ''; | |||
| 298 | 47 | 31 | my $gv_enc = urlencode($gval); | |||
| 299 | 47 | 48 | my $sep = ($base =~ /\?/) ? '&' : '?'; | |||
| 300 | 47 | 25 | $drill_url = $base . $sep . 'f=' . $cat_enc . ':eq:' . $gv_enc; | |||
| 301 | # Highlight the outlier row(s): beyond the IQR fence. | |||||
| 302 | 47 | 38 | my $hl_op = ($val > $hi_fence) ? 'gt' : 'lt'; | |||
| 303 | 47 | 31 | my $hl_fence = ($val > $hi_fence) ? $hi_fence : $lo_fence; | |||
| 304 | 47 | 22 | $drill_url .= '&hl_col=' . urlencode($num_col) | |||
| 305 | . '&hl_op=' . $hl_op | |||||
| 306 | . '&hl_val=' . urlencode(sprintf('%.10g', $hl_fence)); | |||||
| 307 | 47 | 31 | if ($base_url) { | |||
| 308 | 44 | 33 | $drill_url .= '&back2=' . urlencode($base_url) | |||
| 309 | . '&back2_label=Back+to+insights'; | |||||
| 310 | } | |||||
| 311 | } | |||||
| 312 | } | |||||
| 313 | ||||||
| 314 | 68 | 185 | push @insights, { | |||
| 315 | kind => 'outlier', | |||||
| 316 | headline => $headline, | |||||
| 317 | detail => $detail, | |||||
| 318 | view_url => $view_url, | |||||
| 319 | ($drill_url ? (drill_url => $drill_url) : ()), | |||||
| 320 | method => 'iqr_fence', | |||||
| 321 | }; | |||||
| 322 | } | |||||
| 323 | } | |||||
| 324 | ||||||
| 325 | 111 | 256 | return @insights; | |||
| 326 | } | |||||
| 327 | ||||||
| 328 | sub _fence_distance { | |||||
| 329 | 57 | 1875 | my ($val, $lo, $hi) = @_; | |||
| 330 | 57 | 47 | return $val > $hi ? $val - $hi | |||
| 331 | : $val < $lo ? $lo - $val | |||||
| 332 | : 0; | |||||
| 333 | } | |||||
| 334 | ||||||
| 335 | # _period_over_period($records, $date_col, $num_col, $spec_key, $base_url) -> @insights | |||||
| 336 | # | |||||
| 337 | # Aggregates $num_col by year-month period, then reports the delta between the | |||||
| 338 | # most recent two periods. | |||||
| 339 | sub _period_over_period { | |||||
| 340 | 79 | 5829 | my ($records, $date_col, $num_col, $spec_key, $base_url) = @_; | |||
| 341 | ||||||
| 342 | 79 | 93 | my %period_totals; | |||
| 343 | 79 | 51 | for my $row (@$records) { | |||
| 344 | 802 | 403 | my $date = $row->{$date_col} // ''; | |||
| 345 | 802 | 530 | next unless $date =~ /\A(\d{4}-\d{2})/; | |||
| 346 | 770 | 323 | my $period = $1; | |||
| 347 | 770 | 321 | my $val = _to_num($row->{$num_col}); | |||
| 348 | 770 | 385 | next unless defined $val; | |||
| 349 | 768 | 401 | $period_totals{$period} += $val; | |||
| 350 | } | |||||
| 351 | ||||||
| 352 | 79 | 588 | my @periods = sort keys %period_totals; | |||
| 353 | 79 | 78 | return () unless @periods >= $MIN_PERIODS_POP; | |||
| 354 | ||||||
| 355 | 31 | 53 | my $cur = $periods[-1]; | |||
| 356 | 31 | 19 | my $prev = $periods[-2]; | |||
| 357 | 31 | 17 | my $cur_val = $period_totals{$cur}; | |||
| 358 | 31 | 17 | my $prev_val = $period_totals{$prev}; | |||
| 359 | ||||||
| 360 | 31 | 21 | my $delta = $cur_val - $prev_val; | |||
| 361 | 31 | 42 | my $pct = $prev_val != 0 ? $delta / abs($prev_val) * 100 : undef; | |||
| 362 | ||||||
| 363 | 31 | 29 | my $dir = $delta >= 0 ? 'up' : 'down'; | |||
| 364 | 31 | 22 | my $sign = $delta >= 0 ? '+' : ''; | |||
| 365 | ||||||
| 366 | 31 | 28 | my $headline = sprintf('%s is %s %s vs prior period (%s)', | |||
| 367 | $num_col, $dir, _fmt_num(abs($delta)), $prev); | |||||
| 368 | ||||||
| 369 | 31 | 27 | my $detail = defined $pct | |||
| 370 | ? sprintf('%s: %s %s: %s (%s%s%%)', | |||||
| 371 | $prev, _fmt_num($prev_val), $cur, _fmt_num($cur_val), | |||||
| 372 | $sign, sprintf('%.1f', $pct)) | |||||
| 373 | : sprintf('%s: %s %s: %s', | |||||
| 374 | $prev, _fmt_num($prev_val), $cur, _fmt_num($cur_val)); | |||||
| 375 | ||||||
| 376 | 31 | 26 | my $enc_spec = urlencode($spec_key); | |||
| 377 | 31 | 27 | my $enc_date = urlencode($date_col); | |||
| 378 | 31 | 27 | my $enc_num = urlencode($num_col); | |||
| 379 | 31 | 26 | my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num"; | |||
| 380 | ||||||
| 381 | # Drill into the data table filtered to the current period. | |||||
| 382 | 31 | 13 | my $drill_url; | |||
| 383 | 31 | 25 | my $base = _spec_to_data_url($spec_key); | |||
| 384 | 31 | 28 | if ($base) { | |||
| 385 | 29 | 38 | my $sep = ($base =~ /\?/) ? '&' : '?'; | |||
| 386 | 29 | 28 | $drill_url = $base . $sep | |||
| 387 | . 'f=' . $enc_date . ':starts:' . urlencode($cur); | |||||
| 388 | 29 | 26 | if ($base_url) { | |||
| 389 | 24 | 74 | $drill_url .= '&back2=' . urlencode($base_url) | |||
| 390 | . '&back2_label=Back+to+insights'; | |||||
| 391 | } | |||||
| 392 | } | |||||
| 393 | ||||||
| 394 | return ({ | |||||
| 395 | 31 | 105 | kind => 'period_delta', | |||
| 396 | headline => $headline, | |||||
| 397 | detail => $detail, | |||||
| 398 | view_url => $view_url, | |||||
| 399 | ($drill_url ? (drill_url => $drill_url) : ()), | |||||
| 400 | method => 'pop_delta', | |||||
| 401 | }); | |||||
| 402 | } | |||||
| 403 | ||||||
| 404 | # _top_movers($records, $date_col, $num_col, \@cat_cols, $spec_key, $base_url) -> @insights | |||||
| 405 | # | |||||
| 406 | # For each categorical group, compute period-over-period delta between the two | |||||
| 407 | # most recent periods, and report the top MAX_TOP_MOVERS movers. | |||||
| 408 | sub _top_movers { | |||||
| 409 | 74 | 4826 | my ($records, $date_col, $num_col, $cat_cols, $spec_key, $base_url) = @_; | |||
| 410 | 74 | 99 | return () unless @$cat_cols; | |||
| 411 | ||||||
| 412 | # Collect totals keyed by (period, group_key). | |||||
| 413 | 68 | 57 | my (%totals, %group_labels); | |||
| 414 | 68 | 0 | my %all_periods; | |||
| 415 | 68 | 49 | for my $row (@$records) { | |||
| 416 | 791 | 372 | my $date = $row->{$date_col} // ''; | |||
| 417 | 791 | 492 | next unless $date =~ /\A(\d{4}-\d{2})/; | |||
| 418 | 770 | 299 | my $period = $1; | |||
| 419 | 770 | 332 | $all_periods{$period}++; | |||
| 420 | 770 1226 | 310 694 | my $gkey = join("\x00", map { $row->{$_} // '' } @$cat_cols); | |||
| 421 | 770 | 364 | my $val = _to_num($row->{$num_col}); | |||
| 422 | 770 | 379 | next unless defined $val; | |||
| 423 | 770 | 353 | $totals{$period}{$gkey} += $val; | |||
| 424 | 770 714 | 479 547 | $group_labels{$gkey} //= join(', ', map { $row->{$_} // '' } @$cat_cols); | |||
| 425 | } | |||||
| 426 | ||||||
| 427 | 68 | 85 | my @periods = sort keys %all_periods; | |||
| 428 | 68 | 60 | return () unless @periods >= $MIN_PERIODS_POP; | |||
| 429 | ||||||
| 430 | 23 | 32 | my $cur = $periods[-1]; | |||
| 431 | 23 | 63 | my $prev = $periods[-2]; | |||
| 432 | ||||||
| 433 | 23 | 11 | my (@movers); | |||
| 434 | 23 | 19 | for my $gkey (keys %group_labels) { | |||
| 435 | 64 | 53 | my $cur_val = $totals{$cur}{$gkey} // 0; | |||
| 436 | 64 | 37 | my $prev_val = $totals{$prev}{$gkey} // 0; | |||
| 437 | 64 | 34 | my $delta = $cur_val - $prev_val; | |||
| 438 | 64 | 70 | push @movers, { gkey => $gkey, label => $group_labels{$gkey}, | |||
| 439 | delta => $delta, cur => $cur_val, prev => $prev_val }; | |||||
| 440 | } | |||||
| 441 | ||||||
| 442 | 23 | 19 | return () unless @movers; | |||
| 443 | ||||||
| 444 | # Sort by absolute delta descending. | |||||
| 445 | 23 76 | 22 46 | @movers = sort { abs($b->{delta}) <=> abs($a->{delta}) } @movers; | |||
| 446 | 23 | 17 | splice @movers, $MAX_TOP_MOVERS if @movers > $MAX_TOP_MOVERS; | |||
| 447 | ||||||
| 448 | 23 | 42 | my $cat_col = $cat_cols->[0]; | |||
| 449 | 23 | 17 | my $enc_spec = urlencode($spec_key); | |||
| 450 | 23 | 15 | my $enc_date = urlencode($date_col); | |||
| 451 | 23 | 21 | my $enc_num = urlencode($num_col); | |||
| 452 | 23 | 13 | my $enc_cat = urlencode($cat_col); | |||
| 453 | ||||||
| 454 | 23 | 10 | my @insights; | |||
| 455 | 23 | 18 | for my $m (@movers) { | |||
| 456 | 56 | 46 | my $dir = $m->{delta} >= 0 ? 'up' : 'down'; | |||
| 457 | 56 | 29 | my $sign = $m->{delta} >= 0 ? '+' : ''; | |||
| 458 | my $headline = sprintf('%s %s %s by %s from %s to %s', | |||||
| 459 | 56 | 51 | $m->{label}, $num_col, $dir, _fmt_num(abs($m->{delta})), $prev, $cur); | |||
| 460 | my $detail = sprintf('%s: %s %s: %s', | |||||
| 461 | 56 | 32 | $prev, _fmt_num($m->{prev}), $cur, _fmt_num($m->{cur})); | |||
| 462 | ||||||
| 463 | # Encode the group value for the filter. | |||||
| 464 | 56 | 55 | my $gval_enc = urlencode((split /\x00/, $m->{gkey})[0] // ''); | |||
| 465 | 56 | 44 | my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num" | |||
| 466 | . "&f=$enc_cat:eq:$gval_enc"; | |||||
| 467 | ||||||
| 468 | # Drill into data table filtered to category + current period. | |||||
| 469 | 56 | 30 | my $drill_url; | |||
| 470 | 56 | 28 | my $base = _spec_to_data_url($spec_key); | |||
| 471 | 56 | 35 | if ($base) { | |||
| 472 | 55 | 44 | my $sep = ($base =~ /\?/) ? '&' : '?'; | |||
| 473 | 55 | 33 | $drill_url = $base . $sep | |||
| 474 | . 'f=' . $enc_date . ':starts:' . urlencode($cur) | |||||
| 475 | . '&f=' . $enc_cat . ':eq:' . $gval_enc; | |||||
| 476 | 55 | 38 | if ($base_url) { | |||
| 477 | 53 | 30 | $drill_url .= '&back2=' . urlencode($base_url) | |||
| 478 | . '&back2_label=Back+to+insights'; | |||||
| 479 | } | |||||
| 480 | } | |||||
| 481 | ||||||
| 482 | 56 | 92 | push @insights, { | |||
| 483 | kind => 'top_mover', | |||||
| 484 | headline => $headline, | |||||
| 485 | detail => $detail, | |||||
| 486 | view_url => $view_url, | |||||
| 487 | ($drill_url ? (drill_url => $drill_url) : ()), | |||||
| 488 | method => 'top_mover', | |||||
| 489 | }; | |||||
| 490 | } | |||||
| 491 | ||||||
| 492 | 23 | 80 | return @insights; | |||
| 493 | } | |||||
| 494 | ||||||
| 495 | # _seasonality($records, $date_col, $num_col, $spec_key, $base_url) -> @insights | |||||
| 496 | # | |||||
| 497 | # Computes period sums (year-month), then calculates the lag-1 autocorrelation | |||||
| 498 | # coefficient on the sequence of sums. A coefficient >= SEASON_R_THRESHOLD | |||||
| 499 | # is flagged as seasonal. | |||||
| 500 | # | |||||
| 501 | # Autocorrelation formula: | |||||
| 502 | # r(1) = sum_{t=1}^{n-1}[(x_t - xbar)(x_{t+1} - xbar)] / sum_{t=0}^{n-1}[(x_t - xbar)^2] | |||||
| 503 | # | |||||
| 504 | # This is the Pearson correlation between the series and itself shifted by one | |||||
| 505 | # period. For a regular, evenly-spaced time series this is the lag-1 Moran | |||||
| 506 | # coefficient. With uneven spacing it is an approximation, but adequate for | |||||
| 507 | # detecting year-over-year periodicity in monthly business data. | |||||
| 508 | sub _seasonality { | |||||
| 509 | 74 | 4140 | my ($records, $date_col, $num_col, $spec_key, $base_url) = @_; | |||
| 510 | ||||||
| 511 | 74 | 73 | my %period_totals; | |||
| 512 | 74 | 56 | for my $row (@$records) { | |||
| 513 | 863 | 408 | my $date = $row->{$date_col} // ''; | |||
| 514 | 863 | 544 | next unless $date =~ /\A(\d{4}-\d{2})/; | |||
| 515 | 833 | 330 | my $period = $1; | |||
| 516 | 833 | 397 | my $val = _to_num($row->{$num_col}); | |||
| 517 | 833 | 441 | next unless defined $val; | |||
| 518 | 833 | 394 | $period_totals{$period} += $val; | |||
| 519 | } | |||||
| 520 | ||||||
| 521 | 74 | 95 | my @periods = sort keys %period_totals; | |||
| 522 | 74 | 69 | return () unless @periods >= $MIN_PERIODS_SEASON; | |||
| 523 | ||||||
| 524 | 24 282 | 38 112 | my @y = map { $period_totals{$_} } @periods; | |||
| 525 | 24 | 13 | my $n = scalar @y; | |||
| 526 | 24 | 3483 | my $ybar = (sum(@y)) / $n; | |||
| 527 | ||||||
| 528 | 24 | 13 | my $num = 0; | |||
| 529 | 24 | 14 | my $denom = 0; | |||
| 530 | 24 | 26 | for my $i (0 .. $n - 1) { | |||
| 531 | 282 | 112 | my $dev = $y[$i] - $ybar; | |||
| 532 | 282 | 84 | $denom += $dev * $dev; | |||
| 533 | 282 | 169 | $num += $dev * ($y[$i + 1] - $ybar) if $i < $n - 1; | |||
| 534 | } | |||||
| 535 | ||||||
| 536 | 24 | 27 | return () unless $denom > 0; | |||
| 537 | 22 | 13 | my $r = $num / $denom; | |||
| 538 | ||||||
| 539 | 22 | 21 | return () unless $r >= $SEASON_R_THRESHOLD; | |||
| 540 | ||||||
| 541 | 4 | 23 | my $headline = sprintf('%s shows a repeating period-over-period pattern (r=%.2f)', | |||
| 542 | $num_col, $r); | |||||
| 543 | 4 | 6 | my $detail = sprintf( | |||
| 544 | 'Lag-1 autocorrelation %.2f across %d periods (%s to %s)', | |||||
| 545 | $r, $n, $periods[0], $periods[-1] | |||||
| 546 | ); | |||||
| 547 | ||||||
| 548 | 4 | 7 | my $enc_spec = urlencode($spec_key); | |||
| 549 | 4 | 5 | my $enc_date = urlencode($date_col); | |||
| 550 | 4 | 5 | my $enc_num = urlencode($num_col); | |||
| 551 | 4 | 4 | my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num"; | |||
| 552 | ||||||
| 553 | return ({ | |||||
| 554 | 4 | 15 | kind => 'seasonality', | |||
| 555 | headline => $headline, | |||||
| 556 | detail => $detail, | |||||
| 557 | view_url => $view_url, | |||||
| 558 | method => 'autocorr', | |||||
| 559 | }); | |||||
| 560 | } | |||||
| 561 | ||||||
| 562 | # _fmt_num($n) -> $string | |||||
| 563 | # Format a number to 4 significant figures, stripping trailing zeros. | |||||
| 564 | sub _fmt_num { | |||||
| 565 | 482 | 2237 | my $n = shift; | |||
| 566 | 482 | 240 | return 'N/A' unless defined $n; | |||
| 567 | 480 | 651 | return sprintf('%s', $n) if $n == int($n) && abs($n) < 1e12; | |||
| 568 | 80 | 231 | return sprintf('%s', 0 + sprintf('%.4g', $n)); | |||
| 569 | } | |||||
| 570 | ||||||
| 571 | ||||||
| 572 | # _spec_to_data_url($spec_key) -> $url_or_undef | |||||
| 573 | # | |||||
| 574 | # Converts a l= spec key to the root-relative URL of the data table page. | |||||
| 575 | # table:sales -> /view/sales | |||||
| 576 | # path:/abs/path/f.csv -> /open?path=%2Fabs%2Fpath%2Ff.csv | |||||
| 577 | # Returns undef for unrecognised spec forms. | |||||
| 578 | sub _spec_to_data_url { | |||||
| 579 | 151 | 2889 | my $spec = shift // ''; | |||
| 580 | 151 | 119 | if ($spec =~ /\Atable:(.+)\z/) { | |||
| 581 | 62 | 38 | return '/view/' . urlencode($1); | |||
| 582 | } | |||||
| 583 | 89 | 81 | if ($spec =~ /\Apath:(.+)\z/) { | |||
| 584 | 75 | 70 | require Database::BI::Model::DataSource; | |||
| 585 | 75 | 56 | my ($file, $internal) = Database::BI::Model::DataSource::split_path($1); | |||
| 586 | 75 | 50 | return '/open?path=' . urlencode($file) . (defined $internal ? '&it=' . urlencode($internal) : ''); | |||
| 587 | } | |||||
| 588 | 14 | 15 | return undef; | |||
| 589 | } | |||||
| 590 | ||||||
| 591 | 1; | |||||
| 592 | ||||||