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

commit 7a24e6138a20e6d640c0ce16ef8b3d3e1c2b19fb
parent af2340e1d875d9ad4daa47d2f352dec1f13636b4
Author: Jean Schurger <jean@schurger.org>
Date:   Sun, 15 Nov 2026 22:02:54 -0500

Planner core: recreational mode, repetitive dives, setpoint switches, imperial stops

Ported from Subsurface: the recreational branch of plan() with
track_ascent_gas and enough_gas, init_decompression (tissues after earlier
dives and surface intervals), setpoint switches on the loop (its SP
cylinders), and the stop levels in feet. Its imperial benchmark gives the
known 111 min - 2 s.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MPackages/DiveKit/Sources/DivePlanner/Core.swift | 173++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
MPackages/DiveKit/Tests/DivePlannerTests/SubsurfaceVectorsTests.swift | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 251 insertions(+), 6 deletions(-)

diff --git a/Packages/DiveKit/Sources/DivePlanner/Core.swift b/Packages/DiveKit/Sources/DivePlanner/Core.swift @@ -374,6 +374,25 @@ struct CoreCylinder: Sendable { var gas: CoreGas /// Depth from which the gas is switched to on the way up; nil for a gas that is not used for the ascent. var changeDepth: Int? + /// A setpoint to switch to at `changeDepth` on a closed circuit (Subsurface's "SP" cylinders), in millibars. + var setpoint = 0 + /// Water capacity in millilitres and filling pressure in millibars; 0 when unknown. + var sizeMl = 0 + var startMbar = 0 +} + +/// A dive made before the one being planned: its profile, and how long before the next dive (or the plan) it ended. +struct CorePriorDive: Sendable { + struct Sample: Sendable { + var time: Int + var depth: Int + var gas: CoreGas + var setpoint = 0 + var mode = CoreMode.openCircuit + } + var samples: [Sample] + /// Seconds between the end of this dive and the start of the next one. + var surfaceInterval: Int } struct CorePrefs: Sendable { @@ -388,6 +407,13 @@ struct CorePrefs: Sendable { /// Millilitres per minute. var bottomSac = 20_000.0, decoSac = 17_000.0 var timestep = 60 + /// Stops every 10 ft instead of every 3 m. + var imperialStops = false + /// Subsurface's recreational mode: the bottom time is extended to the no-stop limit or to what the gas + /// allows, then a direct ascent with an optional safety stop. + var recreational = false + var safetyStop = true + var reserveMbar = 40_000 } struct CoreTrackPoint: Sendable, Equatable { @@ -420,6 +446,11 @@ struct CoreOutput: Sendable { var otu = 0.0 var firstCeilingDepth = 0 var timedOut = false + /// Recreational mode: the entered dive already needs decompression stops. + var exceedsNoStopLimit = false + /// Recreational mode: seconds added at the bottom. + var bottomExtension = 0 + var hasSafetyStop = false var finalState: DecoState } @@ -429,6 +460,37 @@ enum CorePlanner { + [100_000, 110_000, 120_000, 130_000, 140_000, 150_000, 160_000, 170_000, 180_000, 190_000, 200_000, 220_000, 240_000, 260_000, 280_000, 300_000, 320_000, 340_000, 360_000, 380_000] + static let decoLevelsImperial: [Int] = (Array(stride(from: 0, through: 300, by: 10)) + + [333, 367, 400, 433, 467, 500, 533, 567, 600, 633, 667, 733, 800, 867, 933, 1000, 1067, 1133, 1200, 1267]) + .map { Int((Double($0) * 304.8).rounded(.toNearestOrEven)) } + + /// `init_decompression`: the tissues at the start of the plan, after the dives made before it. + static func initialState(_ model: DecoState, after prior: [CorePriorDive]) -> DecoState { + var state = model + state.clear() + let environment = state.environment + let air = CoreGas(o2: 209, he: 0) + for dive in prior { + for (previous, sample) in zip(dive.samples, dive.samples.dropFirst()) where sample.time > previous.time { + for second in previous.time..<sample.time { + let exact = (Double(previous.depth) * Double(sample.time - second) + Double(sample.depth) * Double(second - previous.time)) + / Double(sample.time - previous.time) + state.addSegment(pressure: environment.bar(Int(exact.rounded(.toNearestOrEven))), gas: previous.gas, seconds: 1, + setpoint: previous.setpoint, mode: previous.mode) + } + } + state.maxN2Crushing = [Double](repeating: 0, count: 16) + state.maxHeCrushing = state.maxN2Crushing + state.maxAmbientPressure = 0 + state.firstCeilingMbar = 0 + state.maxBottomCeilingMbar = 0 + if dive.surfaceInterval > 0 { + state.addSegment(pressure: environment.surfaceBar, gas: air, seconds: dive.surfaceInterval, setpoint: 0, mode: .openCircuit) + } + } + return state + } + static func ascentVelocity(depth: Int, average: Int, _ prefs: CorePrefs) -> Int { if depth * 4 > average * 3 { return prefs.ascRate75 } if depth * 2 > average { return prefs.ascRate50 } @@ -517,9 +579,9 @@ enum CorePlanner { return out } - static func plan(waypoints: [CoreWaypoint], cylinders: [CoreCylinder], prefs: CorePrefs, model: DecoState) -> CoreOutput { - var state = model - state.clear() + static func plan(waypoints: [CoreWaypoint], cylinders: [CoreCylinder], prefs: CorePrefs, model: DecoState, + after prior: [CorePriorDive] = []) -> CoreOutput { + var state = initialState(model, after: prior) let environment = state.environment var output = CoreOutput(finalState: state) output.gasUsed = [Double](repeating: 0, count: cylinders.count) @@ -585,9 +647,10 @@ enum CorePlanner { let onLoop = mode == .closedCircuit && !prefs.bailout var changes = [(depth: Int, cylinder: Int)]() var firstAscentCylinder = -1 - if !onLoop { + do { var bestDepth = Int.max - for (index, candidate) in cylinders.enumerated() { + // On the loop only the setpoint switches count; off it, only the real gases. + for (index, candidate) in cylinders.enumerated() where onLoop == (candidate.setpoint != 0) { guard let change = candidate.changeDepth else { continue } if change <= depth { let position = changes.firstIndex { change < $0.depth } ?? changes.count @@ -601,7 +664,7 @@ enum CorePlanner { var breakCylinder = 0 if prefs.oxygenBreaks, firstAscentCylinder != -1, cylinders[firstAscentCylinder].gas.o2 <= 320 { breakCylinder = firstAscentCylinder } - var levels = decoLevels + var levels = prefs.imperialStops ? decoLevelsImperial : decoLevels if prefs.lastStopAt6m { levels[1] = 0 } var stopIndex = levels.firstIndex { $0 > depth } ?? levels.count if stopIndex > 0 { stopIndex -= 1 } @@ -612,6 +675,11 @@ enum CorePlanner { state.nuclearRegeneration(seconds: Double(clock)) state.vpmbStartGradient() + if prefs.recreational { + return recreational(output: output, state: state, clock: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint, + average: average, cylinders: cylinders, prefs: prefs) + } + if firstAscentCylinder != -1, firstAscentCylinder != cylinder { cylinder = firstAscentCylinder output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint)) @@ -635,6 +703,7 @@ enum CorePlanner { let bottomCache = state let bottomDepth = depth let bottomCylinder = cylinder + let bottomSetpoint = setpoint let entered = output // VPM-B iterates: the gradients allowed depend on the length of the decompression they produce. @@ -646,6 +715,7 @@ enum CorePlanner { var pass = entered depth = bottomDepth cylinder = bottomCylinder + setpoint = bottomSetpoint clock = bottomTime var gi = changes.count - 1 stopIndex = bottomStopIndex @@ -706,6 +776,7 @@ enum CorePlanner { setpoint: setpoint, mode: mode, prefs: prefs) || current.o2 < 160 { cylinder = changes[gi].cylinder + if mode == .closedCircuit { setpoint = cylinders[cylinder].setpoint } point(&pass, cylinder: cylinder) if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 { state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration, @@ -728,6 +799,7 @@ enum CorePlanner { point(&pass, cylinder: cylinder) if pendingGasChange { cylinder = changes[gi + 1].cylinder + if mode == .closedCircuit { setpoint = cylinders[cylinder].setpoint } point(&pass, cylinder: cylinder) if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 { state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration, @@ -791,4 +863,93 @@ enum CorePlanner { output.finalState = state return output } + + /// Subsurface's recreational mode (the first branch of `plan`): stay as long as a direct ascent is allowed + /// and the gas lasts, then go up, with three minutes at 5 m when asked for. + private static func recreational(output entered: CoreOutput, state initial: DecoState, clock start: Int, depth bottom: Int, cylinder: Int, + mode: CoreMode, setpoint: Int, average: Int, cylinders: [CoreCylinder], prefs: CorePrefs) -> CoreOutput { + var output = entered + var state = initial + var clock = start, depth = bottom + let environment = state.environment + let gas = cylinders[cylinder].gas + let factor = mode == .semiClosed ? state.pscrRatio / 1000 : 1 + let maxDepth = output.track.map(\.depth).max() ?? depth + var safetyStop = prefs.safetyStop && maxDepth >= 10_000 + output.hasSafetyStop = safetyStop + + // What the ascent takes from the cylinder (`track_ascent_gas`). + var ascentGas = 0.0 + do { + var at = depth, pending = safetyStop + while at > 0 { + var rise = ascentVelocity(depth: at, average: average, prefs) * baseTimestep + if rise > at { rise = at } + ascentGas += environment.atm((at + at - rise) / 2) * prefs.decoSac / 60 * Double(baseTimestep) * factor + if at <= 5000, at >= 5000 - rise, pending { + ascentGas += environment.atm(5000) * prefs.decoSac / 60 * 180 * factor + pending = false + } + at -= rise + } + } + /// `enough_gas`: what is above the reserve covers the ascent. + func enoughGas() -> Bool { + let size = cylinders[cylinder].sizeMl, start = cylinders[cylinder].startMbar + guard start > 0, size > 0 else { return true } + let used = output.gasUsed[cylinder] + let end = Double(start) - used * 1000 / Double(size) + return (end - Double(prefs.reserveMbar)) / 1000 * Double(size) > ascentGas + } + func perMinute() -> Double { environment.atm(depth) * prefs.bottomSac / 60 * Double(prefs.timestep) * factor } + func direct(_ state: DecoState) -> Bool { + trialAscent(state, wait: 0, from: depth, to: 0, average: average, gas: gas, setpoint: setpoint, mode: mode, prefs: prefs) + } + + if direct(state) { + repeat { + state.addSegment(pressure: environment.bar(depth), gas: gas, seconds: prefs.timestep, setpoint: setpoint, mode: mode) + if mode != .closedCircuit { output.gasUsed[cylinder] += perMinute() } + clock += prefs.timestep + } while direct(state) && enoughGas() && clock < 6 * 3600 + // One step too many. + if mode != .closedCircuit { output.gasUsed[cylinder] -= perMinute() } + clock -= prefs.timestep + output.bottomExtension = clock - start + let ppO2 = state.ppO2(pressure: environment.bar(depth), gas: gas, setpoint: setpoint, mode: mode) + output.cns += OxygenExposure.cns(ppO2: ppO2, seconds: Double(clock - start)) + output.otu += OxygenExposure.otu(ppO2: ppO2, seconds: Double(clock - start)) + output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint)) + } else { + output.exceedsNoStopLimit = true + } + output.bottomTime = clock + if mode != .closedCircuit { + output.gasUsed[cylinder] += ascentGas + output.decoGasUsed[cylinder] += ascentGas + } + + var lastRate = ascentVelocity(depth: depth, average: average, prefs) + repeat { + let rate = ascentVelocity(depth: depth, average: average, prefs) + var rise = rate * baseTimestep + if rate != lastRate { + output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint)) + lastRate = rate + } + if depth - rise < 0 { rise = depth } + clock += baseTimestep + depth -= rise + if depth <= 5000, depth >= 5000 - rise, safetyStop { + output.track.append(CoreTrackPoint(time: clock, depth: 5000, cylinder: cylinder, mode: mode, setpoint: setpoint)) + clock += 180 + output.track.append(CoreTrackPoint(time: clock, depth: 5000, cylinder: cylinder, mode: mode, setpoint: setpoint)) + safetyStop = false + } + } while depth > 0 + output.track.append(CoreTrackPoint(time: clock, depth: 0, cylinder: cylinder, mode: mode, setpoint: setpoint)) + output.runtime = clock + output.finalState = state + return output + } } diff --git a/Packages/DiveKit/Tests/DivePlannerTests/SubsurfaceVectorsTests.swift b/Packages/DiveKit/Tests/DivePlannerTests/SubsurfaceVectorsTests.swift @@ -148,4 +148,88 @@ final class SubsurfaceVectorsTests: XCTestCase { XCTAssertEqual(cylinder(at: 20 * 60 + 1), 2) XCTAssertEqual(cylinder(at: 30 * 60), 1) } + + /// `testImperial`: the same plan as `testMetric` in feet (260 ft, stops every 10 ft, switches at 110 ft and 20 ft). + func testBuhlmannImperial() { + func feet(_ value: Double) -> Int { Int((value * 304.8).rounded(.toNearestOrEven)) } + func modFeet(_ gas: CoreGas) -> Int { + let environment = CoreEnvironment() + let depth = Double(environment.depth(relativeMbar: 1600 * 1000 / gas.o2 - environment.surfaceMbar)) + return Int(depth / 3048 + 0.1) * 3048 + } + var model = DecoState() + model.gfLow = 1 + model.gfHigh = 1 + var prefs = imperialPrefs + prefs.imperialStops = true + let depth = feet(260) + let drop = depth * 60 / feet(75) + let output = CorePlanner.plan(waypoints: [CoreWaypoint(seconds: drop, depth: depth, cylinder: 0), CoreWaypoint(seconds: 30 * 60 - drop, depth: depth, cylinder: 0)], + cylinders: [CoreCylinder(gas: CoreGas(o2: 150, he: 450)), + CoreCylinder(gas: ean36, changeDepth: modFeet(ean36)), CoreCylinder(gas: oxygen, changeDepth: modFeet(oxygen))], + prefs: prefs, model: model) + XCTAssertEqual(output.runtime, 111 * 60 - 2) + XCTAssertEqual(switches(output).map(\.depth), [33_528, 6096]) + } + + /// Recreational mode: 20 m for 20 minutes on air is within the limit; the bottom time is extended to the + /// no-stop limit or to what a 24 L cylinder allows, and the ascent has its safety stop. + func testRecreational() { + var model = DecoState() + model.gfLow = 1 + model.gfHigh = 1 + var prefs = imperialPrefs + prefs.recreational = true + let cylinder = CoreCylinder(gas: air, sizeMl: 24_000, startMbar: 232_000) + let output = CorePlanner.plan(waypoints: square(20_000, minutes: 20, descent: 23_000), cylinders: [cylinder], prefs: prefs, model: model) + XCTAssertFalse(output.exceedsNoStopLimit) + XCTAssertGreaterThan(output.bottomExtension, 0) + XCTAssertTrue(output.hasSafetyStop) + XCTAssertTrue(output.track.contains { $0.depth == 5000 }) + XCTAssertEqual(output.track.last?.depth, 0) + XCTAssertEqual(output.runtime % 2, 0) + // Whatever limits it, the cylinder keeps its reserve for the ascent. + XCTAssertLessThan(output.gasUsed[0] / 24_000 * 1000, 232_000 - 40_000) + + // 40 m for an hour needs stops: recreational mode says so instead of extending. + let deep = CorePlanner.plan(waypoints: square(40_000, minutes: 60, descent: 23_000), cylinders: [cylinder], prefs: prefs, model: model) + XCTAssertTrue(deep.exceedsNoStopLimit) + XCTAssertEqual(deep.bottomExtension, 0) + } + + /// A dive before the plan leaves gas in the tissues: the same plan is longer after it, less so after a long interval. + func testRepetitiveDive() { + var model = DecoState() + model.gfLow = 0.4 + model.gfHigh = 0.85 + let waypoints = square(40_000, minutes: 25, descent: 18_000) + let cylinders = [CoreCylinder(gas: air)] + let first = CorePlanner.plan(waypoints: waypoints, cylinders: cylinders, prefs: CorePrefs(), model: model) + func prior(interval: Int) -> CorePriorDive { + CorePriorDive(samples: first.track.map { CorePriorDive.Sample(time: $0.time, depth: $0.depth, gas: air) }, surfaceInterval: interval) + } + let soon = CorePlanner.plan(waypoints: waypoints, cylinders: cylinders, prefs: CorePrefs(), model: model, after: [prior(interval: 3600)]) + let later = CorePlanner.plan(waypoints: waypoints, cylinders: cylinders, prefs: CorePrefs(), model: model, after: [prior(interval: 6 * 3600)]) + let nextDay = CorePlanner.plan(waypoints: waypoints, cylinders: cylinders, prefs: CorePrefs(), model: model, after: [prior(interval: 72 * 3600)]) + XCTAssertGreaterThan(soon.runtime, first.runtime) + XCTAssertGreaterThanOrEqual(soon.runtime, later.runtime) + XCTAssertGreaterThanOrEqual(later.runtime, first.runtime) + XCTAssertEqual(nextDay.runtime, first.runtime) + } + + /// On the loop, the setpoint can be raised for the ascent: more oxygen, shorter stops. + func testSetpointSwitch() { + var model = DecoState() + model.gfLow = 0.5 + model.gfHigh = 0.7 + let diluent = CoreGas(o2: 200, he: 210) + let waypoints = [CoreWaypoint(seconds: 20 * 60, depth: 60_000, cylinder: 0, setpoint: 1000, mode: .closedCircuit)] + let plain = CorePlanner.plan(waypoints: waypoints, cylinders: [CoreCylinder(gas: diluent)], prefs: imperialPrefs, model: model) + let raised = CorePlanner.plan(waypoints: waypoints, + cylinders: [CoreCylinder(gas: diluent), CoreCylinder(gas: diluent, changeDepth: 21_000, setpoint: 1500)], + prefs: imperialPrefs, model: model) + XCTAssertLessThan(raised.runtime, plain.runtime) + XCTAssertEqual(raised.track.last { $0.depth == 21_000 }?.setpoint, 1500) + XCTAssertTrue(plain.track.allSatisfy { $0.setpoint == 1000 }) + } }