Implement US-11 context-aware health trend assessments
This commit is contained in:
1 parent
a0a9e2e9b9
commit
cc76c9bde4
9 files changed
+802
-7
No files matched your search
@@ -10,6 +10,10 @@ public sealed class InsightsController(IHttpClientFactory clients) : ControllerB
|
||||
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
||||
|
||||
[HttpGet("patients/{patientId:guid}/trends")]
|
||||
public Task GetTrend(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/trends{Request.QueryString}", cancellationToken);
|
||||
|
||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
|
||||
@@ -18,6 +18,18 @@ public sealed class InsightsApplicationService(ObservationServiceClient observat
|
||||
return calculator.CalculateSummary(patientId, from, to, history, selection);
|
||||
}
|
||||
|
||||
public async Task<TrendAssessment> GetTrendAsync(Guid patientId, DateTime from, DateTime to,
|
||||
ContextSelection selection, CancellationToken cancellationToken)
|
||||
{
|
||||
from = NormalizeTimestamp(from);
|
||||
to = NormalizeTimestamp(to);
|
||||
if (to < from)
|
||||
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
||||
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
|
||||
return calculator.CalculateTrend(patientId, from, to, history, selection);
|
||||
}
|
||||
|
||||
private static DateTime NormalizeTimestamp(DateTime value) =>
|
||||
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
|
||||
DateTimeKind.Unspecified);
|
||||
|
||||
@@ -43,4 +43,32 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
|
||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||
}
|
||||
}
|
||||
[HttpGet("/api/patients/{patientId:guid}/trends")]
|
||||
public async Task<ActionResult<TrendAssessment>> GetTrend(Guid patientId,
|
||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
|
||||
}
|
||||
catch (System.Text.Json.JsonException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed class InsightCalculator
|
||||
public sealed partial class InsightCalculator
|
||||
{
|
||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
||||
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
|
||||
MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
|
||||
|
||||
public sealed record ComparabilityAssessment(string Status, IReadOnlyList<string> KnownSimilarities,
|
||||
IReadOnlyList<string> KnownDifferences, IReadOnlyList<string> MissingDetails,
|
||||
IReadOnlyList<string> Conflicts, string Explanation);
|
||||
|
||||
public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
|
||||
int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
|
||||
decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
|
||||
string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
|
||||
string Interpretation, string Hint);
|
||||
|
||||
public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
|
||||
decimal UpperBoundary, string UpperComparison, IReadOnlyList<ReferenceSource> Sources,
|
||||
string Limitation);
|
||||
|
||||
public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
|
||||
+13
-6
@@ -181,14 +181,13 @@ retains its complete numerical-correction contract and rejects unsupported field
|
||||
rather than silently ignoring context supplied on that route. Use `PATCH` for context
|
||||
updates. Both routes use the same
|
||||
Observation-owned update operation and save changes atomically. Subsequent reads,
|
||||
latest observations and filtered history use current recorded context. US-11 trend
|
||||
integration remains to be verified when that endpoint is implemented.
|
||||
latest observations and filtered history use current recorded context. US-11 trend assessments also use current recorded context on each request.
|
||||
|
||||
US-08 tests cover the original full numerical corrections and rejection scenarios plus context-only/single-value patches, historical context additions, individual field corrections/clears, whole-context clearing, preservation of omitted data and creation time, persistence after restart, fresh filter membership, atomic rejection, missing observations and access restrictions. No new dependencies are introduced.
|
||||
|
||||
`DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved.
|
||||
|
||||
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 trend-specific deletion checks remain to be added with that endpoint. No new dependencies or schema changes are required.
|
||||
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 tests verify fresh trends after deletion. No new dependencies or schema changes are required.
|
||||
|
||||
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient. Arithmetic means use decimal calculations and round only the final result to two decimal places, half-up (away from zero for the positive recorded values); extrema retain their recorded integer values. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
||||
|
||||
@@ -223,13 +222,21 @@ test databases. They cover original summaries, independent/combined/unknown
|
||||
selections, applied selections and counts, context explanations, one-observation
|
||||
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
|
||||
offset bounds, context corrections/clearing/deletions, restart, invalid requests,
|
||||
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story.
|
||||
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. US-11 adds the separate trend endpoint described in [TRENDS.md](TRENDS.md).
|
||||
|
||||
`GET /api/patients/{patientId}/trends?from=...&to=...` implements US-11 with independent
|
||||
systolic, diastolic and pulse assessments, context selections/counts, recorded comparability,
|
||||
full-period numerical direction, reversals and variation, sourced reference comparisons and
|
||||
limited clinical interpretation. Empty/single/tied series report unavailable temporal direction;
|
||||
numerical information remains where supported. See [TRENDS.md](TRENDS.md) for the response,
|
||||
reproducible mathematical methods, reference sources and interpretation limits. Tests cover
|
||||
all US-11 acceptance criteria, current corrections/context/deletion, access controls and failures.
|
||||
No persistence, service boundaries, dependencies or configuration changed.
|
||||
|
||||
US-13 authentication and patient ownership are implemented as described in
|
||||
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
|
||||
in the patient service. US-14 professional reads require predefined gateway assignments; professional
|
||||
writes are rejected. Updated context, tie
|
||||
and rounding requirements in other stories remain to be implemented incrementally.
|
||||
writes are rejected. US-04 through US-11 include updated context, ordering, rounding and trend requirements.
|
||||
|
||||
## Automated acceptance tests
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# US-11 trend API and methods
|
||||
|
||||
`GET /api/patients/{patientId}/trends?from=...&to=...&setting=Home&activityCondition=AtRest`
|
||||
uses the same inclusive UTC measurement-instant semantics and optional context selections as history and
|
||||
numerical insight. Offset-free timestamps mean UTC. Both selected dimensions must match; `Unknown`
|
||||
is an explicit category. Patient ownership or professional assignment is required. Each selection is a
|
||||
separate labelled result for the same requested period. No cross-setting difference is interpreted as
|
||||
improvement. Insights retrieves current observations through the gateway on every request, without persistence.
|
||||
|
||||
A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
|
||||
`Unavailable` direction distinguish empty data from upstream failures (502/504). One observation or
|
||||
all observations at a single instant retain descriptive values, but temporal direction is unavailable.
|
||||
Invalid/missing period or unsupported selections return 400. No new configuration or dependencies are required.
|
||||
|
||||
## Numerical method
|
||||
|
||||
Each metric has its own unit, mean, minimum, maximum and range over every eligible observation. Decimal
|
||||
means are rounded only for output, to two decimals with midpoint rounding away from zero. No numerical
|
||||
range threshold is used to declare clinical stability or instability.
|
||||
|
||||
Temporal calculations group equal measurement instants using the arithmetic mean for each metric,
|
||||
then order those groups by measurement instant. Identifier and storage order play no part. Direction
|
||||
uses every adjacent nonzero change: all positive means Increasing, all negative Decreasing, both signs
|
||||
Mixed, all zero NoClearDirection. Reversal count counts sign changes after excluding zero steps.
|
||||
TotalSuccessiveChange sums absolute changes between consecutive timestamp means. This retains intermediate
|
||||
excursions, while raw min/max retain differences within timestamp ties. No temporal change is assigned
|
||||
between measurements at the same instant.
|
||||
|
||||
OverallDirection additionally reports the sign of an ordinary least-squares line over all timestamp
|
||||
means. Time is scaled from zero to one over the observed span; each distinct timestamp has equal weight.
|
||||
SlopePerDay converts that fitted slope to metric units per day and rounds to six decimals. Classification
|
||||
uses the unrounded slope. An extremely small nonzero slope may round to zero; its sign is a mathematical
|
||||
result, not evidence of clinical significance. The fit describes a linear tendency, not a prediction,
|
||||
causal effect or a monotonic trajectory. Mixed direction and reversal count remain visible even when
|
||||
an overall slope exists. Irregular sampling and repeated observations can affect the description;
|
||||
there is no significance test, smoothing, diagnostic protocol or clinical variability classification.
|
||||
|
||||
## Context and interpretation
|
||||
|
||||
Comparability lists known similarities, differences and missing information for setting, activity,
|
||||
rest duration, body position, measured arm, device and cuff. Differing recorded additional circumstances
|
||||
also limit comparability. Matching complete recorded fields support comparability of recorded details
|
||||
only, without certifying clinical technique or equipment. Missing optional additional circumstances do
|
||||
not block a supported reference comparison. Known inadequate rest is reported separately.
|
||||
|
||||
Limited deterministic conflict detection recognises case-insensitive `during exercise`, `during activity`,
|
||||
`after exercise`, `after activity`, `under motion`, `under træning`, `efter motion`, `efter træning` against
|
||||
AtRest; `at clinic`, `in clinic`, `at the clinic`, `på klinik`, `hos lægen` against Home; and `at home`,
|
||||
`hjemme` against Clinic. It examines preserved context, notes and recorded preparation text, without
|
||||
recategorising observations. This is conservative phrase detection, not general language understanding;
|
||||
negated phrases can still withhold interpretation. Arbitrary narrative is not proof of correct technique.
|
||||
Detected conflicts withhold resting-reference interpretation while preserving numerical information.
|
||||
|
||||
Sources reviewed 2026-10-05:
|
||||
|
||||
- [Lægehåndbogen: Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/)
|
||||
(updated 2024-09-25): separate high-pressure boundaries of home 135/85 and clinic 140/90 mmHg,
|
||||
inclusive. The reference comparison requires a single known setting and recorded AtRest; known rest
|
||||
below five minutes or a non-seated recorded position prevents it. Missing optional preparation
|
||||
details permit only a provisional comparison, explicitly identifying unknown technique. Arbitrary
|
||||
period means do not establish the source's diagnostic protocol. No lower BP boundary is inferred.
|
||||
- [Patienthåndbogen: Bradykardi](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/)
|
||||
(updated 2025-09-02) and [Hurtig puls](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/)
|
||||
(updated 2025-05-12): resting pulse below 50 or above 100 beats/min provides limited rate-reference
|
||||
comparisons. Low pulse can be physiological in trained people. Rate alone does not diagnose rhythm
|
||||
abnormalities; age, fitness, medicines and symptoms remain unknown. These boundaries are not a
|
||||
universal healthy range or a patient-specific target.
|
||||
|
||||
Every metric returns its reference scope, exact comparison operators, source URLs, update/review dates,
|
||||
counts outside the boundaries and limitations. Comparisons remain available despite missing preparation
|
||||
information when the known context supports that limited comparison. Mixed or unknown activity,
|
||||
conflicting narrative, mixed BP settings, or unsupported BP setting make the affected comparison unavailable.
|
||||
|
||||
Interpretation of development requires temporal separation, applicable references and supported recorded
|
||||
comparability. The following are deliberately cautious inferences from the cited references, not new
|
||||
clinical decision rules: a consistent fall from high BP that remains high may be PotentiallyFavourable,
|
||||
while explicitly still high; resting pulse moving from outside towards the reference interval may be
|
||||
PotentiallyFavourable unless any contributing observation crosses the opposite boundary, including values within timestamp ties. Excursions outside a boundary with reversals
|
||||
are Mixed. Other outside-reference levels may be PotentiallyConcerning, including falling low pulse
|
||||
or unchanging high BP. Remaining cases are CannotInterpret. No BP fall below the high threshold is
|
||||
automatically called favourable, because an applicable lower limit or personalised goal is unavailable.
|
||||
|
||||
Each hint distinguishes numerical variation from clinical meaning, explains incomplete/differing context,
|
||||
and disclaims diagnosis and medication advice. There is no combined good/bad classification across metrics.
|
||||
Reference comparisons and hints are for review, not a replacement for individual clinical assessment.
|
||||
Reference in new issue
Block a user