subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

Planner.swift (35548B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 
      4 /// A cylinder taken on the dive.
      5 public struct PlanCylinder: Codable, Sendable, Equatable, Identifiable {
      6     public var id = UUID()
      7     public var gas: BreathingGas
      8     /// Water capacity in litres and filling pressure in bar; nil when only the gas matters.
      9     public var volumeLiters: Double?
     10     public var startBar: Double?
     11     /// A decompression (or bailout) gas is switched to on the way up, from `switchDepth` (nil: its depth at the
     12     /// decompression limit on the partial pressure of oxygen).
     13     public var isDeco = false
     14     public var switchDepth: Double?
     15 
     16     public init(gas: BreathingGas, volumeLiters: Double? = nil, startBar: Double? = nil, isDeco: Bool = false, switchDepth: Double? = nil) {
     17         self.gas = gas
     18         self.volumeLiters = volumeLiters
     19         self.startBar = startBar
     20         self.isDeco = isDeco
     21         self.switchDepth = switchDepth
     22     }
     23 
     24     /// Litres of gas at the surface, compressibility taken into account.
     25     public var availableLiters: Double? {
     26         guard let volumeLiters, let startBar else { return nil }
     27         return RealGas.liters(gas, volumeLiters: volumeLiters, bar: startBar)
     28     }
     29 
     30     /// Pressure left after breathing `liters` (at the surface) from a full cylinder; negative when it does not hold that much.
     31     public func pressure(afterUsing liters: Double) -> Double? {
     32         guard let volumeLiters, volumeLiters > 0, let available = availableLiters else { return nil }
     33         let left = available - liters
     34         return left >= 0 ? RealGas.pressure(gas, liters: left, volumeLiters: volumeLiters) : left / volumeLiters
     35     }
     36 }
     37 
     38 /// Compressibility of breathing gases (Subsurface's `core/gas-model.cpp`: cubic virial fit for O2, N2 and He at 300 K).
     39 public enum RealGas {
     40     private static func virial(_ coefficients: [Double], _ x: Double) -> Double {
     41         x * coefficients[0] + x * x * coefficients[1] + x * x * x * coefficients[2]
     42     }
     43 
     44     /// Z = pV / nRT at a pressure in bar.
     45     public static func compressibility(_ gas: BreathingGas, bar: Double) -> Double {
     46         let pressure = min(max(bar, 0), 500)
     47         let o2 = (gas.o2 * 1000).rounded(), he = (gas.he * 1000).rounded()
     48         let z = virial([-7.18092073703e-04, 2.81852572808e-06, -1.50290620492e-09], pressure) * o2
     49             + virial([4.87320026468e-04, -8.83632921053e-08, 5.33304543646e-11], pressure) * he
     50             + virial([-2.19260353292e-04, 2.92844845532e-06, -2.07613482075e-09], pressure) * (1000 - o2 - he)
     51         return z * 0.001 + 1
     52     }
     53 
     54     /// Litres at the surface held by a cylinder at a pressure.
     55     public static func liters(_ gas: BreathingGas, volumeLiters: Double, bar: Double) -> Double {
     56         volumeLiters * bar / compressibility(gas, bar: bar) * compressibility(gas, bar: 1)
     57     }
     58 
     59     /// Pressure of `liters` (at the surface) put into a cylinder (`isothermal_pressure`).
     60     public static func pressure(_ gas: BreathingGas, liters: Double, volumeLiters: Double) -> Double {
     61         guard volumeLiters > 0 else { return 0 }
     62         let ideal = liters / volumeLiters / compressibility(gas, bar: 1)
     63         return ideal * compressibility(gas, bar: ideal)
     64     }
     65 }
     66 
     67 /// One part of the dive as the diver intends it: go to a depth and stay there.
     68 public struct PlanLevel: Codable, Sendable, Equatable, Identifiable {
     69     public var id = UUID()
     70     public var depth: Double
     71     /// Minutes from leaving the previous depth (or the surface): the way there counts, as in dive tables.
     72     public var minutes: Double
     73     /// Index of the cylinder breathed (the diluent, on a closed circuit), in the plan's list.
     74     public var cylinder = 0
     75 
     76     public init(depth: Double, minutes: Double, cylinder: Int = 0) {
     77         self.depth = depth
     78         self.minutes = minutes
     79         self.cylinder = cylinder
     80     }
     81 }
     82 
     83 public enum DecoModel: String, Codable, Sendable, CaseIterable {
     84     /// Bühlmann ZHL-16C with gradient factors.
     85     case buhlmann
     86     /// Varying permeability model with Boyle compensation.
     87     case vpmb
     88     /// No-stop diving: the bottom time is extended to the no-stop limit (Bühlmann, with the gradient factors) or
     89     /// to what the gas allows with its reserve, then a direct ascent.
     90     case recreational
     91 }
     92 
     93 public enum BreathingMode: String, Codable, Sendable, CaseIterable {
     94     case openCircuit
     95     /// Closed circuit rebreather, at a constant partial pressure of oxygen (the setpoint).
     96     case closedCircuit
     97     /// Passive semi-closed rebreather.
     98     case semiClosed
     99 }
    100 
    101 public struct PlanSettings: Codable, Sendable, Equatable {
    102     public var model = DecoModel.buhlmann
    103     /// Gradient factors, as fractions (0.40 and 0.85 for "40/85").
    104     public var gfLow = 0.40
    105     public var gfHigh = 0.85
    106     /// VPM-B conservatism, 0 (nominal) to 4.
    107     public var vpmbConservatism = 2
    108     /// Metres per minute.
    109     public var descentRate = 18.0
    110     /// Ascent rates by zone, as Subsurface has them: below 75 % of the average depth, from 75 % to 50 %, from
    111     /// 50 % to 6 m, and above 6 m.
    112     public var ascentRate75 = 9.0
    113     public var ascentRate50 = 9.0
    114     public var ascentRateStops = 9.0
    115     public var ascentRateLast6m = 9.0
    116     /// Last stop at 6 m instead of 3 m.
    117     public var lastStopAt6m = false
    118     /// Three minutes at 5 m on the way up of a dive without mandatory stops, deeper than 10 m.
    119     public var safetyStop = true
    120     /// A gas is only switched to where a stop is required anyway.
    121     public var switchOnlyAtRequiredStops = false
    122     /// Twelve minutes on oxygen, then six on a leaner gas, during long oxygen stops.
    123     public var oxygenBreaks = false
    124     /// Surface air consumption, in litres per minute: at the bottom, and during the ascent and the stops.
    125     public var sacBottom = 20.0
    126     public var sacDeco = 17.0
    127     /// Limits on the partial pressure of oxygen, in bar.
    128     public var ppO2Bottom = 1.4
    129     public var ppO2Deco = 1.6
    130     /// Time spent on a gas switch before the stop clock starts, in seconds.
    131     public var gasSwitchSeconds = 60.0
    132     /// Minimum gas: minutes to sort a problem out at the bottom, and factor on the consumption (two divers, stressed).
    133     public var problemMinutes = 4.0
    134     public var minimumGasFactor = 4.0
    135     /// Pressure to keep in every cylinder, in bar.
    136     public var reserveBar = 40.0
    137     /// Stops every 10 ft instead of every 3 m.
    138     public var stopsInFeet = false
    139     /// Minutes shown at the surface after the dive (for the profile only).
    140     public var surfaceSegmentMinutes = 0.0
    141     public var environment = DiveEnvironment.sea
    142 
    143     public init() {}
    144 
    145     /// Sets every ascent rate at once.
    146     public mutating func setAscentRate(_ rate: Double, last6m: Double? = nil) {
    147         ascentRate75 = rate
    148         ascentRate50 = rate
    149         ascentRateStops = rate
    150         ascentRateLast6m = last6m ?? rate
    151     }
    152     /// Tolerant decoding: a plan saved by an earlier version, without the newer settings, still opens.
    153     public init(from decoder: Decoder) throws {
    154         let container = try decoder.container(keyedBy: CodingKeys.self)
    155         if let value = try container.decodeIfPresent(type(of: model), forKey: .model) { model = value }
    156         if let value = try container.decodeIfPresent(type(of: gfLow), forKey: .gfLow) { gfLow = value }
    157         if let value = try container.decodeIfPresent(type(of: gfHigh), forKey: .gfHigh) { gfHigh = value }
    158         if let value = try container.decodeIfPresent(type(of: vpmbConservatism), forKey: .vpmbConservatism) { vpmbConservatism = value }
    159         if let value = try container.decodeIfPresent(type(of: descentRate), forKey: .descentRate) { descentRate = value }
    160         if let value = try container.decodeIfPresent(type(of: ascentRate75), forKey: .ascentRate75) { ascentRate75 = value }
    161         if let value = try container.decodeIfPresent(type(of: ascentRate50), forKey: .ascentRate50) { ascentRate50 = value }
    162         if let value = try container.decodeIfPresent(type(of: ascentRateStops), forKey: .ascentRateStops) { ascentRateStops = value }
    163         if let value = try container.decodeIfPresent(type(of: ascentRateLast6m), forKey: .ascentRateLast6m) { ascentRateLast6m = value }
    164         if let value = try container.decodeIfPresent(type(of: lastStopAt6m), forKey: .lastStopAt6m) { lastStopAt6m = value }
    165         if let value = try container.decodeIfPresent(type(of: safetyStop), forKey: .safetyStop) { safetyStop = value }
    166         if let value = try container.decodeIfPresent(type(of: switchOnlyAtRequiredStops), forKey: .switchOnlyAtRequiredStops) { switchOnlyAtRequiredStops = value }
    167         if let value = try container.decodeIfPresent(type(of: oxygenBreaks), forKey: .oxygenBreaks) { oxygenBreaks = value }
    168         if let value = try container.decodeIfPresent(type(of: sacBottom), forKey: .sacBottom) { sacBottom = value }
    169         if let value = try container.decodeIfPresent(type(of: sacDeco), forKey: .sacDeco) { sacDeco = value }
    170         if let value = try container.decodeIfPresent(type(of: ppO2Bottom), forKey: .ppO2Bottom) { ppO2Bottom = value }
    171         if let value = try container.decodeIfPresent(type(of: ppO2Deco), forKey: .ppO2Deco) { ppO2Deco = value }
    172         if let value = try container.decodeIfPresent(type(of: gasSwitchSeconds), forKey: .gasSwitchSeconds) { gasSwitchSeconds = value }
    173         if let value = try container.decodeIfPresent(type(of: problemMinutes), forKey: .problemMinutes) { problemMinutes = value }
    174         if let value = try container.decodeIfPresent(type(of: minimumGasFactor), forKey: .minimumGasFactor) { minimumGasFactor = value }
    175         if let value = try container.decodeIfPresent(type(of: reserveBar), forKey: .reserveBar) { reserveBar = value }
    176         if let value = try container.decodeIfPresent(type(of: stopsInFeet), forKey: .stopsInFeet) { stopsInFeet = value }
    177         if let value = try container.decodeIfPresent(type(of: surfaceSegmentMinutes), forKey: .surfaceSegmentMinutes) { surfaceSegmentMinutes = value }
    178         if let value = try container.decodeIfPresent(type(of: environment), forKey: .environment) { environment = value }
    179     }
    180 }
    181 
    182 public extension DiveEnvironment {
    183     /// Altitude above sea level for the surface pressure, in metres (Subsurface's formula).
    184     var altitude: Double {
    185         get { log(1.013 / surfacePressure) * 7800 }
    186         set { surfacePressure = 1.013 * exp(-newValue / 7800) }
    187     }
    188 }
    189 
    190 public struct DivePlan: Codable, Sendable, Equatable {
    191     public var levels: [PlanLevel]
    192     public var cylinders: [PlanCylinder]
    193     public var settings = PlanSettings()
    194     public var mode = BreathingMode.openCircuit
    195     /// Setpoint of a closed circuit, in bar.
    196     public var setpoint = 1.3
    197     /// A rebreather dive ends on open circuit: the deco gases are the bailout gases.
    198     public var bailout = false
    199     /// Closed circuit without bailout: a setpoint to switch to on the way up (nil: the same to the surface), and
    200     /// the depth from which it applies, in metres.
    201     public var ascentSetpoint: Double?
    202     public var ascentSetpointDepth = 21.0
    203 
    204     public init(levels: [PlanLevel], cylinders: [PlanCylinder], settings: PlanSettings = PlanSettings()) {
    205         self.levels = levels
    206         self.cylinders = cylinders
    207         self.settings = settings
    208     }
    209     /// Tolerant decoding: a plan saved by an earlier version, without the newer settings, still opens.
    210     public init(from decoder: Decoder) throws {
    211         let container = try decoder.container(keyedBy: CodingKeys.self)
    212         levels = try container.decode([PlanLevel].self, forKey: .levels)
    213         cylinders = try container.decode([PlanCylinder].self, forKey: .cylinders)
    214         if let value = try container.decodeIfPresent(type(of: settings), forKey: .settings) { settings = value }
    215         if let value = try container.decodeIfPresent(type(of: mode), forKey: .mode) { mode = value }
    216         if let value = try container.decodeIfPresent(type(of: setpoint), forKey: .setpoint) { setpoint = value }
    217         if let value = try container.decodeIfPresent(type(of: bailout), forKey: .bailout) { bailout = value }
    218         ascentSetpoint = try container.decodeIfPresent(Double.self, forKey: .ascentSetpoint)
    219         if let value = try container.decodeIfPresent(type(of: ascentSetpointDepth), forKey: .ascentSetpointDepth) { ascentSetpointDepth = value }
    220     }
    221 }
    222 
    223 /// A dive made before the one being planned, whose leftover gas counts.
    224 public struct PriorDive: Sendable, Equatable {
    225     public struct Sample: Sendable, Equatable {
    226         /// Seconds since the start of that dive, metres, and the gas breathed from this point on.
    227         public var time: Double
    228         public var depth: Double
    229         public var gas: BreathingGas
    230 
    231         public init(time: Double, depth: Double, gas: BreathingGas) {
    232             self.time = time
    233             self.depth = depth
    234             self.gas = gas
    235         }
    236     }
    237     public var samples: [Sample]
    238     /// Seconds between the end of this dive and the start of the next one (or of the plan).
    239     public var surfaceInterval: Double
    240 
    241     public init(samples: [Sample], surfaceInterval: Double) {
    242         self.samples = samples
    243         self.surfaceInterval = surfaceInterval
    244     }
    245 }
    246 
    247 /// A point of the planned profile.
    248 public struct PlanPoint: Sendable, Equatable {
    249     /// Seconds since leaving the surface.
    250     public var time: Double
    251     public var depth: Double
    252     /// Cylinder breathed from this point on.
    253     public var cylinder: Int
    254     /// False once the diver is off the loop of a rebreather.
    255     public var onLoop = false
    256 }
    257 
    258 /// A stop on the way up: mandatory decompression stop, time taken by a gas switch, or safety stop.
    259 public struct PlanStop: Sendable, Equatable {
    260     public enum Kind: Sendable, Equatable { case deco, gasSwitch, safety }
    261     public var depth: Double
    262     public var seconds: Double
    263     public var cylinder: Int
    264     public var kind: Kind
    265     /// Run time when the stop ends, in seconds.
    266     public var endTime: Double
    267 }
    268 
    269 public enum PlanWarning: Sendable, Equatable {
    270     /// Partial pressure of oxygen above the limit: gas, depth, bar.
    271     case oxygenTooHigh(cylinder: Int, depth: Double, ppO2: Double)
    272     /// Not enough oxygen to breathe the gas there.
    273     case oxygenTooLow(cylinder: Int, depth: Double, ppO2: Double)
    274     /// Equivalent narcotic depth beyond 30 m.
    275     case narcosis(cylinder: Int, depth: Double, end: Double)
    276     /// Gas density above 5.2 g/L.
    277     case density(cylinder: Int, depth: Double, gramsPerLiter: Double)
    278     /// The plan uses more than the cylinder holds: litres needed, litres available.
    279     case notEnoughGas(cylinder: Int, needed: Double, available: Double)
    280     /// The cylinder ends under the reserve: bar left, bar to keep.
    281     case underReserve(cylinder: Int, leftBar: Double, reserveBar: Double)
    282     /// What is left at the end of the bottom time is under the minimum gas.
    283     case underMinimumGas(cylinder: Int, leftBar: Double, minimumBar: Double)
    284     case cnsHigh(percent: Double)
    285     /// Recreational mode: the dive as entered already needs decompression stops.
    286     case exceedsNoStopLimit
    287     /// A level uses a cylinder that is not in the list.
    288     case unknownCylinder
    289     /// The decompression does not end (a gas that cannot be breathed up there, usually).
    290     case endless
    291 }
    292 
    293 public struct PlanResult: Sendable, Equatable {
    294     public var points: [PlanPoint] = []
    295     public var stops: [PlanStop] = []
    296     /// Seconds: whole dive, and from the end of the bottom part to the surface.
    297     public var runtime = 0.0
    298     public var ascentTime = 0.0
    299     public var maxDepth = 0.0
    300     /// Litres of gas (at the surface) used per cylinder, same order as the plan's list. On a closed circuit only
    301     /// what is breathed off the loop is counted.
    302     public var gasUsed: [Double] = []
    303     /// Minimum gas to keep in the bottom cylinder when leaving the bottom, in litres.
    304     public var minimumGasLiters: Double?
    305     public var bottomCylinder = 0
    306     /// Share of the CNS clock (1 = 100 %) and pulmonary oxygen units.
    307     public var cns = 0.0
    308     public var otu = 0.0
    309     /// Supersaturation on surfacing, as a share of the Bühlmann limit.
    310     public var surfaceGF = 0.0
    311     /// Ceiling when leaving the bottom, in metres.
    312     public var firstCeiling = 0.0
    313     /// Recreational mode: minutes added at the bottom, up to the no-stop limit or to what the gas allows.
    314     public var bottomExtensionMinutes = 0.0
    315     public var warnings: [PlanWarning] = []
    316 
    317     public init() {}
    318 
    319     /// True when the ascent has mandatory decompression stops.
    320     public var hasDecoStops: Bool { stops.contains { $0.kind == .deco } }
    321 }
    322 
    323 /// How the decompression changes around a plan: seconds of run time per metre deeper and per minute longer.
    324 public struct PlanVariations: Sendable, Equatable {
    325     public var perMeter: Double
    326     public var perMinute: Double
    327 }
    328 
    329 public enum DivePlanner {
    330     // MARK: Conversion to the core
    331 
    332     private static func coreGas(_ gas: BreathingGas) -> CoreGas {
    333         CoreGas(o2: Int((gas.o2 * 1000).rounded()), he: Int((gas.he * 1000).rounded()))
    334     }
    335 
    336     private static func coreEnvironment(_ environment: DiveEnvironment) -> CoreEnvironment {
    337         CoreEnvironment(surfaceMbar: Int((environment.surfacePressure * 1000).rounded()), salinity: Int((environment.waterDensity * 10_000).rounded()))
    338     }
    339 
    340     /// Millimetres per second, truncated the way Subsurface stores its rates.
    341     private static func rate(_ metersPerMinute: Double) -> Int { max(1, Int(metersPerMinute * 1000) / 60) }
    342 
    343     private static func model(_ plan: DivePlan) -> DecoState {
    344         var model = DecoState()
    345         model.vpmb = plan.settings.model == .vpmb
    346         model.conservatism = plan.settings.vpmbConservatism
    347         model.gfLow = plan.settings.gfLow
    348         model.gfHigh = plan.settings.gfHigh
    349         model.environment = coreEnvironment(plan.settings.environment)
    350         model.bottomSac = plan.settings.sacBottom * 1000
    351         return model
    352     }
    353 
    354     private static func prefs(_ plan: DivePlan) -> CorePrefs {
    355         let settings = plan.settings
    356         var prefs = CorePrefs()
    357         prefs.ascRate75 = rate(settings.ascentRate75)
    358         prefs.ascRate50 = rate(settings.ascentRate50)
    359         prefs.ascRateStops = rate(settings.ascentRateStops)
    360         prefs.ascRateLast6m = rate(settings.ascentRateLast6m)
    361         prefs.lastStopAt6m = settings.lastStopAt6m
    362         prefs.minSwitchDuration = Int(settings.gasSwitchSeconds.rounded())
    363         prefs.switchAtRequiredStop = settings.switchOnlyAtRequiredStops
    364         prefs.oxygenBreaks = settings.oxygenBreaks
    365         prefs.bailout = plan.mode != .openCircuit && plan.bailout
    366         prefs.problemSolvingMinutes = Int(settings.problemMinutes.rounded())
    367         prefs.bottomSac = settings.sacBottom * 1000
    368         prefs.decoSac = settings.sacDeco * 1000
    369         prefs.imperialStops = settings.stopsInFeet
    370         prefs.recreational = settings.model == .recreational
    371         prefs.safetyStop = settings.safetyStop
    372         prefs.reserveMbar = Int((settings.reserveBar * 1000).rounded())
    373         return prefs
    374     }
    375 
    376     /// Depth from which a decompression gas is breathed, in metres.
    377     public static func switchDepth(of cylinder: PlanCylinder, settings: PlanSettings) -> Double {
    378         cylinder.switchDepth ?? cylinder.gas.switchDepth(ppO2: settings.ppO2Deco, in: settings.environment)
    379     }
    380 
    381     private static func coreCylinders(_ plan: DivePlan) -> [CoreCylinder] {
    382         var out = plan.cylinders.map { cylinder -> CoreCylinder in
    383             let change = cylinder.isDeco ? Int((switchDepth(of: cylinder, settings: plan.settings) * 1000).rounded()) : nil
    384             return CoreCylinder(gas: coreGas(cylinder.gas), changeDepth: change.flatMap { $0 > 0 ? $0 : nil },
    385                                 sizeMl: Int(((cylinder.volumeLiters ?? 0) * 1000).rounded()), startMbar: Int(((cylinder.startBar ?? 0) * 1000).rounded()))
    386         }
    387         // The setpoint for the ascent is one more "cylinder" for the core: the diluent again, with a setpoint.
    388         if plan.mode == .closedCircuit, !plan.bailout, let setpoint = plan.ascentSetpoint, let diluent = plan.levels.last?.cylinder,
    389            plan.cylinders.indices.contains(diluent) {
    390             out.append(CoreCylinder(gas: coreGas(plan.cylinders[diluent].gas), changeDepth: Int((plan.ascentSetpointDepth * 1000).rounded()),
    391                                     setpoint: Int((setpoint * 1000).rounded())))
    392         }
    393         return out
    394     }
    395 
    396     /// The levels as legs: the way to each depth at the descent or ascent rate, then the rest of its time there.
    397     private static func waypoints(_ plan: DivePlan) -> [CoreWaypoint] {
    398         let mode: CoreMode = plan.mode == .closedCircuit ? .closedCircuit : (plan.mode == .semiClosed ? .semiClosed : .openCircuit)
    399         let setpoint = plan.mode == .closedCircuit ? Int((plan.setpoint * 1000).rounded()) : 0
    400         var out = [CoreWaypoint]()
    401         var depth = 0
    402         for level in plan.levels {
    403             let target = Int((level.depth * 1000).rounded())
    404             let total = Int((level.minutes * 60).rounded())
    405             let speed = target >= depth ? plan.settings.descentRate : plan.settings.ascentRate75
    406             let travel = abs(target - depth) * 60 / max(1, Int(speed * 1000))
    407             if travel > 0 { out.append(CoreWaypoint(seconds: travel, depth: target, cylinder: level.cylinder, setpoint: setpoint, mode: mode)) }
    408             if total > travel { out.append(CoreWaypoint(seconds: total - travel, depth: target, cylinder: level.cylinder, setpoint: setpoint, mode: mode)) }
    409             depth = target
    410         }
    411         return out
    412     }
    413 
    414     // MARK: Planning
    415 
    416     /// Plans the ascent of a dive: stops, run time, gas, oxygen exposure and what to worry about.
    417     public static func plan(_ plan: DivePlan, after prior: [PriorDive] = []) -> PlanResult {
    418         var result = PlanResult()
    419         result.gasUsed = [Double](repeating: 0, count: plan.cylinders.count)
    420         let legs = waypoints(plan)
    421         guard !plan.cylinders.isEmpty, !legs.isEmpty, plan.levels.allSatisfy({ plan.cylinders.indices.contains($0.cylinder) }) else {
    422             result.warnings = [.unknownCylinder]
    423             return result
    424         }
    425         let settings = plan.settings
    426         let earlier = prior.map { dive in
    427             CorePriorDive(samples: dive.samples.map {
    428                 CorePriorDive.Sample(time: Int($0.time.rounded()), depth: Int(($0.depth * 1000).rounded()), gas: coreGas($0.gas))
    429             }, surfaceInterval: Int(dive.surfaceInterval.rounded()))
    430         }
    431         var output = CorePlanner.plan(waypoints: legs, cylinders: coreCylinders(plan), prefs: prefs(plan), model: model(plan), after: earlier)
    432         // The setpoint "cylinder" is the diluent of the last level.
    433         let diluent = plan.levels.last?.cylinder ?? 0
    434         func real(_ cylinder: Int) -> Int { plan.cylinders.indices.contains(cylinder) ? cylinder : diluent }
    435         output.gasUsed = Array(output.gasUsed.prefix(plan.cylinders.count))
    436         output.decoGasUsed = Array(output.decoGasUsed.prefix(plan.cylinders.count))
    437 
    438         result.points = output.track.map {
    439             PlanPoint(time: Double($0.time), depth: Double($0.depth) / 1000, cylinder: real($0.cylinder), onLoop: $0.mode != .openCircuit)
    440         }
    441         result.stops = output.stops.map {
    442             PlanStop(depth: Double($0.depth) / 1000, seconds: Double($0.seconds), cylinder: real($0.cylinder),
    443                      kind: $0.isGasSwitch ? .gasSwitch : .deco, endTime: Double($0.endTime))
    444         }
    445         result.bottomExtensionMinutes = Double(output.bottomExtension) / 60
    446         if output.exceedsNoStopLimit { result.warnings.append(.exceedsNoStopLimit) }
    447         if settings.model == .recreational, output.hasSafetyStop,
    448            let end = output.track.last(where: { $0.depth == 5000 }), let cylinder = result.points.last?.cylinder {
    449             result.stops.append(PlanStop(depth: 5, seconds: 180, cylinder: cylinder, kind: .safety, endTime: Double(end.time)))
    450         }
    451         result.runtime = Double(output.runtime)
    452         result.ascentTime = Double(output.runtime - output.bottomTime)
    453         result.maxDepth = plan.levels.map(\.depth).max() ?? 0
    454         result.gasUsed = output.gasUsed.map { $0 / 1000 }
    455         result.bottomCylinder = output.bottomCylinder
    456         result.cns = output.cns
    457         result.otu = output.otu
    458         result.firstCeiling = Double(output.firstCeilingDepth) / 1000
    459         result.surfaceGF = surfaceGF(output.finalState)
    460         if output.timedOut { result.warnings.append(.endless) }
    461 
    462         if settings.model != .recreational, !result.hasDecoStops, settings.safetyStop, result.maxDepth >= 10, !output.timedOut {
    463             insertSafetyStop(&result, plan: plan)
    464         }
    465         if settings.surfaceSegmentMinutes > 0, let last = result.points.last {
    466             result.points.append(PlanPoint(time: last.time + settings.surfaceSegmentMinutes * 60, depth: 0, cylinder: last.cylinder))
    467         }
    468 
    469         // Minimum gas (`plannernotes.cpp`): from the end of the bottom time, a problem to sort out and the ascent
    470         // to the first gas switch (or the surface), at a stressed consumption for two.
    471         let bottom = output.bottomCylinder
    472         let minimum = settings.minimumGasFactor * (settings.problemMinutes * settings.sacBottom * coreEnvironment(settings.environment).bar(output.bottomDepth)
    473                                                    + output.decoGasUsed[bottom] / 1000)
    474         if plan.mode == .openCircuit, settings.model != .recreational { result.minimumGasLiters = minimum }
    475         let usedAtBottom = (output.gasUsed[bottom] - output.decoGasUsed[bottom]) / 1000
    476         result.warnings += warnings(for: plan, result: result, usedAtBottom: usedAtBottom, minimum: result.minimumGasLiters)
    477         return result
    478     }
    479 
    480     private static func surfaceGF(_ state: DecoState) -> Double {
    481         let surface = state.environment.surfaceBar
    482         var highest = 0.0
    483         for index in 0..<16 {
    484             let total = state.n2[index] + state.he[index]
    485             let a = (Tissues.n2A[index] * state.n2[index] + Tissues.heA[index] * state.he[index]) / total
    486             let b = (Tissues.n2B[index] * state.n2[index] + Tissues.heB[index] * state.he[index]) / total
    487             highest = max(highest, (total - surface) / (a + surface / b - surface))
    488         }
    489         return highest
    490     }
    491 
    492     /// Adds three minutes at 5 m to an ascent that had no mandatory stop: gas and oxygen for the stop are added,
    493     /// the profile gets the plateau. (The tissues only off-gas more: nothing else changes.)
    494     private static func insertSafetyStop(_ result: inout PlanResult, plan: DivePlan) {
    495         let settings = plan.settings, environment = settings.environment
    496         let stopDepth = 5.0, seconds = 180.0
    497         guard let index = result.points.lastIndex(where: { $0.depth > stopDepth }), index + 1 < result.points.count else { return }
    498         let before = result.points[index], after = result.points[index + 1]
    499         guard before.depth > after.depth else { return }
    500         let crossing = before.time + (after.time - before.time) * (before.depth - stopDepth) / (before.depth - after.depth)
    501         for later in (index + 1)..<result.points.count { result.points[later].time += seconds }
    502         result.points.insert(contentsOf: [PlanPoint(time: crossing, depth: stopDepth, cylinder: before.cylinder, onLoop: before.onLoop),
    503                                           PlanPoint(time: crossing + seconds, depth: stopDepth, cylinder: before.cylinder, onLoop: before.onLoop)], at: index + 1)
    504         let pressure = environment.pressure(atDepth: stopDepth)
    505         let gas = plan.cylinders[before.cylinder].gas
    506         if !before.onLoop {
    507             result.gasUsed[before.cylinder] += settings.sacDeco * pressure * seconds / 60
    508             result.cns += OxygenExposure.cns(ppO2: pressure * gas.o2, seconds: seconds)
    509             result.otu += OxygenExposure.otu(ppO2: pressure * gas.o2, seconds: seconds)
    510         }
    511         result.stops.append(PlanStop(depth: stopDepth, seconds: seconds, cylinder: before.cylinder, kind: .safety, endTime: crossing + seconds))
    512         result.runtime += seconds
    513         result.ascentTime += seconds
    514     }
    515 
    516     private static func warnings(for plan: DivePlan, result: PlanResult, usedAtBottom: Double, minimum: Double?) -> [PlanWarning] {
    517         let settings = plan.settings, environment = settings.environment
    518         var found = [PlanWarning]()
    519         // Each cylinder at the deepest and at the shallowest point where it is breathed on open circuit.
    520         var deepest = [Int: Double](), shallowest = [Int: Double]()
    521         for (index, point) in result.points.enumerated() where !point.onLoop {
    522             let until = index + 1 < result.points.count ? result.points[index + 1].depth : point.depth
    523             for depth in [point.depth, until] {
    524                 deepest[point.cylinder] = max(deepest[point.cylinder] ?? 0, depth)
    525                 if depth > 0 { shallowest[point.cylinder] = min(shallowest[point.cylinder] ?? .infinity, depth) }
    526             }
    527         }
    528         for (cylinder, depth) in deepest.sorted(by: { $0.key < $1.key }) {
    529             let gas = plan.cylinders[cylinder].gas
    530             let limit = plan.cylinders[cylinder].isDeco ? settings.ppO2Deco : settings.ppO2Bottom
    531             let ppO2 = gas.ppO2(atDepth: depth, in: environment)
    532             if ppO2 > limit + 0.005 { found.append(.oxygenTooHigh(cylinder: cylinder, depth: depth, ppO2: ppO2)) }
    533             let end = gas.equivalentNarcoticDepth(atDepth: depth, in: environment)
    534             if end > 30.5 { found.append(.narcosis(cylinder: cylinder, depth: depth, end: end)) }
    535             let density = gas.density(atDepth: depth, in: environment)
    536             if density > 5.2 { found.append(.density(cylinder: cylinder, depth: depth, gramsPerLiter: density)) }
    537         }
    538         // On the loop the setpoint decides the oxygen; the diluent still has to be narcotically sane at the bottom.
    539         if plan.mode == .closedCircuit {
    540             if plan.setpoint > settings.ppO2Bottom + 0.005, let first = plan.levels.first {
    541                 found.append(.oxygenTooHigh(cylinder: first.cylinder, depth: result.maxDepth, ppO2: plan.setpoint))
    542             }
    543         }
    544         for cylinder in Set(result.points.filter { !$0.onLoop }.map(\.cylinder)).sorted() {
    545             let gas = plan.cylinders[cylinder].gas
    546             let startsAtSurface = result.points.first?.cylinder == cylinder && result.points.first?.onLoop == false
    547             let depth = startsAtSurface ? 0 : (shallowest[cylinder] ?? 0)
    548             let ppO2 = gas.ppO2(atDepth: depth, in: environment)
    549             if ppO2 < 0.16 { found.append(.oxygenTooLow(cylinder: cylinder, depth: depth, ppO2: ppO2)) }
    550         }
    551         for (cylinder, used) in result.gasUsed.enumerated() where used > 0 {
    552             guard let available = plan.cylinders[cylinder].availableLiters else { continue }
    553             if used > available {
    554                 found.append(.notEnoughGas(cylinder: cylinder, needed: used, available: available))
    555             } else if let left = plan.cylinders[cylinder].pressure(afterUsing: used), left < settings.reserveBar {
    556                 found.append(.underReserve(cylinder: cylinder, leftBar: left, reserveBar: settings.reserveBar))
    557             }
    558         }
    559         let bottom = result.bottomCylinder
    560         if let minimum, let available = plan.cylinders[bottom].availableLiters, let volume = plan.cylinders[bottom].volumeLiters, volume > 0,
    561            usedAtBottom <= available, available - usedAtBottom < minimum {
    562             found.append(.underMinimumGas(cylinder: bottom,
    563                                           leftBar: RealGas.pressure(plan.cylinders[bottom].gas, liters: available - usedAtBottom, volumeLiters: volume),
    564                                           minimumBar: RealGas.pressure(plan.cylinders[bottom].gas, liters: minimum, volumeLiters: volume)))
    565         }
    566         if result.cns > 0.8 { found.append(.cnsHigh(percent: result.cns * 100)) }
    567         return found
    568     }
    569 
    570     /// How much the run time moves for a metre deeper and for a minute longer at the last level (central
    571     /// differences, as Subsurface's "plan variations").
    572     public static func variations(of plan: DivePlan) -> PlanVariations? {
    573         guard let last = plan.levels.indices.last, plan.levels[last].minutes > 1, plan.levels[last].depth > 1 else { return nil }
    574         guard plan.settings.model != .recreational else { return nil }
    575         func runtime(depth: Double, minutes: Double) -> Double {
    576             var changed = plan
    577             changed.levels[last].depth += depth
    578             changed.levels[last].minutes += minutes
    579             changed.settings.safetyStop = false
    580             return DivePlanner.plan(changed).runtime
    581         }
    582         return PlanVariations(perMeter: (runtime(depth: 1, minutes: 0) - runtime(depth: -1, minutes: 0)) / 2,
    583                               perMinute: (runtime(depth: 0, minutes: 1) - runtime(depth: 0, minutes: -1)) / 2 - 60)
    584     }
    585 
    586     // MARK: Quick answers
    587 
    588     /// How long the diver can stay at a depth and still go straight up, in minutes from leaving the surface (the
    589     /// descent counts); nil when there is no limit within `ceiling` minutes.
    590     public static func noStopLimit(depth: Double, gas: BreathingGas, settings: PlanSettings = PlanSettings(), ceiling: Int = 300) -> Int? {
    591         var plan = DivePlan(levels: [], cylinders: [PlanCylinder(gas: gas)], settings: settings)
    592         plan.settings.safetyStop = false
    593         plan.settings.model = .buhlmann
    594         // The limit is the last whole minute whose plan has no mandatory stop: found by bisection.
    595         func free(_ minutes: Int) -> Bool {
    596             plan.levels = [PlanLevel(depth: depth, minutes: Double(minutes))]
    597             return !DivePlanner.plan(plan).hasDecoStops
    598         }
    599         let descent = Int((depth / max(settings.descentRate, 1)).rounded(.up))
    600         guard free(max(descent, 1)) else { return max(0, descent - 1) }
    601         guard !free(ceiling) else { return nil }
    602         var low = max(descent, 1), high = ceiling
    603         while high - low > 1 {
    604             let middle = (low + high) / 2
    605             if free(middle) { low = middle } else { high = middle }
    606         }
    607         return low
    608     }
    609 
    610     /// How long a cylinder lasts at a depth, in minutes from leaving the surface, keeping `reserveBar` and the gas
    611     /// for a direct ascent with a safety stop.
    612     public static func gasLimit(depth: Double, gas: BreathingGas = .air, volumeLiters: Double, startBar: Double, reserveBar: Double = 50,
    613                                 settings: PlanSettings = PlanSettings()) -> Int {
    614         let environment = settings.environment
    615         let usable = RealGas.liters(gas, volumeLiters: volumeLiters, bar: startBar) - RealGas.liters(gas, volumeLiters: volumeLiters, bar: min(reserveBar, startBar))
    616         // Descent and ascent at the mean pressure, three minutes at 5 m.
    617         let mean = environment.pressure(atDepth: depth / 2)
    618         let descentMinutes = depth / settings.descentRate
    619         let ascentMinutes = depth / settings.ascentRateStops
    620         let travel = settings.sacBottom * mean * descentMinutes + settings.sacDeco * mean * ascentMinutes
    621             + (settings.safetyStop && depth >= 10 ? settings.sacDeco * environment.pressure(atDepth: 5) * 3 : 0)
    622         let perMinute = settings.sacBottom * environment.pressure(atDepth: depth)
    623         guard usable > travel, perMinute > 0 else { return 0 }
    624         return Int((descentMinutes + (usable - travel) / perMinute).rounded(.down))
    625     }
    626 }