Implement US-11 context-aware health trend assessments

This commit is contained in:
Steffen committed 2026-10-05 13:51:16 +02:00
1 parent a0a9e2e9b9
commit cc76c9bde4
9 files changed
+802 -7

No files matched your search

@@ -0,0 +1,223 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
public sealed partial class InsightCalculator
{
private const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
"This is a descriptive assessment, not a diagnosis or medication recommendation. " +
"Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
var comparability = AssessComparability(observations);
return new(patientId, from, to, selection, observations.Count, comparability,
AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
}
private static MeasurementAssessment AssessMeasurement(string metric, string unit,
IReadOnlyList<ObservationDto> observations, Func<ObservationDto, int> value,
ComparabilityAssessment comparability)
{
if (observations.Count == 0)
return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
null, "No matching observations; insufficient observation data for trend calculation.",
null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
// Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
.Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
var minimum = observations.Min(value);
var maximum = observations.Max(value);
var mean = observations.Average(o => (decimal)value(o));
var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
.Where(s => s != 0).ToArray();
var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
decimal? slope = null;
var overall = "Unavailable";
decimal? totalChange = null;
if (points.Length >= 2)
{
// Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
var xMean = xs.Average();
var yMean = points.Average(p => p.Value);
var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
var scaledSlope = numerator / denominator;
slope = scaledSlope / (span / TimeSpan.TicksPerDay);
overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
}
var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
$"range {maximum - minimum} {unit}. " + (points.Length < 2
? "Direction is unavailable: at least two distinct measurement timestamps are required."
: $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
$"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
" Range and successive change describe observed variation; no clinical stability classification is made.";
var reference = SelectReference(metric, observations, comparability);
var comparison = "Unavailable: known, non-conflicting resting conditions" +
(metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
var interpretation = "CannotInterpret";
var hint = "Numerical changes alone do not establish favourable or concerning development.";
if (reference is not null)
{
var above = observations.Count(o => IsHigh(value(o), reference));
var below = observations.Count(o => IsLow(value(o), reference));
comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
$"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
(reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
" This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
{
var first = points[0].Value;
var last = points[^1].Value;
if (reversals > 0 && (above > 0 || below > 0))
{
interpretation = "Mixed";
hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
"an overall slope does not establish consistent improvement or deterioration.";
}
else if (direction == "Decreasing" && IsHigh(first, reference) &&
!IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
"This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
(IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
"Reaching the reference interval does not establish an individual treatment target or good health.");
}
else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
!IsHigh(last, reference) && above == 0)
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
"but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
(IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
"Being within these boundaries does not establish good health.");
}
else if (above > 0 || below > 0)
{
interpretation = "PotentiallyConcerning";
hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
"Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
"is not automatically favourable. The cause and individual significance cannot be determined here.";
}
}
else
hint = "The recorded context supports this limited reference comparison, but " +
(points.Length < 2 ? "temporal direction is unavailable. " :
"missing or differing conditions limit interpretation of the combined trajectory. ") +
"An outside-reference value is not dismissed because preparation information is incomplete.";
}
return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
}
private static ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
ComparabilityAssessment comparability)
{
if (comparability.Conflicts.Count > 0 ||
observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
if (metric == "Pulse")
return new("Recorded resting pulse", 50, "<", 100, ">",
[new("Patienthåndbogen: Bradykardi (langsom puls)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
"2025-09-02", "2026-10-05"),
new("Patienthåndbogen: Hurtig puls (takykardi)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
"2025-05-12", "2026-10-05")],
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
// Known inadequate rest prevents even a provisional resting-pressure comparison.
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
return null;
var threshold = metric == "Systolic" ? (settings[0] == "Home" ? 135 : 140) :
(settings[0] == "Home" ? 85 : 90);
return new($"Recorded {settings[0]} resting blood pressure", null, null, threshold, ">=",
[new("Lægehåndbogen: Højt blodtryk",
"https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
"2024-09-25", "2026-10-05")],
"Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
"five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
"Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
}
private static bool IsHigh(decimal value, ClinicalReference reference) =>
reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
private static bool IsLow(decimal value, ClinicalReference reference) =>
reference.LowerBoundary is { } lower && value < lower;
private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
private static ComparabilityAssessment AssessComparability(IReadOnlyList<ObservationDto> observations)
{
List<string> similarities = [], differences = [], missing = [], conflicts = [];
if (observations.Count == 0)
return new("InsufficientContext", similarities, differences, missing, conflicts,
"No matching observations are available to assess comparability.");
var details = new (string Name, string?[] Values)[]
{
("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
};
foreach (var (name, values) in details)
{
var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
.Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
}
var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (circumstances.Length > 1) differences.Add("additional circumstances differ");
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
foreach (var observation in observations)
{
var context = observation.MeasurementContext;
var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
if (context?.ActivityCondition == "AtRest" && new[]
{ "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
.Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
conflicts.Add("Home conflicts with a clinic description in recorded text.");
if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
conflicts.Add("Clinic conflicts with a home description in recorded text.");
}
var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
var explanation = $"Recorded comparability: {status}. " +
(missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
(differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
(conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
"Matching recorded details support comparability only of those details; they do not certify identical " +
"conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
"to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
"selections alone is not improvement or deterioration over time.";
return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
}
}