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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 60 additions & 18 deletions apps/macos/Sources/RoveApp/Analysis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = [
"gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "node_time_rates",
Expand All @@ -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<String> = ["birth_difference_scale", "relative_death_scale"]
static let undatedMoves: Set<String> = [
"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<String> = [
"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",
Expand All @@ -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 {
Expand All @@ -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."
}
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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"
Expand Down Expand Up @@ -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."
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions apps/macos/Sources/RoveApp/CommandLineImport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions apps/macos/Sources/RoveApp/HistoryView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion apps/macos/Sources/RoveApp/MarginalLikelihood.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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") + ": "
Expand Down
15 changes: 15 additions & 0 deletions apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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.";
Original file line number Diff line number Diff line change
Expand Up @@ -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.";
3 changes: 3 additions & 0 deletions apps/macos/Sources/RoveApp/RunComparison.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
23 changes: 22 additions & 1 deletion apps/macos/Sources/RoveApp/RunRecord.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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"
Expand Down
5 changes: 5 additions & 0 deletions apps/macos/Sources/RoveApp/RunView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions apps/macos/Sources/RoveApp/SetupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ struct SetupView: View {

if workspace.settings.clock == "reference" { ClockSigmaPriorSection(workspace: workspace) }

TreePriorSection(workspace: workspace)
DatingSection(workspace: workspace)

LabPanel {
Expand Down Expand Up @@ -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"
Expand Down
Loading
Loading