Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions apps/macos/Sources/RoveApp/AdvancedOptionsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,29 @@ struct AdvancedOptionsSection: View {
OverrideEditor(
title: strings("Selection weights"), addLabel: strings("Add weight"),
overrides: $workspace.settings.weights, moves: ProposalSchedule.moves, strings: strings)
Toggle(
strings("Try joint topology/rate exchange"),
isOn: Binding(
get: { settings.weights.contains { $0.move == "narrow_exchange_rates" && $0.value > 0 } },
set: { enabled in
workspace.settings.weights.removeAll { $0.move == "narrow_exchange_rates" }
if enabled {
workspace.settings.weights.append(
MoveOverride(move: "narrow_exchange_rates", value: 10))
}
})
)
.font(.system(size: 12))
.disabled(
(settings.clock != "reference" || settings.dating.enabled)
&& !settings.weights.contains { $0.move == "narrow_exchange_rates" && $0.value > 0 })
Text(
strings(
"Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established."
)
)
.font(.system(size: 10)).foregroundStyle(Lab.muted).fixedSize(
horizontal: false, vertical: true)
Toggle(strings("Tune step sizes during the run"), isOn: $workspace.settings.tuning)
.font(.system(size: 12))
OverrideEditor(
Expand Down
31 changes: 21 additions & 10 deletions apps/macos/Sources/RoveApp/Analysis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,11 @@ enum ProposalSchedule {
"gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "node_time_rates",
"root_time_rates", "clock_sigma_rates", "tip_age", "clock_rate_scale", "fbd_birth_scale",
"fbd_death_scale", "fbd_sampling_scale", "fbd_rho_logit", "fbd_origin_scale",
"narrow_exchange_rates",
]
static let relaxedClockMoves: Set<String> = [
"gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "node_time_rates",
"root_time_rates", "clock_sigma_rates",
"root_time_rates", "clock_sigma_rates", "narrow_exchange_rates",
]
static let datingMoves: Set<String> = [
"tip_age", "clock_rate_scale", "fbd_birth_scale", "fbd_death_scale", "fbd_sampling_scale",
Expand Down Expand Up @@ -198,6 +199,9 @@ enum ProposalSchedule {
})
else { return "Step sizes must be positive; scale factors must be below 1." }
let active = Set(weights.filter { $0.value > 0 }.map(\.move)).union(tuningValues.map(\.move))
if dating.enabled, active.contains("narrow_exchange_rates") {
return "Joint topology/rate exchange is currently available only without fossil dating."
}
if clock != "reference", !active.isDisjoint(with: relaxedClockMoves) {
return "Gamma shape, clock sigma, branch rate and joint moves need the relaxed clock."
}
Expand Down Expand Up @@ -314,6 +318,10 @@ struct AnalysisSettings: Codable, Equatable, Sendable {
|| ![1, 2, 4].contains(chains)
}

var usesJointExchange: Bool {
(weights + tuningValues).contains { $0.move == "narrow_exchange_rates" }
}

static var backends: [String] {
#if arch(arm64)
["automatic", "neon", "portable"]
Expand Down Expand Up @@ -462,14 +470,16 @@ struct AnalysisDraft: Codable, Sendable {
monophyly: [[String]] = [], outgroup: String? = nil
) {
formatVersion =
settings.partitioning == "labels"
? 8
: settings.usesExecutionOptions
? 7
: settings.usesCustomSigmaPrior
? 6
: (settings.usesAdvancedOptions
? 5 : (settings.dating.estimatesProcess ? 4 : (settings.dating.enabled ? 3 : 2)))
settings.usesJointExchange
? 9
: settings.partitioning == "labels"
? 8
: settings.usesExecutionOptions
? 7
: settings.usesCustomSigmaPrior
? 6
: (settings.usesAdvancedOptions
? 5 : (settings.dating.estimatesProcess ? 4 : (settings.dating.enabled ? 3 : 2)))
createdAt = Date()
matrixPath = matrix.path
matrixSHA256 = report.inputSha256
Expand All @@ -493,7 +503,8 @@ struct AnalysisDraft: Codable, Sendable {
}

func validate() throws {
guard (1...8).contains(formatVersion),
guard (1...9).contains(formatVersion),
formatVersion >= 9 || !settings.usesJointExchange,
formatVersion >= 8 || settings.partitioning != "labels",
formatVersion >= 7 || !settings.usesExecutionOptions,
formatVersion >= 6 || !settings.usesCustomSigmaPrior,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1154,3 +1154,8 @@
"%@ valid pairs · %@ undefined" = "%@ valid pairs · %@ undefined";
"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Replicate details are missing or disagree with the check record. The distribution is unavailable.";
"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test.";

/* Optional joint topology/rate exchange. */
"Try joint topology/rate exchange" = "Try joint topology/rate exchange";
"Joint topology/rate exchange is currently available only without fossil dating." = "Joint topology/rate exchange is currently available only without fossil dating.";
"Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established." = "Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established.";
Original file line number Diff line number Diff line change
Expand Up @@ -1154,3 +1154,8 @@
"%@ valid pairs · %@ undefined" = "%@ pares válidos · %@ indefinidos";
"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Os detalhes das réplicas estão ausentes ou não correspondem ao registro da verificação. A distribuição está indisponível.";
"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Cada diferença usa a matriz simulada e a observada na mesma árvore posterior. A estatística observada pode variar conforme a árvore. Zero indica igualdade; este é um gráfico de discrepâncias, não um teste de convergência.";

/* Optional joint topology/rate exchange. */
"Try joint topology/rate exchange" = "Experimentar troca conjunta de topologia e taxas";
"Joint topology/rate exchange is currently available only without fossil dating." = "A troca conjunta de topologia e taxas está disponível, por enquanto, apenas sem datação de fósseis.";
"Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established." = "Experimental, desativada por padrão. Troca subárvores vizinhas e compensa suas taxas de ramo. Exige relógio relaxado sem datação. O peso inicial é 10 e pode ser editado acima; ainda não foi demonstrado ganho de desempenho.";
73 changes: 66 additions & 7 deletions apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ struct AdvancedOptionsTests {
let matrix = URL(fileURLWithPath: "/tmp/m.nex")
let output = URL(fileURLWithPath: "/tmp/out")
let plain = try settings.arguments(matrix: matrix, output: output)
for flag in ["--sample-from-prior", "--no-tuning", "--weight", "--tuning", "--min-ess", "--checkpoint-every"] {
for flag in [
"--sample-from-prior", "--no-tuning", "--weight", "--tuning", "--min-ess",
"--checkpoint-every",
] {
#expect(!plain.contains(flag))
}
#expect(!settings.usesAdvancedOptions)
Expand All @@ -39,7 +42,9 @@ struct AdvancedOptionsTests {
"--chains", "2", "--stop-when-converged", "--min-ess", "300.0", "--max-rhat", "1.02",
"--check-every", "5000", "--checkpoint-every", "20000", "--sample-from-prior",
]
let schedule = ["--no-tuning", "--weight", "gamma_shape_scale=3.0", "--tuning", "subtree_slide=0.00076"]
let schedule = [
"--no-tuning", "--weight", "gamma_shape_scale=3.0", "--tuning", "subtree_slide=0.00076",
]
#expect(arguments.indices.contains { arguments[$0...].starts(with: sampling) })
#expect(arguments.suffix(schedule.count).elementsEqual(schedule))
#expect(try settings.modelArguments().suffix(schedule.count).elementsEqual(schedule))
Expand All @@ -63,7 +68,9 @@ struct AdvancedOptionsTests {
#expect(settings.validationError != nil)
settings.weights = [MoveOverride(move: "node_height", value: -1)]
#expect(settings.validationError != nil)
settings.weights = [MoveOverride(move: "node_height", value: 2), MoveOverride(move: "node_height", value: 3)]
settings.weights = [
MoveOverride(move: "node_height", value: 2), MoveOverride(move: "node_height", value: 3),
]
#expect(settings.validationError != nil)
settings.weights = ProposalSchedule.presets[1].weights
#expect(settings.validationError == nil)
Expand All @@ -82,7 +89,7 @@ struct AdvancedOptionsTests {
#expect(settings.validationError != nil)
settings.checkpointEvery = 3_000
#expect(settings.validationError == nil)
#expect(ProposalSchedule.moves.count == 22 && Set(ProposalSchedule.moves).count == 22)
#expect(ProposalSchedule.moves.count == 23 && Set(ProposalSchedule.moves).count == 23)
#expect(ProposalSchedule.tunable.isSubset(of: ProposalSchedule.moves))
}

Expand All @@ -96,6 +103,7 @@ struct AdvancedOptionsTests {
dating: dating)
}
#expect(issue("birth_difference_scale") != nil && issue("relative_death_scale") != nil)
#expect(issue("narrow_exchange_rates") != nil)
#expect(issue("clock_rate_scale") != nil)
#expect(issue("tip_age") == nil)
dating.clock = .estimated
Expand All @@ -109,6 +117,48 @@ struct AdvancedOptionsTests {
#expect(issue("birth_difference_scale") == nil && issue("fbd_birth_scale") != nil)
}

@Test @MainActor func jointExchangePersistsRunsAndResumesFromHistory() async throws {
let parent = FileManager.default.temporaryDirectory.appendingPathComponent(
"rove-joint-exchange-\(UUID())")
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: parent) }
let matrix = root.appendingPathComponent("fixtures/reference/20x50/matrix.nex")
let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine)
var settings = AnalysisSettings()
settings.steps = 2_000
settings.sampleEvery = 10
settings.weights = [MoveOverride(move: "narrow_exchange_rates", value: 10)]
#expect(settings.validationError == nil)
#expect(try settings.modelArguments().contains("narrow_exchange_rates=10.0"))
settings.clock = "strict"
#expect(settings.validationError != nil)
settings.clock = "reference"
let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings, outgroup: "T20")
#expect(draft.formatVersion == 9)
let file = parent.appendingPathComponent("setup.rove.json")
try draft.write(to: file)
#expect(try AnalysisDraft.read(file).settings == settings)
let directory = parent.appendingPathComponent("run")
let request = RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft)
let worker = RunProcess()
let paused = await worker.execute(request) { event in
if event.event == "started" { worker.pause() }
}
#expect(paused.status == .paused)
#expect(HistoryEntry.read(directory).checkpoint != nil)
let resumed = RunRequest(
id: UUID(), executable: engine, directory: directory, draft: draft, resume: true)
#expect(await RunProcess().execute(resumed) { _ in }.status == .completed)
let record = try EngineRecord.verify(directory: directory, draft: draft)
#expect(record.moves?.first(where: { $0.name == "narrow_exchange_rates" })?.weight == 10)
#expect(HistoryEntry.read(directory).draft?.settings.weights == settings.weights)
var json = try #require(
JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any])
json["formatVersion"] = 8
try JSONSerialization.data(withJSONObject: json).write(to: file)
#expect(throws: (any Error).self) { try AnalysisDraft.read(file) }
}

@Test @MainActor func groupRunsVerifyWithScheduleOverrides() async throws {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
"rove-advanced-group-\(UUID())")
Expand All @@ -135,7 +185,10 @@ struct AdvancedOptionsTests {
#expect(chain.moves?.first { $0.name == "gamma_shape_scale" }?.weight == 3)
var changed = settings
changed.tuningValues = [MoveOverride(move: "tree_scale", value: 0.5)]
#expect(!chain.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed), seed: chain.settings.seed))
#expect(
!chain.matches(
AnalysisDraft(matrix: matrix, report: report, settings: changed), seed: chain.settings.seed)
)
#expect(HistoryEntry.read(directory).status == .completed)
}

Expand Down Expand Up @@ -198,10 +251,16 @@ struct AdvancedOptionsTests {
#expect(record.moves?.first { $0.name == "tree_scale" }?.initialTuning == 0.24)
var changed = settings
changed.weights = [MoveOverride(move: "gamma_shape_scale", value: 0.1)]
#expect(!record.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly)))
#expect(
!record.matches(
AnalysisDraft(
matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly)))
changed = settings
changed.sampleFromPrior = false
#expect(!record.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly)))
#expect(
!record.matches(
AnalysisDraft(
matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly)))
#expect(entry.draft?.settings.advancedRows(strings: AppStrings(language: .english)).count == 5)

let summary = TreeSummaryModel(directory: directory, executable: engine)
Expand Down
17 changes: 17 additions & 0 deletions docs/es/guide/reference-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,20 @@ de modelos conservan el prior; comparar cadenas exige priors iguales.
Registros antiguos usan 5 y 0,2. Las configuraciones personalizadas del app usan
formato 6 para que versiones antiguas no ignoren la elección. Véase
[Priors de árbol](./tree-priors) para la decisión sobre modelos de árbol.

## Intercambio conjunto opcional de topología y tasas

`--weight narrow_exchange_rates=10` activa una propuesta experimental junto con las existentes. Su peso predeterminado es cero y no tiene parámetro de ajuste. En el app, use **Advanced sampling → Try joint topology/rate exchange**; el peso inicial 10 es editable. La selección se conserva en el formato 9 de configuración, revisión, historial, registros y checkpoints. Por ahora requiere reloj relajado sin datación; se rechazan reloj estricto y datación antes del muestreo. Es una propuesta independiente, no todo BEAST ORC. No se ha demostrado una mejora de velocidad o mezcla para morfología; las mediciones comparativas de [#97](https://github.com/getcortexlabs/rove/issues/97) siguen aplazadas.

Sea `G` un nodo interno con hijo interno. Elija `G` uniformemente entre los `C(T)` nodos elegibles, tome su hijo más antiguo `P` y el más reciente `U`, y elija un hijo `X` de `P` con probabilidad 1/2. Intercambie `X` y `U` sin cambiar alturas ni raíz, preservando las distancias de entrada:

```text
rX' = rX (hP − hX) / (hG − hX)
rU' = rU (hG − hU) / (hP − hU)
J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)]
log Hastings = log C(T) − log C(T') + log J
```

Se exigen duraciones y tasas positivas y finitas, y `hP > hU`. Los límites inválidos y desbordamientos se rechazan antes de modificar el estado. La inversa elige los mismos `G` y `P` y devuelve `U` intercambiándolo con `X`; su probabilidad es `1 / (2 C(T'))` frente a `1 / (2 C(T))`. Como las alturas no cambian, el jacobiano continuo es el producto de ambos factores de escala. Las tasas siguen indexadas por los nodos de entrada, incluso cuando la raíz no es el último nodo. Restricciones y rechazos usan la restauración exacta habitual. Preservar estas distancias no preserva la verosimilitud: cambia la topología.

Las pruebas cubren inversión, jacobiano numérico completo, selección directa/inversa enumerada, distribuciones conocidas de topologías uniformes y tasas lognormales independientes, restricciones, verosimilitud recalculada frente a caché, índices de raíz, checkpoints exactos, cancelación/reanudación nativa y muestras idénticas en portable/ARM. No sustituyen estudios de posterior y rendimiento. Véase [Douglas, Zhang y Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322).
17 changes: 17 additions & 0 deletions docs/guide/reference-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,20 @@ preserve the chosen prior; chain comparisons require matching priors.
`scale`, alongside the readable description. Legacy records use 5 and 0.2.
Custom app setups use format 6 so older apps cannot silently ignore the choice.
See [Tree priors](./tree-priors) for the separate decision about tree models.

## Optional joint topology/rate exchange

`--weight narrow_exchange_rates=10` enables an experimental proposal alongside the existing moves. It has zero weight by default and no tuning parameter. In the native app, use **Advanced sampling → Try joint topology/rate exchange**; its initial weight is 10 and remains editable. The choice is preserved in setup format 9, review, history, run records and checkpoints. Only an undated relaxed clock is currently supported; dated and strict-clock use is rejected before sampling. This is one independently implemented proposal, not the full BEAST ORC suite. No morphology speed or mixing benefit has been established; comparative measurements in [#97](https://github.com/getcortexlabs/rove/issues/97) remain deferred.

Let `G` be an internal node with an internal child. Choose `G` uniformly from the `C(T)` such nodes, take its older child `P` and younger child `U`, and choose either child `X` of `P` with probability 1/2. Exchange `X` and `U`, keeping heights and the root unchanged. Preserve the incoming distance of each reattached subtree with:

```text
rX' = rX (hP − hX) / (hG − hX)
rU' = rU (hG − hU) / (hP − hU)
J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)]
log Hastings = log C(T) − log C(T') + log J
```

Positive finite durations/rates and `hP > hU` are required. Boundary/overflow proposals fail before mutation. The reverse chooses the same `G` and `P` and exchanges `U` back with `X`; its probability is `1 / (2 C(T'))`, compared with `1 / (2 C(T))` forward. The continuous map leaves heights unchanged, so the Jacobian is the product of the two rate scale factors. Rates remain attached to node-indexed incoming branches, including the special slot when the root is not the last node. Constraints and likelihood/prior rejection use the normal exact restoration path. Preserving the reattached distances does not preserve the likelihood: the topology changes.

Tests cover the inverse, full numerical Jacobian, enumerated forward/reverse choices, known uniform-topology/independent-lognormal targets, constraint rejection, fresh versus cached likelihood, different root indices, exact checkpoint replay, native cancellation/resumption and identical portable/ARM samples. These correctness checks do not replace posterior and performance studies. Related joint-proposal methods are described by [Douglas, Zhang and Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322).
Loading
Loading