diff --git a/Benchmarks_Numerics/Serialization/UncertainPairedDataConverterBenchmarks.cs b/Benchmarks_Numerics/Serialization/UncertainPairedDataConverterBenchmarks.cs
new file mode 100644
index 00000000..6767672d
--- /dev/null
+++ b/Benchmarks_Numerics/Serialization/UncertainPairedDataConverterBenchmarks.cs
@@ -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
+{
+ ///
+ /// Compares the collection DTO, direct converter, and fully manual JSON methods.
+ ///
+ [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;
+
+ /// The number of normally distributed ordinates.
+ [Params(10, 100, 1000)]
+ public int Ordinates { get; set; }
+
+ ///
+ /// Creates valid curves and verifies identical JSON and reconstructed values outside the timed operations.
+ ///
+ [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(_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.");
+ }
+
+ /// Serializes to a JSON string through the collection DTO.
+ /// The JSON string.
+ [Benchmark(Baseline = true), BenchmarkCategory("Serialize")]
+ public string SerializeDto() => JsonSerializer.Serialize(_data, _dtoOptions);
+
+ /// Serializes to a JSON string through direct property writes.
+ /// The JSON string.
+ [Benchmark, BenchmarkCategory("Serialize")]
+ public string SerializeDirect() => JsonSerializer.Serialize(_data, _directOptions);
+
+ /// Serializes through manual collection and ordinate writers.
+ /// The JSON string.
+ [Benchmark, BenchmarkCategory("Serialize")]
+ public string SerializeManual() => _data.ToJson();
+
+ /// Deserializes a JSON string through the collection DTO, including validation.
+ /// The reconstructed curve.
+ [Benchmark(Baseline = true), BenchmarkCategory("Deserialize")]
+ public UncertainOrderedPairedData? DeserializeDto() => JsonSerializer.Deserialize(_json, _dtoOptions);
+
+ /// Deserializes a JSON string through direct property reads, including validation.
+ /// The reconstructed curve.
+ [Benchmark, BenchmarkCategory("Deserialize")]
+ public UncertainOrderedPairedData? DeserializeDirect() => JsonSerializer.Deserialize(_json, _directOptions);
+
+ /// Deserializes through manual collection and ordinate readers, including validation.
+ /// The reconstructed curve.
+ [Benchmark, BenchmarkCategory("Deserialize")]
+ public UncertainOrderedPairedData? DeserializeManual() => UncertainOrderedPairedData.FromJson(_json);
+ }
+}
diff --git a/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs b/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs
index 87320314..dc8c7476 100644
--- a/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs
+++ b/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs
@@ -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;
@@ -390,6 +393,133 @@ public UncertainOrderedPairedData(XElement el)
#region Methods
+ ///
+ /// Serializes the collection directly to JSON, using the existing converter only for distributions.
+ ///
+ /// The JSON object containing ordinates and validation settings.
+ /// Uses default property names, numeric enums, and named non-finite numbers. Serializer options are not applied.
+ 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));
+ }
+
+ ///
+ /// Deserializes the collection directly from JSON and validates it once.
+ ///
+ /// JSON containing ordinates and all validation settings.
+ /// The reconstructed collection, or null for JSON null.
+ /// The input string is null.
+ /// JSON is malformed, required data is missing, Y is null, or a setting is invalid.
+ /// Uses case-sensitive default property names and numeric enums; unknown properties are skipped.
+ 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();
+ 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;
+ }
+
+ ///
+ /// Reads ordinates into their final list; a repeated property replaces earlier contents.
+ ///
+ private static void ReadJsonOrdinates(ref Utf8JsonReader reader, List 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;
+ }
+
///
/// Resets the event handling of the CollectionChanged event
///
diff --git a/Numerics/Data/Paired Data/UncertainOrdinate.cs b/Numerics/Data/Paired Data/UncertainOrdinate.cs
index b6a83639..b7b8c22c 100644
--- a/Numerics/Data/Paired Data/UncertainOrdinate.cs
+++ b/Numerics/Data/Paired Data/UncertainOrdinate.cs
@@ -129,6 +129,84 @@ public UncertainOrdinate(XElement xElement, UnivariateDistributionType distribut
#region Methods
+ private static readonly UnivariateDistributionConverter JsonDistributionConverter = new UnivariateDistributionConverter();
+
+ ///
+ /// Writes this ordinate directly to the collection's JSON writer.
+ ///
+ 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();
+ }
+
+ ///
+ /// Reads X and Y directly and computes ordinate validity.
+ ///
+ 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);
+ }
+
+ ///
+ /// Reads a numeric value or a named non-finite number.
+ ///
+ 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.");
+ }
+
+ ///
+ /// Writes non-finite numbers as their named string literals.
+ ///
+ 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);
+ }
+
///
/// Recomputes validity after reading X and Y from JSON.
///
diff --git a/Numerics/Utilities/UncertainOrderedPairedDataDirectConverter.cs b/Numerics/Utilities/UncertainOrderedPairedDataDirectConverter.cs
new file mode 100644
index 00000000..59434a74
--- /dev/null
+++ b/Numerics/Utilities/UncertainOrderedPairedDataDirectConverter.cs
@@ -0,0 +1,149 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Numerics.Data;
+using Numerics.Distributions;
+
+namespace Numerics.Utilities
+{
+ ///
+ /// Reads and writes paired-data properties directly without a collection DTO.
+ ///
+ ///
+ /// Register this converter in JsonSerializerOptions to override the collection's attributed converter.
+ /// Ordinates retain their attribute-based serialization and existing distribution converter.
+ ///
+ public sealed class UncertainOrderedPairedDataDirectConverter : JsonConverter
+ {
+ private static readonly string[] PropertyNames =
+ {
+ "StrictX", "StrictY", "OrderX", "OrderY", "Distribution",
+ "AllowDifferentDistributionTypes", "ValidationTailProbability", "Ordinates"
+ };
+
+ ///
+ /// Creates the direct paired-data converter.
+ ///
+ public UncertainOrderedPairedDataDirectConverter() { }
+
+ ///
+ /// Reads the settings and takes ownership of the deserialized ordinate list.
+ ///
+ /// The JSON reader.
+ /// The target type.
+ /// Serialization options.
+ /// The reconstructed collection, or null for JSON null.
+ /// Required data is missing or invalid.
+ public override UncertainOrderedPairedData? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.Null) 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;
+ List? ordinates = null;
+ int seen = 0;
+
+ while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
+ {
+ if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException("Expected a property name.");
+ string? name = ResolvePropertyName(reader.GetString(), options);
+ if (!reader.Read()) throw new JsonException("Expected a property value.");
+ switch (name)
+ {
+ case "StrictX": strictX = JsonSerializer.Deserialize(ref reader, options); seen |= 1; break;
+ case "StrictY": strictY = JsonSerializer.Deserialize(ref reader, options); seen |= 2; break;
+ case "OrderX": orderX = JsonSerializer.Deserialize(ref reader, options); seen |= 4; break;
+ case "OrderY": orderY = JsonSerializer.Deserialize(ref reader, options); seen |= 8; break;
+ case "Distribution": distribution = JsonSerializer.Deserialize(ref reader, options); seen |= 16; break;
+ case "AllowDifferentDistributionTypes": allowDifferentTypes = JsonSerializer.Deserialize(ref reader, options); seen |= 32; break;
+ case "ValidationTailProbability": tailProbability = ReadTailProbability(ref reader); seen |= 64; break;
+ case "Ordinates":
+ ordinates = JsonSerializer.Deserialize>(ref reader, options)
+ ?? throw new JsonException("Ordinates cannot be null.");
+ seen |= 128;
+ break;
+ default:
+ if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Disallow)
+ throw new JsonException("Unknown paired-data property.");
+ reader.Skip();
+ break;
+ }
+ }
+
+ if (reader.TokenType != JsonTokenType.EndObject || seen != 255 || ordinates is null)
+ throw new JsonException("All paired-data settings and Ordinates are required.");
+ try
+ {
+ return new UncertainOrderedPairedData(ordinates, strictX, orderX, strictY, orderY,
+ distribution, allowDifferentTypes, tailProbability);
+ }
+ catch (ArgumentOutOfRangeException exception)
+ {
+ throw new JsonException("Invalid validation tail probability.", exception);
+ }
+ }
+
+ ///
+ /// Writes settings directly and serializes the existing ordinate list.
+ ///
+ /// The JSON writer.
+ /// The paired data.
+ /// Serialization options.
+ public override void Write(Utf8JsonWriter writer, UncertainOrderedPairedData value, JsonSerializerOptions options)
+ {
+ writer.WriteStartObject();
+ WriteProperty(writer, "StrictX", value.StrictX, options);
+ WriteProperty(writer, "StrictY", value.StrictY, options);
+ WriteProperty(writer, "OrderX", value.OrderX, options);
+ WriteProperty(writer, "OrderY", value.OrderY, options);
+ WriteProperty(writer, "Distribution", value.Distribution, options);
+ WriteProperty(writer, "AllowDifferentDistributionTypes", value.AllowDifferentDistributionTypes, options);
+ writer.WritePropertyName(GetPropertyName("ValidationTailProbability", options));
+ if (double.IsNaN(value.ValidationTailProbability) || double.IsInfinity(value.ValidationTailProbability))
+ writer.WriteStringValue(value.ValidationTailProbability.ToString(CultureInfo.InvariantCulture));
+ else
+ writer.WriteNumberValue(value.ValidationTailProbability);
+ WriteProperty(writer, "Ordinates", value.OrdinatesForSerialization, options);
+ writer.WriteEndObject();
+ }
+
+ private static string GetPropertyName(string name, JsonSerializerOptions options)
+ {
+ return options.PropertyNamingPolicy?.ConvertName(name) ?? name;
+ }
+
+ private static string? ResolvePropertyName(string? name, JsonSerializerOptions options)
+ {
+ if (options.PropertyNamingPolicy is null && !options.PropertyNameCaseInsensitive) return name;
+ var comparison = options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+ foreach (string property in PropertyNames)
+ if (string.Equals(name, GetPropertyName(property, options), comparison)) return property;
+ return null;
+ }
+
+ private static void WriteProperty(Utf8JsonWriter writer, string name, T value, JsonSerializerOptions options)
+ {
+ writer.WritePropertyName(GetPropertyName(name, options));
+ JsonSerializer.Serialize(writer, value, options);
+ }
+
+ private static double ReadTailProbability(ref Utf8JsonReader reader)
+ {
+ if (reader.TokenType == JsonTokenType.Number) return reader.GetDouble();
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ switch (reader.GetString())
+ {
+ case "NaN": return double.NaN;
+ case "Infinity": return double.PositiveInfinity;
+ case "-Infinity": return double.NegativeInfinity;
+ }
+ }
+ throw new JsonException("Expected a numeric tail probability or a named floating-point literal.");
+ }
+ }
+}
diff --git a/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataDirectJson.cs b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataDirectJson.cs
new file mode 100644
index 00000000..14e03492
--- /dev/null
+++ b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataDirectJson.cs
@@ -0,0 +1,141 @@
+using System;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Numerics.Data;
+using Numerics.Distributions;
+using Numerics.Utilities;
+
+namespace Serialization
+{
+ /// Checks equivalence of the DTO and direct collection converters.
+ [TestClass]
+ public class Test_UncertainOrderedPairedDataDirectJson
+ {
+ private static JsonSerializerOptions Options(bool direct, bool custom = false)
+ {
+ var options = new JsonSerializerOptions();
+ if (direct) options.Converters.Add(new UncertainOrderedPairedDataDirectConverter());
+ if (custom)
+ {
+ options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
+ options.PropertyNameCaseInsensitive = true;
+ options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
+ options.Converters.Add(new JsonStringEnumConverter());
+ }
+ return options;
+ }
+
+ /// Both strategies write identical JSON and cross-read it with equivalent validity.
+ /// The ordinate count.
+ /// Whether to use nondefault serializer options.
+ [TestMethod]
+ [DataRow(0, false)]
+ [DataRow(10, false)]
+ [DataRow(100, false)]
+ [DataRow(1000, false)]
+ [DataRow(10, true)]
+ public void RoundTrip_MatchesDto(int count, bool custom)
+ {
+ var data = new UncertainOrderedPairedData(false, SortOrder.Ascending, true, SortOrder.Ascending, UnivariateDistributionType.Normal);
+ for (int i = 0; i < count; i++) data.Add(new UncertainOrdinate(i, new Normal(i * 10, 1)));
+ var dto = Options(false, custom);
+ var direct = Options(true, custom);
+ string json = JsonSerializer.Serialize(data, dto);
+ Assert.AreEqual(json, JsonSerializer.Serialize(data, direct));
+ foreach (var options in new[] { dto, direct })
+ {
+ var restored = JsonSerializer.Deserialize(json, options);
+ Assert.IsTrue(data == restored);
+ Assert.IsTrue(restored.IsValid);
+ Assert.IsFalse(restored.StrictX);
+ Assert.IsTrue(restored.StrictY);
+ Assert.AreEqual(SortOrder.Ascending, restored.OrderX);
+ Assert.AreEqual(SortOrder.Ascending, restored.OrderY);
+ Assert.AreEqual(data.Distribution, restored.Distribution);
+ Assert.IsFalse(restored.AllowDifferentDistributionTypes);
+ Assert.IsTrue(double.IsNaN(restored.ValidationTailProbability));
+ }
+ }
+
+ /// All collection properties are required by both converters.
+ /// The missing property.
+ [TestMethod]
+ [DataRow("StrictX")]
+ [DataRow("StrictY")]
+ [DataRow("OrderX")]
+ [DataRow("OrderY")]
+ [DataRow("Distribution")]
+ [DataRow("AllowDifferentDistributionTypes")]
+ [DataRow("ValidationTailProbability")]
+ [DataRow("Ordinates")]
+ public void Read_RejectsMissingSettings(string property)
+ {
+ var data = new UncertainOrderedPairedData(false, SortOrder.None, false, SortOrder.None, UnivariateDistributionType.Normal);
+ var json = JsonNode.Parse(JsonSerializer.Serialize(data)).AsObject();
+ json.Remove(property);
+ foreach (bool direct in new[] { false, true })
+ Assert.ThrowsExactly(() => JsonSerializer.Deserialize(json.ToJsonString(), Options(direct)));
+ }
+
+ /// Null distributions, null collections of ordinates, and invalid tail settings are rejected.
+ /// The property to replace.
+ /// The replacement JSON.
+ [TestMethod]
+ [DataRow("Ordinates", "null")]
+ [DataRow("Ordinates", "[{\"X\":0,\"Y\":null}]")]
+ [DataRow("Ordinates", "[{\"X\":0,\"Y\":{}}]")]
+ [DataRow("ValidationTailProbability", "0.6")]
+ [DataRow("ValidationTailProbability", "\"Infinity\"")]
+ [DataRow("ValidationTailProbability", "\"0.1\"")]
+ public void Read_RejectsInvalidData(string property, string replacement)
+ {
+ var data = new UncertainOrderedPairedData(false, SortOrder.None, false, SortOrder.None, UnivariateDistributionType.Normal);
+ var json = JsonNode.Parse(JsonSerializer.Serialize(data)).AsObject();
+ json[property] = JsonNode.Parse(replacement);
+ foreach (bool direct in new[] { false, true })
+ Assert.ThrowsExactly(() => JsonSerializer.Deserialize(json.ToJsonString(), Options(direct)));
+ }
+
+ /// Property order and unknown nested fields do not affect reconstruction or tail validation.
+ [TestMethod]
+ public void Read_ReorderedSettings_RecomputesTailValidity()
+ {
+ var data = new UncertainOrderedPairedData(new[] { 0d, 1d },
+ new UnivariateDistributionBase[] { new Normal(0, 1), new Normal(4.6, 0.1) },
+ true, SortOrder.Ascending, true, SortOrder.Ascending, UnivariateDistributionType.Normal)
+ { ValidationTailProbability = 1E-12 };
+ var original = JsonNode.Parse(JsonSerializer.Serialize(data, Options(false, true))).AsObject();
+ var reordered = new JsonObject { ["Unknown"] = JsonNode.Parse("{\"nested\":[{}]}") };
+ foreach (var property in original.Reverse()) reordered[property.Key.ToUpperInvariant()] = property.Value.DeepClone();
+ foreach (bool direct in new[] { false, true })
+ {
+ var restored = JsonSerializer.Deserialize(reordered.ToJsonString(), Options(direct, true));
+ Assert.AreEqual(1E-12, restored.ValidationTailProbability);
+ Assert.IsFalse(restored.IsValid);
+ restored.ValidationTailProbability = double.NaN;
+ Assert.IsTrue(restored.IsValid);
+ }
+ }
+
+ /// Null roots and non-finite ordinate values preserve the existing behavior.
+ [TestMethod]
+ public void RoundTrip_NullAndInvalidOrdinate()
+ {
+ foreach (bool direct in new[] { false, true })
+ {
+ var options = Options(direct);
+ Assert.IsNull(JsonSerializer.Deserialize("null", options));
+ Assert.AreEqual("null", JsonSerializer.Serialize(null, options));
+ var data = new UncertainOrderedPairedData(false, SortOrder.None, false, SortOrder.None, UnivariateDistributionType.Normal);
+ data.Add(new UncertainOrdinate(double.NaN, new Normal(0, 1)));
+ var restored = JsonSerializer.Deserialize(JsonSerializer.Serialize(data, options), options);
+ Assert.IsTrue(double.IsNaN(restored[0].X));
+ Assert.IsFalse(restored[0].IsValid);
+ Assert.IsFalse(restored.IsValid);
+ }
+ }
+ }
+}
diff --git a/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs
new file mode 100644
index 00000000..f1383ca2
--- /dev/null
+++ b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs
@@ -0,0 +1,160 @@
+using System;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Numerics.Data;
+using Numerics.Distributions;
+
+namespace Serialization
+{
+ /// Checks the manual JSON path against the collection DTO contract.
+ [TestClass]
+ public class Test_UncertainOrderedPairedDataManualJson
+ {
+ private static UncertainOrderedPairedData CreateData(int count)
+ {
+ var data = new UncertainOrderedPairedData(true, SortOrder.Ascending, true, SortOrder.Ascending, UnivariateDistributionType.Normal);
+ for (int i = 0; i < count; i++) data.Add(new UncertainOrdinate(i, new Normal(10 * i, 1)));
+ return data;
+ }
+
+ /// Manual and DTO paths produce identical JSON and reconstructed curves.
+ /// The ordinate count.
+ [TestMethod]
+ [DataRow(0)]
+ [DataRow(10)]
+ [DataRow(100)]
+ [DataRow(1000)]
+ public void RoundTrip_MatchesDto(int count)
+ {
+ var data = CreateData(count);
+ string json = data.ToJson();
+ Assert.AreEqual(JsonSerializer.Serialize(data), json);
+ var manual = UncertainOrderedPairedData.FromJson(json);
+ var dto = JsonSerializer.Deserialize(json);
+ Assert.IsTrue(data == manual);
+ Assert.IsTrue(dto == manual);
+ Assert.IsTrue(manual.IsValid);
+ Assert.AreEqual(json, manual.ToJson());
+ }
+
+ /// All collection settings must be present.
+ /// The missing property.
+ [TestMethod]
+ [DataRow("StrictX")]
+ [DataRow("StrictY")]
+ [DataRow("OrderX")]
+ [DataRow("OrderY")]
+ [DataRow("Distribution")]
+ [DataRow("AllowDifferentDistributionTypes")]
+ [DataRow("ValidationTailProbability")]
+ [DataRow("Ordinates")]
+ public void Read_RejectsMissingSettings(string property)
+ {
+ var json = JsonNode.Parse(CreateData(1).ToJson()).AsObject();
+ json.Remove(property);
+ Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString()));
+ }
+
+ /// Invalid ordinate JSON and null distributions are rejected.
+ /// The invalid array JSON.
+ [TestMethod]
+ [DataRow("null")]
+ [DataRow("{}")]
+ [DataRow("[null]")]
+ [DataRow("[{}]")]
+ [DataRow("[{\"X\":0}]")]
+ [DataRow("[{\"X\":0,\"Y\":null}]")]
+ [DataRow("[{\"X\":0,\"Y\":{}}]")]
+ [DataRow("[{\"X\":\"bad\",\"Y\":{}}]")]
+ public void Read_RejectsInvalidOrdinates(string ordinates)
+ {
+ var json = JsonNode.Parse(CreateData(1).ToJson()).AsObject();
+ json["Ordinates"] = JsonNode.Parse(ordinates);
+ Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString()));
+ }
+
+ /// Invalid primitive settings preserve JSON error behavior.
+ /// The replaced setting.
+ /// The replacement JSON.
+ [TestMethod]
+ [DataRow("StrictX", "1")]
+ [DataRow("OrderX", "1.5")]
+ [DataRow("OrderY", "\"Ascending\"")]
+ [DataRow("ValidationTailProbability", "0.6")]
+ [DataRow("ValidationTailProbability", "\"Infinity\"")]
+ [DataRow("ValidationTailProbability", "\"0.1\"")]
+ public void Read_RejectsInvalidSettings(string property, string replacement)
+ {
+ var json = JsonNode.Parse(CreateData(1).ToJson()).AsObject();
+ json[property] = JsonNode.Parse(replacement);
+ Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString()));
+ }
+
+ /// Root null is supported, while missing input and trailing content are rejected.
+ [TestMethod]
+ public void Read_HandlesNullAndMalformedRoots()
+ {
+ Assert.IsNull(UncertainOrderedPairedData.FromJson("null"));
+ Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(null));
+ foreach (string json in new[] { "", "[]", "{", "null {}", CreateData(0).ToJson() + "{}" })
+ Assert.Throws(() => UncertainOrderedPairedData.FromJson(json));
+ }
+
+ /// Non-finite X values round trip without persisting stale validity.
+ /// The X value.
+ [TestMethod]
+ [DataRow(double.NaN)]
+ [DataRow(double.PositiveInfinity)]
+ [DataRow(double.NegativeInfinity)]
+ public void RoundTrip_RecomputesOrdinateValidity(double x)
+ {
+ var data = CreateData(0);
+ data.Add(new UncertainOrdinate(x, new Normal(0, 1)) { IsValid = true });
+ var restored = UncertainOrderedPairedData.FromJson(data.ToJson());
+ Assert.AreEqual(x, restored[0].X);
+ Assert.IsFalse(restored[0].IsValid);
+ Assert.IsFalse(restored.IsValid);
+ }
+
+ /// Reordered properties and unknown nested values preserve tail validation.
+ [TestMethod]
+ public void Read_ReorderedPropertiesAndTailValidation()
+ {
+ var data = new UncertainOrderedPairedData(new[] { 0d, 1d },
+ new UnivariateDistributionBase[] { new Normal(0, 1), new Normal(4.6, 0.1) },
+ true, SortOrder.Ascending, true, SortOrder.Ascending, UnivariateDistributionType.Normal)
+ { ValidationTailProbability = 1E-12 };
+ var json = JsonNode.Parse(data.ToJson()).AsObject();
+ var reordered = new JsonObject { ["Unknown"] = JsonNode.Parse("{\"nested\":[{}]}") };
+ foreach (var property in json.Reverse()) reordered[property.Key] = property.Value.DeepClone();
+ var ordinate = reordered["Ordinates"][0].AsObject();
+ ordinate["Unknown"] = JsonNode.Parse("[{}]");
+ ordinate["IsValid"] = false;
+ var restored = UncertainOrderedPairedData.FromJson(reordered.ToJsonString());
+ Assert.IsTrue(restored[0].IsValid);
+ Assert.IsFalse(restored.IsValid);
+ Assert.AreEqual(1E-12, restored.ValidationTailProbability);
+ restored.ValidationTailProbability = double.NaN;
+ Assert.IsTrue(restored.IsValid);
+ }
+
+ /// Mixed distribution validation uses the restored setting.
+ /// Whether mixed distributions are permitted.
+ [TestMethod]
+ [DataRow(false)]
+ [DataRow(true)]
+ public void RoundTrip_MixedDistributions(bool allowDifferentTypes)
+ {
+ var data = CreateData(1);
+ data.AllowDifferentDistributionTypes = allowDifferentTypes;
+ data.Add(new UncertainOrdinate(1, new Uniform(10, 11)));
+ Assert.AreEqual(JsonSerializer.Serialize(data), data.ToJson());
+ var restored = UncertainOrderedPairedData.FromJson(data.ToJson());
+ Assert.AreEqual(allowDifferentTypes, restored.AllowDifferentDistributionTypes);
+ Assert.AreEqual(allowDifferentTypes, restored.IsValid);
+ Assert.AreEqual(UnivariateDistributionType.Uniform, restored[1].Y.Type);
+ }
+ }
+}
diff --git a/python/pynumerics/src/pynumerics/_coverage.py b/python/pynumerics/src/pynumerics/_coverage.py
index 447a5726..8f354b4e 100644
--- a/python/pynumerics/src/pynumerics/_coverage.py
+++ b/python/pynumerics/src/pynumerics/_coverage.py
@@ -755,6 +755,7 @@ def todo_counts() -> Counter:
'Count': 'count',
'CurveSample': 'curve_sample',
'Distribution': 'distribution',
+ 'FromJson': Excluded('Experimental manual JSON path for serialization benchmarks; use to_xml/from_xml'),
'GetEnumerator': '__iter__',
'GetErrors': 'errors',
'IndexOf': 'index_of',
@@ -773,6 +774,7 @@ def todo_counts() -> Counter:
'StrictX': 'strict_x',
'StrictY': 'strict_y',
'SuppressCollectionChanged': Excluded('collection-change notification for UI binding'),
+ 'ToJson': Excluded('Experimental manual JSON path for serialization benchmarks; use to_xml/from_xml'),
'Validate': 'validate',
'ValidationTailProbability': 'validation_tail_probability',
},
@@ -3822,6 +3824,8 @@ def todo_counts() -> Counter:
'Numerics.Utilities.String2DArrayConverter': Excluded('Utilities serialization converter'),
'Numerics.Utilities.UncertainOrderedPairedDataConverter':
Excluded('Utilities serialization converter; paired data XML round trip is to_xml'),
+ 'Numerics.Utilities.UncertainOrderedPairedDataDirectConverter':
+ Excluded('Experimental serialization converter for the DTO comparison benchmark'),
'Numerics.Utilities.UnivariateDistributionConverter':
Excluded('Utilities serialization converter; XML round trip is to_xml'),
}