Files

142 lines
4.5 KiB
C#
Raw Permalink Normal View History

2024-10-27 16:11:08 -07:00
using System.Runtime.CompilerServices;
2024-09-22 17:31:24 -07:00
namespace QuanTAlib;
2024-10-27 09:38:53 -07:00
/// <summary>
/// Convolution: A fundamental signal processing operation that combines two signals to form a third signal
/// Applies a custom kernel (weight array) to the input data through convolution, allowing for flexible
/// filtering operations. The kernel is automatically normalized to ensure consistent output scaling.
/// </summary>
/// <remarks>
/// Implementation:
/// Based on standard discrete convolution principles from signal processing
/// </remarks>
2024-09-22 17:31:24 -07:00
public class Convolution : AbstractBase
{
private readonly double[] _kernel;
private readonly int _kernelSize;
2024-10-06 14:44:43 -07:00
private readonly CircularBuffer _buffer;
private readonly double[] _normalizedKernel;
2024-10-27 16:11:08 -07:00
private int _activeLength;
2024-09-22 17:31:24 -07:00
2024-10-27 09:38:53 -07:00
/// <param name="kernel">Array of weights defining the convolution operation. The length of this array determines the filter's window size.</param>
/// <exception cref="ArgumentException">Thrown when kernel is null or empty.</exception>
2024-09-22 17:31:24 -07:00
public Convolution(double[] kernel)
{
if (kernel == null || kernel.Length == 0)
{
throw new ArgumentException("Kernel must not be null or empty.", nameof(kernel));
}
_kernel = kernel;
_kernelSize = kernel.Length;
_buffer = new CircularBuffer(_kernelSize);
_normalizedKernel = new double[_kernelSize];
Init();
}
2024-10-27 09:38:53 -07:00
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="kernel">Array of weights defining the convolution operation.</param>
2024-09-22 17:31:24 -07:00
public Convolution(object source, double[] kernel) : this(kernel)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-22 17:31:24 -07:00
private new void Init()
{
base.Init();
_buffer.Clear();
2024-10-27 16:11:08 -07:00
System.Array.Copy(_kernel, _normalizedKernel, _kernelSize);
_activeLength = 0;
2024-09-22 17:31:24 -07:00
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-22 17:31:24 -07:00
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
2024-10-27 16:11:08 -07:00
_activeLength = System.Math.Min(_index, _kernelSize);
2024-09-22 17:31:24 -07:00
}
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-22 17:31:24 -07:00
protected override double GetLastValid()
{
return _lastValidValue;
}
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
// Normalize kernel on each calculation until buffer is full
if (_index <= _kernelSize)
{
NormalizeKernel();
}
double result = ConvolveBuffer();
IsHot = _index >= _kernelSize;
return result;
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-22 17:31:24 -07:00
private void NormalizeKernel()
{
double sum = 0;
// Calculate the sum of the active kernel elements
2024-10-27 16:11:08 -07:00
for (int i = 0; i < _activeLength; i++)
2024-09-22 17:31:24 -07:00
{
sum += _kernel[i];
}
// Normalize the kernel or set equal weights if the sum is zero
2024-11-04 18:08:33 -08:00
double normalizationFactor = (sum >= double.Epsilon) ? sum : _activeLength;
2024-10-27 16:11:08 -07:00
double invNormFactor = 1.0 / normalizationFactor;
for (int i = 0; i < _activeLength; i++)
2024-09-22 17:31:24 -07:00
{
2024-10-27 16:11:08 -07:00
_normalizedKernel[i] = _kernel[i] * invNormFactor;
2024-09-22 17:31:24 -07:00
}
// Set the rest of the normalized kernel to zero
2024-10-27 16:11:08 -07:00
if (_activeLength < _kernelSize)
{
System.Array.Clear(_normalizedKernel, _activeLength, _kernelSize - _activeLength);
}
2024-09-22 17:31:24 -07:00
}
2024-10-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-22 17:31:24 -07:00
private double ConvolveBuffer()
{
double sum = 0;
var bufferSpan = _buffer.GetSpan();
2024-10-27 16:11:08 -07:00
int offset = _activeLength - 1;
// Unroll the loop for better performance when possible
int i = 0;
while (i <= offset - 3)
{
2024-11-03 23:03:24 +00:00
sum += (bufferSpan[offset - i] * _normalizedKernel[i]) +
(bufferSpan[offset - (i + 1)] * _normalizedKernel[i + 1]) +
(bufferSpan[offset - (i + 2)] * _normalizedKernel[i + 2]) +
(bufferSpan[offset - (i + 3)] * _normalizedKernel[i + 3]);
2024-10-27 16:11:08 -07:00
i += 4;
}
2024-09-22 17:31:24 -07:00
2024-10-27 16:11:08 -07:00
// Handle remaining elements
while (i < _activeLength)
2024-09-22 17:31:24 -07:00
{
2024-10-27 16:11:08 -07:00
sum += bufferSpan[offset - i] * _normalizedKernel[i];
i++;
2024-09-22 17:31:24 -07:00
}
return sum;
}
2024-10-27 09:38:53 -07:00
}