diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index 598b650..3fd6cf3 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -143,7 +143,7 @@ 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", + "narrow_exchange_rates", "birth_rate_scale", ] static let relaxedClockMoves: Set = [ "gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "node_time_rates", @@ -153,11 +153,13 @@ enum ProposalSchedule { "tip_age", "clock_rate_scale", "fbd_birth_scale", "fbd_death_scale", "fbd_sampling_scale", "fbd_rho_logit", "fbd_origin_scale", ] - static let undatedMoves: Set = ["birth_difference_scale", "relative_death_scale"] + static let undatedMoves: Set = [ + "birth_difference_scale", "relative_death_scale", "birth_rate_scale", + ] /// Moves with a tunable step: a slide size for `subtree_slide`, otherwise a /// scale factor strictly between zero and one. static let tunable: Set = [ - "subtree_slide", "root_scale", "tree_scale", "birth_difference_scale", + "subtree_slide", "root_scale", "tree_scale", "birth_difference_scale", "birth_rate_scale", "relative_death_scale", "gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "root_time_rates", "clock_sigma_rates", "clock_rate_scale", "fbd_birth_scale", "fbd_death_scale", "fbd_sampling_scale", "fbd_rho_logit", "fbd_origin_scale", @@ -179,7 +181,8 @@ enum ProposalSchedule { ] static func validate( - weights: [MoveOverride], tuningValues: [MoveOverride], clock: String, dating: DatingSettings + weights: [MoveOverride], tuningValues: [MoveOverride], clock: String, dating: DatingSettings, + treePrior: String = "birth-death" ) -> String? { for list in [weights, tuningValues] { guard Set(list.map(\.move)).count == list.count else { @@ -199,6 +202,14 @@ 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 treePrior == "yule", + !active.isDisjoint(with: ["birth_difference_scale", "relative_death_scale"]) + { + return "Birth-difference and relative-death moves require the birth-death prior." + } + if active.contains("birth_rate_scale"), treePrior != "yule" || dating.enabled { + return "The birth-rate move requires Yule without fossil dating." + } if dating.enabled, active.contains("narrow_exchange_rates") { return "Joint topology/rate exchange is currently available only without fossil dating." } @@ -235,6 +246,8 @@ enum ProposalSchedule { struct AnalysisSettings: Codable, Equatable, Sendable { var dating = DatingSettings() + var treePrior = "birth-death" + var birthRateUpper = "1000" var clock = "reference" var clockSigmaShape = "5" var clockSigmaScale = "0.2" @@ -272,7 +285,8 @@ struct AnalysisSettings: Codable, Equatable, Sendable { } private enum CodingKeys: String, CodingKey { - case dating, clock, clockSigmaShape, clockSigmaScale, conditioning, partitioning, steps, + case dating, treePrior, birthRateUpper, clock, clockSigmaShape, clockSigmaScale, conditioning, + partitioning, steps, sampleEvery, seed, gapsAsMissing, chains, comparisonBurnin, backend, printEvery, stopWhenConverged, sampleFromPrior, minESS, maxRhat, checkEvery, checkpointEvery, tuning, weights, tuningValues @@ -281,6 +295,8 @@ struct AnalysisSettings: Codable, Equatable, Sendable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) dating = try values.decodeIfPresent(DatingSettings.self, forKey: .dating) ?? DatingSettings() + treePrior = try values.decodeIfPresent(String.self, forKey: .treePrior) ?? "birth-death" + birthRateUpper = try values.decodeIfPresent(String.self, forKey: .birthRateUpper) ?? "1000" clock = try values.decode(String.self, forKey: .clock) clockSigmaShape = try values.decodeIfPresent(String.self, forKey: .clockSigmaShape) ?? "5" clockSigmaScale = try values.decodeIfPresent(String.self, forKey: .clockSigmaScale) ?? "0.2" @@ -344,13 +360,29 @@ struct AnalysisSettings: Codable, Equatable, Sendable { clock == "reference" && clockSigmaPrior != .reference } + var yuleBirthRateUpper: Double? { + guard let value = Double(birthRateUpper.replacingOccurrences(of: ",", with: ".")), + value.isFinite, value > 0, value / 2 > 0 + else { return nil } + return value + } + var validationError: String? { - guard ["strict", "reference"].contains(clock), + guard ["birth-death", "yule"].contains(treePrior), + ["strict", "reference"].contains(clock), ["variable", "informative", "none"].contains(conditioning), ["observed", "declared", "labels"].contains(partitioning) else { return "This setup uses an unsupported model." } + if treePrior == "yule" { + if dating.enabled { + return "Yule requires contemporaneous tips without fossil dating or calibrations." + } + if yuleBirthRateUpper == nil { + return "Use a positive, finite upper bound for the Yule birth-rate prior." + } + } if clock == "reference" && clockSigmaPrior == nil { return "Use positive, finite shape and scale values for the clock sigma prior." } @@ -380,7 +412,8 @@ struct AnalysisSettings: Codable, Equatable, Sendable { return "Check and checkpoint intervals must be positive multiples of the sampling interval." } if let issue = ProposalSchedule.validate( - weights: weights, tuningValues: tuningValues, clock: clock, dating: dating) + weights: weights, tuningValues: tuningValues, clock: clock, dating: dating, + treePrior: treePrior) { return issue } @@ -416,6 +449,12 @@ struct AnalysisSettings: Codable, Equatable, Sendable { "--model", clock, "--conditioning", conditioning, "--gaps", gapsAsMissing ? "missing" : "reject", "--partitioning", partitioning, ] + if treePrior == "yule" { + guard !dating.enabled, let upper = yuleBirthRateUpper else { + throw ImportError.message(validationError ?? "This setup uses an unsupported model.") + } + arguments += ["--tree-prior", "yule", "--birth-rate-upper", String(upper)] + } if backend != "automatic" { arguments += ["--backend", backend] } if clock == "reference" { guard let prior = clockSigmaPrior else { @@ -470,16 +509,18 @@ struct AnalysisDraft: Codable, Sendable { monophyly: [[String]] = [], outgroup: String? = nil ) { formatVersion = - 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))) + settings.treePrior == "yule" + ? 10 + : 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 @@ -503,7 +544,8 @@ struct AnalysisDraft: Codable, Sendable { } func validate() throws { - guard (1...9).contains(formatVersion), + guard (1...10).contains(formatVersion), + formatVersion >= 10 || settings.treePrior != "yule", formatVersion >= 9 || !settings.usesJointExchange, formatVersion >= 8 || settings.partitioning != "labels", formatVersion >= 7 || !settings.usesExecutionOptions, diff --git a/apps/macos/Sources/RoveApp/CommandLineImport.swift b/apps/macos/Sources/RoveApp/CommandLineImport.swift index 44ea719..7deebfe 100644 --- a/apps/macos/Sources/RoveApp/CommandLineImport.swift +++ b/apps/macos/Sources/RoveApp/CommandLineImport.swift @@ -70,6 +70,14 @@ enum CommandLineImport { ?? option("--conditioning") else { throw RunFailure.invalidCompletion } var value = AnalysisSettings() + value.treePrior = record.model.treePriorKind ?? "birth-death" + if value.treePrior == "yule" { + guard let prior = record.model.birthRatePriorParameters, prior.valid else { + throw RunFailure.invalidCompletion + } + value.birthRateUpper = String(prior.upper) + } + guard record.model.treePriorMatches(value) else { throw RunFailure.invalidCompletion } value.clock = record.model.preset let sigma = record.model.clockSigmaPriorParameters ?? .reference value.clockSigmaShape = String(sigma.shape) diff --git a/apps/macos/Sources/RoveApp/HistoryView.swift b/apps/macos/Sources/RoveApp/HistoryView.swift index 2fc13b1..fcfe4da 100644 --- a/apps/macos/Sources/RoveApp/HistoryView.swift +++ b/apps/macos/Sources/RoveApp/HistoryView.swift @@ -281,6 +281,7 @@ private struct HistoryDetail: View { if let prior = draft.settings.clockSigmaPrior { field("Clock sigma prior", prior.description(strings: strings)) } + field("Tree prior", draft.settings.treePriorDescription(strings: strings)) field( "Character model", strings( diff --git a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift index 8f63f38..1cecf22 100644 --- a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift +++ b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift @@ -108,7 +108,7 @@ struct SavedEstimate: Identifiable, Sendable { && record.model.conditioning == EngineRecord.Model.conditioningDescriptions[settings.conditioning] && (record.model.partitioning ?? "declared") == settings.partitioning - && record.model.dating == dating + && record.model.dating == dating && record.model.treePriorMatches(settings) && (settings.clock != "reference" || (record.model.clockSigmaPriorParameters ?? .reference) == settings.clockSigmaPrior) && (record.settings.tuning ?? true) == settings.tuning diff --git a/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift b/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift index a1d8666..976104a 100644 --- a/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift +++ b/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift @@ -128,6 +128,7 @@ struct MarginalLikelihoodView: View { private func comparison(_ own: SavedEstimate, against others: [SavedEstimate]) -> some View { VStack(alignment: .leading, spacing: 12) { Eyebrow(text: strings("Log Bayes factors")) + Text(describe(own, against: own)).font(.system(size: 11)).foregroundStyle(Lab.secondary) Text( strings( "Estimates saved with other completed runs of the same matrix, constraints and gap policy, against this run's newest estimate. A difference is this model's estimate minus the other's: positive favours this model. Its standard error combines both estimates in quadrature." @@ -183,6 +184,11 @@ struct MarginalLikelihoodView: View { let model = saved.record.model var text = strings(model.preset == "reference" ? "Relaxed clock" : "Strict clock") text += " · " + model.conditioningLabel + if model.treePriorKind == "yule", let prior = model.birthRatePriorParameters { + text += "\n" + strings("Yule · birth rate Uniform(0, %@)", String(prior.upper)) + } else { + text += " · " + strings(model.dating == nil ? "Birth-death" : "Fossilized birth-death") + } if model.preset == "reference" { text += "\n" + strings("Clock sigma prior") + ": " diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index 4e0f96d..c736c20 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -1159,3 +1159,18 @@ "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."; + +// Yule tree prior +"Fossilized birth-death" = "Fossilized birth-death"; +"Yule · pure birth" = "Yule · pure birth"; +"Birth-death" = "Birth-death"; +"Yule · birth rate Uniform(0, %@)" = "Yule · birth rate Uniform(0, %@)"; +"Yule models speciation without extinction for contemporaneous species tips, with complete sampling. It does not support fossil ages, calibrations or population coalescence." = "Yule models speciation without extinction for contemporaneous species tips, with complete sampling. It does not support fossil ages, calibrations or population coalescence."; +"Birth-death allows extinction as well as speciation. Fossil dating uses the fossilized birth-death model below." = "Birth-death allows extinction as well as speciation. Fossil dating uses the fossilized birth-death model below."; +"Birth-rate upper bound" = "Birth-rate upper bound"; +"The birth rate has a Uniform(0, upper bound) prior. Its units are inverse tree-height units on the fixed clock scale. Choose a defensible bound and inspect prior-only runs; 1000 is a starting value, not a general recommendation." = "The birth rate has a Uniform(0, upper bound) prior. Its units are inverse tree-height units on the fixed clock scale. Choose a defensible bound and inspect prior-only runs; 1000 is a starting value, not a general recommendation."; +"Yule requires contemporaneous tips without fossil dating or calibrations." = "Yule requires contemporaneous tips without fossil dating or calibrations."; +"Use a positive, finite upper bound for the Yule birth-rate prior." = "Use a positive, finite upper bound for the Yule birth-rate prior."; +"Birth-difference and relative-death moves require the birth-death prior." = "Birth-difference and relative-death moves require the birth-death prior."; +"The birth-rate move requires Yule without fossil dating." = "The birth-rate move requires Yule without fossil dating."; +"Speciation rate under Yule, per source tree-height unit." = "Speciation rate under Yule, per source tree-height unit."; 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 ec11eb7..96ef39f 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -1159,3 +1159,18 @@ "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."; + +// Yule tree prior +"Fossilized birth-death" = "Nascimento-morte fossilizado"; +"Yule · pure birth" = "Yule · nascimento puro"; +"Birth-death" = "Nascimento-morte"; +"Yule · birth rate Uniform(0, %@)" = "Yule · taxa de nascimento Uniforme(0, %@)"; +"Yule models speciation without extinction for contemporaneous species tips, with complete sampling. It does not support fossil ages, calibrations or population coalescence." = "Yule modela especiação sem extinção para espécies contemporâneas, com amostragem completa. Não aceita idades fósseis, calibrações ou coalescência populacional."; +"Birth-death allows extinction as well as speciation. Fossil dating uses the fossilized birth-death model below." = "Nascimento-morte permite extinção e especiação. A datação fóssil usa o modelo de nascimento-morte fossilizado abaixo."; +"Birth-rate upper bound" = "Limite superior da taxa de nascimento"; +"The birth rate has a Uniform(0, upper bound) prior. Its units are inverse tree-height units on the fixed clock scale. Choose a defensible bound and inspect prior-only runs; 1000 is a starting value, not a general recommendation." = "A taxa de nascimento tem prior Uniforme(0, limite superior), em unidades inversas à altura da árvore na escala fixa do relógio. Escolha um limite justificável e examine análises apenas dos priors; 1000 é um valor inicial, não uma recomendação geral."; +"Yule requires contemporaneous tips without fossil dating or calibrations." = "Yule exige terminais contemporâneos, sem datação fóssil ou calibrações."; +"Use a positive, finite upper bound for the Yule birth-rate prior." = "Use um limite superior positivo e finito para o prior da taxa de nascimento de Yule."; +"Birth-difference and relative-death moves require the birth-death prior." = "Movimentos de diversificação líquida e morte relativa exigem o prior de nascimento-morte."; +"The birth-rate move requires Yule without fossil dating." = "O movimento da taxa de nascimento exige Yule sem datação fóssil."; +"Speciation rate under Yule, per source tree-height unit." = "Taxa de especiação sob Yule, por unidade de altura da árvore de origem."; diff --git a/apps/macos/Sources/RoveApp/RunComparison.swift b/apps/macos/Sources/RoveApp/RunComparison.swift index 71fc7d5..b4b9093 100644 --- a/apps/macos/Sources/RoveApp/RunComparison.swift +++ b/apps/macos/Sources/RoveApp/RunComparison.swift @@ -150,6 +150,9 @@ final class RunComparisonModel { let x = a.draft, let y = b.draft, x.matrixSHA256 == y.matrixSHA256, x.constraints == y.constraints, x.settings.clock == y.settings.clock, x.settings.clockSigmaPrior == y.settings.clockSigmaPrior, + x.settings.treePrior == y.settings.treePrior, + x.settings.treePrior != "yule" + || x.settings.yuleBirthRateUpper == y.settings.yuleBirthRateUpper, x.settings.sampleFromPrior == y.settings.sampleFromPrior, x.settings.conditioning == y.settings.conditioning, x.settings.partitioning == y.settings.partitioning, diff --git a/apps/macos/Sources/RoveApp/RunRecord.swift b/apps/macos/Sources/RoveApp/RunRecord.swift index c79c5db..416d6b5 100644 --- a/apps/macos/Sources/RoveApp/RunRecord.swift +++ b/apps/macos/Sources/RoveApp/RunRecord.swift @@ -48,6 +48,27 @@ struct EngineRecord: Decodable, Sendable { var clockSigmaPriorParameters: ClockSigmaPrior? = nil var sampleFromPrior: Bool? = nil var conditioning: String? = nil + var treePriorKind: String? = nil + var birthRatePriorParameters: BirthRatePrior? = nil + + struct BirthRatePrior: Decodable, Sendable { + let distribution: String + let lower: Double + let upper: Double + let logDensity: Double + + var valid: Bool { + distribution == "uniform" && lower == 0 && upper.isFinite && upper > 0 + && upper / 2 > 0 && abs(logDensity + log(upper)) < 1e-12 + } + } + + func treePriorMatches(_ settings: AnalysisSettings) -> Bool { + guard (treePriorKind ?? "birth-death") == settings.treePrior else { return false } + if settings.treePrior != "yule" { return birthRatePriorParameters == nil } + guard dating == nil, let prior = birthRatePriorParameters, prior.valid else { return false } + return prior.upper == settings.yuleBirthRateUpper + } /// The engine's description of each conditioning option. static let conditioningDescriptions = [ @@ -108,7 +129,7 @@ struct EngineRecord: Decodable, Sendable { let expectedDating: EngineDatingModel? do { expectedDating = try draft.settings.dating.model() } catch { return false } return draft.settings.validationError == nil && input.sha256 == draft.matrixSHA256 - && model.dating == expectedDating + && model.dating == expectedDating && model.treePriorMatches(draft.settings) && input.gaps == (draft.settings.gapsAsMissing ? "missing" : "reject") && model.preset == draft.settings.clock && (model.preset != "reference" diff --git a/apps/macos/Sources/RoveApp/RunView.swift b/apps/macos/Sources/RoveApp/RunView.swift index 34a0566..a3795c9 100644 --- a/apps/macos/Sources/RoveApp/RunView.swift +++ b/apps/macos/Sources/RoveApp/RunView.swift @@ -126,6 +126,11 @@ struct RunView: View { Text(strings("Clock sigma prior") + ": " + prior.description(strings: strings)) .foregroundStyle(Lab.secondary) } + Text( + strings("Tree prior") + ": " + + run.request.draft.settings.treePriorDescription(strings: strings) + ) + .foregroundStyle(Lab.secondary) DatingSummary(dating: run.request.draft.settings.dating, strings: strings) ConstraintSummary( outgroup: run.request.draft.outgroup, taxa: run.request.draft.taxa, diff --git a/apps/macos/Sources/RoveApp/SetupView.swift b/apps/macos/Sources/RoveApp/SetupView.swift index 197ce10..1b46e0a 100644 --- a/apps/macos/Sources/RoveApp/SetupView.swift +++ b/apps/macos/Sources/RoveApp/SetupView.swift @@ -39,6 +39,7 @@ struct SetupView: View { if workspace.settings.clock == "reference" { ClockSigmaPriorSection(workspace: workspace) } + TreePriorSection(workspace: workspace) DatingSection(workspace: workspace) LabPanel { @@ -320,6 +321,7 @@ struct ReviewView: View { Text("NEXUS").font(.system(size: 10, design: .monospaced)).foregroundStyle(Lab.muted) }.padding(.bottom, 22) rule + row("Tree prior", workspace.settings.treePriorDescription(strings: strings)) row( "Character model", workspace.settings.conditioning == "variable" diff --git a/apps/macos/Sources/RoveApp/TraceDiagnosticsView.swift b/apps/macos/Sources/RoveApp/TraceDiagnosticsView.swift index b0bfff4..769995f 100644 --- a/apps/macos/Sources/RoveApp/TraceDiagnosticsView.swift +++ b/apps/macos/Sources/RoveApp/TraceDiagnosticsView.swift @@ -278,10 +278,11 @@ struct TraceDiagnosticsView: View { case "posterior": "Log posterior density combines likelihood and priors. It is not a node’s posterior support." case "likelihood": "Log likelihood measures how the model and tree explain the observed matrix." - case "prior", "birth_death", "gamma_prior", "clock_rate_prior", "clock_sigma_prior": + case "prior", "birth_death", "yule", "gamma_prior", "clock_rate_prior", "clock_sigma_prior": "A log density contribution from the model’s prior distributions." case "tree_height", "tree_length": "Heights and lengths use the source time units; they are not automatically calendar dates." + case "birth_rate": "Speciation rate under Yule, per source tree-height unit." case "birth_difference_rate": "Net diversification rate, per source time unit." case "relative_death_rate": "Extinction relative to speciation; a dimensionless ratio." case "gamma_shape": "Dimensionless shape controlling variation in rates between characters." diff --git a/apps/macos/Sources/RoveApp/TreePriorView.swift b/apps/macos/Sources/RoveApp/TreePriorView.swift new file mode 100644 index 0000000..7d339a3 --- /dev/null +++ b/apps/macos/Sources/RoveApp/TreePriorView.swift @@ -0,0 +1,68 @@ +import SwiftUI + +extension AnalysisSettings { + var treePriorLabel: String { + dating.enabled + ? "Fossilized birth-death" : treePrior == "yule" ? "Yule · pure birth" : "Birth-death" + } + + func treePriorDescription(strings: AppStrings) -> String { + guard treePrior == "yule" else { return strings(treePriorLabel) } + return strings( + "Yule · birth rate Uniform(0, %@)", yuleBirthRateUpper.map(String.init(describing:)) ?? "—") + } +} + +struct TreePriorSection: View { + @Bindable var workspace: Workspace + private var strings: AppStrings { workspace.strings } + + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 14) { + Text(strings("Tree prior")).font(.system(size: 13, weight: .semibold)) + Picker(strings("Tree prior"), selection: $workspace.settings.treePrior) { + Text( + strings(workspace.settings.dating.enabled ? "Fossilized birth-death" : "Birth-death") + ) + .tag("birth-death") + Text(strings("Yule · pure birth")).tag("yule") + }.labelsHidden().frame(maxWidth: 350) + Text( + strings( + workspace.settings.treePrior == "yule" + ? "Yule models speciation without extinction for contemporaneous species tips, with complete sampling. It does not support fossil ages, calibrations or population coalescence." + : "Birth-death allows extinction as well as speciation. Fossil dating uses the fossilized birth-death model below." + ) + ) + .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) + if workspace.settings.treePrior == "yule" { + HStack { + Text(strings("Birth-rate upper bound")).font(.system(size: 12)) + TextField(strings("Birth-rate upper bound"), text: $workspace.settings.birthRateUpper) + .textFieldStyle(.roundedBorder).frame(width: 110) + } + Text( + strings( + "The birth rate has a Uniform(0, upper bound) prior. Its units are inverse tree-height units on the fixed clock scale. Choose a defensible bound and inspect prior-only runs; 1000 is a starting value, not a general recommendation." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) + if workspace.settings.dating.enabled { + Text( + strings("Yule requires contemporaneous tips without fossil dating or calibrations.") + ) + .font(.system(size: 12)).foregroundStyle(Lab.coral).fixedSize( + horizontal: false, vertical: true) + } else if workspace.settings.yuleBirthRateUpper == nil { + Text(strings("Use a positive, finite upper bound for the Yule birth-rate prior.")) + .font(.system(size: 12)).foregroundStyle(Lab.coral).fixedSize( + horizontal: false, vertical: true) + } + } + } + } + } +} diff --git a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift index 791ecc2..e3ce125 100644 --- a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift +++ b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift @@ -89,7 +89,7 @@ struct AdvancedOptionsTests { #expect(settings.validationError != nil) settings.checkpointEvery = 3_000 #expect(settings.validationError == nil) - #expect(ProposalSchedule.moves.count == 23 && Set(ProposalSchedule.moves).count == 23) + #expect(ProposalSchedule.moves.count == 24 && Set(ProposalSchedule.moves).count == 24) #expect(ProposalSchedule.tunable.isSubset(of: ProposalSchedule.moves)) } diff --git a/apps/macos/Tests/RoveAppTests/PreviewTests.swift b/apps/macos/Tests/RoveAppTests/PreviewTests.swift index 36bef9d..64fa5e4 100644 --- a/apps/macos/Tests/RoveAppTests/PreviewTests.swift +++ b/apps/macos/Tests/RoveAppTests/PreviewTests.swift @@ -5,6 +5,40 @@ import Testing @testable import RoveApp struct PreviewTests { + @Test @MainActor func renderYulePrior() async throws { + guard ProcessInfo.processInfo.environment["CI"] == nil else { return } + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent() + let directory = root.appendingPathComponent(".local/ui/yule") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + _ = NSApplication.shared + NSApp.appearance = NSAppearance(named: .darkAqua) + Lab.registerFonts() + let suite = "rove-yule-preview-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppPreferences(defaults: defaults) + let workspace = Workspace( + executable: root.appendingPathComponent("target/release/rove"), preferences: preferences) + workspace.settings.treePrior = "yule" + let view = NSHostingView( + rootView: TreePriorSection(workspace: workspace).padding(24).frame(width: 620, height: 410) + .background(Lab.background)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 620, height: 410), + styleMask: [.borderless], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = view + window.orderBack(nil) + for language in [AppLanguage.english, .portuguese] { + preferences.language = language + try await capture( + view, to: directory.appendingPathComponent("prior-\(language.rawValue).png")) + } + window.close() + } + @Test @MainActor func renderOrderedPartitions() async throws { guard ProcessInfo.processInfo.environment["CI"] == nil else { return } let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() diff --git a/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift b/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift index b245ef5..6b74077 100644 --- a/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift +++ b/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift @@ -69,6 +69,23 @@ struct RunAssessmentTests { #expect(try TreeSource.fingerprint(package.appendingPathComponent(path)) == hash) } #expect(HistoryEntry.read(directory).status == .completed) + if chains == 1 { + let imported = try await CommandLineImport.prepare( + directory.appendingPathComponent("results"), matrix: matrix, under: parent, + executable: engine) + let wrapper = HistoryEntry.read(imported) + let importedPackage = parent.appendingPathComponent("imported-package") + _ = try await AssessmentRequest( + entry: wrapper, executable: engine, output: importedPackage, options: AssessmentOptions(), + export: true + ).execute(with: EngineTool()) + #expect( + HistoryEntry.read(importedPackage.appendingPathComponent("run")).status == .completed) + #expect( + try importedPackage.appendingPathComponent("run/results").resourceValues(forKeys: [ + .isSymbolicLinkKey + ]).isSymbolicLink == false) + } } let entry = HistoryEntry.read(parent.appendingPathComponent("run-1")) try Data("changed".utf8).write(to: matrix) diff --git a/apps/macos/Tests/RoveAppTests/TreeFileTests.swift b/apps/macos/Tests/RoveAppTests/TreeFileTests.swift index d08d584..79781a4 100644 --- a/apps/macos/Tests/RoveAppTests/TreeFileTests.swift +++ b/apps/macos/Tests/RoveAppTests/TreeFileTests.swift @@ -52,7 +52,8 @@ struct TreeFileTests { try "{}".write(to: record, atomically: true, encoding: .utf8) #expect(throws: (any Error).self) { try TreeSource.read(record) } #expect(try TreeSource.prepare(file, under: runs).path == container.path) - #expect(try TreeSource.read(record).path == file.path) + let recovered = try TreeSource.read(record) + #expect(recovered.path == file.path && recovered.sha256 == source.sha256) let model = TreeSummaryModel(directory: container, executable: engine, source: .file(file)) model.burnin = "25" @@ -67,7 +68,8 @@ struct TreeFileTests { let entry = HistoryEntry.read(container) #expect(entry.status == .treeFile && entry.name == "four.trees" && entry.draft == nil) - #expect(entry.source == source && entry.startedAt == source.createdAt) + // Repair creates a new record, whose timestamp can differ from the original. + #expect(entry.source == recovered && entry.startedAt == recovered.createdAt) let scan = HistoryScan.read(roots: [runs], known: [], defaultRoot: runs) #expect(scan.entries.map(\.id) == [entry.id]) diff --git a/apps/macos/Tests/RoveAppTests/TreePriorTests.swift b/apps/macos/Tests/RoveAppTests/TreePriorTests.swift new file mode 100644 index 0000000..16e6c9c --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/TreePriorTests.swift @@ -0,0 +1,126 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct TreePriorTests { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + private var engine: URL { + ProcessInfo.processInfo.environment["ROVE_TEST_ENGINE"].map { URL(fileURLWithPath: $0) } + ?? root.appendingPathComponent("target/release/rove") + } + + @Test func modelAndProposalValidation() throws { + var settings = AnalysisSettings() + #expect(!((try settings.modelArguments()).contains("--tree-prior"))) + settings.treePrior = "yule" + settings.birthRateUpper = "2,5" + #expect(settings.validationError == nil && settings.yuleBirthRateUpper == 2.5) + #expect((try settings.modelArguments()).contains("--birth-rate-upper")) + for name in ["birth_difference_scale", "relative_death_scale"] { + settings.tuningValues = [MoveOverride(move: name, value: 0.5)] + #expect(settings.validationError != nil) + } + settings.tuningValues = [MoveOverride(move: "birth_rate_scale", value: 0.5)] + #expect(settings.validationError == nil) + settings.treePrior = "birth-death" + #expect(settings.validationError != nil) + settings.treePrior = "yule" + for value in ["", "0", "-1", "nan", "inf", "1e-999"] { + settings.birthRateUpper = value + #expect(settings.validationError != nil) + } + settings.birthRateUpper = "2.5" + settings.dating.enabled = true + #expect(settings.validationError?.contains("contemporaneous") == true) + #expect(throws: (any Error).self) { try settings.modelArguments() } + } + + @Test @MainActor func yulePersistsResumesPredictsAndEstimatesItsFullModel() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-yule-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let matrix = parent.appendingPathComponent("matrix.nex") + try "#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=4; MATRIX A 0011 B 0101 C 1010 D 1100; END;" + .write(to: matrix, atomically: true, encoding: .utf8) + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + for clock in ["strict", "reference"] { + var settings = AnalysisSettings() + settings.treePrior = "yule" + settings.birthRateUpper = "4" + settings.clock = clock + settings.steps = 2_000 + settings.sampleEvery = 100 + settings.chains = clock == "strict" ? 1 : 2 + settings.tuningValues = [MoveOverride(move: "birth_rate_scale", value: 0.6)] + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings, outgroup: "D") + #expect(draft.formatVersion == 10) + let file = parent.appendingPathComponent("setup-\(clock).rove.json") + try draft.write(to: file) + #expect(try AnalysisDraft.read(file).settings == settings) + var object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + object["formatVersion"] = 9 + try JSONSerialization.data(withJSONObject: object).write(to: file) + #expect(throws: (any Error).self) { try AnalysisDraft.read(file) } + + let directory = parent.appendingPathComponent(clock) + 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.model.treePriorKind == "yule" && record.model.birthRatePriorParameters?.upper == 4) + let entry = HistoryEntry.read(directory) + #expect(entry.draft?.settings.treePrior == "yule") + var changed = settings + changed.birthRateUpper = "5" + #expect( + !record.matches( + AnalysisDraft(matrix: matrix, report: report, settings: changed, outgroup: "D"))) + + let result = directory.appendingPathComponent( + settings.chains == 1 ? "results" : "results/chain-01") + let trace = try String( + contentsOf: result.appendingPathComponent("trace.log"), encoding: .utf8) + #expect(trace.contains("\tyule\tbirth_rate\t") && !trace.contains("relative_death")) + let child = try EngineRecord.read(result.appendingPathComponent("run.json")) + #expect(child.moves?.contains(where: { $0.name == "birth_rate_scale" }) == true) + #expect(child.moves?.contains(where: { $0.name == "relative_death_scale" }) == false) + + let imported = try await CommandLineImport.prepare( + directory.appendingPathComponent("results"), matrix: matrix, under: parent, + executable: engine) + #expect(HistoryEntry.read(imported).draft?.settings.treePrior == "yule") + let prediction = PredictiveCheckModel(entry: entry, executable: engine) + prediction.replicates = "2" + prediction.start() + await prediction.waitForExit() + #expect(prediction.error == nil, Comment(rawValue: prediction.details ?? "")) + #expect(prediction.predictions.first?.report.replicates == 2) + + let marginal = MarginalLikelihoodModel(entry: entry, executable: engine) + marginal.powers = "4" + marginal.steps = "400" + marginal.start() + await marginal.waitForExit() + #expect(marginal.error == nil, Comment(rawValue: marginal.details ?? "")) + let estimate = try #require(marginal.estimates.first) + #expect(estimate.matches(draft) && estimate.record.model.treePriorKind == "yule") + #expect( + !estimate.matches( + AnalysisDraft(matrix: matrix, report: report, settings: changed, outgroup: "D"))) + } + } +} diff --git a/docs/es/guide/macos-preview.md b/docs/es/guide/macos-preview.md index 2f6c6d2..a428773 100644 --- a/docs/es/guide/macos-preview.md +++ b/docs/es/guide/macos-preview.md @@ -489,7 +489,7 @@ En **History → Evidence review**, elija el porcentaje de burn-in y actualice l Finalización, muestreo de parámetros, concordancia entre cadenas, árboles y evidencia predictiva tienen estados separados. Los criterios escalares exigen al menos 1.000 muestras retenidas y ESS 200 por cadena, sin truncamiento de retardos. Entre cadenas también se requieren semillas distintas, entrada/modelo coincidentes y R-hat dividido y normalizado por rangos ≤ 1,01. Solo se excluyen parámetros verificados como fijos por el modelo. Una sola cadena no permite evaluar concordancia entre cadenas. Estos criterios diagnósticos no prueban convergencia ni sustituyen los umbrales configurables de parada. El soporte de árboles y las fracciones predictivas requieren interpretación; la evidencia ausente o inconsistente permanece visible. Las ejecuciones solo del prior describen su exploración, no la adecuación posterior. -**Export reproducibility package…** crea una carpeta local nueva fuera de la ejecución. `manifest.json` enumera tamaños y SHA-256; `assessment.json` contiene una revisión nueva; `run/` contiene registros conocidos de Rove, muestras, checkpoints y resultados derivados. La matriz original solo se incluye al seleccionar **Include the original matrix in the export**, si coincide su huella registrada. La revisión indica originales modificados o no disponibles. No se copian archivos vecinos desconocidos, revisiones anteriores ni fuentes externas citadas por comparaciones. Se preservan rutas y nombres de taxones, se rechazan enlaces simbólicos y destinos existentes, se detectan cambios durante la copia y se conservan los originales. El ejecutable no se incluye: la reanudación exacta requiere un checkpoint válido y la identidad original del ejecutable, entrada y modelo; revise las rutas antes de reutilizar la configuración. +**Export reproducibility package…** crea una carpeta local nueva fuera de la ejecución. `manifest.json` enumera tamaños y SHA-256; `assessment.json` contiene una revisión nueva; `run/` contiene registros conocidos de Rove, muestras, checkpoints y resultados derivados. La matriz original solo se incluye al seleccionar **Include the original matrix in the export**, si coincide su huella registrada. La revisión indica originales modificados o no disponibles. No se copian archivos vecinos desconocidos, revisiones anteriores ni fuentes externas citadas por comparaciones. Se preservan rutas y nombres de taxones, se rechazan enlaces simbólicos dentro de los artefactos y destinos existentes, se detectan cambios durante la copia y se conservan los originales. El ejecutable no se incluye: la reanudación exacta requiere un checkpoint válido y la identidad original del ejecutable, entrada y modelo; revise las rutas antes de reutilizar la configuración. Las mismas operaciones están disponibles en el motor: @@ -503,3 +503,7 @@ rove export-run run-folder --output another-package --include-matrix matrix.nex La fuente puede ser una carpeta del app o de la CLI. Las ejecuciones incompletas pueden revisarse y archivarse conservando su estado. Se rechazan registros inválidos o estructuras de archivos inseguras. Los paquetes son carpetas locales, sin cargas a internet. Las comprobaciones predictivas guardadas muestran un histograma de estadísticas pareadas **simulado − observado**. Cada par usa el mismo árbol posterior; la estadística de parsimonia observada puede variar entre pares. Cero indica igualdad. El gráfico verifica conteos, empates y colas contra `predictive.json`, informa pares indefinidos y no se muestra si los registros discrepan. No evalúa convergencia ni decide automáticamente la adecuación. + +Las copias de la matriz original guardadas por las comprobaciones predictivas en `source/matrix.nex` se omiten del paquete, aunque se incluya la comprobación. La inclusión explícita escribe una sola `matrix.nex` verificada en la raíz; `omitted_source_matrices` enumera las copias omitidas. Las matrices réplicas simuladas siguen incluidas. + +Los registros nativos de ejecuciones importadas de la CLI pueden enlazar su carpeta principal `results`; esta fuente declarada se copia como archivos normales en el paquete. diff --git a/docs/es/guide/reference-model.md b/docs/es/guide/reference-model.md index 72d836b..426c40d 100644 --- a/docs/es/guide/reference-model.md +++ b/docs/es/guide/reference-model.md @@ -198,3 +198,45 @@ 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). + +## Prior opcional de Yule + +Elija **Tree prior → Yule · pure birth** o utilice +`--tree-prior yule --birth-rate-upper 1000` en `sample` o `marginal`. +Nacimiento–muerte sigue siendo el valor predeterminado; la datación fósil usa +FBD. Yule supone muestreo completo de especies contemporáneas con terminales +a edad cero, sin extinción. Rechaza datación fósil y no ofrece calibraciones +de nodos ni coalescencia poblacional. Especies actuales, fósiles y muestras +dentro de una población necesitan supuestos biológicos diferentes. + +Solo se estima λ, con prior propio Uniforme(0,U), log densidad −log U y valor +inicial min(1,U/2); U debe ser positivo y finito. Las alturas representan +cambios esperados en la escala fija del reloj unitario; λ es por unidad de +altura, no automáticamente por millón de años. U=1000 es un punto de partida, +no una recomendación universal. Examine ejecuciones solo del prior y pruebe +límites justificables. No hay coordenada, propuesta ni estadística de +extinción. `birth_rate_scale` admite controles de peso y ajuste. + +La convención no escalada de BEAST 2.7.8 es +`(n−1) log λ − λ (suma de alturas internas + altura de la raíz)`. +Se condiciona al número de terminales, no a la altura de raíz u origen; la +raíz contribuye dos veces. Esperas independientes Exp(kλ) y selección uniforme +entre k(k−1)/2 pares dan el multiplicador normalizador `2^(n−1)/(n−1)!` para +árboles etiquetados y ordenados por eventos. Es independiente de parámetros +y coincide con la convención actual de nacimiento–muerte para el mismo n. +Las estimaciones por posteriores de potencia usan Z(1)/Z(0), cancelando ese +factor y calculando evidencia bajo el prior normalizado en el dominio +admitido. La monofilia restringe ese dominio. Mantenga matriz, taxones y +restricciones consistentes y compare el modelo completo, incluido U. + +El modelo y su límite aparecen en revisión, historial y comparación; persisten +en configuraciones de formato 10, registros, checkpoints, predicciones y +estimaciones marginales. Las apps anteriores rechazan estas configuraciones. +Las comparaciones de convergencia no mezclan Yule con nacimiento–muerte ni +límites diferentes. La reanudación exacta exige el ejecutable original. + +La validación incluye 24 estados sintéticos fijos de BEAST.base 2.7.8 +(`fixtures/validation/yule`), el límite sin extinción, simulación independiente +de esperas, alturas y frecuencias de topologías con y sin monofilia, y una +comprobación por cuadratura de la evidencia. Son pruebas de corrección, sin +afirmaciones comparativas sobre velocidad o mezcla. diff --git a/docs/guide/macos-preview.md b/docs/guide/macos-preview.md index 3a4e7a8..d0b27b8 100644 --- a/docs/guide/macos-preview.md +++ b/docs/guide/macos-preview.md @@ -477,7 +477,7 @@ In **History → Evidence review**, choose the burn-in percentage and refresh th Completion, scalar sampling, independent-chain agreement, trees and predictive evidence have separate statuses. Scalar criteria are at least 1,000 retained draws and ESS 200 per chain without lag truncation. Between-chain criteria additionally require distinct seeds, matching input/model and rank-normalized split R-hat ≤ 1.01. Only independently verified model-fixed parameters are excluded. A single chain has no between-chain assessment. These are diagnostic reference criteria, not proof of convergence or the run's configurable stopping thresholds. Tree support and predictive tail fractions require interpretation; missing or inconsistent evidence stays visible. Prior-only runs describe prior exploration, not posterior adequacy. -**Export reproducibility package…** creates a new local directory outside the run. `manifest.json` records the size and SHA-256 of each included file. `assessment.json` holds a fresh review; `run/` contains known Rove records, samples, checkpoints and derived-result folders. The original matrix is excluded unless **Include the original matrix in the export** is selected; inclusion requires its recorded fingerprint. Changed or unavailable originals appear in the review. Unknown neighboring files, previous assessments and external sources referenced by comparisons are not copied. Export preserves recorded paths and taxon names, refuses symbolic links and existing destinations, checks for changing source files and leaves originals untouched. It does not include the executable: exact resumption requires a valid checkpoint and the original executable/input/model identity; review paths before reusing the setup. +**Export reproducibility package…** creates a new local directory outside the run. `manifest.json` records the size and SHA-256 of each included file. `assessment.json` holds a fresh review; `run/` contains known Rove records, samples, checkpoints and derived-result folders. The original matrix is excluded unless **Include the original matrix in the export** is selected; inclusion requires its recorded fingerprint. Changed or unavailable originals appear in the review. Unknown neighboring files, previous assessments and external sources referenced by comparisons are not copied. Export preserves recorded paths and taxon names, refuses symbolic links inside artifacts and existing destinations, checks for changing source files and leaves originals untouched. It does not include the executable: exact resumption requires a valid checkpoint and the original executable/input/model identity; review paths before reusing the setup. The same operations are available in the engine: @@ -491,3 +491,7 @@ rove export-run run-folder --output another-package --include-matrix matrix.nex The source may be an app run folder or a CLI output folder. Incomplete runs can be reviewed and archived; their status is preserved. Malformed source records or unsafe file layouts are refused. Packages are directories, not uploaded archives. Saved posterior predictive checks also show a histogram of **simulated − observed** paired statistics. Each pair uses the same posterior tree; the observed parsimony statistic can therefore differ between pairs. Zero marks equality. The plot verifies replicate counts, ties and tails against `predictive.json`, reports undefined pairs and becomes unavailable if records disagree. It does not assess convergence or turn a tail fraction into an automatic adequacy decision. + +Copies of the original matrix stored by predictive checks in `source/matrix.nex` are omitted from the package even when the check itself is included. Explicit matrix inclusion writes one verified `matrix.nex` at the package root; `omitted_source_matrices` lists the omitted copies. Simulated replicate matrices remain included. + +Native wrappers for imported CLI runs may link their top-level `results` directory; this declared source is materialized as regular files in the package. diff --git a/docs/guide/reference-model.md b/docs/guide/reference-model.md index f2553b3..d2c394c 100644 --- a/docs/guide/reference-model.md +++ b/docs/guide/reference-model.md @@ -189,3 +189,46 @@ 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). + +## Optional Yule tree prior + +Choose **Tree prior → Yule · pure birth** in Setup, or pass +`--tree-prior yule --birth-rate-upper 1000` to `sample` or `marginal`. +Birth–death remains the default; fossil dating keeps FBD. Yule is a +complete-sampling species-tree prior for contemporaneous terminals at zero, +without extinction. It rejects fossil dating and does not supply node +calibrations or a population coalescent. Extant species, fossil terminals and +within-species population samples require different biological assumptions. + +Only the birth rate λ is estimated, with a proper Uniform(0,U) prior whose +log density is −log U; U must be positive and finite. The initial λ is +min(1,U/2). Tree heights use expected changes on the fixed unit-clock scale, +so λ is per unit of those heights, not automatically per million years. +U=1000 is a reference starting value, not a recommendation for every matrix. +Inspect prior-only runs and repeat with scientifically defensible bounds. +There is no extinction coordinate, proposal or trace statistic under Yule. +The `birth_rate_scale` proposal supports the usual weight and tuning controls. + +The BEAST 2.7.8 unscaled convention is +`(n−1) log λ − λ (sum of internal heights + root height)`. +It conditions on tip count, not root height or an origin. The root contributes +twice. For a labeled ranked tree, independent backwards waits Exp(kλ) and +uniform choices among k(k−1)/2 pairs give a normalized density multiplier +`2^(n−1)/(n−1)!`. This parameter-independent coefficient is the same for the +current birth–death convention at the same n. Power-posterior estimates use +Z(1)/Z(0), so a constant prior multiplier cancels; the resulting evidence is +relative to the normalized prior on the supported domain. Monophyly restricts +that domain. Keep the matrix, taxa and constraints consistent when comparing +evidence, and compare the full model including U and all other priors. + +The selected model and bound appear in Review, History and model comparisons, +and persist in format-10 setups, run records, checkpoints, predictions and +marginal estimates. Earlier apps reject these setups. Convergence diagnostics +never combine Yule with birth–death or different birth-rate bounds. Exact +checkpoint resume still requires the original executable. + +Validation includes 24 synthetic fixed states from pinned BEAST.base 2.7.8 +(`fixtures/validation/yule`), the zero-extinction birth–death limit, independent +prior simulation of waiting times, heights and topology frequencies with and +without monophyly, and a power-posterior quadrature check. These are correctness +checks, not comparative timing or mixing claims. diff --git a/docs/pt-BR/guide/macos-preview.md b/docs/pt-BR/guide/macos-preview.md index 5fa830d..e5f2a15 100644 --- a/docs/pt-BR/guide/macos-preview.md +++ b/docs/pt-BR/guide/macos-preview.md @@ -493,7 +493,7 @@ Em **Histórico → Revisão das evidências**, escolha o burn-in e atualize a r Conclusão, amostragem dos parâmetros, concordância entre cadeias, árvores e evidências preditivas têm estados separados. Os critérios para parâmetros são pelo menos 1.000 amostras retidas e ESS de 200 por cadeia, sem truncamento de defasagens. A comparação entre cadeias exige também sementes distintas, entrada/modelo correspondentes e R-hat dividido e normalizado por postos ≤ 1,01. Somente parâmetros comprovadamente fixos pelo modelo são excluídos. Uma cadeia única não permite avaliar concordância entre cadeias. Esses critérios de diagnóstico não comprovam convergência nem substituem os limites configuráveis de parada da execução. Suporte de árvores e frações de cauda preditivas exigem interpretação; evidências ausentes ou inconsistentes ficam visíveis. Execuções apenas do prior descrevem a exploração do prior, não a adequação posterior. -**Exportar pacote de reprodução…** cria uma pasta local nova fora da execução. `manifest.json` registra tamanho e SHA-256 de cada arquivo. `assessment.json` contém uma revisão nova; `run/` contém registros conhecidos do Rove, amostras, checkpoints e pastas de resultados derivados. A matriz original só é incluída com a opção **Incluir a matriz original na exportação**, mediante confirmação do identificador registrado. A revisão indica originais alterados ou indisponíveis. Arquivos vizinhos desconhecidos, revisões anteriores e fontes externas citadas em comparações não são copiados. A exportação preserva caminhos registrados e nomes de táxons, recusa links simbólicos e destinos existentes, verifica alterações das fontes e mantém os originais intactos. O executável não é incluído: a retomada exata exige checkpoint válido e a identidade original do executável, entrada e modelo; revise os caminhos antes de reutilizar a configuração. +**Exportar pacote de reprodução…** cria uma pasta local nova fora da execução. `manifest.json` registra tamanho e SHA-256 de cada arquivo. `assessment.json` contém uma revisão nova; `run/` contém registros conhecidos do Rove, amostras, checkpoints e pastas de resultados derivados. A matriz original só é incluída com a opção **Incluir a matriz original na exportação**, mediante confirmação do identificador registrado. A revisão indica originais alterados ou indisponíveis. Arquivos vizinhos desconhecidos, revisões anteriores e fontes externas citadas em comparações não são copiados. A exportação preserva caminhos registrados e nomes de táxons, recusa links simbólicos dentro dos artefatos e destinos existentes, verifica alterações das fontes e mantém os originais intactos. O executável não é incluído: a retomada exata exige checkpoint válido e a identidade original do executável, entrada e modelo; revise os caminhos antes de reutilizar a configuração. As mesmas operações estão disponíveis no motor: @@ -507,3 +507,7 @@ rove export-run run-folder --output another-package --include-matrix matrix.nex A origem pode ser uma pasta de execução do app ou da CLI. Execuções incompletas podem ser revisadas e arquivadas, preservando seu estado. Registros de origem inválidos ou estruturas de arquivos inseguras são recusados. Os pacotes são pastas locais, sem envio para a internet. As verificações preditivas salvas também mostram um histograma de estatísticas pareadas **simulado − observado**. Cada par usa a mesma árvore posterior; a estatística de parcimônia observada pode variar entre pares. Zero indica igualdade. O gráfico confere contagens, empates e caudas com `predictive.json`, informa pares indefinidos e fica indisponível quando os registros divergem. Não avalia convergência nem transforma uma fração de cauda em decisão automática de adequação. + +Cópias da matriz original guardadas pelas verificações preditivas em `source/matrix.nex` são omitidas do pacote, mesmo quando a verificação é incluída. A inclusão explícita escreve uma única `matrix.nex` verificada na raiz do pacote; `omitted_source_matrices` lista as cópias omitidas. Matrizes réplicas simuladas continuam incluídas. + +Registros nativos de execuções importadas da CLI podem vincular a pasta `results` principal; essa origem declarada é copiada como arquivos comuns no pacote. diff --git a/docs/pt-BR/guide/reference-model.md b/docs/pt-BR/guide/reference-model.md index b8d37c3..a6b6fa3 100644 --- a/docs/pt-BR/guide/reference-model.md +++ b/docs/pt-BR/guide/reference-model.md @@ -197,3 +197,47 @@ 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). + +## Prior opcional de Yule + +Em Configuração, escolha **Prior da árvore → Yule · nascimento puro**, +ou use `--tree-prior yule --birth-rate-upper 1000` em `sample` ou `marginal`. +Nascimento-morte continua como padrão; a datação fóssil usa FBD. Yule é um +prior de árvore de espécies com amostragem completa, terminais contemporâneos +na idade zero e sem extinção. Rejeita datação fóssil e não oferece calibrações +de nós nem coalescência populacional. Espécies atuais, terminais fósseis e +amostras populacionais dentro de uma espécie exigem pressupostos distintos. + +Apenas a taxa de nascimento λ é estimada, com prior próprio Uniforme(0,U) +e log densidade −log U; U deve ser positivo e finito. O valor inicial de λ é +min(1,U/2). As alturas usam mudanças esperadas na escala fixa do relógio +unitário: λ está por unidade dessas alturas, não automaticamente por milhão +de anos. U=1000 é uma referência inicial, não uma recomendação para toda +matriz. Examine análises apenas dos priors e repita com limites justificáveis. +Yule não possui coordenada, proposta ou estatística de extinção. A proposta +`birth_rate_scale` aceita os controles usuais de peso e ajuste. + +A convenção não escalada do BEAST 2.7.8 é +`(n−1) log λ − λ (soma das alturas internas + altura da raiz)`. +É condicionada ao número de terminais, não à altura da raiz ou à origem; a +raiz contribui duas vezes. Esperas independentes Exp(kλ), com escolha uniforme +entre k(k−1)/2 pares, dão à árvore rotulada e ordenada por eventos o fator +normalizador `2^(n−1)/(n−1)!`. Esse coeficiente independente dos parâmetros é +o mesmo da convenção atual de nascimento-morte para o mesmo n. As estimativas +por posteriores de potência usam Z(1)/Z(0), cancelando multiplicadores +constantes do prior; a evidência corresponde ao prior normalizado no domínio +aceito. A monofilia restringe esse domínio. Mantenha matriz, terminais e +restrições consistentes nas comparações e compare o modelo completo, +incluindo U e os demais priors. + +A escolha e o limite aparecem em Revisão, Histórico e comparações de modelos, +e persistem em configurações de formato 10, registros, checkpoints, predições +e estimativas marginais. Apps antigos rejeitam essas configurações. As +comparações de convergência não misturam Yule com nascimento-morte nem limites +diferentes. Retomar exatamente ainda exige o executável original. + +A validação inclui 24 estados sintéticos fixos do BEAST.base 2.7.8 +(`fixtures/validation/yule`), o limite de extinção zero, simulação independente +dos tempos, alturas e frequências de topologias com e sem monofilia, e teste +de posteriores de potência contra quadratura. São testes de correção, sem +alegações comparativas de velocidade ou mistura. diff --git a/docs/zh-CN/guide/macos-preview.md b/docs/zh-CN/guide/macos-preview.md index bb62324..7fb7a44 100644 --- a/docs/zh-CN/guide/macos-preview.md +++ b/docs/zh-CN/guide/macos-preview.md @@ -390,7 +390,7 @@ History 中已完成的运行包含 **Can the model reproduce the matrix?** 面 运行完成、标量采样、独立链一致性、树证据和预测证据分别显示状态。标量标准为每条链至少保留 1,000 个样本、ESS 至少 200,且没有滞后截断。链间比较还要求不同随机种子、相同输入与模型,以及秩归一化分割 R-hat ≤ 1.01。仅排除经核实由模型固定的参数。单链无法评估链间一致性。这些诊断参考标准既不证明收敛,也不替代可配置的停止阈值。树支持度和预测尾部比例仍需解释;缺失或不一致的证据会明确显示。仅先验运行描述先验探索,不能说明后验模型适合度。 -**Export reproducibility package…** 在运行目录外新建本地文件夹。`manifest.json` 列出文件大小和 SHA-256;`assessment.json` 保存新审查;`run/` 包含已知的 Rove 记录、样本、检查点及派生结果。只有明确选中 **Include the original matrix in the export** 且指纹匹配时才包含原矩阵。审查会标明原矩阵已更改或不可用。不复制未知相邻文件、以前的审查或比较报告引用的外部数据源。导出保留记录中的路径和分类单元名称,拒绝符号链接和现有目标,检查复制过程中源文件是否变化,并保持原件不变。数据包不包含可执行文件:精确恢复需要有效检查点以及原可执行文件、输入和模型身份;复用配置前请检查路径。 +**Export reproducibility package…** 在运行目录外新建本地文件夹。`manifest.json` 列出文件大小和 SHA-256;`assessment.json` 保存新审查;`run/` 包含已知的 Rove 记录、样本、检查点及派生结果。只有明确选中 **Include the original matrix in the export** 且指纹匹配时才包含原矩阵。审查会标明原矩阵已更改或不可用。不复制未知相邻文件、以前的审查或比较报告引用的外部数据源。导出保留记录中的路径和分类单元名称,拒绝结果文件内部的符号链接和现有目标,检查复制过程中源文件是否变化,并保持原件不变。数据包不包含可执行文件:精确恢复需要有效检查点以及原可执行文件、输入和模型身份;复用配置前请检查路径。 引擎提供相同操作: @@ -404,3 +404,7 @@ rove export-run run-folder --output another-package --include-matrix matrix.nex 源目录可以来自应用或 CLI。未完成运行也可审查和归档,其状态会保留。无效源记录或不安全的文件结构会被拒绝。数据包是本地文件夹,不会上载网络。 已保存的后验预测检验还显示 **模拟值 − 观测值** 的配对统计量直方图。每一对使用同一后验树,因此观测简约统计量可能随树变化。零表示相等。图表将配对数量、相等次数和尾部计数与 `predictive.json` 核对,报告未定义配对;记录不一致时不显示分布。它不评估收敛,也不会根据尾部比例自动判断模型适合度。 + +预测检验保存在 `source/matrix.nex` 中的原矩阵副本不会进入数据包,即使检验本身被包含。明确选择包含矩阵时,只在数据包根目录写入一份经核验的 `matrix.nex`;`omitted_source_matrices` 列出省略的副本。模拟产生的重复矩阵仍会包含。 + +原生应用导入 CLI 运行时,可用链接指向顶层 `results` 目录;导出会将此已声明的源目录复制为数据包中的普通文件。 diff --git a/docs/zh-CN/guide/reference-model.md b/docs/zh-CN/guide/reference-model.md index 01e14ee..9bb68a5 100644 --- a/docs/zh-CN/guide/reference-model.md +++ b/docs/zh-CN/guide/reference-model.md @@ -154,3 +154,35 @@ 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)。 + +## 可选的 Yule 树先验 + +在设置中选择 **Tree prior → Yule · pure birth**,或在 `sample`、`marginal` +中使用 `--tree-prior yule --birth-rate-upper 1000`。默认仍为出生–死亡模型, +化石定年仍使用 FBD。Yule 假设完全采样、同时代且年龄为零的物种末端,并且 +没有灭绝。它拒绝化石定年,不提供节点校准或种群溯祖模型。现生物种、化石末端 +及物种内种群样本需要不同的生物学假设。 + +仅估计出生率 λ,采用适当的 Uniform(0,U) 先验,其对数密度为 −log U,初值为 +min(1,U/2)。U 必须为正有限数。树高使用固定单位时钟下的预期变化数,因此 λ +的单位是树高单位的倒数,并非自动解释为每百万年。U=1000 是参考初值,不是 +普遍建议。请检查仅先验采样,并使用有科学依据的界限进行敏感性分析。Yule +没有灭绝参数、提议或轨迹统计量。`birth_rate_scale` 支持权重和调节控制。 + +BEAST 2.7.8 的未缩放约定为 +`(n−1) log λ − λ (内部节点高度之和 + 根高度)`,以末端数量为条件, +不以根高或起源为条件,根贡献两次。独立的 Exp(kλ) 等待时间以及从 k(k−1)/2 +对中均匀选择合并对,为带标签且按事件排序的树提供归一化乘数 +`2^(n−1)/(n−1)!`。该乘数与参数无关,与相同 n 下现有出生–死亡约定一致。 +幂后验估计计算 Z(1)/Z(0),常数因子抵消,所得证据对应于支持域上归一化的 +先验。单系约束会限制该域。比较证据时保持矩阵、分类单元和约束一致,并比较 +包括 U 及其他先验的完整模型。 + +模型和界限显示于复核、历史记录及模型比较,并保存在格式 10 的设置、运行记录、 +检查点、预测和边际似然估计中。旧版应用会拒绝这些设置。收敛比较不会混合 Yule +与出生–死亡模型,也不会混合不同出生率界限。精确续跑仍要求原始可执行文件。 + +验证包含来自固定版本 BEAST.base 2.7.8 的 24 个合成固定状态 +(`fixtures/validation/yule`)、零灭绝极限、独立模拟等待时间、树高和拓扑频率 +(有、无单系约束),以及幂后验证据与数值积分的比较。这些是正确性测试,不是 +速度或混合效率的比较声明。 diff --git a/fixtures/validation/yule/README.md b/fixtures/validation/yule/README.md new file mode 100644 index 0000000..b33e6bd --- /dev/null +++ b/fixtures/validation/yule/README.md @@ -0,0 +1,19 @@ +# Yule fixed-state reference + +`beast-2.7.8.tsv` contains 24 synthetic ladder trees: 2/3/5/8 tips, birth +rates 0.02/1.3/200, and successive node-height increments 0.001/0.7. +`provenance.json` pins the BEAST.base jar fingerprint and Java version. +No private matrix is used. No BEAST code is required at engine runtime. + +To regenerate with the pinned jar: + +```sh +javac --release 17 -cp /path/to/BEAST.base.jar -d /tmp/rove-yule tools/beast/YuleStates.java +java -cp /tmp/rove-yule:/path/to/BEAST.base.jar YuleStates > /tmp/yule.tsv +``` + +`tests/yule.rs` compares all three logged densities, derives the labeled-tree +normalization coefficient independently, and tests MCMC against a separate +waiting-time/pair-merger simulator, with and without monophyly. It also checks +the proper birth-rate prior. These are correctness checks, not performance +measurements. See the reference-model guide for model scope and constants. diff --git a/fixtures/validation/yule/beast-2.7.8.tsv b/fixtures/validation/yule/beast-2.7.8.tsv new file mode 100644 index 0000000..25cd450 --- /dev/null +++ b/fixtures/validation/yule/beast-2.7.8.tsv @@ -0,0 +1,25 @@ +tips birth_rate height_step yule_log_density zero_death_log_density labeled_log_density +2 0.02 0.001 -3.912063005428146 -3.912063005428146 -3.2189158248682004 +2 0.02 0.7 -3.940023005428146 -3.940023005428146 -3.2468758248682006 +2 1.3 0.001 0.25976426446749107 0.25976426446749107 0.9529114450274363 +2 1.3 0.7 -1.5576357355325088 -1.5576357355325088 -0.8644885549725635 +2 200.0 0.001 4.898317366548036 4.898317366548036 5.591464547107981 +2 200.0 0.7 -274.701682633452 -274.701682633452 -274.00853545289203 +3 0.02 0.001 -7.824146010856292 -7.824146010856292 -7.130998830296347 +3 0.02 0.7 -7.894046010856292 -7.894046010856292 -7.200898830296348 +3 1.3 0.001 0.5182285289349822 0.5182285289349822 1.211375709494927 +3 1.3 0.7 -4.025271471065017 -4.025271471065017 -3.3321242905050728 +3 200.0 0.001 9.596634733096073 9.596634733096073 10.289781913656018 +3 200.0 0.7 -689.403365266904 -689.403365266904 -688.710218086344 +5 0.02 0.001 -15.648372021712582 -15.648372021712582 -16.05383712982075 +5 0.02 0.7 -15.844092021712584 -15.844092021712584 -16.249557129820747 +5 1.3 0.001 1.0312570578699642 1.0312570578699642 0.6257919497617996 +5 1.3 0.7 -11.690542942130033 -11.690542942130033 -12.096008050238199 +5 200.0 0.001 18.393269466192145 18.393269466192145 17.98780435808398 +5 200.0 0.7 -1938.8067305338077 -1938.8067305338077 -1939.212195641916 +8 0.02 0.001 -27.38486103799702 -27.38486103799702 -31.057992135142815 +8 0.02 0.7 -27.874161037997023 -27.874161037997023 -31.54729213514282 +8 1.3 0.001 1.7910498512724373 1.7910498512724373 -1.8820812458733587 +8 1.3 0.7 -30.01345014872756 -30.01345014872756 -33.686581245873356 +8 200.0 0.001 30.088221565836253 30.088221565836253 26.415090468690455 +8 200.0 0.7 -4862.911778434163 -4862.911778434163 -4866.58490953131 diff --git a/fixtures/validation/yule/provenance.json b/fixtures/validation/yule/provenance.json new file mode 100644 index 0000000..c1175d6 --- /dev/null +++ b/fixtures/validation/yule/provenance.json @@ -0,0 +1,7 @@ +{ + "reference": "BEAST.base 2.7.8", + "java": "Temurin 17.0.15", + "jar_sha256": "7e2133989c1cc0a8d78e23917db90e86236e0b4f17213c5d439bfd908c93a359", + "generator": "tools/beast/YuleStates.java", + "scope": "24 fixed synthetic states; unscaled Yule, zero-extinction birth-death and labeled density constants; no MCMC or timing measurement" +} diff --git a/src/bin/rove/assessment.rs b/src/bin/rove/assessment.rs index fa77aed..ee10441 100644 --- a/src/bin/rove/assessment.rs +++ b/src/bin/rove/assessment.rs @@ -46,7 +46,20 @@ fn inventory(root: &Path, cancel: &dyn Fn() -> bool) -> Result 16 || out.len() >= 100_000 { return Err("run archive exceeds file/depth limit".into()); } - let path = root.join(relative); + let mut path = root.join(relative); + // Native CLI imports intentionally link their top-level results folder. + // Materialize that declared source; reject links inside its artifacts. + if depth == 0 + && relative == Path::new("results") + && root.join("setup.rove.json").is_file() + && root.join("session.json").is_file() + && fs::symlink_metadata(&path)?.file_type().is_symlink() + { + path = path.canonicalize()?; + if !path.is_dir() { + return Err("imported results must reference a directory".into()); + } + } let meta = fs::symlink_metadata(&path)?; if meta.file_type().is_symlink() { return Err("run archive contains a symbolic link".into()); @@ -331,7 +344,13 @@ pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { let output = parent .canonicalize()? .join(output.file_name().ok_or("invalid output directory")?); - if export && output.starts_with(&root) { + if export + && (output.starts_with(&root) + || root + .join("results") + .canonicalize() + .is_ok_and(|p| output.starts_with(p))) + { return Err("export destination must be outside the source run".into()); } if output.exists() { @@ -346,8 +365,21 @@ pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { write(&output.join("assessment.json"), &report)?; if export { let mut entries = Vec::new(); + let mut omitted_source_matrices = Vec::new(); for (relative, hash) in &before { check(&cancel)?; + // Predictive checks retain an exact original in source/matrix.nex. + // Matrix consent applies to that copy too, including foreign checks. + // Include only the explicitly supplied, verified matrix at package root. + if relative.file_name().is_some_and(|n| n == "matrix.nex") + && relative + .parent() + .and_then(Path::file_name) + .is_some_and(|n| n == "source") + { + omitted_source_matrices.push(relative); + continue; + } let target = output.join("run").join(relative); fs::create_dir_all(target.parent().unwrap())?; fs::copy(root.join(relative), &target)?; @@ -377,6 +409,7 @@ pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { "created_unix_seconds":report["created_unix_seconds"],"rove_version":env!("CARGO_PKG_VERSION"), "export_executable_sha256":sha256::file(&std::env::current_exe()?)?,"source":root, "matrix_included":matrix.is_some(),"files":entries, + "omitted_source_matrices":omitted_source_matrices, "exact_resume":"Requires a valid checkpoint, the original executable fingerprint and original model/input identity. This package does not include the executable. Paths in source records are preserved; review paths before reuse.", "scope":"Known Rove records, raw samples and derived-result folders; previous assessments, neighboring files and external comparison sources are not copied. Export does not certify convergence."}), )?; diff --git a/src/bin/rove/main.rs b/src/bin/rove/main.rs index ecdca00..2fe92c5 100644 --- a/src/bin/rove/main.rs +++ b/src/bin/rove/main.rs @@ -27,6 +27,7 @@ use rove::data::GapTreatment; use rove::mcmc::output::{TraceWriter, TreeWriter, is_plain_label}; use rove::mcmc::{Conditioning, Move, Sampler, Settings}; use rove::rates::SigmaPrior; +use rove::speciation::TreePrior; use rove::{Backend, nexus}; const USAGE: &str = @@ -34,6 +35,7 @@ const USAGE: &str = [--monophyly ]... [--gaps reject|missing] [--model strict|reference] [--conditioning variable|informative|none] [--sample-from-prior] [--clock-sigma-shape ] [--clock-sigma-scale ] + [--tree-prior birth-death|yule] [--birth-rate-upper ] [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--chains <1..16>] [--burnin-percent <0..99>] @@ -46,6 +48,7 @@ const USAGE: &str = [--monophyly ]... [--gaps reject|missing] [--model strict|reference] [--conditioning variable|informative|none] [--clock-sigma-shape ] [--clock-sigma-scale ] + [--tree-prior birth-death|yule] [--birth-rate-upper ] [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--print-every ] [--cancel-on-stdin-close] @@ -101,6 +104,8 @@ struct Options { conditioning: Conditioning, reference_model: bool, clock_sigma_prior: SigmaPrior, + tree_prior: TreePrior, + birth_rate_upper: f64, sample_from_prior: bool, tuning: bool, tuning_values: Vec<(Move, f64)>, @@ -138,6 +143,8 @@ fn parse_options(arguments: &[String]) -> Result { let mut reference_model = false; let mut sigma_shape = 5.0; let mut sigma_scale = 0.2; + let mut tree_prior = TreePrior::BirthDeath; + let mut birth_rate_upper = 1000.0f64; let mut sample_from_prior = false; let mut tuning = true; let mut tuning_values = Vec::new(); @@ -286,6 +293,18 @@ fn parse_options(arguments: &[String]) -> Result { } }; } + "--tree-prior" => { + tree_prior = match value("--tree-prior")?.as_str() { + "birth-death" => TreePrior::BirthDeath, + "yule" => TreePrior::Yule, + _ => return Err("--tree-prior must be birth-death or yule".into()), + }; + } + "--birth-rate-upper" => { + birth_rate_upper = value("--birth-rate-upper")? + .parse() + .map_err(|_| "--birth-rate-upper needs a number")? + } "--backend" => { let name = value("--backend")?; backend = Backend::ALL @@ -326,6 +345,17 @@ fn parse_options(arguments: &[String]) -> Result { return Err("clock sigma prior options require --model reference".into()); } let clock_sigma_prior = SigmaPrior::new(sigma_shape, sigma_scale).map_err(|e| e.to_string())?; + if !birth_rate_upper.is_finite() || birth_rate_upper <= 0.0 || birth_rate_upper / 2.0 == 0.0 { + return Err( + "--birth-rate-upper must be finite and positive with a representable interior".into(), + ); + } + if tree_prior != TreePrior::Yule && seen.contains("--birth-rate-upper") { + return Err("--birth-rate-upper requires --tree-prior yule".into()); + } + if tree_prior == TreePrior::Yule && dating.is_some() { + return Err("Yule does not support fossil dating or calibrations".into()); + } let options = Options { command, powers: match command { @@ -358,6 +388,8 @@ fn parse_options(arguments: &[String]) -> Result { conditioning, reference_model, clock_sigma_prior, + tree_prior, + birth_rate_upper, sample_from_prior, tuning, tuning_values, @@ -634,6 +666,11 @@ fn configure(options: &mut Options) -> Result> { if let Some(config) = &options.dating { settings.set_dating(dating::parse(config, taxa)?); } + if options.tree_prior == TreePrior::Yule { + settings.set_tree_prior(TreePrior::Yule); + settings.birth_difference_upper = options.birth_rate_upper; + settings.initial.birth_difference = 1.0f64.min(options.birth_rate_upper / 2.0); + } for &(kind, weight) in &options.weights { if let Some(entry) = settings.weights.iter_mut().find(|(k, _)| *k == kind) { entry.1 = weight; @@ -686,7 +723,7 @@ fn model_json( Conditioning::None => "none (Mk)", }; let names = |tips: &[usize]| Json::List(tips.iter().map(|&t| Json::text(&taxa[t])).collect()); - Json::Object(vec![ + let mut fields = vec![ ("partitioning", Json::text(options.partitioning.name())), ("partitions", partitions::describe(patterns)), ( @@ -820,6 +857,8 @@ fn model_json( "FBD joint sampling density, origin-conditioned, removal probability zero, no survival conditioning; observed specimen count, age evidence and imposed terminal/clade constraints inform process parameters; not a parameter-wise normalized restricted tree prior or marginal likelihood" } else if settings.dating.is_some() { "FBD, fixed origin and process parameters, removal probability zero, restricted to terminal fossils and supplied age bounds; unnormalized restricted density, not model evidence" + } else if settings.tree_prior == TreePrior::Yule { + "Yule pure birth, unscaled, complete sampling, conditioned on tip count; no root/origin conditioning or calibrations" } else { "birth-death (Gernhard 2008), unscaled, every lineage sampled, conditioned on the number of tips" }, @@ -827,7 +866,7 @@ fn model_json( ), ( "birth_difference_rate_prior", - if settings.dating.is_some() { + if settings.dating.is_some() || settings.tree_prior == TreePrior::Yule { Json::Null } else { Json::text(format!("Uniform(0, {})", settings.birth_difference_upper)) @@ -835,7 +874,7 @@ fn model_json( ), ( "relative_death_rate_prior", - if settings.dating.is_some() { + if settings.dating.is_some() || settings.tree_prior == TreePrior::Yule { Json::Null } else { Json::text("Uniform(0, 1)") @@ -846,7 +885,26 @@ fn model_json( "monophyly", Json::List(settings.monophyly.iter().map(|c| names(c)).collect()), ), - ]) + ]; + if settings.tree_prior == TreePrior::Yule { + fields.extend([ + ("tree_prior_kind", Json::text("yule")), + ( + "birth_rate_prior_parameters", + Json::Object(vec![ + ("distribution", Json::text("uniform")), + ("lower", Json::Number(0.0)), + ("upper", Json::Number(settings.birth_difference_upper)), + ("log_density", Json::Number(-settings.birth_difference_upper.ln())), + ]), + ), + ( + "tree_density_normalization", + Json::text("unscaled BEAST convention; the labeled-tree multiplier 2^(n-1)/(n-1)! is parameter-independent and cancels in power-posterior ratios; monophyly restricts the prior domain"), + ), + ]); + } + Json::Object(fields) } fn optional(value: Option) -> Json { @@ -1141,11 +1199,27 @@ fn run_chain( ("sample_every", Json::Integer(options.sample_every)), ( "initial_birth_difference_rate", - Json::Number(settings.initial.birth_difference), + if settings.tree_prior == TreePrior::Yule { + Json::Null + } else { + Json::Number(settings.initial.birth_difference) + }, + ), + ( + "initial_birth_rate", + if settings.tree_prior == TreePrior::Yule { + Json::Number(settings.initial.birth_difference) + } else { + Json::Null + }, ), ( "initial_relative_death_rate", - Json::Number(settings.initial.relative_death), + if settings.tree_prior == TreePrior::Yule { + Json::Null + } else { + Json::Number(settings.initial.relative_death) + }, ), ( "initial_tree", diff --git a/src/bin/rove/predict.rs b/src/bin/rove/predict.rs index 2ff5187..c594653 100644 --- a/src/bin/rove/predict.rs +++ b/src/bin/rove/predict.rs @@ -292,6 +292,27 @@ pub(super) fn run(args: &[String]) -> Result<()> { } else { record["model"]["clock_multiplier"] == 1.0 }; + let yule_upper = match record["model"]["tree_prior_kind"].as_str() { + None => None, + Some("yule") => { + let prior = &record["model"]["birth_rate_prior_parameters"]; + let upper = prior["upper"] + .as_f64() + .filter(|u| u.is_finite() && *u > 0.0 && *u / 2.0 > 0.0) + .ok_or("invalid Yule birth-rate prior")?; + if dating.is_some() + || prior["distribution"] != "uniform" + || prior["lower"] != 0.0 + || prior["log_density"] + .as_f64() + .is_none_or(|v| (v + upper.ln()).abs() > 1e-12) + { + return Err("unsupported Yule prior or dated tips".into()); + } + Some(upper) + } + _ => return Err("unsupported tree prior".into()), + }; if !multiplier_matches || record["model"]["mutation_rate"] != 1.0 { return Err("unsupported rate multiplier".into()); } @@ -387,6 +408,11 @@ pub(super) fn run(args: &[String]) -> Result<()> { Settings::default() } }; + if let Some(upper) = yule_upper { + settings.set_tree_prior(rove::speciation::TreePrior::Yule); + settings.birth_difference_upper = upper; + settings.initial.birth_difference = column(&trace, "birth_rate", row)?; + } if let Some(dating) = &dating { let mut live = dating.clone(); if let Some(priors) = dating.process_priors { diff --git a/src/mcmc/checkpoint.rs b/src/mcmc/checkpoint.rs index a5bd0a4..080bb09 100644 --- a/src/mcmc/checkpoint.rs +++ b/src/mcmc/checkpoint.rs @@ -7,7 +7,7 @@ use crate::random::Random; use crate::rates::{GammaRates, RateVariation, RelaxedClock}; use crate::tree::Tree; -const MAGIC: &[u8; 8] = b"ROVECP06"; +const MAGIC: &[u8; 8] = b"ROVECP07"; impl Sampler { /// Saves a between-proposals state, including the live likelihood buffers. @@ -59,9 +59,11 @@ impl Sampler { write_f64(&mut out, v)?; } } + write_f64(&mut out, self.speciation.rate())?; + if let Some(p) = self.speciation.birth_death() { + write_f64(&mut out, p.relative_death)?; + } for value in [ - self.birth_death.birth_difference, - self.birth_death.relative_death, self.posterior.likelihood, self.posterior.tree_prior, self.posterior.parameter_prior, @@ -186,7 +188,12 @@ impl Sampler { }; let mut initial = settings.clone(); initial.initial.birth_difference = read_f64(&mut input)?; - initial.initial.relative_death = read_f64(&mut input)?; + initial.initial.relative_death = + if settings.tree_prior == crate::speciation::TreePrior::BirthDeath { + read_f64(&mut input)? + } else { + 0.0 + }; let mut sampler = Self::from_tree( patterns, &initial, diff --git a/src/mcmc/coupled.rs b/src/mcmc/coupled.rs index 8b0dc84..f04bf70 100644 --- a/src/mcmc/coupled.rs +++ b/src/mcmc/coupled.rs @@ -369,7 +369,8 @@ mod tests { let mut birth = crate::speciation::BirthDeath { birth_difference: 1.0, relative_death: 0.5, - }; + } + .into(); for step in 0..250_000 { if random.uniform() < 0.15 { // Exact independent conditional draws for a known target. diff --git a/src/mcmc/mod.rs b/src/mcmc/mod.rs index 435245c..ad2adf5 100644 --- a/src/mcmc/mod.rs +++ b/src/mcmc/mod.rs @@ -23,7 +23,7 @@ use crate::data::Patterns; use crate::model::{CharacterOrdering, Mk}; use crate::random::Random; use crate::rates::{self, GammaRates, RateVariation, RelaxedClock}; -use crate::speciation::BirthDeath; +use crate::speciation::{BirthDeath, SpeciationState, TreePrior}; use crate::tree::Tree; use crate::{Backend, LikelihoodCore, Scaling}; @@ -139,6 +139,7 @@ pub struct Settings { /// Tip sets that must stay monophyletic. pub monophyly: Vec>, pub birth_difference_upper: f64, + pub tree_prior: TreePrior, pub initial: BirthDeath, /// Relative selection weights; a move with weight zero is never chosen. pub weights: Vec<(Move, f64)>, @@ -166,6 +167,7 @@ impl Default for Settings { likelihood_power: 1.0, monophyly: Vec::new(), birth_difference_upper: 1000.0, + tree_prior: TreePrior::BirthDeath, initial: BirthDeath { birth_difference: 1.0, relative_death: 0.5, @@ -190,6 +192,28 @@ impl Default for Settings { } impl Settings { + /// Select an undated tree prior, replacing its parameter proposals. + pub fn set_tree_prior(&mut self, prior: TreePrior) { + self.tree_prior = prior; + self.weights.retain(|(m, _)| { + !matches!( + m, + Move::BirthDifferenceScale | Move::RelativeDeathScale | Move::BirthRateScale + ) + }); + match prior { + TreePrior::Yule => { + self.initial.relative_death = 0.0; + self.weights.push((Move::BirthRateScale, 3.0)); + } + TreePrior::BirthDeath => { + self.weights.extend([ + (Move::BirthDifferenceScale, 3.0), + (Move::RelativeDeathScale, 3.0), + ]); + } + } + } pub fn set_dating(&mut self, dating: crate::dating::Dating) { self.weights.retain(|(m, _)| { !m.changes_fbd() @@ -453,7 +477,7 @@ pub struct Sampler { tree: Tree, rates: RateVariation, stored_rates: RateVariation, - birth_death: BirthDeath, + speciation: SpeciationState, stored_tree: Tree, likelihoods: Vec, patterns: Vec, @@ -548,6 +572,14 @@ impl Sampler { random: Random, ) -> Result { let tips = tree.tips(); + if !settings.birth_difference_upper.is_finite() || settings.birth_difference_upper <= 0.0 { + return Err(Error::InitialState); + } + if settings.tree_prior == TreePrior::Yule && settings.dating.is_some() { + return Err(Error::Dating( + "Yule requires contemporaneous tips without fossil dating or calibrations".into(), + )); + } if patterns.is_empty() || patterns.iter().any(|p| p.tip_partials().len() != tips) { return Err(Error::Partitions); } @@ -596,6 +628,17 @@ impl Sampler { return Err(Error::Rates(rates::Error::BranchRates)); } for &(kind, weight) in &settings.weights { + if weight > 0.0 + && ((settings.tree_prior == TreePrior::Yule + && matches!(kind, Move::BirthDifferenceScale | Move::RelativeDeathScale)) + || (kind == Move::BirthRateScale + && (settings.tree_prior != TreePrior::Yule || settings.dating.is_some()))) + { + return Err(Error::Dating(format!( + "{} is incompatible with the selected tree prior", + kind.name() + ))); + } 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())); } @@ -652,6 +695,13 @@ impl Sampler { return Err(Error::Weights); } for &(kind, value) in &settings.tuning_values { + if (settings.tree_prior == TreePrior::Yule + && matches!(kind, Move::BirthDifferenceScale | Move::RelativeDeathScale)) + || (kind == Move::BirthRateScale + && (settings.tree_prior != TreePrior::Yule || settings.dating.is_some())) + { + return Err(Error::Tuning(kind)); + } let in_range = match kind { Move::SubtreeSlide => value > 0.0, _ => value > 0.0 && value < 1.0, @@ -703,7 +753,12 @@ impl Sampler { stored_rates: rates.clone(), rates, tree, - birth_death: settings.initial, + speciation: match settings.tree_prior { + TreePrior::BirthDeath => settings.initial.into(), + TreePrior::Yule => SpeciationState::Yule { + birth_rate: settings.initial.birth_difference, + }, + }, likelihoods, patterns: patterns.to_vec(), conditioning: settings.conditioning, @@ -752,8 +807,14 @@ impl Sampler { self.fbd } - pub fn birth_death(&self) -> BirthDeath { - self.birth_death + pub fn birth_death(&self) -> Option { + self.speciation.birth_death() + } + pub fn tree_prior(&self) -> TreePrior { + self.speciation.kind() + } + pub fn speciation_rate(&self) -> f64 { + self.speciation.rate() } pub fn posterior(&self) -> Posterior { @@ -785,10 +846,11 @@ impl Sampler { fn priors(&self) -> Posterior { #[cfg(feature = "profile-sampler")] let _profile = crate::profiling::enter(crate::profiling::Phase::Priors); - let BirthDeath { - birth_difference: r, - relative_death: a, - } = self.birth_death; + let r = self.speciation.rate(); + let a = self + .speciation + .birth_death() + .map_or(0.0, |p| p.relative_death); let upper = self.birth_difference_upper; let parameters = if (0.0..=upper).contains(&r) && (0.0..=1.0).contains(&a) { -upper.ln() @@ -798,7 +860,7 @@ impl Sampler { Posterior { likelihood: 0.0, tree_prior: self.dating.as_ref().map_or_else( - || self.birth_death.log_density(&self.tree), + || self.speciation.log_density(&self.tree), |_| self.fbd.unwrap().log_density(&self.tree), ), parameter_prior: self.dating.as_ref().map_or(parameters, |d| { @@ -856,7 +918,7 @@ impl Sampler { self.steps += 1; let index = self.choose(); let kind = self.operators[index].kind; - let stored_birth_death = self.birth_death; + let stored_speciation = self.speciation; let stored_fbd = self.fbd; self.stored_tree.clone_from(&self.tree); self.stored_rates.clone_from(&self.rates); @@ -884,7 +946,7 @@ impl Sampler { } else { kind.propose( &mut self.tree, - &mut self.birth_death, + &mut self.speciation, &mut self.rates, self.birth_difference_upper, self.operators[index].tuning, @@ -926,7 +988,7 @@ impl Sampler { } if !accepted { std::mem::swap(&mut self.tree, &mut self.stored_tree); - self.birth_death = stored_birth_death; + self.speciation = stored_speciation; self.fbd = stored_fbd; std::mem::swap(&mut self.rates, &mut self.stored_rates); for likelihood in &mut self.likelihoods { diff --git a/src/mcmc/moves.rs b/src/mcmc/moves.rs index 5de93f1..1c998a9 100644 --- a/src/mcmc/moves.rs +++ b/src/mcmc/moves.rs @@ -6,7 +6,7 @@ use super::coupled; use crate::random::Random; use crate::rates::{GammaRates, RateVariation}; -use crate::speciation::BirthDeath; +use crate::speciation::SpeciationState; use crate::tree::Tree; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -48,10 +48,12 @@ pub enum Move { ClockSigmaRates, /// Narrow exchange with compensation of the two reattached branch rates. NarrowExchangeRates, + /// Scale the pure-birth rate of a Yule prior. + BirthRateScale, } impl Move { - pub const ALL: [Move; 23] = [ + pub const ALL: [Move; 24] = [ Move::FbdBirthScale, Move::FbdDeathScale, Move::FbdSamplingScale, @@ -75,6 +77,7 @@ impl Move { Move::RootTimeRates, Move::ClockSigmaRates, Move::NarrowExchangeRates, + Move::BirthRateScale, ]; pub fn name(self) -> &'static str { @@ -102,6 +105,7 @@ impl Move { Self::RootTimeRates => "root_time_rates", Self::ClockSigmaRates => "clock_sigma_rates", Self::NarrowExchangeRates => "narrow_exchange_rates", + Self::BirthRateScale => "birth_rate_scale", } } @@ -118,6 +122,7 @@ impl Move { | Self::RootScale | Self::TreeScale | Self::BirthDifferenceScale + | Self::BirthRateScale | Self::RelativeDeathScale | Self::RootTimeRates => Some(0.75), Self::GammaShapeScale @@ -189,7 +194,7 @@ impl Move { pub(crate) fn propose( self, tree: &mut Tree, - birth_death: &mut BirthDeath, + speciation: &mut SpeciationState, rates: &mut RateVariation, upper: f64, tuning: Option, @@ -215,9 +220,23 @@ impl Move { Self::RootScale => root_scale(tree, tuning, random), Self::TreeScale => tree_scale(tree, tuning, random), Self::BirthDifferenceScale => { - scale(&mut birth_death.birth_difference, upper, tuning, random) + let SpeciationState::BirthDeath(parameters) = speciation else { + return None; + }; + scale(&mut parameters.birth_difference, upper, tuning, random) + } + Self::BirthRateScale => { + let SpeciationState::Yule { birth_rate } = speciation else { + return None; + }; + scale(birth_rate, upper, tuning, random) + } + Self::RelativeDeathScale => { + let SpeciationState::BirthDeath(parameters) = speciation else { + return None; + }; + scale(&mut parameters.relative_death, 1.0, tuning, random) } - Self::RelativeDeathScale => scale(&mut birth_death.relative_death, 1.0, tuning, random), Self::GammaShapeScale => { let shape = rates.gamma.as_ref()?.shape(); let factor = scaler(tuning, random); @@ -625,7 +644,8 @@ mod tests { let mut birth_death = BirthDeath { birth_difference: 1.0, relative_death: 0.5, - }; + } + .into(); let mut current = log_target(&tree); let mut counts: HashMap, usize> = HashMap::new(); for step in 0..steps { diff --git a/src/mcmc/output.rs b/src/mcmc/output.rs index c0f9525..dc04aab 100644 --- a/src/mcmc/output.rs +++ b/src/mcmc/output.rs @@ -26,6 +26,7 @@ pub struct TraceWriter { dated: bool, ages: usize, process: bool, + yule: bool, } impl TraceWriter { @@ -38,6 +39,7 @@ impl TraceWriter { dated: rates.mean.is_some(), ages: 0, process: false, + yule: false, } } @@ -45,6 +47,7 @@ impl TraceWriter { let mut writer = Self::resume(out, sampler.rates()); writer.ages = sampler.dating().map_or(0, |d| d.ages.len()); writer.process = sampler.dating().is_some_and(|d| d.process_priors.is_some()); + writer.yule = sampler.tree_prior() == crate::speciation::TreePrior::Yule; writer } @@ -55,6 +58,7 @@ impl TraceWriter { sampler.rates(), sampler.dating().map_or(0, |d| d.ages.len()), sampler.dating().is_some_and(|d| d.process_priors.is_some()), + sampler.tree_prior() == crate::speciation::TreePrior::Yule, ) } @@ -63,7 +67,7 @@ impl TraceWriter { } pub fn with_rates(out: W, comments: &[String], rates: &RateVariation) -> io::Result { - Self::header(out, comments, rates, 0, false) + Self::header(out, comments, rates, 0, false, false) } fn header( @@ -72,6 +76,7 @@ impl TraceWriter { rates: &RateVariation, ages: usize, process: bool, + yule: bool, ) -> io::Result { for comment in comments { writeln!(out, "# {comment}")?; @@ -81,6 +86,11 @@ impl TraceWriter { out, "Sample\tposterior\tlikelihood\tprior\tfossilized_birth_death\tclock_rate\tdating_parameter_prior\ttree_height\ttree_length" )?; + } else if yule { + write!( + out, + "Sample\tposterior\tlikelihood\tprior\tyule\tbirth_rate\ttree_height\ttree_length" + )?; } else { write!(out, "{}", TRACE_COLUMNS.join("\t"))?; } @@ -110,6 +120,7 @@ impl TraceWriter { dated: rates.mean.is_some(), ages, process, + yule, }) } @@ -122,6 +133,7 @@ impl TraceWriter { if self.gamma != sampler.rates().gamma.is_some() || self.clock != sampler.rates().clock.is_some() || self.dated != sampler.rates().mean.is_some() + || self.yule != (sampler.tree_prior() == crate::speciation::TreePrior::Yule) { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -130,17 +142,27 @@ impl TraceWriter { } write!( self.out, - "{sample}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", + "{sample}\t{}\t{}\t{}\t{}\t{}", posterior.total(), posterior.likelihood, posterior.prior(), posterior.tree_prior, - sampler.rates().mean.unwrap_or(birth_death.birth_difference), - if self.dated { - posterior.parameter_prior - } else { - birth_death.relative_death - }, + sampler.rates().mean.unwrap_or(sampler.speciation_rate()), + )?; + if !self.yule { + write!( + self.out, + "\t{}", + if self.dated { + posterior.parameter_prior + } else { + birth_death.unwrap().relative_death + } + )?; + } + write!( + self.out, + "\t{}\t{}", tree.height(tree.root()), tree.tree_length() )?; diff --git a/src/speciation.rs b/src/speciation.rs index 47e8ead..8abad84 100644 --- a/src/speciation.rs +++ b/src/speciation.rs @@ -1,10 +1,73 @@ //! The birth–death tree prior of Gernhard (2008), as BEAST 2.7 evaluates //! `BirthDeathGernhard08Model` with `type="unscaled"`: every extant lineage is //! sampled, and the density is conditioned on the number of tips but not on -//! the root height or an origin. +//! the root height or an origin. Optional Yule uses the same convention with +//! a birth rate and no extinction coordinate. use crate::tree::Tree; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TreePrior { + BirthDeath, + Yule, +} + +/// The live undated speciation parameters. Yule has no extinction coordinate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum SpeciationState { + BirthDeath(BirthDeath), + Yule { birth_rate: f64 }, +} + +impl SpeciationState { + pub fn rate(&self) -> f64 { + match *self { + Self::BirthDeath(p) => p.birth_difference, + Self::Yule { birth_rate } => birth_rate, + } + } + pub fn birth_death(&self) -> Option { + match *self { + Self::BirthDeath(p) => Some(p), + Self::Yule { .. } => None, + } + } + pub fn log_density(&self, tree: &Tree) -> f64 { + match *self { + Self::BirthDeath(p) => p.log_density(tree), + Self::Yule { birth_rate } => yule_log_density(tree, birth_rate), + } + } + pub fn kind(&self) -> TreePrior { + match self { + Self::BirthDeath(_) => TreePrior::BirthDeath, + Self::Yule { .. } => TreePrior::Yule, + } + } +} + +impl From for SpeciationState { + fn from(value: BirthDeath) -> Self { + Self::BirthDeath(value) + } +} + +/// BEAST 2.7.8's unscaled, tip-count-conditioned Yule convention. The root +/// contributes twice; no root/origin conditioning or tip calibrations. +pub fn yule_log_density(tree: &Tree, birth_rate: f64) -> f64 { + if !birth_rate.is_finite() + || birth_rate <= 0.0 + || (0..tree.tips()).any(|t| tree.height(t) != 0.0) + { + return f64::NEG_INFINITY; + } + let total = (tree.tips()..tree.nodes()) + .map(|n| tree.height(n)) + .sum::() + + tree.height(tree.root()); + (tree.tips() - 1) as f64 * birth_rate.ln() - birth_rate * total +} + #[derive(Clone, Copy, Debug, PartialEq)] pub struct BirthDeath { /// λ − μ, the net diversification rate. diff --git a/tests/assessment_cli.rs b/tests/assessment_cli.rs index 93489d8..04981d7 100644 --- a/tests/assessment_cli.rs +++ b/tests/assessment_cli.rs @@ -220,3 +220,65 @@ fn exports_reject_symlinked_artifacts() { ); assert!(!root.join("package").exists()); } + +#[test] +fn predictive_source_copies_respect_matrix_consent() { + let root = fixture("assessment-predictive-matrix-consent", "1"); + fs::create_dir(root.join("run/predictions")).unwrap(); + good(call(&[ + "predict", + root.join("run").to_str().unwrap(), + "--matrix", + root.join("matrix.nex").to_str().unwrap(), + "--output", + root.join("run/predictions/check").to_str().unwrap(), + "--seed", + "7", + "--replicates", + "2", + "--burnin-percent", + "10", + ])); + let original = root.join("run/predictions/check/source/matrix.nex"); + assert!(original.exists()); + for include in [false, true] { + let name = if include { "included" } else { "excluded" }; + let package = root.join(name); + let source = root.join("run"); + let matrix = root.join("matrix.nex"); + let mut args = vec![ + "export-run", + source.to_str().unwrap(), + "--output", + package.to_str().unwrap(), + ]; + if include { + args.extend(["--include-matrix", matrix.to_str().unwrap()]); + } + good(call(&args)); + assert_eq!(package.join("matrix.nex").exists(), include); + assert!( + !package + .join("run/predictions/check/source/matrix.nex") + .exists() + ); + assert!( + package + .join("run/predictions/check/matrices/replicate-00001.nex") + .exists() + ); + let manifest = read(package.join("manifest.json")); + assert_eq!( + manifest["omitted_source_matrices"][0], + "predictions/check/source/matrix.nex" + ); + assert_eq!( + status(&read(package.join("assessment.json")), "prediction"), + "review_required" + ); + } + assert_eq!( + fs::read(original).unwrap(), + fs::read(root.join("matrix.nex")).unwrap() + ); +} diff --git a/tests/checkpoint.rs b/tests/checkpoint.rs index 0e9eebe..9349e7d 100644 --- a/tests/checkpoint.rs +++ b/tests/checkpoint.rs @@ -77,6 +77,7 @@ fn pause_crash_and_resume_preserve_all_samples_and_moves() { for (kind, matrix, conditioning) in [ ("binary", MATRIX, "variable"), ("sigma-prior", MATRIX, "variable"), + ("yule", MATRIX, "variable"), ("dated", MATRIX, "variable"), ( "multistate", @@ -99,6 +100,9 @@ fn pause_crash_and_resume_preserve_all_samples_and_moves() { fs::write(root.join("matrix.nex"), matrix).unwrap(); let configured = |name: &str| { let mut cmd = command(&root, name, chains); + if kind == "yule" { + cmd.args(["--tree-prior", "yule", "--birth-rate-upper", "4"]); + } if kind == "sigma-prior" { cmd.args(["--clock-sigma-shape", "2.5", "--clock-sigma-scale", "0.4"]); } diff --git a/tests/marginal.rs b/tests/marginal.rs index 3dfca13..4a7afba 100644 --- a/tests/marginal.rs +++ b/tests/marginal.rs @@ -187,3 +187,19 @@ fn power_posteriors_recover_the_quadrature_evidence_of_a_three_taxon_tree() { ); assert!(analysis.powers.iter().all(|p| p.ess.unwrap() > 1000.0)); } + +#[test] +fn yule_power_posteriors_recover_normalized_evidence() { + let patterns = three_taxa(); + let mut settings = one_height_settings(); + settings.set_tree_prior(rove::speciation::TreePrior::Yule); + // Fix lambda and the root: only the inner height is integrated here. + settings.weights = vec![(Move::NodeHeight, 1.0)]; + let expected = quadrature_log_evidence(&patterns, &settings, 8000); + let analysis = power_chain_analysis(&patterns, &settings, 53); + let estimate = analysis.stepping_stone; + assert!( + (estimate.log_marginal_likelihood - expected).abs() + < 4.0 * estimate.standard_error.unwrap() + 0.005 + ); +} diff --git a/tests/sampler.rs b/tests/sampler.rs index a711962..2e89dec 100644 --- a/tests/sampler.rs +++ b/tests/sampler.rs @@ -137,7 +137,7 @@ fn sample_prior(settings: &Settings, steps: u64, thin: u64, seed: u64) -> PriorS sampler.step(); if step % thin == 0 { let tree = sampler.tree(); - let birth_death = sampler.birth_death(); + let birth_death = sampler.birth_death().unwrap(); *sample.topologies.entry(clades(tree)).or_default() += 1; sample .root @@ -269,7 +269,7 @@ fn the_rate_parameters_keep_their_uniform_priors() { for step in 1..=2_000_000u64 { sampler.step(); if step % 10 == 0 { - let birth_death = sampler.birth_death(); + let birth_death = sampler.birth_death().unwrap(); let tree = sampler.tree(); r += birth_death.birth_difference / settings.birth_difference_upper; a += birth_death.relative_death; diff --git a/tests/yule.rs b/tests/yule.rs new file mode 100644 index 0000000..a8023d8 --- /dev/null +++ b/tests/yule.rs @@ -0,0 +1,190 @@ +use rove::data::{GapTreatment, Patterns}; +use rove::mcmc::{Move, Sampler, Settings}; +use rove::nexus; +use rove::random::Random; +use rove::speciation::{BirthDeath, TreePrior, yule_log_density}; +use rove::tree::Tree; +use std::collections::BTreeMap; + +fn ladder(tips: usize, step: f64) -> Tree { + let mut children = vec![None; tips]; + let mut heights = vec![0.0; tips]; + for i in 0..tips - 1 { + children.push(Some((if i == 0 { 0 } else { tips + i - 1 }, i + 1))); + heights.push((i + 1) as f64 * step); + } + Tree::new(children, heights).unwrap() +} + +#[test] +fn pinned_beast_densities_zero_extinction_and_labeled_constants() { + let table = include_str!("../fixtures/validation/yule/beast-2.7.8.tsv"); + assert_eq!(table.lines().count(), 25); + for row in table.lines().skip(1) { + let values: Vec = row.split('\t').map(|s| s.parse().unwrap()).collect(); + let n = values[0] as usize; + let tree = ladder(n, values[2]); + let actual = yule_log_density(&tree, values[1]); + let bd = BirthDeath { + birth_difference: values[1], + relative_death: 0.0, + }; + assert!((actual - values[3]).abs() < 1e-10, "{row}"); + assert!((actual - values[4]).abs() < 1e-10); + assert!((actual - bd.log_density(&tree)).abs() < 1e-10); + // A backwards simulation draws Exp(k*lambda) waits and one of k(k-1)/2 + // pairs at each event. Their density contributes 2/(k-1) per event. + let log_coefficient: f64 = (2..=n).map(|k| (2.0 / (k - 1) as f64).ln()).sum(); + assert!((actual + log_coefficient - values[5]).abs() < 1e-10); + } + for rate in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(yule_log_density(&ladder(3, 1.0), rate), f64::NEG_INFINITY); + } + let dated = Tree::new(vec![None, None, Some((0, 1))], vec![0.0, 0.2, 1.0]).unwrap(); + assert_eq!(yule_log_density(&dated, 1.0), f64::NEG_INFINITY); +} + +fn patterns() -> Patterns { + let matrix = + nexus::parse("#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=1; MATRIX a 0 b 0 c 1 d 1; END;") + .unwrap(); + matrix + .compress(std::slice::from_ref(&(0..1)), GapTreatment::Reject) + .unwrap() + .remove(0) +} + +fn clades(tree: &Tree) -> Vec { + let mut masks = vec![0; tree.nodes()]; + for n in tree.postorder() { + masks[n] = tree + .children(n) + .map_or(1 << n, |(a, b)| masks[a] | masks[b]); + } + let mut clades = masks[tree.tips()..].to_vec(); + clades.sort_unstable(); + clades +} + +/// Independent generative prior; no engine density or proposal is used. +fn prior_tree(random: &mut Random, tips: usize, rate: f64) -> Tree { + let mut active: Vec<_> = (0..tips).collect(); + let mut children = vec![None; tips]; + let mut heights = vec![0.0; tips]; + let mut height = 0.0; + while active.len() > 1 { + height += random.exponential() / (active.len() as f64 * rate); + let a = active.swap_remove(random.below(active.len())); + let b = active.swap_remove(random.below(active.len())); + active.push(children.len()); + children.push(Some((a, b))); + heights.push(height); + } + Tree::new(children, heights).unwrap() +} + +fn scaled_statistics(tree: &Tree, rate: f64) -> [f64; 4] { + let mut heights: Vec<_> = (tree.tips()..tree.nodes()) + .map(|n| tree.height(n)) + .collect(); + heights.sort_by(f64::total_cmp); + [ + 4.0 * rate * heights[0], + 3.0 * rate * (heights[1] - heights[0]), + 2.0 * rate * (heights[2] - heights[1]), + rate * heights[2], + ] +} + +#[test] +fn prior_sampling_matches_independent_waits_heights_and_topologies_with_constraints() { + for constrained in [false, true] { + let mut settings = Settings { + sample_from_prior: true, + birth_difference_upper: 3.0, + ..Settings::default() + }; + settings.set_tree_prior(TreePrior::Yule); + if constrained { + settings.monophyly = vec![vec![0, 1]]; + } + let mut random = Random::new(71); + let mut expected = BTreeMap::, usize>::new(); + let mut independent = [0.0; 4]; + let mut draws = 0; + let mut attempts = 0; + while draws < 20_000 { + attempts += 1; + let tree = prior_tree(&mut random, 4, 1.3); + let key = clades(&tree); + if constrained && !key.contains(&3) { + continue; + } + *expected.entry(key).or_default() += 1; + for (total, value) in independent.iter_mut().zip(scaled_statistics(&tree, 1.3)) { + *total += value; + } + draws += 1; + } + if constrained { + assert!((20_000.0 / attempts as f64 - 2.0 / 9.0).abs() < 0.01); + } + let mut sampler = Sampler::new(patterns(), &settings, 83).unwrap(); + assert!(sampler.birth_death().is_none()); + let mut observed = BTreeMap::, usize>::new(); + let mut totals = [0.0; 4]; + let mut rate_sum = 0.0; + for step in 0..330_000 { + sampler.step(); + if step < 30_000 || step % 10 != 0 { + continue; + } + let key = clades(sampler.tree()); + if constrained { + assert!(key.contains(&3)); + } + *observed.entry(key).or_default() += 1; + let rate = sampler.speciation_rate(); + assert!((0.0..3.0).contains(&rate)); + rate_sum += rate; + for (total, value) in totals + .iter_mut() + .zip(scaled_statistics(sampler.tree(), rate)) + { + *total += value; + } + } + assert!((rate_sum / 30_000.0 - 1.5).abs() < 0.10, "{rate_sum}"); + for (i, target) in [1.0, 1.0, 1.0, 13.0 / 12.0].into_iter().enumerate() { + assert!((independent[i] / 20_000.0 - target).abs() < 0.025); + assert!( + (totals[i] / 30_000.0 - target).abs() < 0.08, + "{constrained}: {totals:?}" + ); + } + assert_eq!(observed.len(), expected.len()); + for (topology, count) in expected { + assert!( + (observed[&topology] as f64 / 30_000.0 - count as f64 / 20_000.0).abs() < 0.035 + ); + } + } +} + +#[test] +fn extinction_proposals_and_inert_tuning_are_rejected_for_yule() { + for movement in [Move::BirthDifferenceScale, Move::RelativeDeathScale] { + let mut settings = Settings::default(); + settings.set_tree_prior(TreePrior::Yule); + settings.tuning_values = vec![(movement, 0.5)]; + assert!(Sampler::new(patterns(), &settings, 1).is_err()); + settings.tuning_values.clear(); + settings.weights.push((movement, 1.0)); + assert!(Sampler::new(patterns(), &settings, 1).is_err()); + } + let settings = Settings { + tuning_values: vec![(Move::BirthRateScale, 0.5)], + ..Settings::default() + }; + assert!(Sampler::new(patterns(), &settings, 1).is_err()); +} diff --git a/tests/yule_cli.rs b/tests/yule_cli.rs new file mode 100644 index 0000000..ce6cb0f --- /dev/null +++ b/tests/yule_cli.rs @@ -0,0 +1,54 @@ +use std::fs; +use std::path::Path; +use std::process::Command; + +const BIN: &str = env!("CARGO_BIN_EXE_rove"); + +#[test] +fn incompatible_yule_options_fail_before_creating_output() { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("yule-invalid"); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let matrix = root.join("matrix.nex"); + fs::write( + &matrix, + "#NEXUS BEGIN DATA; DIMENSIONS NTAX=3 NCHAR=1; MATRIX a 0 b 1 c 0; END;", + ) + .unwrap(); + for options in [ + vec!["--tree-prior", "unknown"], + vec!["--birth-rate-upper", "4"], + vec!["--tree-prior", "yule", "--birth-rate-upper", "0"], + vec!["--tree-prior", "yule", "--birth-rate-upper", "nan"], + vec!["--tree-prior", "yule", "--birth-rate-upper", "1e-999"], + vec!["--tree-prior", "yule", "--dating-json", "{}"], + vec!["--tree-prior", "yule", "--weight", "relative_death_scale=1"], + vec![ + "--tree-prior", + "yule", + "--tuning", + "birth_difference_scale=0.5", + ], + vec!["--tuning", "birth_rate_scale=0.5"], + ] { + let output = root.join("rejected"); + let result = Command::new(BIN) + .arg("sample") + .arg(&matrix) + .args([ + "--steps", + "20", + "--sample-every", + "10", + "--seed", + "42", + "--output", + ]) + .arg(&output) + .args(&options) + .output() + .unwrap(); + assert!(!result.status.success(), "{options:?}"); + assert!(!output.exists(), "{options:?}"); + } +} diff --git a/tools/beast/YuleStates.java b/tools/beast/YuleStates.java new file mode 100644 index 0000000..93a1aca --- /dev/null +++ b/tools/beast/YuleStates.java @@ -0,0 +1,37 @@ +import beast.base.evolution.speciation.YuleModel; +import beast.base.evolution.speciation.BirthDeathGernhard08Model; +import beast.base.evolution.tree.Node; +import beast.base.evolution.tree.Tree; +import beast.base.inference.parameter.RealParameter; + +/** Fixed, synthetic states for BEAST.base 2.7.8. No MCMC or timing study. */ +public class YuleStates { + static RealParameter parameter(double x) { return new RealParameter(Double.toString(x)); } + public static void main(String[] args) { + System.out.println("tips\tbirth_rate\theight_step\tyule_log_density\tzero_death_log_density\tlabeled_log_density"); + for (int tips : new int[]{2,3,5,8}) { + for (double rate : new double[]{0.02,1.3,200.0}) { + for (double step : new double[]{0.001,0.7}) { + Node[] nodes = new Node[2*tips-1]; + for (int i=0; i