Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
Benchmark results, 2026-12-03: fully manual deserialization used 25-27% less time
and allocated 13-19% fewer bytes than the DTO path. Manual serialization had only
small timing gains at 100 and 1000 ordinates, with substantially more allocations.
Direct collection conversion did not consistently improve on the DTO. All three
strategies retain the existing distribution converter, list ownership, and validation.
DTO/direct use attributed ordinate serialization; manual reads/writes ordinates
directly and matches property names without allocating strings.

Mean time is elapsed microseconds per call; memory is managed bytes allocated per
call, not peak live memory. All columns are from the same 18-case benchmark run.

Operation | Ordinates | DTO us | Direct us | Manual us | DTO bytes | Direct bytes | Manual bytes
Deserialize | 10 | 9.797 | 10.119 | 7.190 | 5,184 | 5,512 | 4,184
Deserialize | 100 | 86.821 | 89.167 | 64.822 | 44,472 | 44,800 | 38,256
Deserialize | 1000 | 872.133 | 870.026 | 654.382 | 425,952 | 426,280 | 369,336
Serialize | 10 | 3.749 | 4.151 | 3.827 | 2,384 | 2,336 | 8,544
Serialize | 100 | 34.646 | 34.188 | 33.613 | 17,864 | 17,816 | 34,832
Serialize | 1000 | 392.166 | 393.864 | 377.407 | 176,295 | 176,247 | 272,023

Manual read savings versus DTO: 2.608/22.000/217.751 us (26.6/25.3/25.0%) and
1,000/6,216/56,616 bytes (19.3/14.0/13.3%) at 10/100/1000 ordinates. Manual write
time changes are +2.1/-3.0/-3.8%, with allocation increases of 258.4/95.0/54.3%.
The manual writer uses Utf8JsonWriter over MemoryStream, retaining writer/stream
buffers in addition to the returned string. The input UTF-8 byte array is included
in manual read allocations. There are no intermediate per-ordinate JSON strings.

Direct conversion saves 48 bytes on writing and adds 328 bytes on reading, where
it allocates outer property-name strings. At 1000 ordinates DTO/direct timing
confidence intervals overlap for both operations; manual/DTO write intervals also
overlap at 10. From 100 to 1000 ordinates, read time grows 9.8-10.1x and allocations
9.5-9.7x across strategies, consistent with linear scaling. Write time grows
11.2-11.5x, with Gen2 collections at 1000 ordinates for all three strategies.

BenchmarkDotNet 0.15.8; Release, .NET 10.0.9 x64, Windows 11; concurrent workstation
GC; one launch, five warmups, fifteen measurement iterations per case. CPU model
was not detected and the power plan could not be changed. These are warm-cache
microbenchmarks, not CPU-counter measurements. Fixture: X=i, Y=Normal(10*i,1),
strict ascending X/Y, default NaN tail probability. Valid curves require a full
validation pass. Each operation uses a JSON string; setup verifies identical JSON
and reconstruction outside the timed work. No benchmark runs overlap.

Run: dotnet run -c Release --project Benchmarks_Numerics -- --filter
'*UncertainPairedDataConverterBenchmarks*' --artifacts
BenchmarkDotNet.Artifacts/uopd-three-strategies
Raw reports: BenchmarkDotNet.Artifacts/uopd-three-strategies/results/
Benchmarks_Numerics.Serialization.UncertainPairedDataConverterBenchmarks-report-*
*/
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Exporters;
using Numerics.Data;
using Numerics.Distributions;
using Numerics.Utilities;

namespace Benchmarks_Numerics.Serialization
{
/// <summary>
/// Compares the collection DTO, direct converter, and fully manual JSON methods.
/// </summary>
[MemoryDiagnoser]
[JsonExporterAttribute.Full]
[SimpleJob(launchCount: 1, warmupCount: 5, iterationCount: 15)]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class UncertainPairedDataConverterBenchmarks
{
private readonly JsonSerializerOptions _dtoOptions = new();
private readonly JsonSerializerOptions _directOptions = new();
private UncertainOrderedPairedData _data = null!;
private string _json = string.Empty;

/// <summary>The number of normally distributed ordinates.</summary>
[Params(10, 100, 1000)]
public int Ordinates { get; set; }

/// <summary>
/// Creates valid curves and verifies identical JSON and reconstructed values outside the timed operations.
/// </summary>
[GlobalSetup]
public void Setup()
{
_dtoOptions.Converters.Add(new UncertainOrderedPairedDataConverter());
_directOptions.Converters.Add(new UncertainOrderedPairedDataDirectConverter());
var x = new double[Ordinates];
var y = new UnivariateDistributionBase[Ordinates];
for (int i = 0; i < Ordinates; i++)
{
x[i] = i;
y[i] = new Normal(i * 10, 1);
}
_data = new UncertainOrderedPairedData(x, y, true, SortOrder.Ascending,
true, SortOrder.Ascending, UnivariateDistributionType.Normal);
_json = JsonSerializer.Serialize(_data, _dtoOptions);
if (_json != JsonSerializer.Serialize(_data, _directOptions) || _json != _data.ToJson())
throw new InvalidOperationException("The strategies produced different JSON.");
foreach (var options in new[] { _dtoOptions, _directOptions })
{
ValidateRestored(JsonSerializer.Deserialize<UncertainOrderedPairedData>(_json, options));
}
ValidateRestored(UncertainOrderedPairedData.FromJson(_json));
}

private void ValidateRestored(UncertainOrderedPairedData? restored)
{
if (restored is null || !restored.IsValid || restored.Count != Ordinates || restored != _data
|| !restored.StrictX || !restored.StrictY || restored.OrderX != SortOrder.Ascending
|| restored.OrderY != SortOrder.Ascending || restored.Distribution != UnivariateDistributionType.Normal
|| restored.AllowDifferentDistributionTypes || !double.IsNaN(restored.ValidationTailProbability))
throw new InvalidOperationException("The reconstructed curve does not match the fixture.");
}

/// <summary>Serializes to a JSON string through the collection DTO.</summary>
/// <returns>The JSON string.</returns>
[Benchmark(Baseline = true), BenchmarkCategory("Serialize")]
public string SerializeDto() => JsonSerializer.Serialize(_data, _dtoOptions);

/// <summary>Serializes to a JSON string through direct property writes.</summary>
/// <returns>The JSON string.</returns>
[Benchmark, BenchmarkCategory("Serialize")]
public string SerializeDirect() => JsonSerializer.Serialize(_data, _directOptions);

/// <summary>Serializes through manual collection and ordinate writers.</summary>
/// <returns>The JSON string.</returns>
[Benchmark, BenchmarkCategory("Serialize")]
public string SerializeManual() => _data.ToJson();

/// <summary>Deserializes a JSON string through the collection DTO, including validation.</summary>
/// <returns>The reconstructed curve.</returns>
[Benchmark(Baseline = true), BenchmarkCategory("Deserialize")]
public UncertainOrderedPairedData? DeserializeDto() => JsonSerializer.Deserialize<UncertainOrderedPairedData>(_json, _dtoOptions);

/// <summary>Deserializes a JSON string through direct property reads, including validation.</summary>
/// <returns>The reconstructed curve.</returns>
[Benchmark, BenchmarkCategory("Deserialize")]
public UncertainOrderedPairedData? DeserializeDirect() => JsonSerializer.Deserialize<UncertainOrderedPairedData>(_json, _directOptions);

/// <summary>Deserializes through manual collection and ordinate readers, including validation.</summary>
/// <returns>The reconstructed curve.</returns>
[Benchmark, BenchmarkCategory("Deserialize")]
public UncertainOrderedPairedData? DeserializeManual() => UncertainOrderedPairedData.FromJson(_json);
}
}
130 changes: 130 additions & 0 deletions Numerics/Data/Paired Data/UncertainOrderedPairedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Linq;
using Numerics.Distributions;
Expand Down Expand Up @@ -390,6 +393,133 @@ public UncertainOrderedPairedData(XElement el)

#region Methods

/// <summary>
/// Serializes the collection directly to JSON, using the existing converter only for distributions.
/// </summary>
/// <returns>The JSON object containing ordinates and validation settings.</returns>
/// <remarks>Uses default property names, numeric enums, and named non-finite numbers. Serializer options are not applied.</remarks>
public string ToJson()
{
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream))
{
writer.WriteStartObject();
writer.WriteBoolean(nameof(StrictX), StrictX);
writer.WriteBoolean(nameof(StrictY), StrictY);
writer.WriteNumber(nameof(OrderX), (int)OrderX);
writer.WriteNumber(nameof(OrderY), (int)OrderY);
writer.WriteNumber(nameof(Distribution), (int)Distribution);
writer.WriteBoolean(nameof(AllowDifferentDistributionTypes), AllowDifferentDistributionTypes);
writer.WritePropertyName(nameof(ValidationTailProbability));
UncertainOrdinate.WriteJsonDouble(writer, ValidationTailProbability);
writer.WriteStartArray("Ordinates");
foreach (var ordinate in _uncertainOrdinates) ordinate.WriteJson(writer);
writer.WriteEndArray();
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.GetBuffer(), 0, checked((int)stream.Length));
}

/// <summary>
/// Deserializes the collection directly from JSON and validates it once.
/// </summary>
/// <param name="json">JSON containing ordinates and all validation settings.</param>
/// <returns>The reconstructed collection, or null for JSON null.</returns>
/// <exception cref="ArgumentNullException">The input string is null.</exception>
/// <exception cref="JsonException">JSON is malformed, required data is missing, Y is null, or a setting is invalid.</exception>
/// <remarks>Uses case-sensitive default property names and numeric enums; unknown properties are skipped.</remarks>
public static UncertainOrderedPairedData? FromJson(string json)
{
if (json is null) throw new ArgumentNullException(nameof(json));
var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json));
if (!reader.Read()) throw new JsonException("Expected a paired-data object.");
if (reader.TokenType == JsonTokenType.Null)
{
if (reader.Read()) throw new JsonException("Unexpected content after the collection.");
return null;
}
if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Expected a paired-data object.");
bool strictX = false, strictY = false, allowDifferentTypes = false;
SortOrder orderX = default, orderY = default;
UnivariateDistributionType distribution = default;
double tailProbability = double.NaN;
var ordinates = new List<UncertainOrdinate>();
int seen = 0;
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected a property name.");
int property = GetJsonPropertyFlag(ref reader);
if (!reader.Read()) throw new JsonException("Expected a property value.");
switch (property)
{
case 1: strictX = ReadJsonBoolean(ref reader); break;
case 2: strictY = ReadJsonBoolean(ref reader); break;
case 4: orderX = (SortOrder)ReadJsonInt32(ref reader); break;
case 8: orderY = (SortOrder)ReadJsonInt32(ref reader); break;
case 16: distribution = (UnivariateDistributionType)ReadJsonInt32(ref reader); break;
case 32: allowDifferentTypes = ReadJsonBoolean(ref reader); break;
case 64: tailProbability = UncertainOrdinate.ReadJsonDouble(ref reader); break;
case 128: ReadJsonOrdinates(ref reader, ordinates); break;
default: reader.Skip(); break;
}
seen |= property;
}
if (reader.TokenType != JsonTokenType.EndObject || seen != 255)
throw new JsonException("All paired-data settings and Ordinates are required.");
if (reader.Read()) throw new JsonException("Unexpected content after the collection.");
try
{
return new UncertainOrderedPairedData(ordinates, strictX, orderX, strictY, orderY,
distribution, allowDifferentTypes, tailProbability);
}
catch (ArgumentOutOfRangeException exception)
{
throw new JsonException("Invalid validation tail probability.", exception);
}
}

private static int GetJsonPropertyFlag(ref Utf8JsonReader reader)
{
if (reader.ValueTextEquals(nameof(StrictX))) return 1;
if (reader.ValueTextEquals(nameof(StrictY))) return 2;
if (reader.ValueTextEquals(nameof(OrderX))) return 4;
if (reader.ValueTextEquals(nameof(OrderY))) return 8;
if (reader.ValueTextEquals(nameof(Distribution))) return 16;
if (reader.ValueTextEquals(nameof(AllowDifferentDistributionTypes))) return 32;
if (reader.ValueTextEquals(nameof(ValidationTailProbability))) return 64;
if (reader.ValueTextEquals("Ordinates")) return 128;
return 0;
}

/// <summary>
/// Reads ordinates into their final list; a repeated property replaces earlier contents.
/// </summary>
private static void ReadJsonOrdinates(ref Utf8JsonReader reader, List<UncertainOrdinate> ordinates)
{
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Ordinates must be an array.");
ordinates.Clear();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndArray) return;
ordinates.Add(UncertainOrdinate.ReadJson(ref reader));
}
throw new JsonException("Incomplete ordinate array.");
}

private static bool ReadJsonBoolean(ref Utf8JsonReader reader)
{
if (reader.TokenType != JsonTokenType.True && reader.TokenType != JsonTokenType.False)
throw new JsonException("Expected a boolean.");
return reader.GetBoolean();
}

private static int ReadJsonInt32(ref Utf8JsonReader reader)
{
if (reader.TokenType != JsonTokenType.Number || !reader.TryGetInt32(out int value))
throw new JsonException("Expected a 32-bit integer.");
return value;
}

/// <summary>
/// Resets the event handling of the CollectionChanged event
/// </summary>
Expand Down
78 changes: 78 additions & 0 deletions Numerics/Data/Paired Data/UncertainOrdinate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,84 @@ public UncertainOrdinate(XElement xElement, UnivariateDistributionType distribut

#region Methods

private static readonly UnivariateDistributionConverter JsonDistributionConverter = new UnivariateDistributionConverter();

/// <summary>
/// Writes this ordinate directly to the collection's JSON writer.
/// </summary>
internal void WriteJson(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(X));
WriteJsonDouble(writer, X);
writer.WritePropertyName(nameof(Y));
if (Y is null)
writer.WriteNullValue();
else
JsonDistributionConverter.Write(writer, Y, JsonSerializerOptions.Default);
writer.WriteEndObject();
}

/// <summary>
/// Reads X and Y directly and computes ordinate validity.
/// </summary>
internal static UncertainOrdinate ReadJson(ref Utf8JsonReader reader)
{
if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Expected an ordinate object.");
double x = 0;
UnivariateDistributionBase? y = null;
bool hasX = false, hasY = false;
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected an ordinate property name.");
bool isX = reader.ValueTextEquals(nameof(X));
bool isY = reader.ValueTextEquals(nameof(Y));
if (!reader.Read()) throw new JsonException("Expected an ordinate property value.");
if (isX)
{
x = ReadJsonDouble(ref reader);
hasX = true;
}
else if (isY)
{
y = JsonDistributionConverter.Read(ref reader, typeof(UnivariateDistributionBase), JsonSerializerOptions.Default);
hasY = true;
}
else
reader.Skip();
}
if (reader.TokenType != JsonTokenType.EndObject || !hasX || !hasY)
throw new JsonException("Ordinate X and Y are required.");
if (y is null) throw new JsonException("Ordinate Y distribution cannot be null.");
return new UncertainOrdinate(x, y);
}

/// <summary>
/// Reads a numeric value or a named non-finite number.
/// </summary>
internal static double ReadJsonDouble(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.Number && reader.TryGetDouble(out double value)) return value;
if (reader.TokenType == JsonTokenType.String)
{
if (reader.ValueTextEquals("NaN")) return double.NaN;
if (reader.ValueTextEquals("Infinity")) return double.PositiveInfinity;
if (reader.ValueTextEquals("-Infinity")) return double.NegativeInfinity;
}
throw new JsonException("Expected a number or a named floating-point literal.");
}

/// <summary>
/// Writes non-finite numbers as their named string literals.
/// </summary>
internal static void WriteJsonDouble(Utf8JsonWriter writer, double value)
{
if (double.IsNaN(value)) writer.WriteStringValue("NaN");
else if (double.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity");
else if (double.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity");
else writer.WriteNumberValue(value);
}

/// <summary>
/// Recomputes validity after reading X and Y from JSON.
/// </summary>
Expand Down
Loading