remora-kit

RemoraKit, shared dive computer engine (Buhlmann ZHL-16C + GF) and SwiftUI components for Open Remora and Open Merou
git clone https://git.schurger.org/remora-kit.git
Log | Files | Refs | README | LICENSE

DecoTests.swift (16780B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import Testing
      4 @testable import RemoraDeco
      5 
      6 let scale = DepthScale(surfacePressure: standardSurfacePressure, water: .salt)
      7 
      8 /// Diver saturated at the surface, dropped instantly to `depth`, then staying there for `minutes`.
      9 func tissues(after minutes: Double, at depth: Double, gas: Gas = .air) -> TissueState {
     10     var t = TissueState.saturated(surfacePressure: scale.surfacePressure)
     11     t.stay(atPressure: scale.pressure(atDepth: depth), gas: gas, minutes: minutes)
     12     return t
     13 }
     14 
     15 func ndl(at depth: Double, gf: GradientFactors, gas: Gas = .air) -> Double? {
     16     TissueState.saturated(surfacePressure: scale.surfacePressure)
     17         .noDecompressionLimit(atPressure: scale.pressure(atDepth: depth), gas: gas,
     18                               surfacePressure: scale.surfacePressure, gfHigh: gf.high)
     19 }
     20 
     21 @Suite("Physics")
     22 struct PhysicsTests {
     23     @Test func depthRoundTrip() {
     24         let p = scale.pressure(atDepth: 30)
     25         #expect(abs(scale.depth(atPressure: p) - 30) < 1e-9)
     26         #expect(abs(p - (1.01325 + 30 * 0.10052)) < 0.001)
     27     }
     28 
     29     @Test func maximumOperatingDepth() {
     30         #expect(abs(Gas.air.maximumOperatingDepth(ppO2Limit: 1.4, scale: scale) - 56.2) < 0.1)
     31         #expect(abs(Gas.nitrox(32).maximumOperatingDepth(ppO2Limit: 1.4, scale: scale) - 33.4) < 0.3)
     32     }
     33 }
     34 
     35 @Suite("Tissues")
     36 struct TissueTests {
     37     @Test func surfaceSaturationHasNoCeiling() {
     38         let t = TissueState.saturated(surfacePressure: scale.surfacePressure)
     39         #expect(t.ceiling(gradientFactor: 1) < scale.surfacePressure)
     40         #expect(t.ceiling(gradientFactor: 0.3) < scale.surfacePressure)
     41         #expect(ndl(at: 0, gf: .conservative) == nil)
     42         #expect(ndl(at: 3, gf: .conservative) == nil)
     43         #expect(ndl(at: 6, gf: .conservative)! > 24 * 60)   // finite but out of reach (shown as ">99")
     44     }
     45 
     46     @Test func schreinerMatchesFineConstantSteps() {
     47         let start = scale.pressure(atDepth: 0), end = scale.pressure(atDepth: 30)
     48         var exact = TissueState.saturated(), stepped = TissueState.saturated()
     49         exact.change(from: start, to: end, gas: .air, minutes: 2)
     50         let n = 4000
     51         for i in 0..<n {
     52             let mid = start + (end - start) * (Double(i) + 0.5) / Double(n)
     53             stepped.stay(atPressure: mid, gas: .air, minutes: 2 / Double(n))
     54         }
     55         for (a, b) in zip(exact.nitrogen, stepped.nitrogen) { #expect(abs(a - b) < 1e-5) }
     56     }
     57 
     58     @Test func schreinerAtConstantPressureIsHaldane() {
     59         let p = scale.pressure(atDepth: 20)
     60         var a = TissueState.saturated(), b = TissueState.saturated()
     61         a.change(from: p, to: p, gas: .air, minutes: 17)
     62         b.stay(atPressure: p, gas: .air, minutes: 17)
     63         for (x, y) in zip(a.nitrogen, b.nitrogen) { #expect(abs(x - y) < 1e-12) }
     64     }
     65 
     66     @Test func surfaceIntervalOffgasses() {
     67         let loaded = tissues(after: 30, at: 25)
     68         let rested = DiveComputer.surfaceInterval(loaded, minutes: 60, surfacePressure: scale.surfacePressure)
     69         for (a, b) in zip(loaded.nitrogen, rested.nitrogen) { #expect(b < a) }
     70     }
     71 }
     72 
     73 @Suite("No-decompression limit")
     74 struct NoDecoTests {
     75     @Test func decreasesWithDepth() throws {
     76         var previous = Double.infinity
     77         for depth in [12.0, 18, 24, 30, 40] {
     78             let v = try #require(ndl(at: depth, gf: .conservative))
     79             #expect(v < previous)
     80             previous = v
     81         }
     82     }
     83 
     84     @Test func conservativeIsShorterThanPureBuhlmann() throws {
     85         let strict = try #require(ndl(at: 30, gf: .conservative))
     86         let pure = try #require(ndl(at: 30, gf: .pureBuhlmann))
     87         #expect(strict < pure)
     88     }
     89 
     90     @Test func nitroxExtendsLimit() throws {
     91         let air = try #require(ndl(at: 30, gf: .conservative))
     92         let ean32 = try #require(ndl(at: 30, gf: .conservative, gas: .nitrox(32)))
     93         #expect(ean32 > air)
     94     }
     95 
     96     /// Orders of magnitude only: fine validation will be done against Subsurface.
     97     @Test func plausibleValues() throws {
     98         let pure30 = try #require(ndl(at: 30, gf: .pureBuhlmann))
     99         let pure18 = try #require(ndl(at: 18, gf: .pureBuhlmann))
    100         print("NDL air, GF 100/100: 18 m = \(pure18) min, 30 m = \(pure30) min")
    101         print("NDL air, GF 30/70: 18 m = \(ndl(at: 18, gf: .conservative)!) min, 30 m = \(ndl(at: 30, gf: .conservative)!) min")
    102         #expect((10...25).contains(pure30))
    103         #expect((40...70).contains(pure18))
    104     }
    105 
    106     @Test func limitReachedMeansSurfaceCeiling() throws {
    107         let gf = GradientFactors.conservative
    108         let limit = try #require(ndl(at: 30, gf: gf))
    109         let t = tissues(after: limit, at: 30)
    110         #expect(abs(t.ceiling(gradientFactor: gf.high) - scale.surfacePressure) < 0.002)
    111     }
    112 }
    113 
    114 @Suite("Decompression stops")
    115 struct DecoPlanTests {
    116     func plan(minutes: Double, depth: Double, settings: DecoSettings = DecoSettings()) -> AscentPlan {
    117         AscentPlanner.plan(tissues: tissues(after: minutes, at: depth),
    118                            pressure: scale.pressure(atDepth: depth), gas: .air,
    119                            scale: scale, settings: settings)
    120     }
    121 
    122     @Test func noStopsInsideLimit() {
    123         let p = plan(minutes: 5, depth: 18)
    124         #expect(!p.inDecompression)
    125         #expect(p.noDecompressionLimit ?? .infinity > 0)
    126         #expect(abs(p.timeToSurface - 2) < 1e-9)   // 18 m at 9 m/min
    127     }
    128 
    129     @Test func decoDiveHasOrderedStops() throws {
    130         let p = plan(minutes: 25, depth: 40)
    131         print("40 m, 25 min, air, GF 30/70:", p.stops.map { "\(Int($0.depth)) m \($0.minutes) min" }, "TTS", p.timeToSurface)
    132         #expect(p.inDecompression)
    133         #expect(p.noDecompressionLimit == 0)
    134         let depths = p.stops.map(\.depth)
    135         #expect(depths == depths.sorted(by: >))
    136         #expect(depths.allSatisfy { $0.truncatingRemainder(dividingBy: 3) == 0 && $0 >= 3 })
    137         let first = try #require(depths.first)
    138         #expect((6...24).contains(first))
    139         #expect(p.gradientAnchorDepth == first)
    140         #expect(p.timeToSurface > 40 / 9)
    141     }
    142 
    143     @Test func followingThePlanAllowsSurfacing() throws {
    144         let settings = DecoSettings()
    145         let p = plan(minutes: 25, depth: 40, settings: settings)
    146         var t = tissues(after: 25, at: 40)
    147         var depth = 40.0
    148         for stop in p.stops {
    149             t.change(from: scale.pressure(atDepth: depth), to: scale.pressure(atDepth: stop.depth),
    150                      gas: .air, minutes: (depth - stop.depth) / settings.ascentRate)
    151             t.stay(atPressure: scale.pressure(atDepth: stop.depth), gas: .air, minutes: Double(stop.minutes))
    152             depth = stop.depth
    153         }
    154         t.change(from: scale.pressure(atDepth: depth), to: scale.surfacePressure, gas: .air,
    155                  minutes: depth / settings.ascentRate)
    156         #expect(t.ceiling(gradientFactor: settings.gradientFactors.high) <= scale.surfacePressure + 1e-6)
    157     }
    158 
    159     /// A diver right on a stop, whose depth comes back from the pressure as 2.9999999999999996 m (fresh
    160     /// water, low surface pressure): the stop is the 3 m one, not a depth the display truncates to "2 m".
    161     @Test func stopOfADiverOnTheGridIsOnTheGrid() throws {
    162         let lake = DepthScale(surfacePressure: 0.976, water: .fresh)
    163         var t = TissueState.saturated(surfacePressure: lake.surfacePressure)
    164         t.stay(atPressure: lake.pressure(atDepth: 40), gas: .air, minutes: 25)
    165         for depth in [3.0, 6.0, 9.0] {
    166             let pressure = lake.pressure(atDepth: depth)
    167             let p = AscentPlanner.plan(tissues: t, pressure: pressure, gas: .air, scale: lake, settings: DecoSettings())
    168             let first = try #require(p.stops.first)
    169             #expect(first.depth.truncatingRemainder(dividingBy: 3) == 0 && first.depth >= depth)
    170         }
    171     }
    172 
    173     @Test func moreConservativeMeansLongerDeco() {
    174         var pure = DecoSettings(); pure.gradientFactors = .pureBuhlmann
    175         let strict = plan(minutes: 25, depth: 40)
    176         let loose = plan(minutes: 25, depth: 40, settings: pure)
    177         #expect(strict.timeToSurface > loose.timeToSurface)
    178     }
    179 }
    180 
    181 @Suite("Dive computer")
    182 struct DiveComputerTests {
    183     /// Profile sampled at 1 Hz: (target depth, rate in m/min or bottom time).
    184     func run(_ computer: inout DiveComputer, from depth: inout Double, to target: Double,
    185              rate: Double, time: inout Double) {
    186         while abs(depth - target) > 1e-9 {
    187             let step = rate / 60
    188             depth = depth < target ? min(target, depth + step) : max(target, depth - step)
    189             time += 1
    190             computer.update(time: time, pressure: scale.pressure(atDepth: depth))
    191         }
    192     }
    193 
    194     func hold(_ computer: inout DiveComputer, at depth: Double, seconds: Int, time: inout Double) {
    195         for _ in 0..<seconds {
    196             time += 1
    197             computer.update(time: time, pressure: scale.pressure(atDepth: depth))
    198         }
    199     }
    200 
    201     func makeComputer() -> DiveComputer {
    202         var config = DiveComputer.Configuration()
    203         config.water = .salt
    204         return DiveComputer(configuration: config, surfacePressure: scale.surfacePressure)
    205     }
    206 
    207     @Test func recreationalDive() {
    208         var c = makeComputer()
    209         var t = 0.0, d = 0.0
    210         c.update(time: 0, pressure: scale.surfacePressure)
    211         run(&c, from: &d, to: 18, rate: 18, time: &t)
    212         hold(&c, at: 18, seconds: 20 * 60, time: &t)
    213         let s = c.status
    214         #expect(abs(s.depth - 18) < 1e-6)
    215         #expect(abs(s.maxDepth - 18) < 1e-6)
    216         #expect(!s.plan.inDecompression)
    217         #expect(s.plan.noDecompressionLimit ?? .infinity > 0)
    218         #expect(s.safetyStopRecommended)
    219         #expect(s.warnings.isEmpty)
    220         #expect(abs(s.elapsed - 21) < 0.02)
    221     }
    222 
    223     @Test func fastAscentIsFlagged() {
    224         var c = makeComputer()
    225         var t = 0.0, d = 0.0
    226         c.update(time: 0, pressure: scale.surfacePressure)
    227         run(&c, from: &d, to: 20, rate: 18, time: &t)
    228         run(&c, from: &d, to: 14, rate: 18, time: &t)
    229         #expect(c.status.warnings.contains(.ascentTooFast))
    230         run(&c, from: &d, to: 8, rate: 6, time: &t)
    231         #expect(c.status.warnings.isDisjoint(with: [.ascentFast, .ascentTooFast]))
    232     }
    233 
    234     @Test func decoAnchorsGradientAndFlagsCeiling() throws {
    235         var c = makeComputer()
    236         var t = 0.0, d = 0.0
    237         c.update(time: 0, pressure: scale.surfacePressure)
    238         run(&c, from: &d, to: 40, rate: 18, time: &t)
    239         hold(&c, at: 40, seconds: 25 * 60, time: &t)
    240         let s = c.status
    241         #expect(s.plan.inDecompression)
    242         let anchor = try #require(c.gradientAnchorDepth)
    243         #expect(anchor == s.plan.stops.first?.depth)
    244         #expect(s.ceilingDepth > 0)
    245         // Direct ascent above the ceiling: alarm.
    246         run(&c, from: &d, to: 0.5, rate: 9, time: &t)
    247         #expect(c.status.warnings.contains(.ceilingViolated))
    248     }
    249 
    250     @Test func highPpO2() {
    251         var config = DiveComputer.Configuration()
    252         config.gas = .nitrox(36)
    253         config.water = .salt
    254         var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure)
    255         c.update(time: 0, pressure: scale.pressure(atDepth: 33))
    256         #expect(c.status.warnings.contains(.ppO2High))
    257         c.update(time: 1, pressure: scale.pressure(atDepth: 36))
    258         #expect(c.status.warnings.contains(.ppO2Critical))
    259     }
    260 }
    261 
    262 @Suite("Dive screen")
    263 struct DiveScreenEngineTests {
    264     func computer() -> DiveComputer {
    265         var config = DiveComputer.Configuration()
    266         config.water = .salt
    267         return DiveComputer(configuration: config, surfacePressure: scale.surfacePressure)
    268     }
    269 
    270     /// 1 Hz profile: (target depth, rate in m/min, seconds held there).
    271     func run(_ c: inout DiveComputer, _ legs: [(Double, Double, Int)]) {
    272         var t = 0.0, d = 0.0
    273         c.update(time: 0, pressure: scale.surfacePressure)
    274         for (target, rate, hold) in legs {
    275             while abs(d - target) > 1e-9 {
    276                 d = d < target ? min(target, d + rate / 60) : max(target, d - rate / 60)
    277                 t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d))
    278             }
    279             for _ in 0..<hold { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) }
    280         }
    281     }
    282 
    283     @Test func firstStopHasSecondsCountdown() throws {
    284         let p = AscentPlanner.plan(tissues: tissues(after: 25, at: 40), pressure: scale.pressure(atDepth: 40),
    285                                    gas: .air, scale: scale, settings: DecoSettings())
    286         let first = try #require(p.stops.first)
    287         let seconds = try #require(first.seconds)
    288         #expect(seconds % 10 == 0)
    289         #expect(seconds <= first.minutes * 60)          // the countdown never exceeds the displayed minute
    290         #expect(seconds > (first.minutes - 1) * 60)
    291         #expect(p.stops.dropFirst().allSatisfy { $0.seconds == nil })
    292     }
    293 
    294     @Test func safetyStopCountsDownThenDone() {
    295         var c = computer()
    296         run(&c, [(18, 18, 600), (5, 9, 90)])
    297         guard case .running(let remaining) = c.safetyStop else { Issue.record("expected running: \(c.safetyStop)"); return }
    298         #expect(abs(remaining - 90) < 15)
    299         var d = c
    300         let t0 = 18.0 / 18 * 60 + 600 + 13.0 / 9 * 60 + 90
    301         for i in 1...120 { d.update(time: t0 + Double(i), pressure: scale.pressure(atDepth: 5)) }
    302         #expect(d.safetyStop == .done)
    303     }
    304 
    305     @Test func skippingSafetyStopIsFlagged() {
    306         var c = computer()
    307         run(&c, [(18, 18, 600), (0, 9, 5)])
    308         #expect(c.safetyStop == .missed)
    309         #expect(c.status.warnings.contains(.missedSafetyStop))
    310     }
    311 
    312     @Test func shallowDiveNeedsNoSafetyStop() {
    313         var c = computer()
    314         run(&c, [(8, 18, 600), (0, 9, 5)])
    315         #expect(c.safetyStop == .notRequired)
    316         #expect(!c.status.warnings.contains(.missedSafetyStop))
    317     }
    318 
    319     @Test func depthLimitAndLowNoDecoWarnings() {
    320         var c = computer()
    321         run(&c, [(38.5, 18, 5)])
    322         #expect(c.status.warnings.contains(.depthLimit))
    323         var l = computer()
    324         run(&l, [(30, 18, 360)])
    325         let ndl = l.status.plan.noDecompressionLimit ?? 99
    326         #expect(ndl < 5)
    327         #expect(l.status.warnings.contains(.lowNoDecompression))
    328     }
    329 }
    330 
    331 @Suite("0.2 review")
    332 struct ReviewTests {
    333     @Test func aboveRequiredStopIsAViolation() {
    334         var config = DiveComputer.Configuration(); config.water = .salt
    335         var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure)
    336         var t = 0.0, d = 0.0
    337         c.update(time: 0, pressure: scale.surfacePressure)
    338         while d < 40 { d = min(40, d + 0.3); t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) }
    339         for _ in 0..<(25 * 60) { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) }
    340         // Continuous ascent at 9 m/min, skipping the stops (the first ones clear on the way up, not the last).
    341         var flagged = false
    342         while d > 1 {
    343             d -= 0.15; t += 1
    344             c.update(time: t, pressure: scale.pressure(atDepth: d))
    345             let status = c.status
    346             if let stop = status.plan.stops.first, d < stop.depth - 0.6 {
    347                 #expect(status.warnings.contains(.ceilingViolated))
    348                 flagged = true
    349             }
    350         }
    351         #expect(flagged)
    352     }
    353 
    354     @Test func missedSafetyStopCanBeRedone() {
    355         var config = DiveComputer.Configuration(); config.water = .salt
    356         var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure)
    357         var t = 0.0
    358         func at(_ depth: Double, _ seconds: Int) { for _ in 0..<seconds { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: depth)) } }
    359         c.update(time: 0, pressure: scale.surfacePressure)
    360         at(15, 300); at(0.2, 5)
    361         #expect(c.safetyStop == .missed)
    362         at(12, 60)
    363         #expect(c.safetyStop == .pending)
    364         at(5, 181)
    365         #expect(c.safetyStop == .done)
    366         #expect(!c.status.warnings.contains(.missedSafetyStop))
    367     }
    368 
    369     @Test func oscillatingAlarmIsLoggedOncePerPeriod() {
    370         var config = DiveComputer.Configuration(); config.water = .salt
    371         var r = DiveRecorder(configuration: config, surfacePressure: scale.surfacePressure,
    372                              start: Date(timeIntervalSince1970: 1_800_000_000))
    373         var t = 0.0
    374         r.record(time: 0, pressure: scale.surfacePressure)
    375         // Around 38 m: above then below the depth limit, every 2 s for 40 s.
    376         for i in 0..<20 {
    377             t += 2
    378             r.record(time: t, pressure: scale.pressure(atDepth: i % 2 == 0 ? 38.2 : 37.8))
    379         }
    380         let count = r.finish().events.filter { $0.warning == .depthLimit }.count
    381         #expect(count == 2)   // at t=2 s, then once 30 s have passed
    382     }
    383 }