-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataFrameExtensionsScan.cs
More file actions
44 lines (40 loc) · 2.29 KB
/
Copy pathDataFrameExtensionsScan.cs
File metadata and controls
44 lines (40 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Numerics;
using Microsoft.Data.Analysis;
namespace Dimension.DataFrameExtensions;
/// <summary>
/// Methods for adding stateful recursive-scan extension methods to make Microsoft's DataFrame a little more user-friendly.
/// </summary>
public static class DataFrameExtensionsScan
{
/// <summary>
/// Carries a state value row-to-row across a column, where each row's output state depends on the
/// previous row's output state (not just the previous row's input) — e.g. EMA, GARCH variance,
/// or any other recursive time-series update that a windowed <see cref="DataFrameExtensionsRolling.Rolling{T}(PrimitiveDataFrameColumn{T}, int, Func{IEnumerable{T?}, T})"/>
/// call cannot express, since it has no access to its own prior output.
/// </summary>
/// <typeparam name="T">Numeric type of the source column</typeparam>
/// <typeparam name="TState">Numeric type of the carried state / output column</typeparam>
/// <param name="column">Column to scan</param>
/// <param name="seed">Initial state, used as the carried state for row 0</param>
/// <param name="folder">Computes the next state from the current state and the current row's value</param>
/// <param name="name">Name of the result column; defaults to "{column.Name}_Scan"</param>
/// <returns>A column of the same length as <paramref name="column"/>, holding the state after each row</returns>
public static PrimitiveDataFrameColumn<TState> Scan<T, TState>(this PrimitiveDataFrameColumn<T> column,
TState seed,
Func<TState, T?, TState> folder,
string name = "")
where T : unmanaged, INumber<T>
where TState : unmanaged, INumber<TState>
{
var resultName = string.IsNullOrEmpty(name) ? column.Name + "_Scan" : name;
var result = new PrimitiveDataFrameColumn<TState>(resultName, column.Length);
var state = seed;
for (var i = 0; i < column.Length; i++)
{
state = folder(state, column[i]);
result[i] = state;
}
return result;
}
}