diff --git a/Benchmarks_Numerics/Serialization/UncertainPairedDataManualJsonBenchmarks.cs b/Benchmarks_Numerics/Serialization/UncertainPairedDataManualJsonBenchmarks.cs new file mode 100644 index 00000000..6d9cc196 --- /dev/null +++ b/Benchmarks_Numerics/Serialization/UncertainPairedDataManualJsonBenchmarks.cs @@ -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 +{ + /// + /// Compares manual and converter-based JSON persistence of valid uncertain paired data. + /// + [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!; + + /// The number of uncertain ordinates in each collection. + [Params(10, 50, 100, 1000)] + public int OrdinateCount { get; set; } + + /// + /// Creates identical input for both readers and verifies their reconstructed values before measurement. + /// + [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(_json)); + Verify(UncertainOrderedPairedData.FromJson(_json)); + } + + /// Reads the prepared JSON string using the attributed collection converter and DTOs. + /// The reconstructed collection. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Deserialize")] + public UncertainOrderedPairedData? ConverterDeserialize() => JsonSerializer.Deserialize(_json); + + /// Reads the same JSON string directly into the collection without DTOs. + /// The reconstructed collection. + [Benchmark] + [BenchmarkCategory("Deserialize")] + public UncertainOrderedPairedData? ManualDeserialize() => UncertainOrderedPairedData.FromJson(_json); + + /// Writes a JSON string using the attributed collection converter and DTOs. + /// The serialized collection. + [Benchmark(Baseline = true)] + [BenchmarkCategory("Serialize")] + public string ConverterSerialize() => JsonSerializer.Serialize(_data); + + /// Writes a JSON string directly without DTOs. + /// The serialized collection. + [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."); + } + } + } +} diff --git a/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs b/Numerics/Data/Paired Data/UncertainOrderedPairedData.cs index 7855e876..37fef6ff 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; @@ -34,6 +37,7 @@ public class UncertainOrderedPairedData : IList, INotifyColle private bool _isValid = true; private bool _allowDifferentDistributionTypes = false; private double _validationTailProbability = double.NaN; + private static readonly UnivariateDistributionConverter _jsonDistributionConverter = new UnivariateDistributionConverter(); /// /// Gets or sets whether to allow different distribution types in the list. @@ -845,6 +849,234 @@ IEnumerator IEnumerable.GetEnumerator() return _uncertainOrdinates.GetEnumerator(); } + /// + /// Writes the ordinates and validation settings as JSON without DTOs or serialization attributes. + /// + /// The JSON object representing this collection. + /// + /// Uses the same format as 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 explicitly. + /// Computed validity and collection notification state are omitted. + /// + 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)); + } + + /// + /// Reads JSON directly into a collection and recomputes validity after loading. + /// + /// The JSON object to read, or the JSON literal null. + /// The reconstructed collection, or null for the JSON literal null. + /// is null. + /// The JSON is malformed, required properties are missing, a Y distribution is null, or the tail probability is invalid. + /// + /// Reads the default format written by or . + /// 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 explicitly. + /// + 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; + } + + /// + /// Reads an ordinate array directly into collection storage. + /// + /// The reader positioned at the array. + /// The destination list, whose contents are replaced. + /// The array or an ordinate is invalid. + 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(ReadJsonOrdinate(ref reader)); + } + throw new JsonException("Incomplete ordinate array."); + } + + /// + /// Reads an ordinate and computes its validity through the existing constructor. + /// + /// The reader positioned at the ordinate object. + /// The reconstructed ordinate. + /// The object is invalid, X or Y is missing, or Y cannot be reconstructed. + 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); + } + + /// + /// Reads a JSON boolean without accepting strings or numbers. + /// + /// The reader positioned at the value. + /// The boolean value. + /// The token is not a boolean. + 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(); + } + + /// + /// Reads a numeric enum value without accepting strings or fractional numbers. + /// + /// The reader positioned at the value. + /// The integer value. + /// The token is not a 32-bit integer. + 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; + } + + /// + /// Reads a number or a named non-finite floating-point string. + /// + /// The reader positioned at the value. + /// The double value. + /// The token is not a supported floating-point value. + 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."); + } + + /// + /// Writes finite values as numbers and non-finite values as named strings. + /// + /// The JSON writer. + /// The value to write. + 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); + } + /// /// Converts the uncertain ordered paired data set to an XElement for saving to xml. /// diff --git a/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs new file mode 100644 index 00000000..f18d9e1d --- /dev/null +++ b/Test_Numerics/Serialization/Test_UncertainOrderedPairedDataManualJson.cs @@ -0,0 +1,276 @@ +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 +{ + /// + /// Compares manual JSON persistence with the converter-based default format. + /// + [TestClass] + public class Test_UncertainOrderedPairedDataManualJson + { + /// + /// Both paths write identical JSON and can read each other's output for each ordering configuration. + /// + /// The X sort order. + /// The Y sort order. + /// Whether X ordering is strict. + /// Whether Y ordering is strict. + [TestMethod] + [DataRow(SortOrder.Ascending, SortOrder.Ascending, true, true)] + [DataRow(SortOrder.Descending, SortOrder.Ascending, false, true)] + [DataRow(SortOrder.Ascending, SortOrder.Descending, true, false)] + [DataRow(SortOrder.Descending, SortOrder.Descending, false, false)] + [DataRow(SortOrder.None, SortOrder.None, false, false)] + public void RoundTrip_MatchesConverter(SortOrder orderX, SortOrder orderY, bool strictX, bool strictY) + { + var original = new UncertainOrderedPairedData( + new[] { 0d, orderX == SortOrder.Ascending ? 1d : -1d }, + new UnivariateDistributionBase[] { new Normal(0, 1), new Normal(orderY == SortOrder.Ascending ? 10 : -10, 1) }, + strictX, orderX, strictY, orderY, UnivariateDistributionType.Normal); + + AssertEquivalentRoundTrip(original); + } + + /// + /// Mixed distribution settings and types survive both serialization paths. + /// + /// Whether mixed distributions are allowed. + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void RoundTrip_MixedDistributions(bool allowDifferentTypes) + { + var original = CreateCollection(); + original.AllowDifferentDistributionTypes = allowDifferentTypes; + original.Add(new UncertainOrdinate(1, new Uniform(10, 11))); + + AssertEquivalentRoundTrip(original); + } + + /// + /// Tail validation and stale source validity are recomputed identically by both readers. + /// + [TestMethod] + public void RoundTrip_RecomputesTailValidity() + { + var original = 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); + original.SuppressCollectionChanged = true; + original.ValidationTailProbability = 1E-12; + Assert.IsTrue(original.IsValid); + + AssertEquivalentRoundTrip(original); + var restored = UncertainOrderedPairedData.FromJson(original.ToJson()); + Assert.IsFalse(restored.IsValid); + Assert.IsFalse(restored.SuppressCollectionChanged); + restored.ValidationTailProbability = double.NaN; + Assert.IsTrue(restored.IsValid); + } + + /// + /// Empty collections and the JSON null literal retain the default converter semantics. + /// + [TestMethod] + public void RoundTrip_EmptyAndNull() + { + var empty = CreateCollection(); + empty.Clear(); + AssertEquivalentRoundTrip(empty); + Assert.IsNull(UncertainOrderedPairedData.FromJson("null")); + Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(null)); + } + + /// + /// Non-finite X values use named strings and retain invalid ordinate status. + /// + /// The non-finite X value. + [TestMethod] + [DataRow(double.NaN)] + [DataRow(double.PositiveInfinity)] + [DataRow(double.NegativeInfinity)] + public void RoundTrip_NonFiniteX(double x) + { + var original = CreateCollection(); + original[0] = new UncertainOrdinate(x, new Normal(0, 1)); + AssertEquivalentRoundTrip(original); + Assert.IsFalse(UncertainOrderedPairedData.FromJson(original.ToJson()).IsValid); + } + + /// + /// Settings after ordinates are applied before validation, and nested unknown properties are ignored. + /// + [TestMethod] + public void Read_AcceptsReorderedPropertiesAndIgnoresUnknownObjects() + { + var original = CreateCollection(); + original.AllowDifferentDistributionTypes = true; + original.ValidationTailProbability = 1E-12; + original.Add(new UncertainOrdinate(1, new Uniform(10, 11))); + var source = JsonNode.Parse(original.ToJson()).AsObject(); + var reordered = new JsonObject { ["Unknown"] = new JsonObject { ["StrictX"] = false } }; + foreach (var property in source.Reverse()) + reordered[property.Key] = property.Value.DeepClone(); + var first = reordered["Ordinates"][0]; + reordered["Ordinates"][0] = new JsonObject + { + ["Y"] = first["Y"].DeepClone(), + ["Unknown"] = new JsonArray(new JsonObject { ["X"] = -100 }), + ["X"] = first["X"].DeepClone(), + ["IsValid"] = false + }; + reordered["IsValid"] = false; + + var restored = UncertainOrderedPairedData.FromJson(reordered.ToJsonString()); + + Assert.AreEqual(original.ToJson(), restored.ToJson()); + Assert.IsTrue(restored.IsValid); + } + + /// + /// Escaped property names and duplicate properties match the default reader's interpretation. + /// + [TestMethod] + public void Read_AcceptsEscapedAndRepeatedProperties() + { + string json = CreateCollection().ToJson(); + string repeated = json.Insert(1, "\"StrictX\":false,\"Ordinates\":[],"); + string escaped = repeated.Replace("\"StrictX\"", "\"Str\\u0069ctX\""); + + Assert.AreEqual(json, UncertainOrderedPairedData.FromJson(escaped).ToJson()); + Assert.AreEqual(json, JsonSerializer.Serialize(JsonSerializer.Deserialize(escaped))); + } + + /// + /// Each collection property is required even when its value would otherwise default. + /// + /// The property to omit. + [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(CreateCollection().ToJson()).AsObject(); + json.Remove(property); + Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString())); + } + + /// + /// Both ordinate values are required. + /// + /// The ordinate property to omit. + [TestMethod] + [DataRow("X")] + [DataRow("Y")] + public void Read_RejectsMissingOrdinateValues(string property) + { + var json = JsonNode.Parse(CreateCollection().ToJson()); + json["Ordinates"][0].AsObject().Remove(property); + Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString())); + } + + /// + /// Null distributions and distributions that cannot be reconstructed are rejected. + /// + /// The replacement Y representation. + [TestMethod] + [DataRow("null")] + [DataRow("{}")] + public void Read_RejectsNullDistribution(string distributionJson) + { + var json = JsonNode.Parse(CreateCollection().ToJson()); + json["Ordinates"][0]["Y"] = JsonNode.Parse(distributionJson); + Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString())); + } + + /// + /// Invalid settings and ordinate structures are rejected as JSON errors. + /// + /// The collection property to change. + /// The invalid replacement value. + [TestMethod] + [DataRow("StrictX", "0")] + [DataRow("OrderX", "\"Ascending\"")] + [DataRow("ValidationTailProbability", "0.5")] + [DataRow("ValidationTailProbability", "0")] + [DataRow("ValidationTailProbability", "\"Infinity\"")] + [DataRow("Ordinates", "null")] + [DataRow("Ordinates", "[null]")] + [DataRow("Ordinates", "[{}]")] + public void Read_RejectsInvalidValues(string property, string valueJson) + { + var json = JsonNode.Parse(CreateCollection().ToJson()); + json[property] = JsonNode.Parse(valueJson); + var exception = Assert.ThrowsExactly(() => UncertainOrderedPairedData.FromJson(json.ToJsonString())); + if (property == "ValidationTailProbability") + Assert.IsInstanceOfType(exception.InnerException); + } + + /// + /// Malformed, incomplete, and trailing JSON content is rejected. + /// + /// The malformed JSON input. + [TestMethod] + [DataRow("")] + [DataRow("{")] + [DataRow("[]")] + [DataRow("true")] + [DataRow("{}")] + [DataRow("null true")] + public void Read_RejectsMalformedJson(string json) + { + Assert.Throws(() => UncertainOrderedPairedData.FromJson(json)); + } + + /// + /// A valid object cannot be followed by extra content or omit its closing token. + /// + [TestMethod] + public void Read_RejectsTrailingAndTruncatedContent() + { + string json = CreateCollection().ToJson(); + Assert.Throws(() => UncertainOrderedPairedData.FromJson(json + " {}")); + Assert.Throws(() => UncertainOrderedPairedData.FromJson(json.Substring(0, json.Length - 1))); + } + + private static UncertainOrderedPairedData CreateCollection() + { + var data = new UncertainOrderedPairedData(true, SortOrder.Ascending, true, SortOrder.Ascending, UnivariateDistributionType.Normal); + data.Add(new UncertainOrdinate(0, new Normal(0, 1))); + return data; + } + + private static void AssertEquivalentRoundTrip(UncertainOrderedPairedData original) + { + string converterJson = JsonSerializer.Serialize(original); + string manualJson = original.ToJson(); + Assert.AreEqual(converterJson, manualJson); + var manual = UncertainOrderedPairedData.FromJson(converterJson); + var converted = JsonSerializer.Deserialize(manualJson); + Assert.IsNotNull(manual); + Assert.IsNotNull(converted); + Assert.AreEqual(converterJson, manual.ToJson()); + Assert.AreEqual(converterJson, JsonSerializer.Serialize(converted)); + Assert.AreEqual(converted.IsValid, manual.IsValid); + Assert.AreEqual(converted.Count, manual.Count); + for (int i = 0; i < manual.Count; i++) + { + Assert.AreEqual(converted[i].IsValid, manual[i].IsValid); + Assert.AreEqual(converted[i].Y.Type, manual[i].Y.Type); + CollectionAssert.AreEqual(converted[i].Y.GetParameters, manual[i].Y.GetParameters); + } + } + } +} diff --git a/python/pynumerics/src/pynumerics/_coverage.py b/python/pynumerics/src/pynumerics/_coverage.py index 447a5726..9a11e79f 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('Manual JSON comparison API; Python persistence uses to_xml and 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('Manual JSON comparison API; Python persistence uses to_xml and from_xml'), 'Validate': 'validate', 'ValidationTailProbability': 'validation_tail_probability', },