diff --git a/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift b/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift index 16ca507..8b3cc88 100644 --- a/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift +++ b/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift @@ -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( diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index 5e22cec..598b650 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -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 = [ "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 = [ "tip_age", "clock_rate_scale", "fbd_birth_scale", "fbd_death_scale", "fbd_sampling_scale", @@ -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." } @@ -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"] @@ -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 @@ -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, diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index 012f01a..4e0f96d 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -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."; diff --git a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings index 033c33a..ec11eb7 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -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."; diff --git a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift index 336762d..791ecc2 100644 --- a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift +++ b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift @@ -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) @@ -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)) @@ -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) @@ -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)) } @@ -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 @@ -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())") @@ -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) } @@ -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) diff --git a/docs/es/guide/reference-model.md b/docs/es/guide/reference-model.md index 02ef62a..72d836b 100644 --- a/docs/es/guide/reference-model.md +++ b/docs/es/guide/reference-model.md @@ -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). diff --git a/docs/guide/reference-model.md b/docs/guide/reference-model.md index d88c130..f2553b3 100644 --- a/docs/guide/reference-model.md +++ b/docs/guide/reference-model.md @@ -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). diff --git a/docs/pt-BR/guide/reference-model.md b/docs/pt-BR/guide/reference-model.md index 46d1652..b8d37c3 100644 --- a/docs/pt-BR/guide/reference-model.md +++ b/docs/pt-BR/guide/reference-model.md @@ -180,3 +180,20 @@ preservam o prior; comparar cadeias exige priors iguais. `run.json` registra Registros antigos usam 5 e 0,2. Configurações personalizadas do app usam formato 6 para impedir que apps antigos ignorem a escolha. Veja [Priors de árvore](./tree-priors) para a decisão separada sobre modelos de árvore. + +## Troca conjunta opcional de topologia e taxas + +`--weight narrow_exchange_rates=10` ativa uma proposta experimental junto às existentes. Seu peso padrão é zero e não há parâmetro de ajuste do passo. No app, use **Amostragem avançada → Experimentar troca conjunta de topologia e taxas**; o peso inicial é 10 e permanece editável. A escolha fica no formato 9 de configuração, revisão, histórico, registros e checkpoints. Por enquanto, exige relógio relaxado sem datação; relógio estrito e datação são recusados antes da amostragem. É uma proposta implementada independentemente, não o conjunto completo do BEAST ORC. Nenhum ganho de velocidade ou mistura para morfologia foi demonstrado; as medições comparativas da [#97](https://github.com/getcortexlabs/rove/issues/97) continuam adiadas. + +Seja `G` um nó interno com filho interno. Escolha `G` uniformemente entre os `C(T)` nós assim definidos, tome seu filho mais antigo `P` e o mais recente `U`, e escolha um dos filhos `X` de `P` com probabilidade 1/2. Troque `X` e `U`, mantendo alturas e raiz. Preserve a distância de entrada de cada subárvore realocada: + +```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 +``` + +Durações e taxas devem ser positivas e finitas, com `hP > hU`. Limites inválidos ou overflow são rejeitados antes da alteração. O reverso escolhe os mesmos `G` e `P` e troca `U` de volta com `X`; sua probabilidade é `1 / (2 C(T'))`, contra `1 / (2 C(T))` na ida. A transformação contínua preserva alturas, portanto o jacobiano é o produto dos dois fatores de escala das taxas. As taxas continuam associadas aos ramos de entrada indexados por nó, incluindo o índice especial quando a raiz não é o último nó. Restrições e rejeições pela verossimilhança/prior usam a restauração exata normal. Preservar as distâncias dos ramos realocados não preserva a verossimilhança, pois a topologia muda. + +Os testes cobrem inversão, jacobiano numérico completo, escolhas de ida/volta enumeradas, alvos conhecidos de topologias uniformes e taxas lognormais independentes, rejeição por restrições, verossimilhança recalculada versus cache, diferentes índices de raiz, checkpoints exatos, cancelamento/retomada no app e amostras idênticas nos backends portátil/ARM. Esses testes de correção não substituem estudos de posterior e desempenho. Métodos relacionados são descritos por [Douglas, Zhang e Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322). diff --git a/docs/zh-CN/guide/reference-model.md b/docs/zh-CN/guide/reference-model.md index e72c1e3..01e14ee 100644 --- a/docs/zh-CN/guide/reference-model.md +++ b/docs/zh-CN/guide/reference-model.md @@ -137,3 +137,20 @@ CLI 在 `--model reference` 下接受 `--clock-sigma-shape 2.5 --clock-sigma-sca `run.json` 中的 `clock_sigma_prior_parameters` 记录数值 `shape` 和 `scale`,并保留文字说明。 旧记录按 5 和 0.2 解释。自定义应用设置使用格式 6,防止旧应用忽略设置。 树模型的独立决策见[树先验](./tree-priors)。 + +## 可选的拓扑与速率联合交换 + +`--weight narrow_exchange_rates=10` 在现有提议之外启用一项实验性提议。默认权重为零,没有步长调节参数。原生应用中使用 **Advanced sampling → Try joint topology/rate exchange**,初始权重为 10,可继续编辑。选项保存在格式 9 的配置、审查、历史、运行记录和检查点中。目前仅支持无定年的松弛钟;严格钟和定年分析会在采样前被拒绝。这是独立实现的一项提议,并非完整 BEAST ORC 套件。尚未证明形态数据上的速度或混合收益;[#97](https://github.com/getcortexlabs/rove/issues/97) 的比较测量仍然推迟。 + +设 `G` 为具有内部子节点的内部节点。从这样的 `C(T)` 个节点中均匀选择 `G`,取其较老子节点 `P` 和较年轻子节点 `U`,再以 1/2 概率选择 `P` 的一个子节点 `X`。交换 `X` 和 `U`,保持高度及根不变,并保持两个重接子树的入枝距离: + +```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 +``` + +持续时间和速率必须为正且有限,并满足 `hP > hU`。无效边界或溢出在修改前拒绝。逆映射选择相同的 `G`、`P`,将 `U` 与 `X` 换回;逆向概率为 `1 / (2 C(T'))`,正向为 `1 / (2 C(T))`。连续映射不改变高度,因此雅可比是两个速率缩放因子的乘积。速率仍对应节点索引的入枝,包括根不是最后节点时的特殊槽位。约束与似然/先验拒绝沿用精确恢复路径。保留重接枝距离并不保留似然,因为拓扑改变了。 + +测试覆盖逆映射、完整数值雅可比、枚举的正反选择、已知均匀拓扑与独立对数正态速率目标、约束拒绝、重新计算与缓存似然、不同根索引、精确检查点回放、原生取消/恢复,以及 portable/ARM 后端样本一致性。这些正确性测试不能替代后验及性能研究。相关方法见 [Douglas、Zhang 与 Bouckaert(2021)](https://doi.org/10.1371/journal.pcbi.1008322)。 diff --git a/src/mcmc/checkpoint.rs b/src/mcmc/checkpoint.rs index 6584c7b..a5bd0a4 100644 --- a/src/mcmc/checkpoint.rs +++ b/src/mcmc/checkpoint.rs @@ -303,6 +303,7 @@ mod tests { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 10.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); } let mut chain = Sampler::new(&patterns, &settings, 42).unwrap(); diff --git a/src/mcmc/coupled.rs b/src/mcmc/coupled.rs index 08c53e4..8b0dc84 100644 --- a/src/mcmc/coupled.rs +++ b/src/mcmc/coupled.rs @@ -4,6 +4,58 @@ use crate::rates::RelaxedClock; use crate::tree::Tree; +/// Exchange a child of `parent` with its uncle, preserving each reattached +/// subtree's incoming rate × duration. Heights and the root stay fixed. +/// The involution scales two rates by old/new durations; its Jacobian is +/// their product. The caller adds the forward/reverse node-selection ratio. +pub(super) fn exchange_rates( + tree: &mut Tree, + clock: &mut RelaxedClock, + parent: usize, + child: usize, + uncle: usize, +) -> Option { + let grandparent = tree.parent(parent)?; + if tree.parent(child) != Some(parent) + || tree.parent(uncle) != Some(grandparent) + || uncle == parent + || tree.height(uncle) >= tree.height(parent) + || tree.height(child) >= tree.height(parent) + { + return None; + } + let branches = [child, uncle]; + let durations = [ + tree.height(grandparent) - tree.height(child), + tree.height(parent) - tree.height(uncle), + ]; + let mut proposed = [0.0; 2]; + let mut jacobian = 0.0; + for i in 0..2 { + let old = tree.branch_length(branches[i]); + if old <= 0.0 || durations[i] <= 0.0 { + return None; + } + let log_ratio = old.ln() - durations[i].ln(); + proposed[i] = (clock.branch_rate(branches[i], tree.root()).ln() + log_ratio).exp(); + if !proposed[i].is_finite() || proposed[i] <= 0.0 { + return None; + } + jacobian += log_ratio; + } + tree.replace_child(parent, child, uncle); + tree.replace_child(grandparent, uncle, child); + for i in 0..2 { + let index = if branches[i] == tree.nodes() - 1 { + tree.root() + } else { + branches[i] + }; + clock.set_rate(index, proposed[i]); + } + Some(jacobian) +} + /// Change one internal height, preserving rate × duration on incident branches. /// For a symmetric height draw, the Hastings factor is the product of old/new /// branch durations. The root has two incident branches; other nodes have three. @@ -209,6 +261,174 @@ mod tests { determinant(matrix) } + #[test] + fn exchange_is_an_involution_with_correct_rate_slots_and_jacobian() { + for root_last in [false, true] { + let (original, parent, child, uncle) = if root_last { + ( + Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((3, 4)), + Some((0, 1)), + Some((6, 2)), + Some((7, 5)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.6, 1.0, 1.5], + ) + .unwrap(), + 7, + 6, + 5, + ) + } else { + ( + Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((6, 8)), + Some((7, 2)), + Some((0, 1)), + Some((3, 4)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.5, 1.0, 0.6, 0.2], + ) + .unwrap(), + 6, + 7, + 8, + ) + }; + let original_clock = + RelaxedClock::new(0.7, vec![0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]).unwrap(); + let mut tree = original.clone(); + let mut clock = original_clock.clone(); + let h = exchange_rates(&mut tree, &mut clock, parent, child, uncle).unwrap(); + tree.validate().unwrap(); + assert_eq!(tree.root(), original.root()); + for node in 0..tree.nodes() { + near( + tree.branch_length(node) * clock.branch_rate(node, tree.root()), + original.branch_length(node) + * original_clock.branch_rate(node, original.root()), + 1e-13, + ); + } + // Continuous coordinates include all internal heights and all + // rates. Height derivatives enter off-diagonal blocks only. + let mut x = (tree.tips()..tree.nodes()) + .map(|i| original.height(i)) + .collect::>(); + x.extend(original_clock.rates()); + let numerical = numerical_jacobian(&x, |values| { + let mut t = original.clone(); + for i in t.tips()..t.nodes() { + t.set_height(i, values[i - t.tips()]); + } + let mut c = RelaxedClock::new(0.7, values[4..].to_vec()).unwrap(); + exchange_rates(&mut t, &mut c, parent, child, uncle).unwrap(); + let mut y = values[..4].to_vec(); + y.extend(c.rates()); + y + }); + near(h.exp(), numerical, 1e-7); + near( + h + exchange_rates(&mut tree, &mut clock, parent, uncle, child).unwrap(), + 0.0, + 1e-13, + ); + assert_eq!(tree, original); + for (a, b) in clock.rates().iter().zip(original_clock.rates()) { + near(*a, *b, 1e-13); + } + // Invalid ancestry and singular support leave every coordinate intact. + let saved = clock.clone(); + assert!(exchange_rates(&mut tree, &mut clock, parent, uncle, child).is_none()); + assert_eq!(tree, original); + assert_eq!(clock, saved); + } + } + + #[test] + fn joint_exchange_preserves_uniform_topologies_and_independent_lognormal_rates() { + let mut random = Random::new(97001); + let mut t = tree(true); + let mut clock = RelaxedClock::new(0.7, vec![1.0; 4]).unwrap(); + let mut counts = [0usize; 3]; + let mut log_sums = [0.0; 3]; + let mut squares = 0.0; + let mut n = 0usize; + let mut birth = crate::speciation::BirthDeath { + birth_difference: 1.0, + relative_death: 0.5, + }; + for step in 0..250_000 { + if random.uniform() < 0.15 { + // Exact independent conditional draws for a known target. + t.set_height(3, 0.05 + 0.9 * random.uniform()); + for i in 0..4 { + clock.set_rate(i, (0.7 * random.normal() - 0.245).exp()); + } + } else { + let mut proposal = t.clone(); + let mut rates = crate::rates::RateVariation { + clock: Some(clock.clone()), + ..Default::default() + }; + let h = super::super::Move::NarrowExchangeRates + .propose( + &mut proposal, + &mut birth, + &mut rates, + 1000.0, + None, + &mut random, + ) + .unwrap(); + let c = rates.clock.unwrap(); + let alpha = c.log_rate_prior() - clock.log_rate_prior() + h; + if alpha >= 0.0 || random.uniform() < alpha.exp() { + t = proposal; + clock = c; + } + } + if step >= 10_000 { + let (a, b) = t.children(t.root()).unwrap(); + let outside = if a < 3 { a } else { b }; + counts[outside] += 1; + for rate in clock.rates() { + log_sums[outside] += rate.ln() / 4.0; + squares += (rate.ln() + 0.245).powi(2) / 4.0; + } + n += 1; + } + } + for i in 0..3 { + near(counts[i] as f64 / n as f64, 1.0 / 3.0, 0.015); + near(log_sums[i] / counts[i] as f64, -0.245, 0.025); + } + near(squares / n as f64, 0.49, 0.025); + } + + #[test] + fn exchange_overflow_is_rejected_before_mutating_rates_or_topology() { + let mut t = tree(true); + let mut c = RelaxedClock::new(0.7, vec![0.8, 1.3, 1e308, 0.4]).unwrap(); + let old_t = t.clone(); + let old_c = c.clone(); + assert!(exchange_rates(&mut t, &mut c, 3, 0, 2).is_none()); + assert_eq!(t, old_t); + assert_eq!(c, old_c); + } + #[test] fn augmented_jacobians_match_finite_differences() { // These maps include the reverse auxiliary variable. Differentiating diff --git a/src/mcmc/mod.rs b/src/mcmc/mod.rs index 6dee067..435245c 100644 --- a/src/mcmc/mod.rs +++ b/src/mcmc/mod.rs @@ -596,6 +596,9 @@ impl Sampler { return Err(Error::Rates(rates::Error::BranchRates)); } for &(kind, weight) in &settings.weights { + if weight > 0.0 && kind == Move::NarrowExchangeRates && settings.dating.is_some() { + return Err(Error::Dating("narrow_exchange_rates is experimental and currently restricted to undated trees".into())); + } if weight > 0.0 && kind.changes_fbd() && settings @@ -633,6 +636,7 @@ impl Sampler { | Move::NodeTimeRates | Move::RootTimeRates | Move::ClockSigmaRates + | Move::NarrowExchangeRates ) && rates.clock.is_none())) { return Err(Error::RateMove(kind)); diff --git a/src/mcmc/moves.rs b/src/mcmc/moves.rs index 9abd43e..5de93f1 100644 --- a/src/mcmc/moves.rs +++ b/src/mcmc/moves.rs @@ -46,10 +46,12 @@ pub enum Move { RootTimeRates, /// Scale clock sigma while preserving standardized log branch rates. ClockSigmaRates, + /// Narrow exchange with compensation of the two reattached branch rates. + NarrowExchangeRates, } impl Move { - pub const ALL: [Move; 22] = [ + pub const ALL: [Move; 23] = [ Move::FbdBirthScale, Move::FbdDeathScale, Move::FbdSamplingScale, @@ -72,6 +74,7 @@ impl Move { Move::NodeTimeRates, Move::RootTimeRates, Move::ClockSigmaRates, + Move::NarrowExchangeRates, ]; pub fn name(self) -> &'static str { @@ -98,6 +101,7 @@ impl Move { Self::NodeTimeRates => "node_time_rates", Self::RootTimeRates => "root_time_rates", Self::ClockSigmaRates => "clock_sigma_rates", + Self::NarrowExchangeRates => "narrow_exchange_rates", } } @@ -148,6 +152,7 @@ impl Move { | Self::TreeScale | Self::NodeTimeRates | Self::RootTimeRates + | Self::NarrowExchangeRates ) } @@ -165,7 +170,11 @@ impl Move { pub fn changes_topology(self) -> bool { matches!( self, - Self::SubtreeSlide | Self::NarrowExchange | Self::WideExchange | Self::WilsonBalding + Self::SubtreeSlide + | Self::NarrowExchange + | Self::WideExchange + | Self::WilsonBalding + | Self::NarrowExchangeRates ) } @@ -198,6 +207,9 @@ impl Move { Self::NodeHeight => node_height(tree, random), Self::SubtreeSlide => subtree_slide(tree, tuning, random), Self::NarrowExchange => narrow_exchange(tree, random), + Self::NarrowExchangeRates => { + narrow_exchange_with_rates(tree, Some(rates.clock.as_mut()?), random) + } Self::WideExchange => wide_exchange(tree, random), Self::WilsonBalding => wilson_balding(tree, random), Self::RootScale => root_scale(tree, tuning, random), @@ -418,6 +430,14 @@ fn subtree_slide(tree: &mut Tree, size: f64, random: &mut Random) -> Option } fn narrow_exchange(tree: &mut Tree, random: &mut Random) -> Option { + narrow_exchange_with_rates(tree, None, random) +} + +fn narrow_exchange_with_rates( + tree: &mut Tree, + clock: Option<&mut crate::rates::RelaxedClock>, + random: &mut Random, +) -> Option { let internal = tree.nodes() - tree.tips(); if internal <= 1 { return None; @@ -446,9 +466,14 @@ fn narrow_exchange(tree: &mut Tree, random: &mut Random) -> Option { let (a, b) = tree.children(parent)?; let before = count(tree); let child = if random.coin() { a } else { b }; - tree.replace_child(parent, child, uncle); - tree.replace_child(grandparent, uncle, child); - Some((before as f64 / count(tree) as f64).ln()) + let jacobian = if let Some(clock) = clock { + coupled::exchange_rates(tree, clock, parent, child, uncle)? + } else { + tree.replace_child(parent, child, uncle); + tree.replace_child(grandparent, uncle, child); + 0.0 + }; + Some((before as f64 / count(tree) as f64).ln() + jacobian) } fn wide_exchange(tree: &mut Tree, random: &mut Random) -> Option { @@ -639,6 +664,51 @@ mod tests { (observed + unobserved) / 2.0 } + #[test] + fn joint_exchange_selection_ratio_matches_enumerated_reverse_choices() { + let mut tree = Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((0, 1)), + Some((5, 2)), + Some((6, 3)), + Some((7, 4)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8], + ) + .unwrap(); + let choices = |tree: &Tree| { + (tree.tips()..tree.nodes()) + .filter(|&parent| { + tree.parent(parent).is_some() + && tree.height(parent) > tree.height(tree.sibling(parent)) + }) + .count() + * 2 + }; + let mut random = Random::new(97002); + let mut changed_selection = false; + for _ in 0..2000 { + let before = tree.clone(); + let mut clock = crate::rates::RelaxedClock::new(0.7, vec![1.0; 8]).unwrap(); + let h = super::narrow_exchange_with_rates(&mut tree, Some(&mut clock), &mut random) + .unwrap(); + let ratio = (choices(&before) as f64 / choices(&tree) as f64).ln(); + changed_selection |= ratio != 0.0; + let jacobian = (0..tree.nodes()) + .filter(|&i| i != tree.root()) + .map(|i| before.branch_length(i).ln() - tree.branch_length(i).ln()) + .sum::(); + assert!((h - ratio - jacobian).abs() < 1e-13); + tree.validate().unwrap(); + } + assert!(changed_selection); + } + /// The subtree slide mixes slowest; dropping either of its counts raises /// its distance to about 0.026 at 6.4 million steps, against 0.009. #[test] diff --git a/tests/dating.rs b/tests/dating.rs index bb30192..c537000 100644 --- a/tests/dating.rs +++ b/tests/dating.rs @@ -42,6 +42,20 @@ fn settings(dating: Dating, prior: bool) -> Settings { s } +#[test] +fn experimental_joint_exchange_is_not_enabled_for_dated_runs() { + let mut s = Settings::reference(); + s.set_dating(model(&[(0.0, 0.0), (0.2, 0.4), (0.0, 0.0)])); + s.weights.push((Move::NarrowExchangeRates, 10.0)); + assert!( + Sampler::new(patterns(3), &s, 97) + .err() + .unwrap() + .to_string() + .contains("restricted to undated") + ); +} + #[test] fn fixed_densities_match_beast_sa() { for row in include_str!("../fixtures/validation/dating/beast-sa-2.1.1.tsv") diff --git a/tests/rates.rs b/tests/rates.rs index fcd78a3..00348f4 100644 --- a/tests/rates.rs +++ b/tests/rates.rs @@ -121,6 +121,11 @@ fn invalid_rate_states_are_rejected() { ..Settings::default() }; assert!(Sampler::new(small(), &settings, 1).is_err()); + let settings = Settings { + weights: vec![(Move::NarrowExchangeRates, 1.0)], + ..Settings::default() + }; + assert!(Sampler::new(small(), &settings, 1).is_err()); } #[test] @@ -203,6 +208,7 @@ fn rate_moves_and_root_changes_restore_all_cached_values() { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 5.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); let mut chain = Sampler::new(&patterns, &settings, 29).unwrap(); let mut root_changes = 0; @@ -242,6 +248,7 @@ fn rate_moves_and_root_changes_restore_all_cached_values() { Move::NodeTimeRates, Move::RootTimeRates, Move::ClockSigmaRates, + Move::NarrowExchangeRates, ] { let operator = chain.operators().iter().find(|o| o.kind == kind).unwrap(); assert!( @@ -267,6 +274,7 @@ fn relaxed_clock_backends_give_identical_samples() { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 5.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); Sampler::new(&data, &settings, 21).unwrap() }) diff --git a/tools/native/cli-parity.json b/tools/native/cli-parity.json index 246e029..724f471 100644 --- a/tools/native/cli-parity.json +++ b/tools/native/cli-parity.json @@ -159,7 +159,7 @@ }, "--weight": { "native": "apps/macos/Sources/RoveApp/AdvancedOptionsView.swift", - "control": "Advanced sampling" + "control": "Advanced sampling, including opt-in undated joint topology/rate exchange" }, "--include-matrix": { "native": "apps/macos/Sources/RoveApp/RunAssessmentView.swift",