Separate preserved Analytics policies and reviewed reference ownership

This commit is contained in:
Steffen committed 2026-10-14 11:48:58 +02:00
1 parent 3a70e3e296
commit cab10c5306
23 files changed
+15906 -3

No files matched your search

@@ -0,0 +1,12 @@
namespace HealthApp.Contracts;
public interface ReferenceCatalog
{
ClinicalReference Pulse();
ClinicalReference Pressure(string metric,string setting);
string Version {get;}
}
public interface AnalyticsQueries
{
Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
}
+6
View File
@@ -0,0 +1,6 @@
namespace HealthApp.Contracts;
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -0,0 +1,21 @@
namespace HealthApp.Contracts;
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);
@@ -0,0 +1,19 @@
using HealthApp.Contracts;
using HealthApp.Security;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace HealthApp.Controllers;
[ApiController]
public sealed class InsightsController(AnalyticsQueries analytics,AccessPolicy access) : ControllerBase
{
[HttpGet("api/patients/{patientId:guid}/insights")]
public Task<IActionResult> Insight(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,false,ct);
[HttpGet("api/patients/{patientId:guid}/trends")]
public Task<IActionResult> Trend(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,true,ct);
private async Task<IActionResult> Calculate(Guid patientId,DateTime from,DateTime to,ContextSelection selection,bool trend,CancellationToken ct)
{
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null){Response.StatusCode=404;return new EmptyResult();}
try{if(trend)return Ok(await analytics.TrendAsync(scope,from,to,selection,ct));var insight=await analytics.InsightAsync(scope,from,to,selection,ct);return insight is null?Problem(statusCode:404,title:"Insufficient observation data for calculation."):Ok(insight);}
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/><ProjectReference Include="../Modules/Observations/Observations.csproj"/></ItemGroup>
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/><ProjectReference Include="../Modules/Observations/Observations.csproj"/><ProjectReference Include="../Modules/Analytics/Analytics.csproj"/></ItemGroup>
</Project>
+3 -1
View File
@@ -2,6 +2,8 @@ using HealthApp.Guidance;
using HealthApp.Infrastructure;
using HealthApp.Profile;
using HealthApp.Observations;
using HealthApp.Analytics;
using HealthApp.Contracts;
using Npgsql;
using HealthApp.Security;
using Microsoft.AspNetCore.Authorization;
@@ -17,7 +19,7 @@ public class Program
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<PrototypeAccounts>();
builder.Services.AddSingleton<ProfessionalAssignments>();
builder.Services.AddSingleton<GuidanceQueries>();
builder.Services.AddSingleton<GuidanceQueries>();builder.Services.AddSingleton<ReferenceCatalog,ReviewedReferenceCatalog>();builder.Services.AddAnalytics();
builder.Services.AddSingleton(sp=> {
var c=sp.GetRequiredService<IConfiguration>();
var text=c.GetConnectionString("HealthDatabase");
+4
View File
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
</Project>
+25
View File
@@ -0,0 +1,25 @@
using HealthApp.Contracts;
using HealthApp.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
namespace HealthApp.Analytics;
internal sealed class AnalyticsFacade(ObservationQueries observations,RequestTransaction tx,SummaryPolicy summary,TrendPolicy trend) : AnalyticsQueries
{
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return summary.CalculateSummary(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return trend.CalculateTrend(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
}
public static class AnalyticsModule
{
public static IServiceCollection AddAnalytics(this IServiceCollection s)
{s.AddSingleton<SummaryPolicy>();s.AddSingleton<ClinicalPolicy>();s.AddSingleton<TrendPolicy>();s.AddScoped<AnalyticsQueries,AnalyticsFacade>();return s;}
}
// Test-only-compatible calculation entry, internal to the module; no public repository/SQL access.
internal sealed class InsightCalculator
{
private readonly SummaryPolicy summary=new();
private readonly TrendPolicy trend;
internal InsightCalculator(ReferenceCatalog catalog){trend=new(new ClinicalPolicy(catalog));}
public HealthInsight? CalculateSummary(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>summary.CalculateSummary(patientId,from,to,observations,selection);
public TrendAssessment CalculateTrend(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>trend.CalculateTrend(patientId,from,to,observations,selection);
}
+2
View File
@@ -0,0 +1,2 @@
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
+92
View File
@@ -0,0 +1,92 @@
using System.Globalization;
using HealthApp.Contracts;
namespace HealthApp.Analytics;
internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
{
internal 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.";
internal (ClinicalReference? Reference,string Comparison,string Interpretation,string Hint) Apply(string metric,string unit,IReadOnlyList<ObservationDto> observations,ComparabilityAssessment comparability,(DateTime Time,decimal Value)[] points,string direction,int reversals,decimal mean,Func<ObservationDto,int> value)
{
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 (reference,comparison,interpretation,hint);
}
private 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 catalog.Pulse();
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;
return catalog.Pressure(metric,settings[0]!);
}
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);
}
+50
View File
@@ -0,0 +1,50 @@
using System.Globalization;
using HealthApp.Contracts;
namespace HealthApp.Analytics;
internal sealed class SummaryPolicy
{
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
if (observations.Count == 0)
return null;
return new HealthInsight(patientId, from, to,
Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
selection, observations.Count, DescribeContext(observations));
}
private static string DescribeContext(IReadOnlyList<ObservationDto> observations)
{
var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
explanation += " This numerical summary pools mixed settings or activity conditions.";
if (settings.Contains("Unknown") || activities.Contains("Unknown"))
explanation += " Some setting or activity information is unknown.";
var details = new (string Name, string?[] Values)[]
{
("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()),
("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
};
var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
.Select(d => d.Name).ToArray();
if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
}
private static string Counts(IEnumerable<string> values) => string.Join(", ", values.GroupBy(v => v)
.OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
}
+131
View File
@@ -0,0 +1,131 @@
using System.Globalization;
using HealthApp.Contracts;
namespace HealthApp.Analytics;
internal sealed class TrendPolicy(ClinicalPolicy clinical)
{
private const string GeneralLimits=ClinicalPolicy.GeneralLimits;
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 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 result = clinical.Apply(metric,unit,observations,comparability,points,direction,reversals,mean,value);
var reference=result.Reference;var comparison=result.Comparison;var interpretation=result.Interpretation;var hint=result.Hint;
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 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);
}
}
@@ -0,0 +1,31 @@
using HealthApp.Contracts;
namespace HealthApp.Guidance;
// Pinned content and thresholds; this relocation does not imply a new clinical review.
public sealed class ReviewedReferenceCatalog : ReferenceCatalog
{
public string Version=>"baseline-2026-10-05";
public ClinicalReference 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.");
}
public ClinicalReference Pressure(string metric,string setting)
{
var threshold = metric == "Systolic" ? (setting == "Home" ? 135 : 140) :
(setting == "Home" ? 85 : 90);
return new($"Recorded {setting} 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.");
}
}
+85
View File
@@ -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. Analytics obtains current immutable observations through the typed ObservationQueries interface inside the authorized request snapshot, without result persistence.
A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
`Unavailable` direction distinguish empty data from dependency/deadline failures (503/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. The algorithm is unchanged; method version is baseline-2026-10-05.
## 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.