commit 5345b59e5f18df377243eea84c0adc5638ef1182
parent c27df568652a9d434479b7dbeb744140c7b27cbf
Author: Jean Schurger <jean@schurger.org>
Date: Sun, 15 Nov 2026 21:10:31 -0500
DivePlanner: gas calculations and a Buhlmann ZHL-16C planner with gradient factors
Nitrogen and helium, several cylinders with gas switches, stops every 3 m
ending on whole minutes of run time, gas used, minimum gas, oxygen exposure
(CNS, OTU), warnings, and quick answers for no-stop diving (no-stop limit,
how long a cylinder lasts).
The coefficients and the algorithm follow Subsurface (core/deco.cpp,
core/planner.cpp): its benchmark plan (79 m, 30 min, trimix 15/45, EAN36 and
oxygen) gives the same 109 minutes here.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
5 files changed, 855 insertions(+), 0 deletions(-)
diff --git a/Packages/DiveKit/Package.swift b/Packages/DiveKit/Package.swift
@@ -9,6 +9,7 @@ let package = Package(
.library(name: "GitLite", targets: ["GitLite"]),
.library(name: "SubsurfaceLog", targets: ["SubsurfaceLog"]),
.library(name: "DiveComputerKit", targets: ["DiveComputerKit"]),
+ .library(name: "DivePlanner", targets: ["DivePlanner"]),
],
targets: [
// Minimal git client in pure Swift: objects, packfiles, smart HTTP protocol.
@@ -22,12 +23,15 @@ let package = Package(
// Small C shims: libdivecomputer macros that Swift cannot import.
.target(name: "CDiveComputerShims", dependencies: ["CLibDiveComputer"]),
.target(name: "DiveComputerKit", dependencies: ["CLibDiveComputer", "CDiveComputerShims", "SubsurfaceLog"]),
+ // Gas calculations and decompression planning (Bühlmann ZHL-16C with gradient factors). No dependency.
+ .target(name: "DivePlanner"),
// Test support: drives the real command-line git (macOS only).
.target(name: "GitTestSupport", dependencies: ["GitLite"]),
// Command-line tool (macOS): import a file into a cloud logbook, list a logbook.
.executableTarget(name: "divelog-cli", dependencies: ["SubsurfaceLog", "GitLite"]),
.testTarget(name: "GitLiteTests", dependencies: ["GitLite", "GitTestSupport"]),
.testTarget(name: "SubsurfaceLogTests", dependencies: ["SubsurfaceLog", "GitLite", "GitTestSupport"]),
+ .testTarget(name: "DivePlannerTests", dependencies: ["DivePlanner"]),
.testTarget(name: "DiveComputerKitTests", dependencies: ["DiveComputerKit", "SubsurfaceLog", "GitTestSupport"]),
]
)
diff --git a/Packages/DiveKit/Sources/DivePlanner/Gas.swift b/Packages/DiveKit/Sources/DivePlanner/Gas.swift
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// Where the dive takes place: pressure at the surface and density of the water.
+public struct DiveEnvironment: Codable, Sendable, Equatable {
+ /// Bar. 1.01325 at sea level; lower in altitude.
+ public var surfacePressure = 1.01325
+ /// Kilograms per litre: 1.03 for sea water, 1.00 for fresh water.
+ public var waterDensity = 1.03
+
+ public init(surfacePressure: Double = 1.01325, waterDensity: Double = 1.03) {
+ self.surfacePressure = surfacePressure
+ self.waterDensity = waterDensity
+ }
+
+ public static let sea = DiveEnvironment()
+ public static let freshWater = DiveEnvironment(waterDensity: 1.0)
+
+ public var barPerMeter: Double { waterDensity * 0.0980665 }
+ /// Absolute pressure at a depth, in bar.
+ public func pressure(atDepth meters: Double) -> Double { surfacePressure + max(0, meters) * barPerMeter }
+ /// Depth where the absolute pressure is `bar`; 0 above the surface.
+ public func depth(atPressure bar: Double) -> Double { max(0, (bar - surfacePressure) / barPerMeter) }
+}
+
+/// A breathing gas: fractions of oxygen and helium, the rest being nitrogen.
+public struct BreathingGas: Codable, Sendable, Hashable {
+ public var o2: Double
+ public var he: Double
+
+ public init(o2: Double, he: Double = 0) {
+ self.o2 = min(max(o2, 0.01), 1)
+ self.he = min(max(he, 0), 1 - self.o2)
+ }
+
+ public init(o2Percent: Int, hePercent: Int = 0) {
+ self.init(o2: Double(o2Percent) / 100, he: Double(hePercent) / 100)
+ }
+
+ public static let air = BreathingGas(o2: 0.21)
+ public static let oxygen = BreathingGas(o2: 1)
+ /// Fraction of nitrogen in air, as Subsurface takes it.
+ static let nitrogenInAir = 0.7902
+
+ public var n2: Double { max(0, 1 - o2 - he) }
+ public var o2Percent: Int { Int((o2 * 100).rounded()) }
+ public var hePercent: Int { Int((he * 100).rounded()) }
+ public var isAir: Bool { o2Percent == 21 && hePercent == 0 }
+
+ /// "Air", "EAN32", "Tx18/45", "O2".
+ public var name: String {
+ if hePercent > 0 { return "Tx\(o2Percent)/\(hePercent)" }
+ if o2Percent >= 100 { return "O2" }
+ return isAir ? "Air" : "EAN\(o2Percent)"
+ }
+
+ /// Partial pressure of oxygen at a depth, in bar.
+ public func ppO2(atDepth meters: Double, in environment: DiveEnvironment = .sea) -> Double {
+ environment.pressure(atDepth: meters) * o2
+ }
+
+ /// Maximum operating depth for a limit on the partial pressure of oxygen, in metres.
+ public func maximumOperatingDepth(ppO2 limit: Double, in environment: DiveEnvironment = .sea) -> Double {
+ environment.depth(atPressure: limit / o2)
+ }
+
+ /// The same, rounded down to a multiple of `step` metres; a depth within a tenth of the next step counts for
+ /// it, so that oxygen at 1.6 bar is breathed from 6 m (Subsurface's rounding).
+ public func switchDepth(ppO2 limit: Double = 1.6, step: Double = 3, in environment: DiveEnvironment = .sea) -> Double {
+ (maximumOperatingDepth(ppO2: limit, in: environment) / step + 0.1).rounded(.down) * step
+ }
+
+ /// Shallowest depth where the gas gives at least `limit` bar of oxygen (0: breathable at the surface).
+ public func minimumDepth(ppO2 limit: Double = 0.16, in environment: DiveEnvironment = .sea) -> Double {
+ environment.depth(atPressure: limit / o2)
+ }
+
+ /// Equivalent narcotic depth: the depth where air would be as narcotic. With `oxygenNarcotic`, only helium is
+ /// counted as not narcotic (the cautious convention); otherwise only nitrogen is narcotic.
+ public func equivalentNarcoticDepth(atDepth meters: Double, oxygenNarcotic: Bool = true, in environment: DiveEnvironment = .sea) -> Double {
+ let pressure = environment.pressure(atDepth: meters)
+ let narcotic = oxygenNarcotic ? pressure * (1 - he) : pressure * n2 / Self.nitrogenInAir
+ return environment.depth(atPressure: narcotic)
+ }
+
+ /// Equivalent air depth of a nitrox: the depth where air gives the same partial pressure of nitrogen.
+ public func equivalentAirDepth(atDepth meters: Double, in environment: DiveEnvironment = .sea) -> Double {
+ environment.depth(atPressure: environment.pressure(atDepth: meters) * n2 / Self.nitrogenInAir)
+ }
+
+ /// Density of the gas at a depth, in grams per litre (5.2 is the usual recommended limit, 6.2 the hard one).
+ public func density(atDepth meters: Double, in environment: DiveEnvironment = .sea) -> Double {
+ (o2 * 1.429 + he * 0.1786 + n2 * 1.2506) * environment.pressure(atDepth: meters) / 1.01325
+ }
+
+ /// The richest mix for a depth: oxygen for the limit on its partial pressure, and just enough helium to keep
+ /// the equivalent narcotic depth at `maximumEND` (nil: no helium).
+ public static func bestMix(forDepth meters: Double, ppO2 limit: Double = 1.4, maximumEND: Double? = nil,
+ oxygenNarcotic: Bool = true, in environment: DiveEnvironment = .sea) -> BreathingGas {
+ let pressure = environment.pressure(atDepth: meters)
+ // Whole percents, rounded down: never above the limit.
+ let o2 = min(1, (limit / pressure * 100).rounded(.down) / 100)
+ var he = 0.0
+ if let maximumEND, meters > maximumEND {
+ let allowed = environment.pressure(atDepth: maximumEND)
+ let fraction = oxygenNarcotic ? 1 - allowed / pressure : 1 - o2 - allowed * nitrogenInAir / pressure
+ he = min(1 - o2, max(0, (fraction * 100).rounded(.up) / 100))
+ }
+ return BreathingGas(o2: o2, he: he)
+ }
+}
+
+/// Oxygen exposure: share of the daily "CNS clock" (NOAA limits) and pulmonary units (OTU).
+public enum OxygenExposure {
+ /// Minutes allowed at a partial pressure of oxygen, for a single exposure (NOAA).
+ private static let limits: [(ppO2: Double, minutes: Double)] = [
+ (0.5, .infinity), (0.6, 720), (0.7, 570), (0.8, 450), (0.9, 360), (1.0, 300), (1.1, 240),
+ (1.2, 210), (1.3, 180), (1.4, 150), (1.5, 120), (1.6, 45),
+ ]
+
+ /// Fraction of the CNS clock used by `seconds` at a partial pressure of oxygen (1 = 100 %).
+ public static func cns(ppO2: Double, seconds: Double) -> Double {
+ guard ppO2 > 0.5 else { return 0 }
+ if ppO2 >= 1.6 {
+ // Beyond the table: the limit halves every 0.1 bar or so (it is already an emergency).
+ return seconds / 60 / (45 * pow(0.5, (ppO2 - 1.6) / 0.1))
+ }
+ let upper = limits.firstIndex { $0.ppO2 >= ppO2 } ?? limits.count - 1
+ let high = limits[upper], low = limits[max(1, upper - 1)]
+ guard upper > 1, high.ppO2 > low.ppO2 else { return seconds / 60 / high.minutes }
+ let allowed = low.minutes + (high.minutes - low.minutes) * (ppO2 - low.ppO2) / (high.ppO2 - low.ppO2)
+ return seconds / 60 / allowed
+ }
+
+ /// Oxygen tolerance units for `seconds` at a partial pressure of oxygen.
+ public static func otu(ppO2: Double, seconds: Double) -> Double {
+ guard ppO2 > 0.5 else { return 0 }
+ return seconds / 60 * pow((ppO2 - 0.5) / 0.5, 5.0 / 6.0)
+ }
+}
diff --git a/Packages/DiveKit/Sources/DivePlanner/Planner.swift b/Packages/DiveKit/Sources/DivePlanner/Planner.swift
@@ -0,0 +1,478 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// A cylinder taken on the dive.
+public struct PlanCylinder: Codable, Sendable, Equatable, Identifiable {
+ public var id = UUID()
+ public var gas: BreathingGas
+ /// Water capacity in litres and filling pressure in bar; nil when only the gas matters.
+ public var volumeLiters: Double?
+ public var startBar: Double?
+ /// A decompression gas is switched to on the way up, from `switchDepth` (nil: its depth at 1.6 bar of oxygen).
+ public var isDeco = false
+ public var switchDepth: Double?
+
+ public init(gas: BreathingGas, volumeLiters: Double? = nil, startBar: Double? = nil, isDeco: Bool = false, switchDepth: Double? = nil) {
+ self.gas = gas
+ self.volumeLiters = volumeLiters
+ self.startBar = startBar
+ self.isDeco = isDeco
+ self.switchDepth = switchDepth
+ }
+
+ /// Litres of gas at the surface (ideal gas, which flatters fills above 200 bar by a few percent).
+ public var availableLiters: Double? {
+ guard let volumeLiters, let startBar else { return nil }
+ return volumeLiters * startBar
+ }
+}
+
+/// One part of the dive as the diver intends it: go to a depth and stay there.
+public struct PlanLevel: Codable, Sendable, Equatable, Identifiable {
+ public var id = UUID()
+ public var depth: Double
+ /// Minutes from leaving the previous depth (or the surface): the way there counts, as in dive tables.
+ public var minutes: Double
+ /// Index of the cylinder breathed, in the plan's list.
+ public var cylinder = 0
+
+ public init(depth: Double, minutes: Double, cylinder: Int = 0) {
+ self.depth = depth
+ self.minutes = minutes
+ self.cylinder = cylinder
+ }
+}
+
+public struct PlanSettings: Codable, Sendable, Equatable {
+ /// Gradient factors, as fractions (0.40 and 0.85 for "40/85").
+ public var gfLow = 0.40
+ public var gfHigh = 0.85
+ /// Metres per minute.
+ public var descentRate = 18.0
+ public var ascentRate = 9.0
+ /// Ascent rate above 6 m.
+ public var ascentRateLast6m = 9.0
+ /// Last stop at 6 m instead of 3 m.
+ public var lastStopAt6m = false
+ /// Three minutes at 5 m on the way up of a dive without mandatory stops, deeper than 10 m.
+ public var safetyStop = true
+ /// Surface air consumption, in litres per minute: at the bottom, and during the ascent and the stops.
+ public var sacBottom = 20.0
+ public var sacDeco = 17.0
+ /// Limits on the partial pressure of oxygen, in bar.
+ public var ppO2Bottom = 1.4
+ public var ppO2Deco = 1.6
+ /// Time spent on a gas switch before the stop clock starts, in seconds.
+ public var gasSwitchSeconds = 60.0
+ /// Minimum gas: minutes to sort a problem out at the bottom, and factor on the consumption (two divers, stressed).
+ public var problemMinutes = 4.0
+ public var minimumGasFactor = 4.0
+ public var environment = DiveEnvironment.sea
+
+ public init() {}
+}
+
+public struct DivePlan: Codable, Sendable, Equatable {
+ public var levels: [PlanLevel]
+ public var cylinders: [PlanCylinder]
+ public var settings = PlanSettings()
+
+ public init(levels: [PlanLevel], cylinders: [PlanCylinder], settings: PlanSettings = PlanSettings()) {
+ self.levels = levels
+ self.cylinders = cylinders
+ self.settings = settings
+ }
+}
+
+/// A point of the planned profile.
+public struct PlanPoint: Sendable, Equatable {
+ /// Seconds since leaving the surface.
+ public var time: Double
+ public var depth: Double
+ /// Cylinder breathed from this point on.
+ public var cylinder: Int
+}
+
+/// A stop on the way up: mandatory decompression stop, time taken by a gas switch, or safety stop.
+public struct PlanStop: Sendable, Equatable {
+ public enum Kind: Sendable, Equatable { case deco, gasSwitch, safety }
+ public var depth: Double
+ public var seconds: Double
+ public var cylinder: Int
+ public var kind: Kind
+ /// Run time when the stop ends, in seconds.
+ public var endTime: Double
+}
+
+public enum PlanWarning: Sendable, Equatable {
+ /// Partial pressure of oxygen above the limit: gas, depth, bar.
+ case oxygenTooHigh(cylinder: Int, depth: Double, ppO2: Double)
+ /// Not enough oxygen to breathe the gas there.
+ case oxygenTooLow(cylinder: Int, depth: Double, ppO2: Double)
+ /// Equivalent narcotic depth beyond 30 m.
+ case narcosis(cylinder: Int, depth: Double, end: Double)
+ /// Gas density above 5.2 g/L.
+ case density(cylinder: Int, depth: Double, gramsPerLiter: Double)
+ /// The plan uses more than the cylinder holds: litres needed, litres available.
+ case notEnoughGas(cylinder: Int, needed: Double, available: Double)
+ /// What is left at the end of the bottom time is under the minimum gas.
+ case underMinimumGas(cylinder: Int, leftBar: Double, minimumBar: Double)
+ case cnsHigh(percent: Double)
+ /// A level uses a cylinder that is not in the list.
+ case unknownCylinder
+ /// The decompression does not end (a gas that cannot be breathed up there, usually).
+ case endless
+}
+
+public struct PlanResult: Sendable, Equatable {
+ public var points: [PlanPoint] = []
+ public var stops: [PlanStop] = []
+ /// Seconds: whole dive, and from the end of the bottom part to the surface.
+ public var runtime = 0.0
+ public var ascentTime = 0.0
+ public var maxDepth = 0.0
+ /// Litres of gas (at the surface) used per cylinder, same order as the plan's list.
+ public var gasUsed: [Double] = []
+ /// Minimum gas to keep in the bottom cylinder when leaving the bottom, in litres; nil without deco gas logic.
+ public var minimumGasLiters: Double?
+ public var bottomCylinder = 0
+ /// Share of the CNS clock (1 = 100 %) and pulmonary oxygen units.
+ public var cns = 0.0
+ public var otu = 0.0
+ /// Supersaturation on surfacing, as a share of the Bühlmann limit.
+ public var surfaceGF = 0.0
+ public var warnings: [PlanWarning] = []
+
+ /// True when the ascent has mandatory decompression stops.
+ public var hasDecoStops: Bool { stops.contains { $0.kind == .deco } }
+ public var decoStops: [PlanStop] { stops.filter { $0.kind != .safety } }
+}
+
+public enum DivePlanner {
+ /// Depth step of the ascent simulation, as a duration (Subsurface's `base_timestep`).
+ private static let step = 2.0
+ private static let stopStep = 60.0
+
+ private struct State {
+ var tissues: Tissues
+ var clock = 0.0
+ var depth = 0.0
+ var cylinder = 0
+ var result = PlanResult()
+
+ mutating func mark() {
+ let point = PlanPoint(time: clock, depth: depth, cylinder: cylinder)
+ if let last = result.points.last, last.time == point.time, last.depth == point.depth {
+ result.points[result.points.count - 1] = point
+ } else {
+ result.points.append(point)
+ }
+ }
+ }
+
+ /// Breathes the current cylinder for a while at a depth: tissues, gas used, oxygen exposure.
+ private static func breathe(_ state: inout State, _ plan: DivePlan, seconds: Double, at depth: Double, sac: Double) {
+ let settings = plan.settings, environment = settings.environment
+ let pressure = environment.pressure(atDepth: depth)
+ let gas = plan.cylinders[state.cylinder].gas
+ state.tissues.load(pressure: pressure, gas: gas, seconds: seconds)
+ _ = state.tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
+ state.result.gasUsed[state.cylinder] += sac * pressure * seconds / 60
+ state.result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
+ state.result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
+ }
+
+ /// Plans the ascent of a dive: stops, run time, gas, oxygen exposure and what to worry about.
+ public static func plan(_ plan: DivePlan) -> PlanResult {
+ let settings = plan.settings, environment = settings.environment
+ var state = State(tissues: Tissues(surfacePressure: environment.surfacePressure))
+ state.result.gasUsed = [Double](repeating: 0, count: plan.cylinders.count)
+ guard !plan.cylinders.isEmpty, !plan.levels.isEmpty,
+ plan.levels.allSatisfy({ plan.cylinders.indices.contains($0.cylinder) }) else {
+ state.result.warnings = [.unknownCylinder]
+ return state.result
+ }
+
+ // The part the diver decides: each level is reached at the descent or ascent rate, then held.
+ state.cylinder = plan.levels[0].cylinder
+ state.mark()
+ for level in plan.levels {
+ state.cylinder = level.cylinder
+ state.mark()
+ let rate = (level.depth >= state.depth ? settings.descentRate : settings.ascentRate) / 60
+ var left = max(0, level.minutes * 60)
+ while abs(level.depth - state.depth) > 1e-9 {
+ let seconds = min(1, abs(level.depth - state.depth) / rate)
+ breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacBottom)
+ state.depth += (level.depth > state.depth ? 1 : -1) * rate * seconds
+ if abs(level.depth - state.depth) < 1e-6 { state.depth = level.depth }
+ state.clock += seconds
+ left -= seconds
+ }
+ state.mark()
+ while left > 0 {
+ let seconds = min(60, left)
+ breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacBottom)
+ state.clock += seconds
+ left -= seconds
+ }
+ state.mark()
+ state.result.maxDepth = max(state.result.maxDepth, level.depth)
+ }
+ let bottomTime = state.clock
+ let bottomDepth = state.depth
+ let bottomCylinder = state.cylinder
+ state.result.bottomCylinder = bottomCylinder
+ let usedAtBottom = state.result.gasUsed[bottomCylinder]
+
+ ascend(&state, plan: plan)
+
+ state.result.runtime = state.clock
+ state.result.ascentTime = state.clock - bottomTime
+ state.result.surfaceGF = state.tissues.surfaceGradientFactor(surfacePressure: environment.surfacePressure)
+
+ // Minimum gas: enough, from the end of the bottom time, to sort a problem out and bring two divers up to
+ // the first gas switch (or the surface), at a stressed consumption.
+ let ascentFromBottomCylinder = state.result.gasUsed[bottomCylinder] - usedAtBottom
+ let minimum = settings.minimumGasFactor * (settings.problemMinutes * settings.sacBottom * environment.pressure(atDepth: bottomDepth)
+ + ascentFromBottomCylinder)
+ state.result.minimumGasLiters = minimum
+ state.result.warnings = warnings(for: plan, result: state.result, usedAtBottom: usedAtBottom, minimum: minimum)
+ return state.result
+ }
+
+ /// The gases that can be switched to on the way up, deepest first.
+ private static func gasChanges(_ plan: DivePlan) -> [(depth: Double, cylinder: Int)] {
+ plan.cylinders.enumerated().compactMap { index, cylinder -> (depth: Double, cylinder: Int)? in
+ guard cylinder.isDeco else { return nil }
+ let depth = cylinder.switchDepth ?? cylinder.gas.switchDepth(ppO2: plan.settings.ppO2Deco, in: plan.settings.environment)
+ return depth > 0 ? (depth, index) : nil
+ }.sorted { $0.depth > $1.depth }
+ }
+
+ private static func ascentRate(at depth: Double, _ settings: PlanSettings) -> Double {
+ (depth > 6 ? settings.ascentRate : settings.ascentRateLast6m) / 60
+ }
+
+ /// Whether the diver can go from `depth` up to `target` without crossing the ceiling, after waiting `wait`
+ /// seconds first. The tissues are not changed.
+ private static func canAscend(_ tissues: Tissues, wait: Double, from depth: Double, to target: Double, gas: BreathingGas, settings: PlanSettings) -> Bool {
+ let environment = settings.environment
+ var trial = tissues
+ if wait > 0 { trial.load(pressure: environment.pressure(atDepth: depth), gas: gas, seconds: wait) }
+ var current = depth
+ while current > target + 1e-9 {
+ let rise = min(ascentRate(at: current, settings) * step, current)
+ trial.load(pressure: environment.pressure(atDepth: current), gas: gas, seconds: step)
+ let tolerated = trial.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
+ if environment.depth(atPressure: tolerated) > current - rise + 1e-9 { return false }
+ current -= rise
+ }
+ return true
+ }
+
+ private static func ascend(_ state: inout State, plan: DivePlan) {
+ let settings = plan.settings
+ var changes = gasChanges(plan)
+ // A deco gas that can already be breathed at the bottom is taken straight away (the richest such gas).
+ if let usable = changes.last(where: { $0.depth >= state.depth }), usable.cylinder != state.cylinder {
+ state.mark()
+ state.cylinder = usable.cylinder
+ state.mark()
+ }
+ changes.removeAll { $0.depth >= state.depth }
+
+ // Where the diver may stop: every 3 m (the 3 m stop goes when the last stop is at 6 m) and the gas switches.
+ var levels = Set(stride(from: settings.lastStopAt6m ? 6.0 : 3.0, to: state.depth, by: 3.0))
+ for change in changes { levels.insert(change.depth) }
+ var stops = levels.filter { $0 < state.depth - 1e-9 }.sorted(by: >) + [0.0]
+ var justSwitched = false
+ var decoStopsFound = false
+ var guardCount = 0
+
+ func stay(_ state: inout State, _ seconds: Double, kind: PlanStop.Kind) {
+ breathe(&state, plan, seconds: seconds, at: state.depth, sac: settings.sacDeco)
+ state.clock += seconds
+ if var last = state.result.stops.last, last.depth == state.depth, last.cylinder == state.cylinder, last.kind == kind {
+ last.seconds += seconds
+ last.endTime = state.clock
+ state.result.stops[state.result.stops.count - 1] = last
+ } else {
+ state.result.stops.append(PlanStop(depth: state.depth, seconds: seconds, cylinder: state.cylinder, kind: kind, endTime: state.clock))
+ }
+ }
+
+ while !stops.isEmpty {
+ let target = stops.removeFirst()
+ // Up to the next possible stop.
+ state.mark()
+ while state.depth > target + 1e-9 {
+ let rise = min(ascentRate(at: state.depth, settings) * step, state.depth - target)
+ breathe(&state, plan, seconds: step, at: state.depth, sac: settings.sacDeco)
+ state.clock += step
+ state.depth -= rise
+ if state.depth - target < 1e-9 { state.depth = target }
+ justSwitched = false
+ }
+ guard state.depth > 0 else { break }
+
+ if let change = changes.first, target <= change.depth + 1e-9 {
+ changes.removeFirst()
+ if change.cylinder != state.cylinder {
+ state.mark()
+ state.cylinder = change.cylinder
+ state.mark()
+ if !justSwitched, plan.cylinders[change.cylinder].gas.o2Percent < 100, settings.gasSwitchSeconds > 0 {
+ stay(&state, settings.gasSwitchSeconds, kind: .gasSwitch)
+ justSwitched = true
+ }
+ }
+ }
+
+ let next = stops.first ?? 0
+ let gas = plan.cylinders[state.cylinder].gas
+ if canAscend(state.tissues, wait: 0, from: state.depth, to: next, gas: gas, settings: settings) { continue }
+
+ // A stop: it ends on a whole minute of run time, as soon as the way up to the next stop is clear.
+ decoStopsFound = true
+ state.mark()
+ var end = (state.clock / stopStep).rounded(.down) * stopStep + stopStep
+ while !canAscend(state.tissues, wait: end - state.clock, from: state.depth, to: next, gas: gas, settings: settings) {
+ end += stopStep
+ guardCount += 1
+ if guardCount > 48 * 60 {
+ state.result.warnings.append(.endless)
+ state.mark()
+ return
+ }
+ }
+ stay(&state, end - state.clock, kind: .deco)
+ justSwitched = false
+ state.mark()
+ }
+ state.depth = 0
+ state.mark()
+
+ if !decoStopsFound, settings.safetyStop, state.result.maxDepth >= 10 {
+ insertSafetyStop(&state, plan: plan)
+ }
+ }
+
+ /// Adds three minutes at 5 m to an ascent that had no mandatory stop: gas and oxygen for the stop are added,
+ /// the profile gets the plateau. (The tissues only off-gas more: nothing else changes.)
+ private static func insertSafetyStop(_ state: inout State, plan: DivePlan) {
+ let settings = plan.settings, environment = settings.environment
+ let stopDepth = 5.0, seconds = 180.0
+ guard let index = state.result.points.lastIndex(where: { $0.depth > stopDepth }), index + 1 < state.result.points.count else { return }
+ let before = state.result.points[index], after = state.result.points[index + 1]
+ guard before.depth > after.depth else { return }
+ // Time at which the ascent crosses 5 m, between the two points around it.
+ let crossing = before.time + (after.time - before.time) * (before.depth - stopDepth) / (before.depth - after.depth)
+ let cylinder = before.cylinder
+ for later in (index + 1)..<state.result.points.count { state.result.points[later].time += seconds }
+ state.result.points.insert(contentsOf: [PlanPoint(time: crossing, depth: stopDepth, cylinder: cylinder),
+ PlanPoint(time: crossing + seconds, depth: stopDepth, cylinder: cylinder)], at: index + 1)
+ let pressure = environment.pressure(atDepth: stopDepth)
+ let gas = plan.cylinders[cylinder].gas
+ state.tissues.load(pressure: pressure, gas: gas, seconds: seconds)
+ state.result.gasUsed[cylinder] += settings.sacDeco * pressure * seconds / 60
+ state.result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
+ state.result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
+ state.result.stops.append(PlanStop(depth: stopDepth, seconds: seconds, cylinder: cylinder, kind: .safety, endTime: crossing + seconds))
+ state.clock += seconds
+ }
+
+ private static func warnings(for plan: DivePlan, result: PlanResult, usedAtBottom: Double, minimum: Double) -> [PlanWarning] {
+ let settings = plan.settings, environment = settings.environment
+ var found = result.warnings
+ // Each cylinder at the deepest and at the shallowest point where it is breathed.
+ var deepest = [Int: Double](), shallowest = [Int: Double]()
+ for (index, point) in result.points.enumerated() {
+ let until = index + 1 < result.points.count ? result.points[index + 1].depth : point.depth
+ for depth in [point.depth, until] {
+ deepest[point.cylinder] = max(deepest[point.cylinder] ?? 0, depth)
+ // The first metres of the descent and the last of the ascent are left out for the hypoxia check.
+ if depth > 0 { shallowest[point.cylinder] = min(shallowest[point.cylinder] ?? .infinity, depth) }
+ }
+ }
+ for (cylinder, depth) in deepest.sorted(by: { $0.key < $1.key }) {
+ let gas = plan.cylinders[cylinder].gas
+ let limit = plan.cylinders[cylinder].isDeco ? settings.ppO2Deco : settings.ppO2Bottom
+ let ppO2 = gas.ppO2(atDepth: depth, in: environment)
+ if ppO2 > limit + 0.005 { found.append(.oxygenTooHigh(cylinder: cylinder, depth: depth, ppO2: ppO2)) }
+ let end = gas.equivalentNarcoticDepth(atDepth: depth, in: environment)
+ if end > 30.5 { found.append(.narcosis(cylinder: cylinder, depth: depth, end: end)) }
+ let density = gas.density(atDepth: depth, in: environment)
+ if density > 5.2 { found.append(.density(cylinder: cylinder, depth: depth, gramsPerLiter: density)) }
+ }
+ // A hypoxic bottom gas is a problem from the surface down to the depth where it becomes breathable.
+ for cylinder in Set(result.points.map(\.cylinder)).sorted() {
+ let gas = plan.cylinders[cylinder].gas
+ let startsAtSurface = result.points.first?.cylinder == cylinder
+ let depth = startsAtSurface ? 0 : (shallowest[cylinder] ?? 0)
+ let ppO2 = gas.ppO2(atDepth: depth, in: environment)
+ if ppO2 < 0.16 { found.append(.oxygenTooLow(cylinder: cylinder, depth: depth, ppO2: ppO2)) }
+ }
+ for (cylinder, used) in result.gasUsed.enumerated() {
+ guard let available = plan.cylinders[cylinder].availableLiters, used > 0 else { continue }
+ if used > available { found.append(.notEnoughGas(cylinder: cylinder, needed: used, available: available)) }
+ }
+ let bottom = result.bottomCylinder
+ if let available = plan.cylinders[bottom].availableLiters, let volume = plan.cylinders[bottom].volumeLiters, volume > 0 {
+ let left = available - usedAtBottom
+ if left < minimum, usedAtBottom <= available {
+ found.append(.underMinimumGas(cylinder: bottom, leftBar: left / volume, minimumBar: minimum / volume))
+ }
+ }
+ if result.cns > 0.8 { found.append(.cnsHigh(percent: result.cns * 100)) }
+ return found
+ }
+
+ // MARK: Quick answers
+
+ /// How long the diver can stay at a depth and still go straight up, in minutes from leaving the surface (the
+ /// descent counts); nil when there is no limit within `ceiling` minutes.
+ public static func noStopLimit(depth: Double, gas: BreathingGas, settings: PlanSettings = PlanSettings(), ceiling: Int = 300) -> Int? {
+ let environment = settings.environment
+ var tissues = Tissues(surfacePressure: environment.surfacePressure)
+ // Descent, second by second.
+ var current = 0.0, clock = 0.0
+ let rate = settings.descentRate / 60
+ while current < depth - 1e-9 {
+ let seconds = min(1, (depth - current) / rate)
+ tissues.load(pressure: environment.pressure(atDepth: current), gas: gas, seconds: seconds)
+ current += rate * seconds
+ clock += seconds
+ }
+ let pressure = environment.pressure(atDepth: depth)
+ // To the end of the current minute, then minute by minute.
+ var minutes = Int((clock / 60).rounded(.up))
+ tissues.load(pressure: pressure, gas: gas, seconds: Double(minutes) * 60 - clock)
+ _ = tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
+ guard canAscend(tissues, wait: 0, from: depth, to: 0, gas: gas, settings: settings) else { return max(0, minutes - 1) }
+ while minutes < ceiling {
+ tissues.load(pressure: pressure, gas: gas, seconds: 60)
+ _ = tissues.toleratedPressure(surfacePressure: environment.surfacePressure, gfLow: settings.gfLow, gfHigh: settings.gfHigh)
+ if !canAscend(tissues, wait: 0, from: depth, to: 0, gas: gas, settings: settings) { return minutes }
+ minutes += 1
+ }
+ return nil
+ }
+
+ /// How long a cylinder lasts at a depth, in minutes from leaving the surface, keeping `reserveBar` and the gas
+ /// for a direct ascent with a safety stop.
+ public static func gasLimit(depth: Double, volumeLiters: Double, startBar: Double, reserveBar: Double = 50,
+ settings: PlanSettings = PlanSettings()) -> Int {
+ let environment = settings.environment
+ let usable = volumeLiters * max(0, startBar - reserveBar)
+ // Descent and ascent at the mean pressure, three minutes at 5 m.
+ let mean = environment.pressure(atDepth: depth / 2)
+ let descentMinutes = depth / settings.descentRate
+ let ascentMinutes = depth / settings.ascentRate
+ let travel = settings.sacBottom * mean * descentMinutes + settings.sacDeco * mean * ascentMinutes
+ + (settings.safetyStop && depth >= 10 ? settings.sacDeco * environment.pressure(atDepth: 5) * 3 : 0)
+ let perMinute = settings.sacBottom * environment.pressure(atDepth: depth)
+ guard usable > travel, perMinute > 0 else { return 0 }
+ return Int((descentMinutes + (usable - travel) / perMinute).rounded(.down))
+ }
+}
diff --git a/Packages/DiveKit/Sources/DivePlanner/Tissues.swift b/Packages/DiveKit/Sources/DivePlanner/Tissues.swift
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// Bühlmann ZHL-16C with gradient factors, nitrogen and helium. The coefficients, the water vapour pressure and
+/// the way the gradient factors are applied follow Subsurface (`core/deco.cpp`, GPL-2.0), so that a plan made here
+/// matches a plan made there.
+public struct Tissues: Sendable, Equatable {
+ static let count = 16
+ static let n2A: [Double] = [1.1696, 1.0, 0.8618, 0.7562, 0.62, 0.5043, 0.441, 0.4,
+ 0.375, 0.35, 0.3295, 0.3065, 0.2835, 0.261, 0.248, 0.2327]
+ static let n2B: [Double] = [0.5578, 0.6514, 0.7222, 0.7825, 0.8126, 0.8434, 0.8693, 0.8910,
+ 0.9092, 0.9222, 0.9319, 0.9403, 0.9477, 0.9544, 0.9602, 0.9653]
+ static let n2HalfLife: [Double] = [5.0, 8.0, 12.5, 18.5, 27.0, 38.3, 54.3, 77.0,
+ 109.0, 146.0, 187.0, 239.0, 305.0, 390.0, 498.0, 635.0]
+ static let heA: [Double] = [1.6189, 1.383, 1.1919, 1.0458, 0.922, 0.8205, 0.7305, 0.6502,
+ 0.595, 0.5545, 0.5333, 0.5189, 0.5181, 0.5176, 0.5172, 0.5119]
+ static let heB: [Double] = [0.4770, 0.5747, 0.6527, 0.7223, 0.7582, 0.7957, 0.8279, 0.8553,
+ 0.8757, 0.8903, 0.8997, 0.9073, 0.9122, 0.9171, 0.9217, 0.9267]
+ static let heHalfLife: [Double] = [1.88, 3.02, 4.72, 6.99, 10.21, 14.48, 20.53, 29.11,
+ 41.20, 55.19, 70.69, 90.34, 115.29, 147.42, 188.24, 240.03]
+ /// Water vapour pressure in the lungs, in bar (Bühlmann's value).
+ static let waterVapour = 0.0627
+
+ /// Inert gas pressures in each compartment, in bar.
+ public private(set) var n2: [Double]
+ public private(set) var he: [Double]
+ /// Deepest ceiling (as a pressure) that the low gradient factor has asked for so far in this dive: the gradient
+ /// factor goes from "low" there to "high" at the surface.
+ public private(set) var gfLowPressure = 0.0
+
+ /// Tissues of a diver who has been at the surface, breathing air, long enough to be in equilibrium.
+ public init(surfacePressure: Double) {
+ n2 = [Double](repeating: (surfacePressure - Self.waterVapour) * BreathingGas.nitrogenInAir, count: Self.count)
+ he = [Double](repeating: 0, count: Self.count)
+ }
+
+ /// Breathes a gas for a while at a constant ambient pressure.
+ public mutating func load(pressure: Double, gas: BreathingGas, seconds: Double) {
+ guard seconds > 0 else { return }
+ let inspiredN2 = (pressure - Self.waterVapour) * gas.n2
+ let inspiredHe = (pressure - Self.waterVapour) * gas.he
+ for index in 0..<Self.count {
+ n2[index] += (inspiredN2 - n2[index]) * (1 - pow(2, -seconds / (Self.n2HalfLife[index] * 60)))
+ he[index] += (inspiredHe - he[index]) * (1 - pow(2, -seconds / (Self.heHalfLife[index] * 60)))
+ }
+ }
+
+ /// Lowest ambient pressure the tissues tolerate now, in bar (below the surface pressure: no ceiling). Also
+ /// moves the reference of the low gradient factor when the tissues ask for a deeper first stop than before.
+ public mutating func toleratedPressure(surfacePressure surface: Double, gfLow: Double, gfHigh: Double) -> Double {
+ var a = [Double](repeating: 0, count: Self.count), b = a, saturation = a
+ var lowestCeiling = 0.0
+ for index in 0..<Self.count {
+ let total = n2[index] + he[index]
+ saturation[index] = total
+ a[index] = (Self.n2A[index] * n2[index] + Self.heA[index] * he[index]) / total
+ b[index] = (Self.n2B[index] * n2[index] + Self.heB[index] * he[index]) / total
+ let ceiling = (b[index] * total - gfLow * a[index] * b[index]) / ((1 - b[index]) * gfLow + b[index])
+ lowestCeiling = max(lowestCeiling, ceiling)
+ }
+ gfLowPressure = max(gfLowPressure, lowestCeiling)
+ let low = gfLowPressure
+ var tolerated = 0.0
+ for index in 0..<Self.count {
+ let atSurface = (surface / b[index] + a[index] - surface) * gfHigh + surface
+ let atFirstStop = (low / b[index] + a[index] - low) * gfLow + low
+ guard atSurface < atFirstStop else { continue }
+ let value = (-a[index] * b[index] * (gfHigh * low - gfLow * surface)
+ - (1 - b[index]) * (gfHigh - gfLow) * low * surface
+ + b[index] * (low - surface) * saturation[index])
+ / (-a[index] * b[index] * (gfHigh - gfLow)
+ + (1 - b[index]) * (gfLow * low - gfHigh * surface)
+ + b[index] * (low - surface))
+ tolerated = max(tolerated, value)
+ }
+ return tolerated
+ }
+
+ /// Highest supersaturation among the compartments if the diver were at the surface now, as a share of the
+ /// Bühlmann limit (1 = on the limit): what dive computers show as "surface GF".
+ public func surfaceGradientFactor(surfacePressure surface: Double) -> Double {
+ var highest = 0.0
+ for index in 0..<Self.count {
+ let total = n2[index] + he[index]
+ let a = (Self.n2A[index] * n2[index] + Self.heA[index] * he[index]) / total
+ let b = (Self.n2B[index] * n2[index] + Self.heB[index] * he[index]) / total
+ let limit = a + surface / b
+ highest = max(highest, (total - surface) / (limit - surface))
+ }
+ return highest
+ }
+}
diff --git a/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift b/Packages/DiveKit/Tests/DivePlannerTests/DivePlannerTests.swift
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import XCTest
+@testable import DivePlanner
+
+final class DivePlannerTests: XCTestCase {
+ /// Subsurface's own benchmark (`tests/testplan.cpp`, `testMetric`): 79 m for 30 minutes on trimix 15/45, EAN36
+ /// from 33 m and oxygen from 6 m, gradient factors 100/100, last stop at 6 m. Subsurface gets a run time of
+ /// 109 minutes and a minimum gas of 148 bar in a 36 L cylinder, and accepts 1 % + 1 minute around it.
+ func testSubsurfaceBenchmark() {
+ var settings = PlanSettings()
+ settings.gfLow = 1
+ settings.gfHigh = 1
+ settings.descentRate = 23
+ settings.ascentRate = 9.144
+ settings.ascentRateLast6m = 3.048
+ settings.lastStopAt6m = true
+ settings.safetyStop = false
+ let plan = DivePlan(levels: [PlanLevel(depth: 79, minutes: 30)],
+ cylinders: [PlanCylinder(gas: BreathingGas(o2Percent: 15, hePercent: 45), volumeLiters: 36, startBar: 232),
+ PlanCylinder(gas: BreathingGas(o2Percent: 36), isDeco: true),
+ PlanCylinder(gas: .oxygen, isDeco: true)],
+ settings: settings)
+ let result = DivePlanner.plan(plan)
+ print("BENCHMARK runtime \(result.runtime / 60) min, stops:",
+ result.stops.map { "\(Int($0.depth)) m \(Int($0.seconds / 60))' \(plan.cylinders[$0.cylinder].gas.name)" }.joined(separator: ", "),
+ "min gas \((result.minimumGasLiters ?? 0) / 36) bar, gas", result.gasUsed.map { Int($0) }, "CNS \(result.cns) OTU \(result.otu)")
+ XCTAssertEqual(result.runtime, 109 * 60, accuracy: 109 * 60 * 0.01 + 60)
+ XCTAssertEqual((result.minimumGasLiters ?? 0) / 36, 148, accuracy: 4)
+ // The switches happen where Subsurface makes them.
+ let switches = result.points.enumerated().compactMap { index, point -> (Double, Int)? in
+ index > 0 && result.points[index - 1].cylinder != point.cylinder ? (point.depth, point.cylinder) : nil
+ }
+ XCTAssertEqual(switches.map(\.0), [33, 6])
+ XCTAssertEqual(switches.map(\.1), [1, 2])
+ XCTAssertTrue(result.hasDecoStops)
+ // Stops end on whole minutes of run time and get shallower.
+ for stop in result.stops where stop.kind == .deco { XCTAssertEqual(stop.endTime.truncatingRemainder(dividingBy: 60), 0, accuracy: 1e-6) }
+ XCTAssertEqual(result.stops.map(\.depth), result.stops.map(\.depth).sorted(by: >))
+ XCTAssertEqual(result.points.last?.depth, 0)
+ XCTAssertEqual(result.points.last?.time ?? 0, result.runtime, accuracy: 1e-6)
+ }
+
+ func testGasFormulas() {
+ XCTAssertEqual(BreathingGas.air.name, "Air")
+ XCTAssertEqual(BreathingGas(o2Percent: 32).name, "EAN32")
+ XCTAssertEqual(BreathingGas(o2Percent: 18, hePercent: 45).name, "Tx18/45")
+ XCTAssertEqual(BreathingGas.oxygen.name, "O2")
+ // Sea water, 1.4 bar: about 33 m for EAN32, 56 m for air; oxygen from 6 m at 1.6 bar.
+ XCTAssertEqual(BreathingGas(o2Percent: 32).maximumOperatingDepth(ppO2: 1.4), 33.3, accuracy: 0.3)
+ XCTAssertEqual(BreathingGas.air.maximumOperatingDepth(ppO2: 1.4), 56, accuracy: 0.5)
+ XCTAssertEqual(BreathingGas.oxygen.switchDepth(), 6)
+ XCTAssertEqual(BreathingGas(o2Percent: 50).switchDepth(), 21)
+ XCTAssertEqual(BreathingGas(o2Percent: 36).switchDepth(), 33)
+ // Best mix: EAN32 for 33 m at 1.4; trimix 18/45-ish for 60 m with an END of 30 m.
+ XCTAssertEqual(BreathingGas.bestMix(forDepth: 33).o2Percent, 32)
+ let deep = BreathingGas.bestMix(forDepth: 60, maximumEND: 30)
+ XCTAssertEqual(deep.o2Percent, 19)
+ XCTAssertEqual(deep.equivalentNarcoticDepth(atDepth: 60), 30, accuracy: 0.8)
+ XCTAssertLessThanOrEqual(deep.ppO2(atDepth: 60), 1.4)
+ // Air is as narcotic as air; EAN32 at 30 m is like air at about 24 m.
+ XCTAssertEqual(BreathingGas.air.equivalentNarcoticDepth(atDepth: 40), 40, accuracy: 0.01)
+ XCTAssertEqual(BreathingGas(o2Percent: 32).equivalentAirDepth(atDepth: 30), 24.4, accuracy: 0.5)
+ XCTAssertEqual(BreathingGas.air.density(atDepth: 40), 6.3, accuracy: 0.3)
+ // Oxygen clock: 45 minutes at 1.6 bar is the whole of it, 150 minutes at 1.4.
+ XCTAssertEqual(OxygenExposure.cns(ppO2: 1.6, seconds: 45 * 60), 1, accuracy: 1e-9)
+ XCTAssertEqual(OxygenExposure.cns(ppO2: 1.4, seconds: 75 * 60), 0.5, accuracy: 1e-9)
+ XCTAssertEqual(OxygenExposure.cns(ppO2: 0.4, seconds: 3600), 0)
+ XCTAssertEqual(OxygenExposure.otu(ppO2: 1.0, seconds: 60), 1, accuracy: 1e-9)
+ }
+
+ /// No-stop limits: plausible against published ZHL-16C figures, shorter when deeper or more conservative,
+ /// longer on nitrox.
+ func testNoStopLimits() {
+ var settings = PlanSettings()
+ settings.gfLow = 1
+ settings.gfHigh = 1
+ let air = Dictionary(uniqueKeysWithValues: [12, 18, 21, 30, 40].map { ($0, DivePlanner.noStopLimit(depth: Double($0), gas: .air, settings: settings) ?? 999) })
+ print("NDL air GF 100/100:", air.sorted { $0.key < $1.key })
+ XCTAssertTrue((45...75).contains(air[18]!), "\(air[18]!)")
+ XCTAssertTrue((14...24).contains(air[30]!), "\(air[30]!)")
+ XCTAssertTrue((7...12).contains(air[40]!), "\(air[40]!)")
+ XCTAssertGreaterThan(air[12]!, air[18]!)
+ XCTAssertGreaterThan(air[18]!, air[21]!)
+ XCTAssertGreaterThan(air[21]!, air[30]!)
+
+ var careful = settings
+ careful.gfLow = 0.4
+ careful.gfHigh = 0.85
+ let cautious = DivePlanner.noStopLimit(depth: 30, gas: .air, settings: careful)!
+ XCTAssertLessThan(cautious, air[30]!)
+ XCTAssertGreaterThan(DivePlanner.noStopLimit(depth: 30, gas: BreathingGas(o2Percent: 32), settings: careful)!, cautious)
+ XCTAssertNil(DivePlanner.noStopLimit(depth: 5, gas: .air, settings: careful))
+
+ // A plan just inside the limit has no mandatory stop and gets its safety stop; a minute over it has one.
+ let inside = DivePlanner.plan(DivePlan(levels: [PlanLevel(depth: 30, minutes: Double(cautious))], cylinders: [PlanCylinder(gas: .air)], settings: careful))
+ XCTAssertFalse(inside.hasDecoStops)
+ XCTAssertEqual(inside.stops.map(\.kind), [.safety])
+ XCTAssertEqual(inside.stops.first?.depth, 5)
+ XCTAssertEqual(inside.points.last?.time ?? 0, inside.runtime, accuracy: 1e-6)
+ let over = DivePlanner.plan(DivePlan(levels: [PlanLevel(depth: 30, minutes: Double(cautious) + 2)], cylinders: [PlanCylinder(gas: .air)], settings: careful))
+ XCTAssertTrue(over.hasDecoStops)
+ }
+
+ func testGasAndWarnings() {
+ var settings = PlanSettings()
+ settings.safetyStop = false
+ // 20 minutes at 20 m, 20 L/min: about 3 bar absolute, so roughly 1200 L at the bottom, plus the ascent.
+ let plan = DivePlan(levels: [PlanLevel(depth: 20, minutes: 20)], cylinders: [PlanCylinder(gas: .air, volumeLiters: 15, startBar: 200)], settings: settings)
+ let result = DivePlanner.plan(plan)
+ XCTAssertEqual(result.gasUsed[0], 1280, accuracy: 120)
+ XCTAssertTrue(result.warnings.isEmpty, "\(result.warnings)")
+ // The same dive on a 12 L leaves less than the minimum gas (four minutes for a problem, two stressed divers).
+ let small = DivePlanner.plan(DivePlan(levels: plan.levels, cylinders: [PlanCylinder(gas: .air, volumeLiters: 12, startBar: 200)], settings: settings))
+ XCTAssertTrue(small.warnings.contains { if case .underMinimumGas = $0 { return true } else { return false } })
+ XCTAssertGreaterThan(DivePlanner.gasLimit(depth: 20, volumeLiters: 12, startBar: 200, settings: settings), 20)
+
+ // Air at 66 m: too much oxygen, narcotic, dense; and a small cylinder that does not last.
+ let reckless = DivePlanner.plan(DivePlan(levels: [PlanLevel(depth: 66, minutes: 25)], cylinders: [PlanCylinder(gas: .air, volumeLiters: 10, startBar: 200)], settings: settings))
+ XCTAssertTrue(reckless.warnings.contains { if case .oxygenTooHigh = $0 { return true } else { return false } })
+ XCTAssertTrue(reckless.warnings.contains { if case .narcosis = $0 { return true } else { return false } })
+ XCTAssertTrue(reckless.warnings.contains { if case .density = $0 { return true } else { return false } })
+ XCTAssertTrue(reckless.warnings.contains { if case .notEnoughGas = $0 { return true } else { return false } })
+ // A hypoxic mix breathed from the surface.
+ let hypoxic = DivePlanner.plan(DivePlan(levels: [PlanLevel(depth: 80, minutes: 15)], cylinders: [PlanCylinder(gas: BreathingGas(o2Percent: 10, hePercent: 60))], settings: settings))
+ XCTAssertTrue(hypoxic.warnings.contains { if case .oxygenTooLow = $0 { return true } else { return false } })
+ XCTAssertEqual(DivePlanner.plan(DivePlan(levels: [PlanLevel(depth: 20, minutes: 20, cylinder: 3)], cylinders: [PlanCylinder(gas: .air)])).warnings, [.unknownCylinder])
+
+ // More conservative gradient factors never shorten the ascent; several levels are followed in order.
+ var loose = settings
+ loose.gfLow = 0.9
+ loose.gfHigh = 0.95
+ let levels = [PlanLevel(depth: 45, minutes: 20), PlanLevel(depth: 25, minutes: 10)]
+ let cylinders = [PlanCylinder(gas: BreathingGas(o2Percent: 21, hePercent: 35)), PlanCylinder(gas: BreathingGas(o2Percent: 50), isDeco: true)]
+ let relaxed = DivePlanner.plan(DivePlan(levels: levels, cylinders: cylinders, settings: loose))
+ let strict = DivePlanner.plan(DivePlan(levels: levels, cylinders: cylinders, settings: settings))
+ XCTAssertGreaterThan(strict.runtime, relaxed.runtime)
+ XCTAssertGreaterThanOrEqual(strict.stops.first?.depth ?? 0, relaxed.stops.first?.depth ?? 0)
+ XCTAssertEqual(strict.maxDepth, 45)
+ XCTAssertLessThanOrEqual(strict.surfaceGF, 0.86)
+ }
+}