feature: NEWS2 Composite Scoring Engine

This commit is contained in:
voltsrage
2026-06-18 17:39:31 +08:00
parent c3fbc20ddc
commit e6f7989298
31 changed files with 3118 additions and 45 deletions
@@ -8,7 +8,7 @@ public static class DbResetHelper
{
await db.Database.ExecuteSqlRawAsync(@"
TRUNCATE TABLE reconciliation_alerts, outbox_events, orders,
clinical_alerts, observations, encounters,
clinical_alerts, news2_scores, observations, encounters,
alert_thresholds, patients
RESTART IDENTITY CASCADE;
");
@@ -0,0 +1,107 @@
using FluentAssertions;
public class News2CalculatorTests
{
// --- Respiratory rate ---
[Theory]
[InlineData(8, 3)] // ≤8
[InlineData(9, 1)] // 9-11
[InlineData(11, 1)]
[InlineData(12, 0)] // 12-20
[InlineData(20, 0)]
[InlineData(21, 2)] // 21-24
[InlineData(24, 2)]
[InlineData(25, 3)] // ≥25
public void ScoreRespRate(int value, int expected) =>
News2Calculator.ScoreRespRate(value).Should().Be(expected);
// --- SpO2 (Scale 1) ---
[Theory]
[InlineData(91, 3)]
[InlineData(92, 2)]
[InlineData(93, 2)]
[InlineData(94, 1)]
[InlineData(95, 1)]
[InlineData(96, 0)]
[InlineData(99, 0)]
public void ScoreSpo2(int value, int expected) =>
News2Calculator.ScoreSpo2(value).Should().Be(expected);
// --- Systolic BP ---
[Theory]
[InlineData(90, 3)]
[InlineData(91, 2)]
[InlineData(100, 2)]
[InlineData(101, 1)]
[InlineData(110, 1)]
[InlineData(111, 0)]
[InlineData(219, 0)]
[InlineData(220, 3)]
public void ScoreSystolicBp(int value, int expected) =>
News2Calculator.ScoreSystolicBp(value).Should().Be(expected);
// --- Heart rate ---
[Theory]
[InlineData(40, 3)]
[InlineData(41, 1)]
[InlineData(50, 1)]
[InlineData(51, 0)]
[InlineData(90, 0)]
[InlineData(91, 1)]
[InlineData(110, 1)]
[InlineData(111, 2)]
[InlineData(130, 2)]
[InlineData(131, 3)]
public void ScoreHeartRate(int value, int expected) =>
News2Calculator.ScoreHeartRate(value).Should().Be(expected);
// --- AVPU ---
[Theory]
[InlineData(0, 0)] // Alert
[InlineData(1, 3)] // Voice
[InlineData(2, 3)] // Pain
[InlineData(3, 3)] // Unresponsive
public void ScoreConsciousness(int value, int expected) =>
News2Calculator.ScoreConsciousness(value).Should().Be(expected);
// --- Temperature ---
[Theory]
[InlineData(35.0, 3)]
[InlineData(35.1, 1)]
[InlineData(36.0, 1)]
[InlineData(36.1, 0)]
[InlineData(38.0, 0)]
[InlineData(38.1, 1)]
[InlineData(39.0, 1)]
[InlineData(39.1, 2)]
public void ScoreTemperature(double value, int expected) =>
News2Calculator.ScoreTemperature((decimal)value).Should().Be(expected);
// --- Supplemental O2 ---
[Theory]
[InlineData(0, 0)]
[InlineData(1, 2)]
public void ScoreSupplementalO2(int value, int expected) =>
News2Calculator.ScoreSupplementalO2(value).Should().Be(expected);
// --- Risk level determination ---
[Theory]
[InlineData(0, false, "LOW")]
[InlineData(4, false, "LOW")]
[InlineData(3, true, "LOW_MEDIUM")] // single param = 3
[InlineData(5, false, "MEDIUM")]
[InlineData(6, true, "MEDIUM")] // 5-6 is MEDIUM regardless of single-3
[InlineData(7, false, "HIGH")]
[InlineData(12, true, "HIGH")]
public void DetermineRiskLevel(int total, bool singleThree, string expected) =>
News2Calculator.DetermineRiskLevel(total, singleThree).Should().Be(expected);
// --- All 7 keys returned ---
[Fact]
public void AllParameterKeys_ReturnsSeven()
{
var keys = News2Calculator.AllParameterKeys(Guid.NewGuid());
keys.Should().HaveCount(7);
keys.Select(k => k.ToString()).Should().OnlyHaveUniqueItems();
}
}
@@ -0,0 +1,225 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class News2DetectorTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _encounterId;
private Guid _patientId;
public News2DetectorTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-NEWS2-001", FirstName = "NEWS2", LastName = "Test",
DateOfBirth = new DateOnly(1960, 1, 1), Gender = "M",
CreatedAt = DateTimeOffset.UtcNow
};
var encounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = Department.Icu,
AttendingPhysician = "Dr. NEWS2", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
await db.SaveChangesAsync();
_patientId = patient.Id;
_encounterId = encounter.Id;
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase();
foreach (var key in News2Calculator.AllParameterKeys(_encounterId))
await cache.KeyDeleteAsync(key);
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task AllNormalParameters_ScoreZero_NoAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 16m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 98m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 120m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "AVPU", 0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 36.8m);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "SUPPLEMENTAL_O2", 0m);
result.Outcome.Should().Be(News2Outcome.ScoreComputed);
result.TotalScore.Should().Be(0);
result.RiskLevel.Should().Be("LOW");
result.AlertCreated.Should().BeFalse();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var score = await db.News2Scores.SingleAsync();
score.TotalScore.Should().Be(0);
score.RiskLevel.Should().Be("LOW");
(await db.ClinicalAlerts.CountAsync()).Should().Be(0);
}
[Fact]
public async Task MediumRisk_WarningAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 22m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 93m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 105m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "AVPU", 0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 37.0m);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "SUPPLEMENTAL_O2", 0m);
result.TotalScore.Should().Be(6);
result.RiskLevel.Should().Be("MEDIUM");
result.AlertCreated.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.News2Warning);
alert.Severity.Should().Be(AlertSeverity.Warning);
}
[Fact]
public async Task HighRisk_CriticalAlert()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 25m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 91m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "AVPU", 0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 37.0m);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "SUPPLEMENTAL_O2", 0m);
result.TotalScore.Should().Be(8);
result.RiskLevel.Should().Be("HIGH");
result.AlertCreated.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.News2Emergency);
alert.Severity.Should().Be(AlertSeverity.Critical);
}
[Fact]
public async Task SingleParamThree_LowMedium_Warning()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 8m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 98m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 120m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "AVPU", 0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 37.0m);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "SUPPLEMENTAL_O2", 0m);
result.TotalScore.Should().Be(3);
result.RiskLevel.Should().Be("LOW_MEDIUM");
result.AlertCreated.Should().BeTrue();
result.HasSingleParamThree.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var score = await db.News2Scores.SingleAsync();
score.HasSingleParamThree.Should().BeTrue();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.AlertType.Should().Be(AlertType.News2Warning);
}
[Fact]
public async Task IncompleteParameters_NoScore()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 16m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 98m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "TEMP_C", 37.0m);
result.Outcome.Should().Be(News2Outcome.IncompleteParameters);
result.PresentParameters.Should().Be(4);
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
(await db.News2Scores.CountAsync()).Should().Be(0);
(await db.ClinicalAlerts.CountAsync()).Should().Be(0);
}
[Fact]
public async Task NonNews2Code_Ignored()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var result = await detector.ProcessObservationAsync(
_encounterId, _patientId, "POTASSIUM_MEQ_L", 4.0m);
result.Outcome.Should().Be(News2Outcome.NotNews2Code);
var anyNews2Key = false;
foreach (var key in News2Calculator.AllParameterKeys(_encounterId))
{
if (await redis.GetDatabase().KeyExistsAsync(key))
anyNews2Key = true;
}
anyNews2Key.Should().BeFalse();
}
[Fact]
public async Task DuplicateHighRisk_Idempotent()
{
using var scope = _fixture.Services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// First pass — score 8, creates alert
await FeedHighRiskSet(detector);
// Second scoring event — one parameter update while all 7 keys remain populated.
// Each observation after completeness triggers a new score row; alert must stay deduplicated.
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
(await db.ClinicalAlerts.CountAsync()).Should().Be(1,
"second NEWS2_EMERGENCY must be idempotent while first is still open");
(await db.News2Scores.CountAsync()).Should().Be(2,
"both scores should be persisted even though alert is deduplicated");
}
private async Task FeedHighRiskSet(News2Detector detector)
{
await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 25m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SPO2", 91m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 72m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "AVPU", 0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 37.0m);
await detector.ProcessObservationAsync(_encounterId, _patientId, "SUPPLEMENTAL_O2", 0m);
}
}