Class optimization

This commit is contained in:
Miha
2024-10-27 16:11:08 -07:00
parent b2fcdda785
commit 6c67a0cf31
77 changed files with 2634 additions and 1455 deletions
+19 -10
View File
@@ -1,4 +1,4 @@
using System;
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
@@ -31,13 +31,15 @@ namespace QuanTAlib;
/// Note: Similar to MAPE but allows error cancellation
/// </remarks>
public class Mpe : AbstractBase
[SkipLocalsInit]
public sealed class Mpe : AbstractBase
{
private readonly CircularBuffer _actualBuffer;
private readonly CircularBuffer _predictedBuffer;
/// <param name="period">The number of points over which to calculate the MPE.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Mpe(int period)
{
if (period < 1)
@@ -53,12 +55,14 @@ public class Mpe : AbstractBase
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of points over which to calculate the MPE.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Mpe(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
@@ -66,6 +70,7 @@ public class Mpe : AbstractBase
_predictedBuffer.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
@@ -75,6 +80,13 @@ public class Mpe : AbstractBase
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double CalculatePercentageError(double actual, double predicted)
{
return actual != 0 ? (actual - predicted) / actual : 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(Input.IsNew);
@@ -89,19 +101,16 @@ public class Mpe : AbstractBase
double mpe = 0;
if (_actualBuffer.Count > 0)
{
var actualValues = _actualBuffer.GetSpan().ToArray();
var predictedValues = _predictedBuffer.GetSpan().ToArray();
ReadOnlySpan<double> actualValues = _actualBuffer.GetSpan();
ReadOnlySpan<double> predictedValues = _predictedBuffer.GetSpan();
double sumPercentageError = 0;
for (int i = 0; i < _actualBuffer.Count; i++)
for (int i = 0; i < actualValues.Length; i++)
{
if (actualValues[i] != 0)
{
sumPercentageError += (actualValues[i] - predictedValues[i]) / actualValues[i];
}
sumPercentageError += CalculatePercentageError(actualValues[i], predictedValues[i]);
}
mpe = sumPercentageError / _actualBuffer.Count;
mpe = sumPercentageError / actualValues.Length;
}
IsHot = _index >= WarmupPeriod;