Skip to content
Closed
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,119 @@
/*
Benchmark results (2026-12-02): manual deserialization took 22-31% less time and
allocated 20-26% fewer bytes than the converter/DTO path. Both scaled approximately
linearly: from 50 to 1,000 ordinates (20x), time grew 19.6x/19.7x and allocations
grew 18.8x/19.0x for converter/manual, respectively.

Mean deserialization time per complete collection:
Ordinates | Converter (us) | Manual (us) | Saved (us) | Reduction
10 | 10.068 | 6.972 | 3.096 | 30.7%
50 | 43.960 | 33.793 | 10.167 | 23.1%
100 | 87.653 | 68.255 | 19.398 | 22.1%
1,000 | 861.161 | 665.937 | 195.224 | 22.7%

Managed bytes allocated per deserialization (not peak memory usage):
Ordinates | Converter | Manual | Saved | Reduction
10 | 4,560 | 3,384 | 1,176 | 25.8%
50 | 19,264 | 15,256 | 4,008 | 20.8%
100 | 37,736 | 30,256 | 7,480 | 19.8%
1,000 | 361,680 | 289,336 | 72,344 | 20.0%

Serialization has a different tradeoff. At 1,000 ordinates, manual writing took
372.252 us versus 419.043 us (11.2% less time), but allocated 272,023 versus
184,319 bytes (47.6% more). Its allocation benefit applies to deserialization.

Environment: BenchmarkDotNet 0.15.8, .NET 10.0.9 x64, Windows 11, AMD EPYC 9654
(8 logical cores exposed). Release build; one launch, five warmup iterations,
fifteen measured iterations per case, with BenchmarkDotNet's outlier filtering.
Inputs: valid ascending Normal-distribution curves with default tail validation.
Both readers receive identical prebuilt JSON; reconstruction and full validation
are timed, while fixture creation and equivalence checks are excluded. These are
warmed measurements for this distribution type, not cold-start or universal results.
Raw results: BenchmarkDotNet.Artifacts/uopd-manual-vs-converter-20261202/results/
*/
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Exporters;
using Numerics.Data;
using Numerics.Distributions;

namespace Benchmarks_Numerics.Serialization
{
/// <summary>
/// Compares manual and converter-based JSON persistence of valid uncertain paired data.
/// </summary>
[MemoryDiagnoser]
[JsonExporterAttribute.Full]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
[SimpleJob(launchCount: 1, warmupCount: 5, iterationCount: 15)]
public class UncertainPairedDataManualJsonBenchmarks
{
private UncertainOrderedPairedData _data = null!;
private string _json = null!;

/// <summary>The number of uncertain ordinates in each collection.</summary>
[Params(10, 50, 100, 1000)]
public int OrdinateCount { get; set; }

/// <summary>
/// Creates identical input for both readers and verifies their reconstructed values before measurement.
/// </summary>
[GlobalSetup]
public void Setup()
{
_data = new UncertainOrderedPairedData(true, SortOrder.Ascending, true, SortOrder.Ascending,
UnivariateDistributionType.Normal, capacity: OrdinateCount);
for (int i = 0; i < OrdinateCount; i++)
_data.Add(new UncertainOrdinate(i, new Normal(10d * i, 1)));

_json = JsonSerializer.Serialize(_data);
if (_json != _data.ToJson())
throw new InvalidOperationException("Serialization paths produced different JSON.");

Verify(JsonSerializer.Deserialize<UncertainOrderedPairedData>(_json));
Verify(UncertainOrderedPairedData.FromJson(_json));
}

/// <summary>Reads the prepared JSON string using the attributed collection converter and DTOs.</summary>
/// <returns>The reconstructed collection.</returns>
[Benchmark(Baseline = true)]
[BenchmarkCategory("Deserialize")]
public UncertainOrderedPairedData? ConverterDeserialize() => JsonSerializer.Deserialize<UncertainOrderedPairedData>(_json);

/// <summary>Reads the same JSON string directly into the collection without DTOs.</summary>
/// <returns>The reconstructed collection.</returns>
[Benchmark]
[BenchmarkCategory("Deserialize")]
public UncertainOrderedPairedData? ManualDeserialize() => UncertainOrderedPairedData.FromJson(_json);

/// <summary>Writes a JSON string using the attributed collection converter and DTOs.</summary>
/// <returns>The serialized collection.</returns>
[Benchmark(Baseline = true)]
[BenchmarkCategory("Serialize")]
public string ConverterSerialize() => JsonSerializer.Serialize(_data);

/// <summary>Writes a JSON string directly without DTOs.</summary>
/// <returns>The serialized collection.</returns>
[Benchmark]
[BenchmarkCategory("Serialize")]
public string ManualSerialize() => _data.ToJson();

private void Verify(UncertainOrderedPairedData? restored)
{
if (restored is null || restored.Count != OrdinateCount || !restored.IsValid
|| !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("Deserialized collection settings or validity differ.");

for (int i = 0; i < OrdinateCount; i++)
{
var ordinate = restored[i];
if (ordinate.X != i || !ordinate.IsValid || ordinate.Y is not Normal normal || normal.Mu != 10d * i || normal.Sigma != 1)
throw new InvalidOperationException("Deserialized ordinate values differ.");
}
}
}
}
232 changes: 232 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 @@ -34,6 +37,7 @@ public class UncertainOrderedPairedData : IList<UncertainOrdinate>, INotifyColle
private bool _isValid = true;
private bool _allowDifferentDistributionTypes = false;
private double _validationTailProbability = double.NaN;
private static readonly UnivariateDistributionConverter _jsonDistributionConverter = new UnivariateDistributionConverter();

/// <summary>
/// Gets or sets whether to allow different distribution types in the list.
Expand Down Expand Up @@ -845,6 +849,234 @@ IEnumerator IEnumerable.GetEnumerator()
return _uncertainOrdinates.GetEnumerator();
}

/// <summary>
/// Writes the ordinates and validation settings as JSON without DTOs or serialization attributes.
/// </summary>
/// <returns>The JSON object representing this collection.</returns>
/// <remarks>
/// Uses the same format as <see cref="UncertainOrderedPairedDataConverter"/> with default serializer options:
/// property names are case-sensitive, enums are numeric, and non-finite X values and the default NaN tail
/// probability are strings. Distributions use <see cref="UnivariateDistributionConverter"/> explicitly.
/// Computed validity and collection notification state are omitted.
/// </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));
WriteJsonDouble(writer, ValidationTailProbability);
writer.WriteStartArray("Ordinates");
for (int i = 0; i < Count; i++)
{
var ordinate = _uncertainOrdinates[i];
writer.WriteStartObject();
writer.WritePropertyName(nameof(UncertainOrdinate.X));
WriteJsonDouble(writer, ordinate.X);
writer.WritePropertyName(nameof(UncertainOrdinate.Y));
if (ordinate.Y is null)
writer.WriteNullValue();
else
_jsonDistributionConverter.Write(writer, ordinate.Y, JsonSerializerOptions.Default);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.GetBuffer(), 0, checked((int)stream.Length));
}

/// <summary>
/// Reads JSON directly into a collection and recomputes validity after loading.
/// </summary>
/// <param name="json">The JSON object to read, or the JSON literal null.</param>
/// <returns>The reconstructed collection, or null for the JSON literal null.</returns>
/// <exception cref="ArgumentNullException"><paramref name="json"/> is null.</exception>
/// <exception cref="JsonException">The JSON is malformed, required properties are missing, a Y distribution is null, or the tail probability is invalid.</exception>
/// <remarks>
/// Reads the default format written by <see cref="ToJson"/> or <see cref="UncertainOrderedPairedDataConverter"/>.
/// Properties may appear in any order. Unknown properties are skipped; repeated properties use the last value.
/// Ordinates are appended directly to the collection without an intermediate DTO collection or per-add validation.
/// Distribution reconstruction uses <see cref="UnivariateDistributionConverter"/> explicitly.
/// </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 collection 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 collection object.");

var result = new UncertainOrderedPairedData(false, SortOrder.None, false, SortOrder.None, UnivariateDistributionType.Deterministic);
int propertiesRead = 0;
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected a collection property.");
// Each required property has one bit so missing properties cannot silently use defaults.
int property = reader.ValueTextEquals(nameof(StrictX)) ? 1
: reader.ValueTextEquals(nameof(StrictY)) ? 2
: reader.ValueTextEquals(nameof(OrderX)) ? 4
: reader.ValueTextEquals(nameof(OrderY)) ? 8
: reader.ValueTextEquals(nameof(Distribution)) ? 16
: reader.ValueTextEquals(nameof(AllowDifferentDistributionTypes)) ? 32
: reader.ValueTextEquals(nameof(ValidationTailProbability)) ? 64
: reader.ValueTextEquals("Ordinates") ? 128 : 0;
if (!reader.Read()) throw new JsonException("Expected a collection property value.");
switch (property)
{
case 1: result._strictX = ReadJsonBoolean(ref reader); break;
case 2: result._strictY = ReadJsonBoolean(ref reader); break;
case 4: result._orderX = (SortOrder)ReadJsonInt32(ref reader); break;
case 8: result._orderY = (SortOrder)ReadJsonInt32(ref reader); break;
case 16: result.Distribution = (UnivariateDistributionType)ReadJsonInt32(ref reader); break;
case 32: result._allowDifferentDistributionTypes = ReadJsonBoolean(ref reader); break;
case 64: result._validationTailProbability = ReadJsonDouble(ref reader); break;
case 128: ReadJsonOrdinates(ref reader, result._uncertainOrdinates); break;
default: reader.Skip(); break;
}
propertiesRead |= property;
}
if (reader.TokenType != JsonTokenType.EndObject || propertiesRead != 255)
throw new JsonException("All collection settings and Ordinates are required.");
if (reader.Read()) throw new JsonException("Unexpected content after the collection.");
try
{
UncertainOrdinate.ValidateTailProbability(result._validationTailProbability);
}
catch (ArgumentOutOfRangeException exception)
{
throw new JsonException("Invalid validation tail probability.", exception);
}
result.Validate();
return result;
}

/// <summary>
/// Reads an ordinate array directly into collection storage.
/// </summary>
/// <param name="reader">The reader positioned at the array.</param>
/// <param name="ordinates">The destination list, whose contents are replaced.</param>
/// <exception cref="JsonException">The array or an ordinate is invalid.</exception>
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(ReadJsonOrdinate(ref reader));
}
throw new JsonException("Incomplete ordinate array.");
}

/// <summary>
/// Reads an ordinate and computes its validity through the existing constructor.
/// </summary>
/// <param name="reader">The reader positioned at the ordinate object.</param>
/// <returns>The reconstructed ordinate.</returns>
/// <exception cref="JsonException">The object is invalid, X or Y is missing, or Y cannot be reconstructed.</exception>
private static UncertainOrdinate ReadJsonOrdinate(ref Utf8JsonReader reader)
{
if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException("Expected an ordinate object.");
double x = 0;
UnivariateDistributionBase? y = null;
bool hasX = false;
bool hasY = false;
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected an ordinate property.");
bool isX = reader.ValueTextEquals(nameof(UncertainOrdinate.X));
bool isY = reader.ValueTextEquals(nameof(UncertainOrdinate.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("Each ordinate requires X and Y.");
if (y is null) throw new JsonException("Ordinate Y distribution cannot be null.");
return new UncertainOrdinate(x, y);
}

/// <summary>
/// Reads a JSON boolean without accepting strings or numbers.
/// </summary>
/// <param name="reader">The reader positioned at the value.</param>
/// <returns>The boolean value.</returns>
/// <exception cref="JsonException">The token is not a boolean.</exception>
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();
}

/// <summary>
/// Reads a numeric enum value without accepting strings or fractional numbers.
/// </summary>
/// <param name="reader">The reader positioned at the value.</param>
/// <returns>The integer value.</returns>
/// <exception cref="JsonException">The token is not a 32-bit integer.</exception>
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>
/// Reads a number or a named non-finite floating-point string.
/// </summary>
/// <param name="reader">The reader positioned at the value.</param>
/// <returns>The double value.</returns>
/// <exception cref="JsonException">The token is not a supported floating-point value.</exception>
private 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 named floating-point value.");
}

/// <summary>
/// Writes finite values as numbers and non-finite values as named strings.
/// </summary>
/// <param name="writer">The JSON writer.</param>
/// <param name="value">The value to write.</param>
private 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>
/// Converts the uncertain ordered paired data set to an XElement for saving to xml.
/// </summary>
Expand Down
Loading