MentionSpikes.psm1
|
Set-StrictMode -Version Latest function Get-MentionSpike { <# .SYNOPSIS Find spike days in a daily mentions CSV. .DESCRIPTION The CSV needs a header row with the columns date (yyyy-mm-dd) and mentions (a non-negative whole number, the count you exported from your listening tool); header matching is case-insensitive. Several rows for one date are summed. Days missing between the first and last date count as 0 mentions. Each day that has a full window of earlier days is compared with the mean and the population standard deviation of the previous -Window days. It is a spike when mentions > mean + Threshold * stddev and mentions > 0. When the standard deviation is 0, it is a spike only when mentions > mean. -Window (default 7) and -Threshold (default 2.0) are set by you. Returns one object with DaysCovered, StartDate, EndDate, TotalMentions, DailyAverage, HighestDay, HighestMentions, Spikes (Date, Mentions, WindowMean, WindowStdDev) and Report (the text report). Throws on a missing file, a bad date or count (the data row number is named), fewer days than Window + 1, or a bad Window or Threshold. Data rows are counted after the header, starting at 1. .EXAMPLE Get-MentionSpike -Path sample.csv #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Path, [int]$Window = 7, [double]$Threshold = 2.0 ) if ($Window -lt 1) { throw "bad Window: $Window (must be a whole number of at least 1)" } if ([double]::IsNaN($Threshold) -or [double]::IsInfinity($Threshold) -or $Threshold -lt 0) { throw "bad Threshold: $Threshold (must be a number of at least 0)" } if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "file not found: $Path" } $inv = [System.Globalization.CultureInfo]::InvariantCulture $rows = @(Import-Csv -LiteralPath $Path) if ($rows.Count -eq 0) { throw 'CSV has no data rows' } $names = @{} foreach ($p in $rows[0].PSObject.Properties.Name) { $names[$p.Trim().ToLowerInvariant()] = $p } foreach ($need in 'date', 'mentions') { if (-not $names.ContainsKey($need)) { throw "missing column: $need" } } $dateCol = $names['date'] $countCol = $names['mentions'] $byDay = New-Object 'System.Collections.Generic.Dictionary[datetime,long]' $n = 0 foreach ($r in $rows) { $n++ $dText = ([string]$r.PSObject.Properties[$dateCol].Value).Trim() $d = [datetime]::MinValue if (-not [datetime]::TryParseExact($dText, 'yyyy-MM-dd', $inv, [System.Globalization.DateTimeStyles]::None, [ref]$d)) { throw "row ${n}: bad date '$dText' (expected yyyy-mm-dd)" } $cText = ([string]$r.PSObject.Properties[$countCol].Value).Trim() $c = [long]0 if ($cText -notmatch '^[0-9]{1,15}$' -or -not [long]::TryParse($cText, [ref]$c)) { throw "row ${n}: bad mentions '$cText' (expected a non-negative whole number)" } if ($byDay.ContainsKey($d)) { $byDay[$d] += $c } else { $byDay[$d] = $c } } $first = [datetime]::MaxValue $last = [datetime]::MinValue foreach ($k in $byDay.Keys) { if ($k -lt $first) { $first = $k }; if ($k -gt $last) { $last = $k } } $days = [int](($last - $first).TotalDays) + 1 if ($days -lt ($Window + 1)) { throw "only $days day(s) of data, need at least $($Window + 1) (Window $Window plus one day to test)" } $series = New-Object 'long[]' $days for ($i = 0; $i -lt $days; $i++) { $day = $first.AddDays($i) if ($byDay.ContainsKey($day)) { $series[$i] = $byDay[$day] } } $total = [long]0 $hiIdx = 0 for ($i = 0; $i -lt $days; $i++) { $total += $series[$i] if ($series[$i] -gt $series[$hiIdx]) { $hiIdx = $i } } $avg = [double]$total / $days $spikes = New-Object System.Collections.Generic.List[object] for ($i = $Window; $i -lt $days; $i++) { $sum = [double]0 $sumSq = [double]0 for ($j = $i - $Window; $j -lt $i; $j++) { $sum += $series[$j]; $sumSq += [double]$series[$j] * $series[$j] } $mean = $sum / $Window $varNum = $Window * $sumSq - $sum * $sum # exact for whole numbers of this size; 0 when all equal if ($varNum -lt 0) { $varNum = 0 } $sd = [math]::Sqrt($varNum) / $Window $m = $series[$i] $isSpike = $false if ($m -gt 0) { if ($varNum -eq 0) { $isSpike = ($m -gt $mean) } else { $isSpike = ($m -gt ($mean + $Threshold * $sd)) } } if ($isSpike) { $spikes.Add([pscustomobject]@{ Date = $first.AddDays($i).ToString('yyyy-MM-dd', $inv) Mentions = $m WindowMean = [math]::Round($mean, 1, [System.MidpointRounding]::AwayFromZero) WindowStdDev = [math]::Round($sd, 1, [System.MidpointRounding]::AwayFromZero) }) } } $f1 = { param($v) ([math]::Round([double]$v, 1, [System.MidpointRounding]::AwayFromZero)).ToString('0.0', $inv) } $startText = $first.ToString('yyyy-MM-dd', $inv) $endText = $last.ToString('yyyy-MM-dd', $inv) $highText = $first.AddDays($hiIdx).ToString('yyyy-MM-dd', $inv) $lines = New-Object System.Collections.Generic.List[string] $lines.Add("Days covered: $days ($startText to $endText)") $lines.Add("Total mentions: $total") $lines.Add("Daily average: $(& $f1 $avg)") $lines.Add("Highest day: $highText ($($series[$hiIdx]))") $lines.Add("Window: $Window days, threshold: $(& $f1 $Threshold) standard deviations (set by you)") $lines.Add("Spikes: $($spikes.Count)") foreach ($s in $spikes) { $lines.Add(('{0} {1} window mean {2} stddev {3}' -f $s.Date, $s.Mentions, (& $f1 $s.WindowMean), (& $f1 $s.WindowStdDev))) } [pscustomobject]@{ DaysCovered = $days StartDate = $startText EndDate = $endText TotalMentions = $total DailyAverage = [math]::Round($avg, 1, [System.MidpointRounding]::AwayFromZero) HighestDay = $highText HighestMentions = $series[$hiIdx] Spikes = $spikes.ToArray() Report = ($lines -join [Environment]::NewLine) } } Export-ModuleMember -Function Get-MentionSpike |