diff --git a/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift b/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift index 16ca507..8b3cc88 100644 --- a/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift +++ b/apps/macos/Sources/RoveApp/AdvancedOptionsView.swift @@ -155,6 +155,29 @@ struct AdvancedOptionsSection: View { OverrideEditor( title: strings("Selection weights"), addLabel: strings("Add weight"), overrides: $workspace.settings.weights, moves: ProposalSchedule.moves, strings: strings) + Toggle( + strings("Try joint topology/rate exchange"), + isOn: Binding( + get: { settings.weights.contains { $0.move == "narrow_exchange_rates" && $0.value > 0 } }, + set: { enabled in + workspace.settings.weights.removeAll { $0.move == "narrow_exchange_rates" } + if enabled { + workspace.settings.weights.append( + MoveOverride(move: "narrow_exchange_rates", value: 10)) + } + }) + ) + .font(.system(size: 12)) + .disabled( + (settings.clock != "reference" || settings.dating.enabled) + && !settings.weights.contains { $0.move == "narrow_exchange_rates" && $0.value > 0 }) + Text( + strings( + "Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted).fixedSize( + horizontal: false, vertical: true) Toggle(strings("Tune step sizes during the run"), isOn: $workspace.settings.tuning) .font(.system(size: 12)) OverrideEditor( diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index 96ac878..1150e67 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -23,6 +23,11 @@ struct MatrixReport: Decodable, Sendable { let unobservedCharacters: [Int]? let observationExamples: [ObservationExample]? let stateLabels: [[String]]? + var dataType: String? = nil + var inputFormat: String? = nil + var mixed: MixedInputMetadata? = nil + var isMixed: Bool { dataType == "mixed" } + var isDNA: Bool { dataType == "dna" } var allTaxa: [String] { taxonNames ?? taxa } var missingPercent: Double { @@ -33,7 +38,10 @@ struct MatrixReport: Decodable, Sendable { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let value = try decoder.decode(Self.self, from: data) - guard value.schemaVersion == 1, value.taxonCount > 0, value.characterCount > 0, + guard value.schemaVersion == 1, + ["standard", "dna", "mixed"].contains(value.dataType ?? "standard"), + value.dataType != "mixed" || value.mixed?.valid == true, + value.taxonCount > 0, value.characterCount > 0, value.cells.count == value.taxa.count, !value.cells.isEmpty, value.cells.allSatisfy({ $0.count == value.characterLabels.count }) else { @@ -58,6 +66,7 @@ struct CharacterPartition: Decodable, Sendable { let observedPatterns: Int let sites: [Int] let stateSymbols: [String] + var dataType: String? = nil } enum ImportError: LocalizedError { @@ -143,20 +152,24 @@ 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", "birth_rate_scale", "morphology_rate_scale", ] static let relaxedClockMoves: Set = [ "gamma_shape_scale", "clock_sigma_scale", "branch_rate_scale", "node_time_rates", - "root_time_rates", "clock_sigma_rates", + "root_time_rates", "clock_sigma_rates", "narrow_exchange_rates", ] static let datingMoves: Set = [ "tip_age", "clock_rate_scale", "fbd_birth_scale", "fbd_death_scale", "fbd_sampling_scale", "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", + "morphology_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", @@ -178,7 +191,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 { @@ -198,6 +212,17 @@ 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." + } if clock != "reference", !active.isDisjoint(with: relaxedClockMoves) { return "Gamma shape, clock sigma, branch rate and joint moves need the relaxed clock." } @@ -230,7 +255,13 @@ enum ProposalSchedule { } struct AnalysisSettings: Codable, Equatable, Sendable { + var dataType = "standard" + var morphologyRateMode = "" + var morphologyRate = "1" + var morphologyRateLogSD = "1" var dating = DatingSettings() + var treePrior = "birth-death" + var birthRateUpper = "1000" var clock = "reference" var clockSigmaShape = "5" var clockSigmaScale = "0.2" @@ -268,7 +299,10 @@ struct AnalysisSettings: Codable, Equatable, Sendable { } private enum CodingKeys: String, CodingKey { - case dating, clock, clockSigmaShape, clockSigmaScale, conditioning, partitioning, steps, + case morphologyRateMode, morphologyRate, morphologyRateLogSD + case dataType, 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 @@ -276,7 +310,14 @@ struct AnalysisSettings: Codable, Equatable, Sendable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) + dataType = try values.decodeIfPresent(String.self, forKey: .dataType) ?? "standard" + morphologyRateMode = try values.decodeIfPresent(String.self, forKey: .morphologyRateMode) ?? "" + morphologyRate = try values.decodeIfPresent(String.self, forKey: .morphologyRate) ?? "1" + morphologyRateLogSD = + try values.decodeIfPresent(String.self, forKey: .morphologyRateLogSD) ?? "1" 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" @@ -314,6 +355,10 @@ struct AnalysisSettings: Codable, Equatable, Sendable { || ![1, 2, 4].contains(chains) } + var usesJointExchange: Bool { + (weights + tuningValues).contains { $0.move == "narrow_exchange_rates" } + } + static var backends: [String] { #if arch(arm64) ["automatic", "neon", "portable"] @@ -336,13 +381,50 @@ 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 characterModelLabel: String { + if dataType == "dna" { return "DNA · JC69" } + if dataType == "mixed" { return "Morphology + DNA · Mk + JC69" } + return conditioning == "variable" + ? "Mkv · variable characters" + : conditioning == "informative" ? "Mkparsinf · informative characters" : "Mk · all characters" + } + var validationError: String? { - guard ["strict", "reference"].contains(clock), + guard ["standard", "dna", "mixed"].contains(dataType), + ["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 let error = mixedRateError { return error } + if dataType != "mixed" || morphologyRateMode != "estimate" { + if weights.contains(where: { $0.move == "morphology_rate_scale" && $0.value > 0 }) + || tuningValues.contains(where: { $0.move == "morphology_rate_scale" }) + { + return "The morphology-rate move requires an estimated mixed-data rate ratio." + } + } + if dataType == "dna" && (conditioning != "none" || partitioning != "declared") { + return + "DNA JC69 keeps all four A/C/G/T states and all aligned sites, including constant sites." + } + 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." } @@ -372,7 +454,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 } @@ -408,6 +491,23 @@ 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 dataType == "mixed" { + if let error = mixedRateError { throw ImportError.message(error) } + if morphologyRateMode == "estimate" { + arguments += [ + "--morphology-rate", "estimate", "--morphology-rate-log-sd", + String(morphologyLogSDValue!), + ] + } else { + arguments += ["--morphology-rate", String(morphologyRateValue!)] + } + } if backend != "automatic" { arguments += ["--backend", backend] } if clock == "reference" { guard let prior = clockSigmaPrior else { @@ -453,6 +553,7 @@ struct AnalysisDraft: Codable, Sendable { let outgroup: String? let taxa: [String]? let appliedMonophyly: [[String]]? + var mixedInput: MixedInputMetadata? = nil var constraints: [[String]] { GroupConstraints.applied(monophyly, taxa: taxa ?? [], outgroup: outgroup) } @@ -462,17 +563,27 @@ struct AnalysisDraft: Codable, Sendable { monophyly: [[String]] = [], outgroup: String? = nil ) { formatVersion = - settings.partitioning == "labels" - ? 8 - : settings.usesExecutionOptions - ? 7 - : settings.usesCustomSigmaPrior - ? 6 - : (settings.usesAdvancedOptions - ? 5 : (settings.dating.estimatesProcess ? 4 : (settings.dating.enabled ? 3 : 2))) + settings.dataType == "mixed" + ? 12 + : settings.dataType == "dna" + ? 11 + : 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 + mixedInput = report.mixed self.settings = settings self.monophyly = monophyly self.outgroup = outgroup @@ -493,7 +604,11 @@ struct AnalysisDraft: Codable, Sendable { } func validate() throws { - guard (1...8).contains(formatVersion), + guard (1...12).contains(formatVersion), + settings.dataType != "mixed" || (formatVersion >= 12 && mixedInput?.valid == true), + formatVersion >= 11 || settings.dataType != "dna", + formatVersion >= 10 || settings.treePrior != "yule", + formatVersion >= 9 || !settings.usesJointExchange, formatVersion >= 8 || settings.partitioning != "labels", formatVersion >= 7 || !settings.usesExecutionOptions, formatVersion >= 6 || !settings.usesCustomSigmaPrior, @@ -551,7 +666,7 @@ enum GroupConstraints { static func validate(_ groups: [[String]], taxa: [String], outgroup: String? = nil) -> String? { let known = Set(taxa) if let outgroup, !known.contains(outgroup) || known.count < 3 { - return "Choose one outgroup from a matrix with at least three terminals." + return "Choose one rooting taxon from a matrix with at least three terminals." } var previous: [Set] = [] for group in groups { diff --git a/apps/macos/Sources/RoveApp/AppPreferences.swift b/apps/macos/Sources/RoveApp/AppPreferences.swift index b9959c9..11e2a0e 100644 --- a/apps/macos/Sources/RoveApp/AppPreferences.swift +++ b/apps/macos/Sources/RoveApp/AppPreferences.swift @@ -81,7 +81,8 @@ struct AppStrings: Sendable { } func partitionSummary(_ partition: CharacterPartition) -> String { - partitionSummary(states: partition.states, characters: partition.characters) + (partition.dataType == "dna" ? "DNA · " : "") + + partitionSummary(states: partition.states, characters: partition.characters) + " · " + self(partition.ordering == .ordered ? "Ordered" : "Unordered") } diff --git a/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift b/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift index 1c320b2..22c2067 100644 --- a/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift +++ b/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift @@ -1,3 +1,4 @@ +import Charts import SwiftUI struct ClockSigmaPrior: Codable, Equatable, Sendable { @@ -8,6 +9,109 @@ struct ClockSigmaPrior: Codable, Equatable, Sendable { func description(strings: AppStrings) -> String { strings("Gamma · shape %@ · scale %@", String(shape), String(scale)) } + + var mean: Double { shape * scale } + var standardDeviation: Double { sqrt(shape) * scale } + + /// Shape/scale Gamma density; evaluate in scaled coordinates to avoid + /// subtracting the separate, large shape * log(scale) terms. + func logDensity(at sigma: Double) -> Double? { + guard shape.isFinite, scale.isFinite, shape > 0, scale > 0, + sigma.isFinite, sigma >= 0, lgamma(shape).isFinite + else { return nil } + if sigma == 0 { + if shape < 1 { return .infinity } + return shape == 1 ? -log(scale) : -.infinity + } + let value = sigma / scale + guard value.isFinite, value > 0 else { return nil } + let density = (shape - 1) * log(value) - value - lgamma(shape) - log(scale) + return density.isNaN ? nil : density + } + + struct Curve: Sendable { + struct Point: Identifiable, Sendable { + let id: Int + let sigma: Double + let density: Double + } + let points: [Point] + let upperBound: Double + } + + var curve: Curve? { + let upper = mean + 5 * standardDeviation + // The numerical prior may be valid at scales where a linear display + // cannot draw meaningful axes. Keep that limitation in the preview only. + guard upper.isFinite, upper >= 1e-12, upper <= 1e12, + mean.isFinite, mean > 0, shape > 0, scale > 0 + else { return nil } + let first = shape < 1 ? 1 : 0 + var points: [Curve.Point] = [] + for index in first...240 { + let sigma = upper * Double(index) / 240 + guard let logValue = logDensity(at: sigma) else { return nil } + let value = exp(logValue) + guard value.isFinite, value <= 1e12 else { return nil } + points.append(.init(id: index, sigma: sigma, density: value)) + } + guard points.contains(where: { $0.density > 0 }) else { return nil } + return Curve(points: points, upperBound: upper) + } +} + +struct ClockSigmaPriorChart: View { + let prior: ClockSigmaPrior + let strings: AppStrings + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + if let curve = prior.curve { + Chart { + ForEach(curve.points) { point in + LineMark( + x: .value("Sigma", point.sigma), + y: .value(strings("Prior density"), point.density) + ) + .foregroundStyle(Lab.lilac).lineStyle(StrokeStyle(lineWidth: 2)) + } + RuleMark(x: .value(strings("Expected sigma"), prior.mean)) + .foregroundStyle(Lab.accent).lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + } + .chartXScale(domain: 0...curve.upperBound) + .chartXAxisLabel("Sigma") + .chartYAxisLabel(strings("Prior density")) + .frame(height: 170) + .accessibilityLabel( + strings("Gamma prior for clock sigma; the dashed line marks its expectation.")) + } else { + Text(strings("The density preview is unavailable at this numerical scale.")) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } + if prior.mean.isFinite, prior.standardDeviation.isFinite { + Text( + strings( + "Expected sigma: %@ · standard deviation: %@", + number(prior.mean), number(prior.standardDeviation)) + ) + .font(.system(size: 11, weight: .medium)).foregroundStyle(Lab.accent) + } + if prior.shape < 1 { + Text(strings("The density grows without bound near zero; the curve starts above zero.")) + .font(.system(size: 10)).foregroundStyle(Lab.secondary) + } + Text( + strings( + "This is a prior preview, before seeing the data. The displayed range is not a credible interval." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + } + } + + private func number(_ value: Double) -> String { + value.formatted(.number.precision(.significantDigits(1...5)).locale(strings.locale)) + } } struct ClockSigmaPriorSection: View { @@ -39,6 +143,9 @@ struct ClockSigmaPriorSection: View { ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + if let prior = workspace.settings.clockSigmaPrior { + ClockSigmaPriorChart(prior: prior, strings: strings) + } if workspace.settings.clockSigmaPrior == nil { Text(strings("Use positive, finite shape and scale values for the clock sigma prior.")) .font(.system(size: 12)).foregroundStyle(Lab.accent) diff --git a/apps/macos/Sources/RoveApp/CommandLineImport.swift b/apps/macos/Sources/RoveApp/CommandLineImport.swift index 44ea719..4360ab2 100644 --- a/apps/macos/Sources/RoveApp/CommandLineImport.swift +++ b/apps/macos/Sources/RoveApp/CommandLineImport.swift @@ -64,17 +64,31 @@ enum CommandLineImport { } guard let steps = Int(exactly: record.settings.steps), let interval = Int(exactly: record.settings.sampleEvery), - let conditioning = EngineRecord.Model.conditioningDescriptions.first(where: { - $0.value == record.model.conditioning - })?.key + let conditioning = record.model.conditioningKind ?? option("--conditioning") else { throw RunFailure.invalidCompletion } var value = AnalysisSettings() + value.dataType = record.model.resolvedDataType + 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) value.clockSigmaScale = String(sigma.scale) value.conditioning = conditioning + if value.dataType == "mixed" { + guard let model = record.model.mixedModel else { throw RunFailure.invalidCompletion } + value.morphologyRateMode = model.morphologyRatePrior == nil ? "fixed" : "estimate" + value.morphologyRate = String(model.morphologyRate) + value.morphologyRateLogSD = String(model.morphologyRatePrior?.logSd ?? 1) + } + guard record.model.dataModelMatches(value) else { throw RunFailure.invalidCompletion } value.partitioning = record.model.partitioning ?? "declared" value.steps = steps value.sampleEvery = interval diff --git a/apps/macos/Sources/RoveApp/HistoryView.swift b/apps/macos/Sources/RoveApp/HistoryView.swift index e922010..bbbbfc6 100644 --- a/apps/macos/Sources/RoveApp/HistoryView.swift +++ b/apps/macos/Sources/RoveApp/HistoryView.swift @@ -281,13 +281,16 @@ 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)) + if draft.settings.dataType == "mixed" { + field( + "Morphology/DNA rate ratio", draft.settings.mixedRateDescription(strings: strings)) + field("Morphology conditioning", strings(draft.settings.morphologyConditioningLabel)) + } field( "Character model", strings( - draft.settings.conditioning == "variable" - ? "Mkv · variable characters" - : draft.settings.conditioning == "informative" - ? "Mkparsinf · informative characters" : "Mk · all characters")) + draft.settings.characterModelLabel)) field( "State partitions", strings( @@ -356,6 +359,9 @@ private struct HistoryDetail: View { openWindow(id: "trace-diagnostics") }.buttonStyle(LabButtonStyle(compact: true)) } + if entry.draft != nil && entry.status != .modelSetup { + RunAssessmentView(workspace: workspace, entry: entry) + } if let draft = entry.draft, draft.settings.chains > 1, entry.status != .modelSetup { ChainResultsView( workspace: workspace, directory: entry.directory, diff --git a/apps/macos/Sources/RoveApp/LaunchExperience.swift b/apps/macos/Sources/RoveApp/LaunchExperience.swift index afbd668..f9d5f53 100644 --- a/apps/macos/Sources/RoveApp/LaunchExperience.swift +++ b/apps/macos/Sources/RoveApp/LaunchExperience.swift @@ -99,7 +99,7 @@ struct RoveRelease: Identifiable { id: "morphology", symbol: "square.grid.3x3", title: "Bring all the little differences.", summary: "Morphological matrices, with two, three or more states.", detail: - "Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start.", + "Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start.", action: "Try the example", destination: .example), ReleaseHighlight( id: "history", symbol: "clock.arrow.circlepath", diff --git a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift index 8f63f38..9130a7d 100644 --- a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift +++ b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift @@ -105,10 +105,11 @@ struct SavedEstimate: Identifiable, Sendable { return record.input.sha256 == draft.matrixSHA256 && record.input.gaps == (settings.gapsAsMissing ? "missing" : "reject") && record.model.monophyly == draft.constraints && record.model.preset == settings.clock - && record.model.conditioning - == EngineRecord.Model.conditioningDescriptions[settings.conditioning] + && record.model.conditioningKind == settings.conditioning + && record.model.dataModelMatches(settings) + && record.input.mixed == draft.mixedInput && (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/MatrixView.swift b/apps/macos/Sources/RoveApp/MatrixView.swift index 53ae475..632fe36 100644 --- a/apps/macos/Sources/RoveApp/MatrixView.swift +++ b/apps/macos/Sources/RoveApp/MatrixView.swift @@ -30,7 +30,9 @@ struct MatrixView: View { HStack(spacing: 0) { metric( "TERMINALS", value: strings.number(report.taxonCount), note: "The taxa in your study") - metric("CHARACTERS", value: strings.number(report.characterCount), note: "Observed traits") + metric( + report.isDNA ? "SITES" : "CHARACTERS", value: strings.number(report.characterCount), + note: report.isDNA ? "Aligned positions" : "Observed traits") metric( "PATTERNS", value: report.patternCount.map(strings.number) ?? "—", note: "Distinct patterns within partitions") @@ -43,36 +45,43 @@ struct MatrixView: View { .background(Lab.surface, in: RoundedRectangle(cornerRadius: 15)) .overlay(RoundedRectangle(cornerRadius: 15).strokeBorder(Lab.border.opacity(0.7))) - LabPanel { - VStack(alignment: .leading, spacing: 12) { - HStack { - Text(strings("State partitions")).font(.system(size: 13, weight: .semibold)) - Spacer() - Picker(strings("State partitions"), selection: $workspace.settings.partitioning) { - Text(strings("By observed states")).tag("observed") - Text(strings("Declared alphabet")).tag("declared") - Text(strings("Complete state labels")).tag("labels") - }.labelsHidden().frame(width: 210) - .disabled(workspace.loading) - .onChange(of: workspace.settings.partitioning) { workspace.reloadGapPolicy() } - } - Text( - strings( - workspace.settings.partitioning == "observed" - ? "Characters are grouped by state count and ordering. Ordered characters keep intermediate states; binary alphabets keep both states." - : workspace.settings.partitioning == "labels" - ? "Use each state-label list as the complete possible alphabet, in SYMBOLS order. Choose this only if every character lists all its possible states." - : "Every character uses all states declared in SYMBOLS. Choose this only if they are possible for every character." + if let metadata = report.mixed { MixedSourcesSection(metadata: metadata, strings: strings) } + if report.isDNA { + NucleotideModelSection(strings: strings) + } else { + LabPanel { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text(strings("State partitions")).font(.system(size: 13, weight: .semibold)) + Spacer() + Picker(strings("State partitions"), selection: $workspace.settings.partitioning) { + Text(strings("By observed states")).tag("observed") + Text(strings("Declared alphabet")).tag("declared") + Text(strings("Complete state labels")).tag("labels") + }.labelsHidden().frame(width: 260) + .disabled(workspace.loading) + .onChange(of: workspace.settings.partitioning) { workspace.reloadGapPolicy() } + } + Text( + strings( + workspace.settings.partitioning == "observed" + ? "Characters are grouped by state count and ordering. Ordered characters keep intermediate states; binary alphabets keep both states." + : workspace.settings.partitioning == "labels" + ? "Use each state-label list as the complete possible alphabet, in SYMBOLS order. Choose this only if every character lists all its possible states." + : "Every character uses all states declared in SYMBOLS. Choose this only if they are possible for every character." + ) ) - ) - .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) - if let partitions = report.partitions { - ViewThatFits(in: .horizontal) { - HStack(spacing: 16) { partitionCounts(partitions) } - VStack(alignment: .leading, spacing: 8) { partitionCounts(partitions) } + .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) + if let partitions = report.partitions { + ViewThatFits(in: .horizontal) { + HStack(spacing: 16) { partitionCounts(partitions) } + VStack(alignment: .leading, spacing: 8) { partitionCounts(partitions) } + } } } } + } if let constant = report.constantCharacters, !constant.isEmpty { @@ -84,10 +93,15 @@ struct MatrixView: View { .font(.system(size: 11, design: .monospaced)).textSelection(.enabled) Text( strings( - "These characters remain in the matrix. Variable-only (Mkv) coding cannot include them. Review how characters were selected before choosing All characters (Mk)." + report.isMixed + ? "Constant DNA sites remain in the JC69 block. Variable-only coding excludes constant morphological characters; review the partition and collection method before changing that choice." + : report.isDNA + ? "Constant sites are retained and contribute to the JC69 likelihood." + : "These characters remain in the matrix. Variable-only (Mkv) coding cannot include them. Review how characters were selected before choosing All characters (Mk)." ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) } } } @@ -149,16 +163,22 @@ struct MatrixView: View { .font(.system(size: 11, weight: .medium)) Text( strings( - "Braces such as {01} mean state 0 OR 1. Parentheses such as (01) mean both states are present. Rove preserves this distinction; its current observation model cannot analyze true polymorphism." + report.isDNA + ? "IUPAC codes and braces specify possible bases: R means A or G, and N permits all four. These observations contribute to inference without being recoded as extra states." + : "Braces such as {01} mean state 0 OR 1. Parentheses such as (01) mean both states are present. Rove preserves this distinction; its current observation model cannot analyze true polymorphism." ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) Text( strings( - "If your exporter uses braces for polymorphism, confirm the meaning before running. Reading the file does not resolve that scientific choice." + report.isDNA + ? "Predictive checks currently require single bases or missing cells. Ambiguous observations need an explicit observation model for simulation." + : "If your exporter uses braces for polymorphism, confirm the meaning before running. Reading the file does not resolve that scientific choice." ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) if let examples = report.observationExamples, !examples.isEmpty { DisclosureGroup(strings("Inspect ambiguous observations")) { ForEach(Array(examples.enumerated()), id: \.offset) { _, example in @@ -275,9 +295,18 @@ private struct MatrixGrid: View { let name = report.characterLabels[selected.column] ?? strings("Character %@", strings.number(selected.column + 1)) - Text( - "\(report.taxa[selected.row]) · \(name) · \(report.cells[selected.row][selected.column])" - ) + VStack(alignment: .leading, spacing: 4) { + Text( + "\(report.taxa[selected.row]) · \(name) · \(report.cells[selected.row][selected.column])" + ) + if let labels = report.stateLabels, labels.indices.contains(selected.column) { + Text( + zip(report.symbols, labels[selected.column]) + .map { "\($0.0) = \($0.1)" }.joined(separator: " · ") + ) + .fixedSize(horizontal: false, vertical: true) + } + } } else { Text(strings("Click a cell to inspect it. Scroll to explore.")) } diff --git a/apps/macos/Sources/RoveApp/MixedImportView.swift b/apps/macos/Sources/RoveApp/MixedImportView.swift new file mode 100644 index 0000000..cac9138 --- /dev/null +++ b/apps/macos/Sources/RoveApp/MixedImportView.swift @@ -0,0 +1,103 @@ +import AppKit +import SwiftUI + +struct MixedInputRequest: Sendable { + let morphology: URL + let dna: URL + let output: URL + let missingTaxa: String + + func execute(executable: URL) async throws { + guard ["reject", "missing"].contains(missingTaxa) else { throw RunFailure.invalidCompletion } + let outcome = try await EngineTool().execute( + executable: executable, + arguments: [ + "combine", "--morphology", morphology.path, "--dna", dna.path, + "--output", output.path, "--missing-taxa", missingTaxa, + ], onLine: { _ in }) + guard outcome.status == 0 else { throw ImportError.readerFailed(outcome.log) } + } +} + +struct MixedImportView: View { + @Bindable var workspace: Workspace + @State private var morphology: URL? + @State private var dna: URL? + @State private var missingTaxa = "reject" + @State private var working = false + @State private var error: String? + private var strings: AppStrings { workspace.strings } + + var body: some View { + VStack(alignment: .leading, spacing: 18) { + Text(strings("Combine morphology and DNA")).font(Lab.display(25)) + Text( + strings( + "Select one morphological NEXUS matrix and one aligned DNA file. Rove matches normalized taxon names and preserves both source files in a new combined input." + ) + ) + .font(.system(size: 12)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + Button { + morphology = choose("Choose morphology") + } label: { + Label( + morphology?.lastPathComponent ?? strings("Choose morphology"), + systemImage: "square.grid.3x3") + } + Button { + dna = choose("Choose aligned DNA") + } label: { + Label( + dna?.lastPathComponent ?? strings("Choose aligned DNA"), systemImage: "line.3.horizontal") + } + Picker(strings("Taxa absent from one source"), selection: $missingTaxa) { + Text(strings("Require the same taxa")).tag("reject") + Text(strings("Keep the union; absent cells are missing")).tag("missing") + } + Text( + strings( + "At least two taxa must be shared. Review unmatched names before choosing missing data; spelling differences are not biological absences." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + if let error { Text(error).font(.system(size: 11)).textSelection(.enabled) } + HStack { + Button(strings("Cancel")) { workspace.showingMixedImport = false }.disabled(working) + Spacer() + Button(strings("Save combined input"), action: save).disabled( + working || morphology == nil || dna == nil) + } + } + .padding(28).frame(width: 610).foregroundStyle(Lab.ink).background(Lab.background) + .disabled(working) + } + + private func choose(_ title: String) -> URL? { + let panel = NSOpenPanel() + panel.title = strings(title) + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + return panel.runModal() == .OK ? panel.url : nil + } + private func save() { + guard let morphology, let dna else { return } + let panel = NSSavePanel() + panel.nameFieldStringValue = "analysis.mixed.json" + panel.title = strings("Save combined input") + guard panel.runModal() == .OK, let output = panel.url else { return } + working = true + error = nil + Task { + do { + try await workspace.combineInput( + MixedInputRequest( + morphology: morphology, dna: dna, output: output, missingTaxa: missingTaxa)) + workspace.showingMixedImport = false + workspace.load(output) + } catch { self.error = error.localizedDescription } + working = false + } + } +} diff --git a/apps/macos/Sources/RoveApp/MixedModel.swift b/apps/macos/Sources/RoveApp/MixedModel.swift new file mode 100644 index 0000000..9016789 --- /dev/null +++ b/apps/macos/Sources/RoveApp/MixedModel.swift @@ -0,0 +1,84 @@ +import Foundation + +struct MixedInputMetadata: Codable, Equatable, Sendable { + struct Source: Codable, Equatable, Sendable { + let name: String + let sha256: String + let dataType: String + let missingTaxa: [String] + } + let missingTaxaPolicy: String + let taxonMatching: String + let sources: [Source] + + var valid: Bool { + ["reject", "missing"].contains(missingTaxaPolicy) + && sources.map(\.dataType) == ["standard", "dna"] + && sources.allSatisfy { !$0.name.isEmpty && $0.sha256.count == 64 } + } +} + +struct MixedModel: Decodable, Equatable, Sendable { + struct Prior: Decodable, Equatable, Sendable { + let distribution: String + let logMean: Double + let logSd: Double + } + let topology: String + let branchClock: String + let gammaShape: String + let dnaRate: Double + let morphologyRate: Double + let morphologyRatePrior: Prior? + let morphologyConditioning: String + let dnaConditioning: String + + func matches(_ settings: AnalysisSettings) -> Bool { + guard topology == "shared", branchClock == "shared", gammaShape == "shared", dnaRate == 1, + dnaConditioning == "none", morphologyConditioning == settings.conditioning + else { return false } + if settings.morphologyRateMode == "estimate" { + guard let prior = morphologyRatePrior else { return false } + return morphologyRate == 1 && prior.distribution == "lognormal" && prior.logMean == 0 + && prior.logSd == settings.morphologyLogSDValue + } + return settings.morphologyRateMode == "fixed" && morphologyRatePrior == nil + && morphologyRate == settings.morphologyRateValue + } +} + +extension AnalysisSettings { + private func positive(_ text: String) -> Double? { + guard let value = Double(text.replacingOccurrences(of: ",", with: ".")), value.isFinite, + value > 0 + else { return nil } + return value + } + var morphologyConditioningLabel: String { + conditioning == "variable" + ? "Mkv · variable characters" + : conditioning == "informative" + ? "Mkparsinf · informative characters" : "Mk · all characters" + } + var morphologyRateValue: Double? { positive(morphologyRate) } + var morphologyLogSDValue: Double? { positive(morphologyRateLogSD) } + var mixedRateError: String? { + guard dataType == "mixed" else { return nil } + guard ["estimate", "fixed"].contains(morphologyRateMode) else { + return "Choose whether to fix or estimate the morphology/DNA rate ratio." + } + guard + morphologyRateMode == "estimate" ? morphologyLogSDValue != nil : morphologyRateValue != nil + else { return "Morphology rate and lognormal log-SD must be positive and finite." } + return nil + } + func mixedRateDescription(strings: AppStrings) -> String { + if morphologyRateMode == "estimate" { + return strings( + "Estimated · log(rate) Normal(0, %@²)", + morphologyLogSDValue.map(String.init(describing:)) ?? "—") + } + return strings( + "Fixed morphology/DNA ratio: %@", morphologyRateValue.map(String.init(describing:)) ?? "—") + } +} diff --git a/apps/macos/Sources/RoveApp/MixedModelView.swift b/apps/macos/Sources/RoveApp/MixedModelView.swift new file mode 100644 index 0000000..467def1 --- /dev/null +++ b/apps/macos/Sources/RoveApp/MixedModelView.swift @@ -0,0 +1,90 @@ +import SwiftUI + +struct MixedSourcesSection: View { + let metadata: MixedInputMetadata + let strings: AppStrings + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 12) { + Text(strings("Morphology + DNA")).font(.system(size: 13, weight: .semibold)) + Text( + strings( + "Each block keeps its own alphabet. Morphological conditioning and alphabet choices apply only to morphology; DNA always uses all four bases and includes constant sites." + ) + ) + .font(.system(size: 12)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + ForEach(Array(metadata.sources.enumerated()), id: \.offset) { _, source in + VStack(alignment: .leading, spacing: 5) { + Text( + source.name + " · " + + (source.dataType == "dna" ? "DNA · JC69" : strings("Morphology")) + ) + .font(.system(size: 12, weight: .medium)) + Text("SHA-256 · " + source.sha256).font(.system(size: 9, design: .monospaced)) + .foregroundStyle(Lab.muted).textSelection(.enabled) + if !source.missingTaxa.isEmpty { + Text( + strings( + "Absent taxa filled with missing cells: %@", + source.missingTaxa.joined(separator: ", ")) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + } + } + } + Text( + strings( + metadata.missingTaxaPolicy == "reject" + ? "Require the same taxa" : "Keep the union; absent cells are missing") + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } + } + } +} + +struct MixedRateSection: View { + @Bindable var workspace: Workspace + private var strings: AppStrings { workspace.strings } + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 12) { + Text(strings("Morphology/DNA rate ratio")).font(.system(size: 13, weight: .semibold)) + Text( + strings( + "Both blocks share the topology, branch clock and gamma shape. DNA fixes the reference rate at 1; the ratio scales every morphological partition. Separate clocks are not available." + ) + ) + .font(.system(size: 12)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + Picker( + strings("Morphology/DNA rate ratio"), selection: $workspace.settings.morphologyRateMode + ) { + Text(strings("Choose a rate model")).tag("") + Text(strings("Estimate with a lognormal prior")).tag("estimate") + Text(strings("Fix the rate ratio")).tag("fixed") + } + if workspace.settings.morphologyRateMode == "estimate" { + HStack { + Text(strings("Lognormal log-SD")) + TextField("1", text: $workspace.settings.morphologyRateLogSD).frame(width: 100) + } + Text( + strings( + "The prior is log(rate) ~ Normal(0, log-SD²), with median 1. This is a modeling assumption; assess its sensitivity for your data." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + } else if workspace.settings.morphologyRateMode == "fixed" { + HStack { + Text(strings("Morphology relative rate")) + TextField("1", text: $workspace.settings.morphologyRate).frame(width: 100) + } + } + } + } + } +} diff --git a/apps/macos/Sources/RoveApp/NucleotideModelView.swift b/apps/macos/Sources/RoveApp/NucleotideModelView.swift new file mode 100644 index 0000000..0be23ac --- /dev/null +++ b/apps/macos/Sources/RoveApp/NucleotideModelView.swift @@ -0,0 +1,27 @@ +import SwiftUI + +struct NucleotideModelSection: View { + let strings: AppStrings + + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 12) { + Text(strings("Aligned DNA · JC69")).font(.system(size: 13, weight: .semibold)) + Text( + strings( + "JC69 treats A, C, G and T equally. All four states remain possible at every site, and constant sites stay in the alignment." + ) + ) + .font(.system(size: 12)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) + Text( + strings( + "Import sequences that are already aligned. Ambiguous IUPAC bases represent possible states, not extra nucleotides. Choose a gap policy in the matrix preview." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } +} diff --git a/apps/macos/Sources/RoveApp/OnboardingView.swift b/apps/macos/Sources/RoveApp/OnboardingView.swift index 9639349..fb9b101 100644 --- a/apps/macos/Sources/RoveApp/OnboardingView.swift +++ b/apps/macos/Sources/RoveApp/OnboardingView.swift @@ -17,7 +17,7 @@ struct OnboardingView: View { private let descriptions = [ "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion.", "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything.", - "Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you.", + "Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you.", "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis.", ] @@ -179,7 +179,7 @@ struct OnboardingView: View { VStack(alignment: .leading, spacing: 10) { Label(strings("For the bundled example"), systemImage: "lightbulb") .font(.system(size: 12, weight: .medium)).foregroundStyle(Lab.ice) - Text(strings("Choose T20 as the outgroup. Check the remaining settings before starting.")) + Text(strings("Choose T20 as the taxon used for rooting. Check the remaining settings before starting.")) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) } }.padding(22).background(Lab.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 15)) diff --git a/apps/macos/Sources/RoveApp/PredictiveCheckView.swift b/apps/macos/Sources/RoveApp/PredictiveCheckView.swift index c08aa66..915c29a 100644 --- a/apps/macos/Sources/RoveApp/PredictiveCheckView.swift +++ b/apps/macos/Sources/RoveApp/PredictiveCheckView.swift @@ -201,6 +201,7 @@ struct PredictiveReportView: View { } Button(strings("Open folder")) { NSWorkspace.shared.open(prediction.directory) } }.buttonStyle(LabButtonStyle(compact: true)) + PredictiveDistributionView(prediction: prediction, strings: strings) } } diff --git a/apps/macos/Sources/RoveApp/PredictiveDistribution.swift b/apps/macos/Sources/RoveApp/PredictiveDistribution.swift new file mode 100644 index 0000000..6d640b1 --- /dev/null +++ b/apps/macos/Sources/RoveApp/PredictiveDistribution.swift @@ -0,0 +1,136 @@ +import Charts +import SwiftUI + +struct PredictiveDistribution: Sendable { + struct Bin: Identifiable, Sendable { + let id: Int + let lower: Double + let upper: Double + let count: Int + } + let name: String + let differences: [Double] + let undefined: Int + + var bins: [Bin] { + guard let low = differences.min(), let high = differences.max() else { return [] } + let width = high == low ? max(abs(low) * 0.05, 0.1) : (high - low) / 20 + guard width.isFinite && width > 0 else { return [] } + let start = high == low ? low - width / 2 : low + let count = high == low ? 1 : 20 + var totals = [Int](repeating: 0, count: count) + for value in differences { totals[min(count - 1, max(0, Int((value - start) / width)))] += 1 } + return totals.indices.map { + Bin( + id: $0, lower: start + Double($0) * width, + upper: start + Double($0 + 1) * width, count: totals[$0]) + } + } + + static func read(_ prediction: SavedPrediction) throws -> [Self] { + struct Pair: Decodable { + let replicate: Int + let observed: [String: Double?] + let simulated: [String: Double?] + } + let file = prediction.directory.appendingPathComponent("replicates.jsonl") + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard info.isRegularFile == true, (info.fileSize ?? 0) <= 64 * 1024 * 1024 else { + throw RunFailure.invalidCompletion + } + let data = try Data(contentsOf: file) + let pairs = try data.split(separator: 10).map { + try JSONDecoder().decode(Pair.self, from: Data($0)) + } + guard pairs.count == prediction.report.replicates, + Set(pairs.map(\.replicate)) == Set(1...prediction.report.replicates) + else { throw RunFailure.invalidCompletion } + return try PredictiveReport.statistics.map { name in + let differences = try pairs.compactMap { pair -> Double? in + guard pair.observed.keys.contains(name), pair.simulated.keys.contains(name) else { + throw RunFailure.invalidCompletion + } + guard let a = pair.observed[name] ?? nil, let b = pair.simulated[name] ?? nil else { + return nil + } + let difference = b - a + guard a.isFinite, b.isFinite, difference.isFinite else { + throw RunFailure.invalidCompletion + } + return difference + } + guard let tail = prediction.report.global[name], tail.validPairs == differences.count, + tail.undefinedPairs == pairs.count - differences.count, + tail.lowerCount == differences.filter({ $0 <= 0 }).count, + tail.upperCount == differences.filter({ $0 >= 0 }).count, + tail.ties == differences.filter({ $0 == 0 }).count + else { throw RunFailure.invalidCompletion } + return Self(name: name, differences: differences, undefined: pairs.count - differences.count) + } + } +} + +struct PredictiveDistributionView: View { + let prediction: SavedPrediction + let strings: AppStrings + @State private var distributions: [PredictiveDistribution] = [] + @State private var selected = "parsimony_length" + @State private var failed = false + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Picker(strings("Statistic"), selection: $selected) { + ForEach(PredictiveReport.statistics, id: \.self) { name in + Text(strings(PredictiveReportView.label(name))).tag(name) + } + }.frame(maxWidth: 360) + if let distribution = distributions.first(where: { $0.name == selected }) { + if !distribution.differences.isEmpty { + Chart { + ForEach(distribution.bins) { bin in + RectangleMark( + xStart: .value("Difference", bin.lower), xEnd: .value("Difference", bin.upper), + yStart: .value("Pairs", 0), yEnd: .value("Pairs", bin.count) + ) + .foregroundStyle(Lab.lilac.opacity(0.7)) + } + RuleMark(x: .value("Zero", 0)).lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + .foregroundStyle(Lab.secondary) + }.frame(height: 180) + .chartXAxisLabel(strings("Simulated − observed")) + .chartYAxisLabel(strings("Valid pairs")) + .accessibilityLabel( + strings( + "Distribution of simulated minus observed paired statistics. Zero is equality.")) + } + Text( + strings( + "%@ valid pairs · %@ undefined", String(distribution.differences.count), + String(distribution.undefined)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.secondary) + } else if failed { + Text( + strings( + "Replicate details are missing or disagree with the check record. The distribution is unavailable." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } else { + ProgressView().controlSize(.small) + } + Text( + strings( + "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted).fixedSize( + horizontal: false, vertical: true) + }.task(id: prediction.id) { + let prediction = prediction + distributions = + (try? await Task.detached { try PredictiveDistribution.read(prediction) }.value) ?? [] + failed = distributions.isEmpty + } + } +} diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index d58618d..10e47b2 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -298,7 +298,7 @@ "%@ on one side of the root; the other %@ terminals together on the other." = "%@ on one side of the root; the other %@ terminals together on the other."; "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup." = "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup."; "No outgroup selected. Any applied groups below still constrain the tree." = "No outgroup selected. Any applied groups below still constrain the tree."; -"Choose one outgroup from a matrix with at least three terminals." = "Choose one outgroup from a matrix with at least three terminals."; +"Choose one rooting taxon from a matrix with at least three terminals." = "Choose one rooting taxon from a matrix with at least three terminals."; "No groups applied. Root placement is unconstrained by groups." = "No groups applied. Root placement is unconstrained by groups."; "Applied groups" = "Applied groups"; "Support for an imposed group is not independent evidence from the characters." = "Support for an imposed group is not independent evidence from the characters."; @@ -618,7 +618,7 @@ "Your research.\nRoom to explore." = "Your research.\nRoom to explore."; "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion." = "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion."; "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything." = "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything."; -"Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you." = "Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you."; +"Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you." = "Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you."; "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis." = "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis."; "YOUR FIRST FIELD TRIP" = "YOUR FIRST FIELD TRIP"; "A SMALL INTRODUCTION" = "A SMALL INTRODUCTION"; @@ -637,7 +637,7 @@ "Illustration of a morphological matrix" = "Illustration of a morphological matrix"; "? means an unknown observation." = "? means an unknown observation."; "For the bundled example" = "For the bundled example"; -"Choose T20 as the outgroup. Check the remaining settings before starting." = "Choose T20 as the outgroup. Check the remaining settings before starting."; +"Choose T20 as the taxon used for rooting. Check the remaining settings before starting." = "Choose T20 as the taxon used for rooting. Check the remaining settings before starting."; "Check the sampling" = "Check the sampling"; "Useful samples matter more than step counts." = "Useful samples matter more than step counts."; "Explore the trees" = "Explore the trees"; @@ -655,7 +655,7 @@ "A small beginning, with room for big questions. Meet the tools already inside this beta." = "A small beginning, with room for big questions. Meet the tools already inside this beta."; "Bring all the little differences." = "Bring all the little differences."; "Morphological matrices, with two, three or more states." = "Morphological matrices, with two, three or more states."; -"Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start." = "Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start."; +"Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start." = "Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start."; "Good work deserves a save point." = "Good work deserves a save point."; "Find past runs. Pause a long analysis. Pick up where you left off." = "Find past runs. Pause a long analysis. Pick up where you left off."; "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input." = "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input."; @@ -950,7 +950,7 @@ "The tree file could not be opened." = "The tree file could not be opened."; "The tree file is no longer at its recorded path." = "The tree file is no longer at its recorded path."; "Trees from another program" = "Trees from another program"; -"Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." = "Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence."; +"Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." = "Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence."; "The tree file is no longer at its recorded path. Saved summaries stay available." = "The tree file is no longer at its recorded path. Saved summaries stay available."; "Summaries" = "Summaries"; "No summary yet. Summarize the file to build an annotated MCC tree." = "No summary yet. Summarize the file to build an annotated MCC tree."; @@ -1105,3 +1105,124 @@ "Inspect ambiguous observations" = "Inspect ambiguous observations"; "Up to 100 observations are listed; the counts include the full matrix." = "Up to 100 observations are listed; the counts include the full matrix."; "Alphabet choice" = "Alphabet choice"; + +// Visual model guidance. +"Prior density" = "Prior density"; +"Expected sigma" = "Expected sigma"; +"Gamma prior for clock sigma; the dashed line marks its expectation." = "Gamma prior for clock sigma; the dashed line marks its expectation."; +"The density preview is unavailable at this numerical scale." = "The density preview is unavailable at this numerical scale."; +"Expected sigma: %@ · standard deviation: %@" = "Expected sigma: %@ · standard deviation: %@"; +"The density grows without bound near zero; the curve starts above zero." = "The density grows without bound near zero; the curve starts above zero."; +"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "This is a prior preview, before seeing the data. The displayed range is not a credible interval."; +"Other %@ terminals" = "Other %@ terminals"; +"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here."; + +/* Evidence review and reproducibility exports. */ +"Evidence review" = "Evidence review"; +"What does this run establish?" = "What does this run establish?"; +"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy."; +"Refresh evidence review" = "Refresh evidence review"; +"Matching tree reports: %@ · Predictive reports: %@" = "Matching tree reports: %@ · Predictive reports: %@"; +"Review record" = "Review record"; +"Include the original matrix in the export" = "Include the original matrix in the export"; +"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint."; +"Export reproducibility package…" = "Export reproducibility package…"; +"Choose export folder" = "Choose export folder"; +"Open exported package" = "Open exported package"; +"Run completion" = "Run completion"; +"Scalar sampling" = "Scalar sampling"; +"Independent-chain agreement" = "Independent-chain agreement"; +"Tree evidence" = "Tree evidence"; +"Predictive evidence" = "Predictive evidence"; +"Criteria met" = "Criteria met"; +"Needs attention" = "Needs attention"; +"Interpretation required" = "Interpretation required"; +"Evidence unavailable" = "Evidence unavailable"; +"The original matrix matches the recorded fingerprint." = "The original matrix matches the recorded fingerprint."; +"The original matrix has changed. Matrix inclusion will be refused." = "The original matrix has changed. Matrix inclusion will be refused."; +"The original matrix is unavailable. Records can still be exported without it." = "The original matrix is unavailable. Records can still be exported without it."; +"The review or export was cancelled." = "The review or export was cancelled."; +"The review or export could not be completed." = "The review or export could not be completed."; +"Recorded steps and sample files agree. Completion is not convergence." = "Recorded steps and sample files agree. Completion is not convergence."; +"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "The run is unfinished, incomplete or inconsistent. Review the source records and errors."; +"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not."; +"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence."; +"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space."; +"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy."; +"Simulated − observed" = "Simulated − observed"; +"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribution of simulated minus observed paired statistics. Zero is equality."; +"%@ valid pairs · %@ undefined" = "%@ valid pairs · %@ undefined"; +"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Replicate details are missing or disagree with the check record. The distribution is unavailable."; +"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test."; + +/* Optional joint topology/rate exchange. */ +"Try joint topology/rate exchange" = "Try joint topology/rate exchange"; +"Joint topology/rate exchange is currently available only without fossil dating." = "Joint topology/rate exchange is currently available only without fossil dating."; +"Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established." = "Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established."; + +// 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."; + +// Aligned DNA +"DNA · JC69" = "DNA · JC69"; +"Aligned DNA · JC69" = "Aligned DNA · JC69"; +"JC69 treats A, C, G and T equally. All four states remain possible at every site, and constant sites stay in the alignment." = "JC69 treats A, C, G and T equally. All four states remain possible at every site, and constant sites stay in the alignment."; +"Import sequences that are already aligned. Ambiguous IUPAC bases represent possible states, not extra nucleotides. Choose a gap policy in the matrix preview." = "Import sequences that are already aligned. Ambiguous IUPAC bases represent possible states, not extra nucleotides. Choose a gap policy in the matrix preview."; +"DNA JC69 keeps all four A/C/G/T states and all aligned sites, including constant sites." = "DNA JC69 keeps all four A/C/G/T states and all aligned sites, including constant sites."; +"The saved data type does not match the input." = "The saved data type does not match the input."; +"SITES" = "SITES"; +"Aligned positions" = "Aligned positions"; +"Constant sites are retained and contribute to the JC69 likelihood." = "Constant sites are retained and contribute to the JC69 likelihood."; +"IUPAC codes and braces specify possible bases: R means A or G, and N permits all four. These observations contribute to inference without being recoded as extra states." = "IUPAC codes and braces specify possible bases: R means A or G, and N permits all four. These observations contribute to inference without being recoded as extra states."; +"Predictive checks currently require single bases or missing cells. Ambiguous observations need an explicit observation model for simulation." = "Predictive checks currently require single bases or missing cells. Ambiguous observations need an explicit observation model for simulation."; +"Open a NEXUS matrix or aligned DNA in FASTA. Your data stays on this Mac." = "Open a NEXUS matrix or aligned DNA in FASTA. Your data stays on this Mac."; +"Choose a local NEXUS or aligned FASTA file from your Mac." = "Choose a local NEXUS or aligned FASTA file from your Mac."; +"Choose a NEXUS or aligned FASTA file, rather than a folder." = "Choose a NEXUS or aligned FASTA file, rather than a folder."; +"Drop a NEXUS or aligned FASTA file here, or browse your Mac." = "Drop a NEXUS or aligned FASTA file here, or browse your Mac."; +"Open or drop a NEXUS matrix, tree file or aligned DNA in FASTA" = "Open or drop a NEXUS matrix, tree file or aligned DNA in FASTA"; +"Import a morphological NEXUS matrix or aligned DNA in NEXUS or FASTA. Inspect the observations and review the model before starting an analysis." = "Import a morphological NEXUS matrix or aligned DNA in NEXUS or FASTA. Inspect the observations and review the model before starting an analysis."; +"Declared states: %@ · DNA" = "Declared states: %@ · DNA"; +"Choose a matrix or DNA alignment" = "Choose a matrix or DNA alignment"; +"Combine morphology and DNA" = "Combine morphology and DNA"; +"Select one morphological NEXUS matrix and one aligned DNA file. Rove matches normalized taxon names and preserves both source files in a new combined input." = "Select one morphological NEXUS matrix and one aligned DNA file. Rove matches normalized taxon names and preserves both source files in a new combined input."; +"Choose morphology" = "Choose morphology"; +"Choose aligned DNA" = "Choose aligned DNA"; +"Taxa absent from one source" = "Taxa absent from one source"; +"Require the same taxa" = "Require the same taxa"; +"Keep the union; absent cells are missing" = "Keep the union; absent cells are missing"; +"At least two taxa must be shared. Review unmatched names before choosing missing data; spelling differences are not biological absences." = "At least two taxa must be shared. Review unmatched names before choosing missing data; spelling differences are not biological absences."; +"Save combined input" = "Save combined input"; +"Morphology + DNA" = "Morphology + DNA"; +"Morphology" = "Morphology"; +"Each block keeps its own alphabet. Morphological conditioning and alphabet choices apply only to morphology; DNA always uses all four bases and includes constant sites." = "Each block keeps its own alphabet. Morphological conditioning and alphabet choices apply only to morphology; DNA always uses all four bases and includes constant sites."; +"Absent taxa filled with missing cells: %@" = "Absent taxa filled with missing cells: %@"; +"Morphology/DNA rate ratio" = "Morphology/DNA rate ratio"; +"Both blocks share the topology, branch clock and gamma shape. DNA fixes the reference rate at 1; the ratio scales every morphological partition. Separate clocks are not available." = "Both blocks share the topology, branch clock and gamma shape. DNA fixes the reference rate at 1; the ratio scales every morphological partition. Separate clocks are not available."; +"Choose a rate model" = "Choose a rate model"; +"Estimate with a lognormal prior" = "Estimate with a lognormal prior"; +"Fix the rate ratio" = "Fix the rate ratio"; +"Lognormal log-SD" = "Lognormal log-SD"; +"The prior is log(rate) ~ Normal(0, log-SD²), with median 1. This is a modeling assumption; assess its sensitivity for your data." = "The prior is log(rate) ~ Normal(0, log-SD²), with median 1. This is a modeling assumption; assess its sensitivity for your data."; +"Morphology relative rate" = "Morphology relative rate"; +"Choose whether to fix or estimate the morphology/DNA rate ratio." = "Choose whether to fix or estimate the morphology/DNA rate ratio."; +"Morphology rate and lognormal log-SD must be positive and finite." = "Morphology rate and lognormal log-SD must be positive and finite."; +"Estimated · log(rate) Normal(0, %@²)" = "Estimated · log(rate) Normal(0, %@²)"; +"Fixed morphology/DNA ratio: %@" = "Fixed morphology/DNA ratio: %@"; +"Morphology + DNA · Mk + JC69" = "Morphology + DNA · Mk + JC69"; +"The morphology-rate move requires an estimated mixed-data rate ratio." = "The morphology-rate move requires an estimated mixed-data rate ratio."; +"Declared states: %@ · morphology + DNA" = "Declared states: %@ · morphology + DNA"; +"· Morphology or aligned DNA" = "· Morphology or aligned DNA"; +"Morphology conditioning" = "Morphology conditioning"; +"Constant DNA sites remain in the JC69 block. Variable-only coding excludes constant morphological characters; review the partition and collection method before changing that choice." = "Constant DNA sites remain in the JC69 block. Variable-only coding excludes constant morphological characters; review the partition and collection method before changing that choice."; 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 4245cfb..6e564bc 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -298,7 +298,7 @@ "%@ on one side of the root; the other %@ terminals together on the other." = "%@ de um lado da raiz; os outros %@ terminais juntos do outro."; "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup." = "O grupo externo é um terminal, não o ancestral na raiz. Esta escolha obriga os demais a formar um grupo; o suporte dele é imposto pela configuração."; "No outgroup selected. Any applied groups below still constrain the tree." = "Nenhum grupo externo selecionado. Os grupos aplicados abaixo continuam restringindo a árvore."; -"Choose one outgroup from a matrix with at least three terminals." = "Escolha um grupo externo de uma matriz com pelo menos três terminais."; +"Choose one rooting taxon from a matrix with at least three terminals." = "Escolha um táxon de enraizamento de uma matriz com pelo menos três terminais."; "No groups applied. Root placement is unconstrained by groups." = "Nenhum grupo aplicado. Não há restrição de grupos sobre a posição da raiz."; "Applied groups" = "Grupos aplicados"; "Support for an imposed group is not independent evidence from the characters." = "O suporte de um grupo imposto não é uma evidência independente dos caracteres."; @@ -618,7 +618,7 @@ "Your research.\nRoom to explore." = "Sua pesquisa.\nEspaço para explorar."; "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion." = "O Rove explora relações evolutivas a partir de dados morfológicos. Um aplicativo nativo, um motor em Rust e um companheiro curioso."; "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything." = "As linhas são táxons. As colunas são caracteres. Abra uma matriz NEXUS para conferir os estados e as observações ausentes antes de iniciar uma análise."; -"Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you." = "Revise o modelo e escolha seu grupo externo. Ele define uma restrição para a raiz da análise; o Rove não faz essa escolha por você."; +"Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you." = "Revise o modelo e escolha explicitamente um táxon para enraizamento. Ele restringe a divisão na raiz; o Rove não faz essa escolha por você."; "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis." = "Acompanhe a execução, examine os traços e explore as árvores. O Histórico reúne seu trabalho e os pontos salvos para retomar análises pausadas."; "YOUR FIRST FIELD TRIP" = "SUA PRIMEIRA EXPLORAÇÃO"; "A SMALL INTRODUCTION" = "UMA BREVE APRESENTAÇÃO"; @@ -637,7 +637,7 @@ "Illustration of a morphological matrix" = "Ilustração de uma matriz morfológica"; "? means an unknown observation." = "? indica uma observação desconhecida."; "For the bundled example" = "No exemplo do aplicativo"; -"Choose T20 as the outgroup. Check the remaining settings before starting." = "Escolha T20 como grupo externo. Confira as outras opções antes de começar."; +"Choose T20 as the taxon used for rooting. Check the remaining settings before starting." = "Escolha T20 como táxon de enraizamento. Confira as outras opções antes de começar."; "Check the sampling" = "Confira a amostragem"; "Useful samples matter more than step counts." = "Amostras úteis valem mais do que contar passos."; "Explore the trees" = "Explore as árvores"; @@ -655,7 +655,7 @@ "A small beginning, with room for big questions. Meet the tools already inside this beta." = "Um pequeno começo, com espaço para grandes perguntas. Conheça as ferramentas que já estão neste beta."; "Bring all the little differences." = "Traga cada pequena diferença."; "Morphological matrices, with two, three or more states." = "Matrizes morfológicas com dois, três ou mais estados."; -"Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start." = "Importe uma matriz NEXUS, confira as partições por estados e escolha o grupo externo. O exemplo 20 × 50 do aplicativo é um bom ponto de partida."; +"Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start." = "Importe uma matriz NEXUS, confira as partições por estados e escolha explicitamente o táxon de enraizamento. O exemplo 20 × 50 do aplicativo é um bom ponto de partida."; "Good work deserves a save point." = "Bom trabalho merece um ponto salvo."; "Find past runs. Pause a long analysis. Pick up where you left off." = "Encontre análises anteriores, pause uma execução longa e retome de onde parou."; "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input." = "O Histórico reúne as configurações e os caminhos dos resultados. Os pontos salvos preservam o estado do amostrador; para retomar, use o mesmo motor e os dados originais."; @@ -950,7 +950,7 @@ "The tree file could not be opened." = "Não foi possível abrir o arquivo de árvores."; "The tree file is no longer at its recorded path." = "O arquivo de árvores não está mais no caminho registrado."; "Trees from another program" = "Árvores de outro programa"; -"Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." = "O Rove não rodou esta amostra aqui, então nenhum grupo externo é conhecido. Um resumo e suporte alto nos nós não comprovam convergência."; +"Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." = "O Rove não rodou esta amostra aqui, então a escolha de enraizamento é desconhecida. Um resumo e suporte alto nos nós não comprovam convergência."; "The tree file is no longer at its recorded path. Saved summaries stay available." = "O arquivo de árvores não está mais no caminho registrado. Os resumos salvos continuam disponíveis."; "Summaries" = "Resumos"; "No summary yet. Summarize the file to build an annotated MCC tree." = "Nenhum resumo ainda. Resuma o arquivo para construir uma árvore MCC anotada."; @@ -1105,3 +1105,124 @@ "Inspect ambiguous observations" = "Inspecionar observações ambíguas"; "Up to 100 observations are listed; the counts include the full matrix." = "A lista mostra até 100 observações; as contagens incluem a matriz inteira."; "Alphabet choice" = "Escolha do alfabeto"; + +// Visual model guidance. +"Prior density" = "Densidade do prior"; +"Expected sigma" = "Sigma esperado"; +"Gamma prior for clock sigma; the dashed line marks its expectation." = "Prior gamma do sigma do relógio; a linha tracejada marca sua esperança."; +"The density preview is unavailable at this numerical scale." = "A prévia da densidade não está disponível nessa escala numérica."; +"Expected sigma: %@ · standard deviation: %@" = "Sigma esperado: %@ · desvio padrão: %@"; +"The density grows without bound near zero; the curve starts above zero." = "A densidade cresce sem limite perto de zero; a curva começa acima de zero."; +"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "Esta é uma prévia do prior, antes de observar os dados. O intervalo exibido não é um intervalo de credibilidade."; +"Other %@ terminals" = "Outros %@ terminais"; +"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Diagrama da restrição. Os comprimentos dos ramos e as relações dentro do grupo recolhido não são estimados aqui."; + +/* Evidence review and reproducibility exports. */ +"Evidence review" = "Revisão das evidências"; +"What does this run establish?" = "O que esta execução permite concluir?"; +"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Revise separadamente a conclusão, a amostragem e os relatórios disponíveis. Este registro não certifica convergência nem adequação do modelo."; +"Refresh evidence review" = "Atualizar revisão das evidências"; +"Matching tree reports: %@ · Predictive reports: %@" = "Relatórios de árvores correspondentes: %@ · Relatórios preditivos: %@"; +"Review record" = "Registro da revisão"; +"Include the original matrix in the export" = "Incluir a matriz original na exportação"; +"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "O pacote local inclui configurações, sementes, identificação das compilações, amostras, diagnósticos e relatórios derivados com identificadores SHA-256. Os caminhos registrados e os nomes dos táxons são preservados. A retomada exata ainda exige o executável original e um checkpoint válido."; +"Export reproducibility package…" = "Exportar pacote de reprodução…"; +"Choose export folder" = "Escolher pasta de exportação"; +"Open exported package" = "Abrir pacote exportado"; +"Run completion" = "Conclusão da execução"; +"Scalar sampling" = "Amostragem dos parâmetros"; +"Independent-chain agreement" = "Concordância entre cadeias independentes"; +"Tree evidence" = "Evidências das árvores"; +"Predictive evidence" = "Evidências preditivas"; +"Criteria met" = "Critérios atendidos"; +"Needs attention" = "Precisa de atenção"; +"Interpretation required" = "Requer interpretação"; +"Evidence unavailable" = "Evidência indisponível"; +"The original matrix matches the recorded fingerprint." = "A matriz original corresponde ao identificador registrado."; +"The original matrix has changed. Matrix inclusion will be refused." = "A matriz original foi alterada. Sua inclusão será recusada."; +"The original matrix is unavailable. Records can still be exported without it." = "A matriz original está indisponível. Os registros ainda podem ser exportados sem ela."; +"The review or export was cancelled." = "A revisão ou exportação foi cancelada."; +"The review or export could not be completed." = "Não foi possível concluir a revisão ou exportação."; +"Recorded steps and sample files agree. Completion is not convergence." = "Os passos registrados e os arquivos de amostras correspondem. Concluir a execução não significa convergir."; +"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "A execução não terminou, está incompleta ou contém inconsistências. Revise os registros de origem e os erros."; +"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Revise todos os parâmetros amostrados: pelo menos 1.000 amostras retidas e ESS de 200 por cadeia, sem truncamento das defasagens. Valores comprovadamente fixos pelo modelo são excluídos; parâmetros amostrados que ficaram constantes não são."; +"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "A avaliação entre cadeias exige sementes independentes, entrada e modelo correspondentes, ESS de 200 por cadeia, pelo menos 1.000 amostras retidas e R-hat dividido e normalizado por postos de no máximo 1,01. Esses diagnósticos não comprovam convergência."; +"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Revise os resumos de árvores e as frequências dos clados sem restrição. Suporte alto ou concordância em clados constantes não demonstra exploração do espaço de árvores."; +"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Revise as discrepâncias preditivas pareadas, os pares indefinidos e a incerteza da simulação. Uma verificação salva, por si só, não demonstra adequação do modelo."; +"Simulated − observed" = "Simulado − observado"; +"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribuição das diferenças pareadas entre estatísticas simuladas e observadas. Zero indica igualdade."; +"%@ valid pairs · %@ undefined" = "%@ pares válidos · %@ indefinidos"; +"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Os detalhes das réplicas estão ausentes ou não correspondem ao registro da verificação. A distribuição está indisponível."; +"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Cada diferença usa a matriz simulada e a observada na mesma árvore posterior. A estatística observada pode variar conforme a árvore. Zero indica igualdade; este é um gráfico de discrepâncias, não um teste de convergência."; + +/* Optional joint topology/rate exchange. */ +"Try joint topology/rate exchange" = "Experimentar troca conjunta de topologia e taxas"; +"Joint topology/rate exchange is currently available only without fossil dating." = "A troca conjunta de topologia e taxas está disponível, por enquanto, apenas sem datação de fósseis."; +"Experimental, off by default. Exchanges neighboring subtrees and compensates their branch rates. Requires an undated relaxed clock. The weight starts at 10 and can be edited above; no performance benefit has been established." = "Experimental, desativada por padrão. Troca subárvores vizinhas e compensa suas taxas de ramo. Exige relógio relaxado sem datação. O peso inicial é 10 e pode ser editado acima; ainda não foi demonstrado ganho de desempenho."; + +// 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."; + +// Aligned DNA +"DNA · JC69" = "DNA · JC69"; +"Aligned DNA · JC69" = "DNA alinhado · JC69"; +"JC69 treats A, C, G and T equally. All four states remain possible at every site, and constant sites stay in the alignment." = "JC69 trata A, C, G e T igualmente. Os quatro estados permanecem possíveis em cada sítio, e sítios constantes ficam no alinhamento."; +"Import sequences that are already aligned. Ambiguous IUPAC bases represent possible states, not extra nucleotides. Choose a gap policy in the matrix preview." = "Importe sequências já alinhadas. Bases IUPAC ambíguas representam estados possíveis, não nucleotídeos adicionais. Escolha como tratar gaps na prévia da matriz."; +"DNA JC69 keeps all four A/C/G/T states and all aligned sites, including constant sites." = "JC69 para DNA mantém os quatro estados A/C/G/T e todos os sítios alinhados, inclusive os constantes."; +"The saved data type does not match the input." = "O tipo de dados salvo não corresponde ao arquivo de entrada."; +"SITES" = "SÍTIOS"; +"Aligned positions" = "Posições alinhadas"; +"Constant sites are retained and contribute to the JC69 likelihood." = "Sítios constantes são mantidos e contribuem para a verossimilhança de JC69."; +"IUPAC codes and braces specify possible bases: R means A or G, and N permits all four. These observations contribute to inference without being recoded as extra states." = "Códigos IUPAC e chaves especificam bases possíveis: R significa A ou G, e N permite as quatro. Essas observações entram na inferência sem se tornarem estados adicionais."; +"Predictive checks currently require single bases or missing cells. Ambiguous observations need an explicit observation model for simulation." = "As verificações preditivas atualmente exigem bases individuais ou células ausentes. Observações ambíguas precisam de um modelo de observação explícito para simulação."; +"Open a NEXUS matrix or aligned DNA in FASTA. Your data stays on this Mac." = "Abra uma matriz NEXUS ou DNA alinhado em FASTA. Seus dados ficam neste Mac."; +"Choose a local NEXUS or aligned FASTA file from your Mac." = "Escolha um arquivo NEXUS ou FASTA alinhado neste Mac."; +"Choose a NEXUS or aligned FASTA file, rather than a folder." = "Escolha um arquivo NEXUS ou FASTA alinhado, em vez de uma pasta."; +"Drop a NEXUS or aligned FASTA file here, or browse your Mac." = "Solte um arquivo NEXUS ou FASTA alinhado aqui, ou procure no Mac."; +"Open or drop a NEXUS matrix, tree file or aligned DNA in FASTA" = "Abra ou solte uma matriz NEXUS, arquivo de árvores ou DNA alinhado em FASTA"; +"Import a morphological NEXUS matrix or aligned DNA in NEXUS or FASTA. Inspect the observations and review the model before starting an analysis." = "Importe uma matriz morfológica NEXUS ou DNA alinhado em NEXUS ou FASTA. Confira as observações e revise o modelo antes de iniciar a análise."; +"Declared states: %@ · DNA" = "Estados declarados: %@ · DNA"; +"Choose a matrix or DNA alignment" = "Escolha uma matriz ou um alinhamento de DNA"; +"Combine morphology and DNA" = "Combinar morfologia e DNA"; +"Select one morphological NEXUS matrix and one aligned DNA file. Rove matches normalized taxon names and preserves both source files in a new combined input." = "Selecione uma matriz morfológica NEXUS e um arquivo de DNA alinhado. O Rove compara os nomes normalizados dos táxons e preserva os dois arquivos em uma nova entrada combinada."; +"Choose morphology" = "Escolher morfologia"; +"Choose aligned DNA" = "Escolher DNA alinhado"; +"Taxa absent from one source" = "Táxons ausentes em uma das fontes"; +"Require the same taxa" = "Exigir os mesmos táxons"; +"Keep the union; absent cells are missing" = "Manter a união; preencher ausências com dados faltantes"; +"At least two taxa must be shared. Review unmatched names before choosing missing data; spelling differences are not biological absences." = "As fontes precisam compartilhar ao menos dois táxons. Confira os nomes sem correspondência antes de escolher dados faltantes; diferenças de escrita não são ausências biológicas."; +"Save combined input" = "Salvar entrada combinada"; +"Morphology + DNA" = "Morfologia + DNA"; +"Morphology" = "Morfologia"; +"Each block keeps its own alphabet. Morphological conditioning and alphabet choices apply only to morphology; DNA always uses all four bases and includes constant sites." = "Cada bloco mantém seu próprio alfabeto. A correção de amostragem e a escolha do alfabeto valem só para a morfologia; o DNA sempre usa as quatro bases e inclui sítios constantes."; +"Absent taxa filled with missing cells: %@" = "Táxons ausentes preenchidos com dados faltantes: %@"; +"Morphology/DNA rate ratio" = "Razão de taxas morfologia/DNA"; +"Both blocks share the topology, branch clock and gamma shape. DNA fixes the reference rate at 1; the ratio scales every morphological partition. Separate clocks are not available." = "Os blocos compartilham a topologia, o relógio dos ramos e a forma da gama. O DNA fixa a taxa de referência em 1; a razão multiplica todas as partições morfológicas. Relógios separados não estão disponíveis."; +"Choose a rate model" = "Escolha um modelo de taxa"; +"Estimate with a lognormal prior" = "Estimar com prior lognormal"; +"Fix the rate ratio" = "Fixar a razão de taxas"; +"Lognormal log-SD" = "Desvio padrão do log da taxa"; +"The prior is log(rate) ~ Normal(0, log-SD²), with median 1. This is a modeling assumption; assess its sensitivity for your data." = "O prior é log(taxa) ~ Normal(0, desvio²), com mediana 1. Essa é uma premissa do modelo; avalie a sensibilidade para seus dados."; +"Morphology relative rate" = "Taxa relativa da morfologia"; +"Choose whether to fix or estimate the morphology/DNA rate ratio." = "Escolha entre fixar ou estimar a razão de taxas morfologia/DNA."; +"Morphology rate and lognormal log-SD must be positive and finite." = "A taxa da morfologia e o desvio padrão do log devem ser positivos e finitos."; +"Estimated · log(rate) Normal(0, %@²)" = "Estimada · log(taxa) Normal(0, %@²)"; +"Fixed morphology/DNA ratio: %@" = "Razão morfologia/DNA fixa: %@"; +"Morphology + DNA · Mk + JC69" = "Morfologia + DNA · Mk + JC69"; +"The morphology-rate move requires an estimated mixed-data rate ratio." = "O movimento da taxa morfológica exige uma razão estimada na análise combinada."; +"Declared states: %@ · morphology + DNA" = "Estados declarados: %@ · morfologia + DNA"; +"· Morphology or aligned DNA" = "· Morfologia ou DNA alinhado"; +"Morphology conditioning" = "Correção de amostragem da morfologia"; +"Constant DNA sites remain in the JC69 block. Variable-only coding excludes constant morphological characters; review the partition and collection method before changing that choice." = "Sítios constantes de DNA permanecem no bloco JC69. A seleção de variáveis exclui caracteres morfológicos constantes; confira a partição e o método de coleta antes de mudar essa escolha."; diff --git a/apps/macos/Sources/RoveApp/RootView.swift b/apps/macos/Sources/RoveApp/RootView.swift index dd7245c..2a89462 100644 --- a/apps/macos/Sources/RoveApp/RootView.swift +++ b/apps/macos/Sources/RoveApp/RootView.swift @@ -67,6 +67,7 @@ struct RootView: View { reduceMotion || workspace.preferences.reduceMotion ? nil : .easeInOut(duration: 0.2), value: workspace.page ) + .sheet(isPresented: $workspace.showingMixedImport) { MixedImportView(workspace: workspace) } .sheet(item: $workspace.treeSummary) { summary in TreeSummaryView(model: summary, strings: workspace.strings) { directory in workspace.openTree(directory, run: summary.directory) @@ -125,7 +126,7 @@ struct RootView: View { Text(strings("A first look at Rove")).font(Lab.display(23)) Text( strings( - "Import a morphological NEXUS matrix, inspect its characters and prepare an analysis. The preview supports the engine's current binary Mk and Mkv models." + "Import a morphological NEXUS matrix or aligned DNA in NEXUS or FASTA. Inspect the observations and review the model before starting an analysis." ) ) Text( @@ -158,7 +159,10 @@ struct RootView: View { } else { Text( strings( - "Declared states: %@ · morphological data", + workspace.report?.isMixed == true + ? "Declared states: %@ · morphology + DNA" + : workspace.report?.isDNA == true + ? "Declared states: %@ · DNA" : "Declared states: %@ · morphological data", strings.number(workspace.report?.symbols.count ?? 0)) ) .font(.system(size: 11)).foregroundStyle(Lab.muted) diff --git a/apps/macos/Sources/RoveApp/RootingView.swift b/apps/macos/Sources/RoveApp/RootingView.swift index 7869435..4c0d2be 100644 --- a/apps/macos/Sources/RoveApp/RootingView.swift +++ b/apps/macos/Sources/RoveApp/RootingView.swift @@ -30,6 +30,7 @@ struct RootingSection: View { ) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) if let outgroup = workspace.outgroup { + RootingConstraintDiagram(taxon: outgroup, remaining: taxa.count - 1, strings: strings) HStack(alignment: .top, spacing: 12) { Image(systemName: "point.3.connected.trianglepath.dotted") .font(.system(size: 22)).foregroundStyle(Lab.ice).accessibilityHidden(true) @@ -46,6 +47,7 @@ struct RootingSection: View { ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) } }.padding(16).background(Lab.ice.opacity(0.045), in: RoundedRectangle(cornerRadius: 12)) } else { @@ -66,6 +68,61 @@ struct RootingSection: View { } } +struct RootingConstraintDiagram: View { + let taxon: String + let remaining: Int + let strings: AppStrings + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 14) { + Canvas { context, size in + var branches = Path() + branches.move(to: CGPoint(x: 10, y: 48)) + branches.addLine(to: CGPoint(x: 40, y: 48)) + branches.move(to: CGPoint(x: 40, y: 18)) + branches.addLine(to: CGPoint(x: 40, y: 76)) + branches.move(to: CGPoint(x: 40, y: 18)) + branches.addLine(to: CGPoint(x: size.width - 6, y: 18)) + branches.move(to: CGPoint(x: 40, y: 76)) + branches.addLine(to: CGPoint(x: 70, y: 76)) + context.stroke(branches, with: .color(Lab.ice), lineWidth: 2) + context.fill( + Path(ellipseIn: CGRect(x: 6, y: 44, width: 8, height: 8)), + with: .color(Lab.accent)) + var group = Path() + group.move(to: CGPoint(x: 70, y: 76)) + group.addLine(to: CGPoint(x: size.width - 6, y: 53)) + group.addLine(to: CGPoint(x: size.width - 6, y: 96)) + group.closeSubpath() + context.fill(group, with: .color(Lab.lilac.opacity(0.2))) + context.stroke(group, with: .color(Lab.lilac), lineWidth: 1.5) + }.frame(width: 140, height: 100).accessibilityHidden(true) + VStack(alignment: .leading, spacing: 0) { + Text(taxon).font(.system(size: 12, weight: .medium)).foregroundStyle(Lab.ice) + .frame(height: 36, alignment: .center) + Spacer(minLength: 0) + Text(strings("Other %@ terminals", strings.number(remaining))) + .font(.system(size: 12)).foregroundStyle(Lab.lilac) + .frame(height: 46, alignment: .center) + }.frame(height: 100) + } + Text( + strings( + "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel( + strings( + "%@ on one side of the root; the other %@ terminals together on the other.", taxon, + strings.number(remaining))) + } +} + struct ConstraintSummary: View { let outgroup: String? let taxa: [String]? diff --git a/apps/macos/Sources/RoveApp/RunAssessment.swift b/apps/macos/Sources/RoveApp/RunAssessment.swift new file mode 100644 index 0000000..95bb550 --- /dev/null +++ b/apps/macos/Sources/RoveApp/RunAssessment.swift @@ -0,0 +1,164 @@ +import Foundation +import Observation + +struct RunAssessment: Decodable, Sendable { + struct Section: Decodable, Sendable, Identifiable { + let id: String + let status: String + let message: String + } + let schemaVersion: Int + let kind: String + let createdUnixSeconds: Double + let source: String + let chainCount: Int + let burninPercent: Int + let originalMatrixStatus: String + let sections: [Section] + let treeReports: [String] + let predictiveReports: [String] + let convergenceCertified: Bool + + static func read(_ directory: URL) throws -> Self { + let file = directory.appendingPathComponent("assessment.json") + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard info.isRegularFile == true, (info.fileSize ?? 0) <= 128 * 1024 * 1024 else { + throw RunFailure.invalidCompletion + } + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let value = try decoder.decode(Self.self, from: Data(contentsOf: file)) + guard value.schemaVersion == 1, value.kind == "run_assessment", + value.createdUnixSeconds.isFinite, (1...16).contains(value.chainCount), + (0..<100).contains(value.burninPercent), !value.convergenceCertified, + Set(value.sections.map(\.id)) + == Set(["completion", "sampling", "agreement", "trees", "prediction"]), + value.sections.count == 5, + value.sections.allSatisfy({ + ["passed", "attention", "unavailable", "review_required"].contains($0.status) + }) + else { throw RunFailure.invalidCompletion } + return value + } +} + +struct AssessmentOptions: Codable, Sendable { + var burnin = "10" + var includeMatrix = false + var valid: Bool { Int(burnin).map { (0..<100).contains($0) } == true } +} + +struct AssessmentRequest: Sendable { + let entry: HistoryEntry + let executable: URL + let output: URL + let options: AssessmentOptions + let export: Bool + + func execute(with tool: EngineTool) async throws -> RunAssessment { + guard options.valid else { throw ImportError.message("Choose a burn-in from 0 to 99 percent.") } + var arguments = [ + export ? "export-run" : "assess", entry.directory.path, + "--output", output.path, "--burnin-percent", options.burnin, "--cancel-on-stdin-close", + ] + if export && options.includeMatrix { + guard let draft = entry.draft else { throw RunFailure.invalidCompletion } + arguments += ["--include-matrix", draft.matrixPath] + } + let outcome = try await tool.execute( + executable: executable, arguments: arguments, onLine: { _ in }) + guard outcome.status == 0 else { throw ImportError.readerFailed(outcome.log) } + let report = try RunAssessment.read(output) + guard + URL(fileURLWithPath: report.source).standardizedFileURL.resolvingSymlinksInPath().path + == entry.directory.standardizedFileURL.resolvingSymlinksInPath().path + else { throw RunFailure.invalidCompletion } + return report + } +} + +@MainActor @Observable +final class RunAssessmentModel { + let entry: HistoryEntry + let executable: URL + var options = AssessmentOptions() + private(set) var busy = false + private(set) var report: RunAssessment? + private(set) var reportDirectory: URL? + private(set) var exported: URL? + private(set) var error: String? + private(set) var details: String? + private var tool: EngineTool? + private var task: Task? + private var parent: URL { entry.directory.appendingPathComponent("assessments") } + + init(entry: HistoryEntry, executable: URL) { + self.entry = entry + self.executable = executable + } + + func load() async { + guard !busy else { return } + let directory = parent + let loaded = await Task.detached { + let options = try? JSONDecoder().decode( + AssessmentOptions.self, + from: RecordFile.read(directory.appendingPathComponent("options.json"))) + let children = + (try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil)) ?? [] + let reports = children.compactMap { file -> (URL, RunAssessment)? in + guard let value = try? RunAssessment.read(file) else { return nil } + return (file, value) + }.sorted { $0.1.createdUnixSeconds > $1.1.createdUnixSeconds } + return (options, reports.first) + }.value + if let restored = loaded.0, restored.valid { options = restored } + if let saved = loaded.1, + URL(fileURLWithPath: saved.1.source).standardizedFileURL.resolvingSymlinksInPath().path + == entry.directory.standardizedFileURL.resolvingSymlinksInPath().path + { + reportDirectory = saved.0 + report = saved.1 + } + } + + func start(exportTo destination: URL? = nil) { + guard !busy, options.valid else { return } + busy = true + error = nil + details = nil + exported = nil + let tool = EngineTool() + self.tool = tool + let request = AssessmentRequest( + entry: entry, executable: executable, + output: destination ?? parent.appendingPathComponent("review-\(UUID())"), + options: options, export: destination != nil) + task = Task { + do { + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + try JSONEncoder().encode(request.options).write( + to: parent.appendingPathComponent("options.json"), options: .atomic) + let value = try await request.execute(with: tool) + if destination != nil { + exported = request.output + } else { + report = value + reportDirectory = request.output + } + } catch is CancellationError { + error = "The review or export was cancelled." + } catch { + self.error = "The review or export could not be completed." + details = error.localizedDescription + } + busy = false + self.tool = nil + } + } + + func cancel() { tool?.cancel() } + func waitForExit() async { await task?.value } +} diff --git a/apps/macos/Sources/RoveApp/RunAssessmentView.swift b/apps/macos/Sources/RoveApp/RunAssessmentView.swift new file mode 100644 index 0000000..a67abaf --- /dev/null +++ b/apps/macos/Sources/RoveApp/RunAssessmentView.swift @@ -0,0 +1,131 @@ +import SwiftUI + +struct RunAssessmentView: View { + @Bindable var workspace: Workspace + let entry: HistoryEntry + @State private var model: RunAssessmentModel? + private var strings: AppStrings { workspace.strings } + + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 16) { + Eyebrow(text: strings("Evidence review"), color: Lab.lilac) + Text(strings("What does this run establish?")).font(Lab.display(25)) + Text( + strings( + "Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + if let model { content(model) } + } + }.task(id: entry.id) { + let value = workspace.runAssessment(for: entry) + model = value + await value.load() + } + } + + @ViewBuilder private func content(_ model: RunAssessmentModel) -> some View { + @Bindable var model = model + HStack { + Text(strings("Burn-in (%)")) + TextField(strings("Burn-in (%)"), text: $model.options.burnin).textFieldStyle(.roundedBorder) + .frame(width: 70) + Button(strings("Refresh evidence review")) { model.start() } + .buttonStyle(LabButtonStyle(prominent: true)).disabled( + !model.options.valid || model.busy || workspace.isRunning) + if model.busy { + ProgressView().controlSize(.small) + Button(strings("Cancel")) { model.cancel() }.buttonStyle(LabButtonStyle(compact: true)) + } + }.font(.system(size: 11)) + if let report = model.report { + Text( + Date(timeIntervalSince1970: report.createdUnixSeconds).formatted( + .dateTime.day().month().year().hour().minute().locale(strings.locale)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + ForEach(report.sections) { section in + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(strings(Self.title(section.id))).font(.system(size: 12, weight: .medium)) + Spacer() + Text(strings(Self.status(section.status))).foregroundStyle( + section.status == "passed" ? Lab.accent : Lab.secondary) + } + Text(strings(section.message)).font(.system(size: 10)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + Text( + strings( + "Matching tree reports: %@ · Predictive reports: %@", String(report.treeReports.count), + String(report.predictiveReports.count)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + Text(strings(Self.inputStatus(report.originalMatrixStatus))).font(.system(size: 10)) + .foregroundStyle(Lab.secondary) + if let directory = model.reportDirectory { + Button(strings("Review record")) { + NSWorkspace.shared.open(directory.appendingPathComponent("assessment.json")) + } + .buttonStyle(LabButtonStyle(compact: true)) + } + } + Divider().overlay(Lab.border) + Toggle(strings("Include the original matrix in the export"), isOn: $model.options.includeMatrix) + .font(.system(size: 11)).disabled(model.busy) + Text( + strings( + "The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + Button(strings("Export reproducibility package…")) { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.canCreateDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = strings("Choose export folder") + guard panel.runModal() == .OK, let folder = panel.url else { return } + model.start(exportTo: folder.appendingPathComponent("rove-export-\(UUID().uuidString)")) + }.buttonStyle(LabButtonStyle(compact: true)).disabled( + !model.options.valid || model.busy || workspace.isRunning) + if let exported = model.exported { + Button(strings("Open exported package")) { NSWorkspace.shared.open(exported) }.buttonStyle( + LabButtonStyle(compact: true)) + } + if let error = model.error { + DiagnosticMessage(title: strings(error), details: model.details, strings: strings) + } + } + + static func title(_ id: String) -> String { + switch id { + case "completion": "Run completion" + case "sampling": "Scalar sampling" + case "agreement": "Independent-chain agreement" + case "trees": "Tree evidence" + default: "Predictive evidence" + } + } + static func status(_ value: String) -> String { + switch value { + case "passed": "Criteria met" + case "attention": "Needs attention" + case "review_required": "Interpretation required" + default: "Evidence unavailable" + } + } + static func inputStatus(_ value: String) -> String { + switch value { + case "matches": "The original matrix matches the recorded fingerprint." + case "changed": "The original matrix has changed. Matrix inclusion will be refused." + default: "The original matrix is unavailable. Records can still be exported without it." + } + } +} diff --git a/apps/macos/Sources/RoveApp/RunComparison.swift b/apps/macos/Sources/RoveApp/RunComparison.swift index 71fc7d5..04a1e42 100644 --- a/apps/macos/Sources/RoveApp/RunComparison.swift +++ b/apps/macos/Sources/RoveApp/RunComparison.swift @@ -150,6 +150,15 @@ 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.dataType == y.settings.dataType, x.mixedInput == y.mixedInput, + x.settings.dataType != "mixed" + || (x.settings.morphologyRateMode == y.settings.morphologyRateMode + && (x.settings.morphologyRateMode == "estimate" + ? x.settings.morphologyLogSDValue == y.settings.morphologyLogSDValue + : x.settings.morphologyRateValue == y.settings.morphologyRateValue)), + 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..24d55da 100644 --- a/apps/macos/Sources/RoveApp/RunRecord.swift +++ b/apps/macos/Sources/RoveApp/RunRecord.swift @@ -31,6 +31,7 @@ struct EngineRecord: Decodable, Sendable { struct Input: Decodable, Sendable { let sha256: String let gaps: String + var mixed: MixedInputMetadata? = nil } struct Settings: Decodable, Sendable { let steps: UInt64 @@ -48,6 +49,46 @@ struct EngineRecord: Decodable, Sendable { var clockSigmaPriorParameters: ClockSigmaPrior? = nil var sampleFromPrior: Bool? = nil var conditioning: String? = nil + var dataType: String? = nil + var substitutionModel: String? = nil + var mixedModel: MixedModel? = nil + var resolvedDataType: String { dataType ?? "standard" } + + func dataModelMatches(_ settings: AnalysisSettings) -> Bool { + guard resolvedDataType == settings.dataType else { return false } + if resolvedDataType == "mixed" { + return substitutionModel == "mk+jc69" && mixedModel?.matches(settings) == true + } + return resolvedDataType == "dna" + ? substitutionModel == "jc69" && conditioning == "none (JC69)" : substitutionModel == nil + } + + var conditioningKind: String? { + if conditioning == "none (JC69)", resolvedDataType == "dna" { return "none" } + return Self.conditioningDescriptions.first { $0.value == conditioning }?.key + } + + 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 = [ @@ -57,7 +98,8 @@ struct EngineRecord: Decodable, Sendable { /// The model name in the engine's description of its conditioning. var conditioningLabel: String { - switch conditioning { + if resolvedDataType == "dna" { return "JC69" } + return switch conditioning { case "none (Mk)": "Mk" case "variable characters (Mkv)": "Mkv" case "parsimony-informative characters (Mkparsinf)": "Mkparsinf" @@ -103,12 +145,14 @@ struct EngineRecord: Decodable, Sendable { if let index = command.firstIndex(of: "--conditioning"), command.indices.contains(index + 1) { conditioning = command[index + 1] } else { - conditioning = Model.conditioningDescriptions.first { $0.value == model.conditioning }?.key + conditioning = model.conditioningKind } 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) + && model.dataModelMatches(draft.settings) + && input.mixed == draft.mixedInput && 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..617b11c 100644 --- a/apps/macos/Sources/RoveApp/SetupView.swift +++ b/apps/macos/Sources/RoveApp/SetupView.swift @@ -39,53 +39,60 @@ struct SetupView: View { if workspace.settings.clock == "reference" { ClockSigmaPriorSection(workspace: workspace) } + TreePriorSection(workspace: workspace) DatingSection(workspace: workspace) - LabPanel { - VStack(alignment: .leading, spacing: 15) { - HStack { - VStack(alignment: .leading, spacing: 6) { - Text(strings("Which characters did you include?")).font( - .system(size: 13, weight: .semibold)) - Text(strings("Match the model to how your matrix was collected.")) - .font(.system(size: 11)).foregroundStyle(Lab.secondary) + if workspace.settings.dataType == "mixed" { MixedRateSection(workspace: workspace) } + if workspace.settings.dataType == "dna" { + NucleotideModelSection(strings: strings) + } else { + LabPanel { + VStack(alignment: .leading, spacing: 15) { + HStack { + VStack(alignment: .leading, spacing: 6) { + Text(strings("Which characters did you include?")).font( + .system(size: 13, weight: .semibold)) + Text(strings("Match the model to how your matrix was collected.")) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } + Spacer() + Picker(strings("Character selection"), selection: $workspace.settings.conditioning) { + Text(strings("Variable only · Mkv")).tag("variable") + Text(strings("Informative only · Mkparsinf")).tag("informative") + Text(strings("All characters · Mk")).tag("none") + }.labelsHidden().frame(width: 230).tint(Lab.accent) } - Spacer() - Picker(strings("Character selection"), selection: $workspace.settings.conditioning) { - Text(strings("Variable only · Mkv")).tag("variable") - Text(strings("Informative only · Mkparsinf")).tag("informative") - Text(strings("All characters · Mk")).tag("none") - }.labelsHidden().frame(width: 230).tint(Lab.accent) - } - Text( - strings( - workspace.settings.conditioning == "variable" - ? "Use Mkv when constant characters were excluded. Missing observations can make a character's variability impossible to establish." - : workspace.settings.conditioning == "informative" - ? "Use Mkparsinf only when constant and other parsimony-uninformative characters were excluded when the matrix was collected. Every retained character must remain informative despite missing or uncertain observations." - : "Use Mk when your sampling includes constant as well as variable characters. The matrix can contain both." + Text( + strings( + workspace.settings.conditioning == "variable" + ? "Use Mkv when constant characters were excluded. Missing observations can make a character's variability impossible to establish." + : workspace.settings.conditioning == "informative" + ? "Use Mkparsinf only when constant and other parsimony-uninformative characters were excluded when the matrix was collected. Every retained character must remain informative despite missing or uncertain observations." + : "Use Mk when your sampling includes constant as well as variable characters. The matrix can contain both." + ) ) - ) - .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) - if workspace.settings.conditioning == "variable", - let issue = workspace.report?.variableError - { - DiagnosticMessage( - title: strings( - "Mkv requires characters known to be variable. Check the matrix or choose Mk if it matches how your data were collected." - ), details: issue, strings: strings) - } - if workspace.settings.conditioning == "informative", - let issue = workspace.report?.informativeError - { - DiagnosticMessage( - title: strings( - workspace.report?.partitions?.contains(where: { $0.ordering == .ordered }) == true - ? "Informative-only coding is not available for ordered characters. Keep the coding consistent with how your matrix was collected." - : "Informative-only coding requires at least two states each shared by two or more taxa. Check the matrix and how its characters were selected." - ), details: issue, strings: strings) + .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) + if workspace.settings.conditioning == "variable", + let issue = workspace.report?.variableError + { + DiagnosticMessage( + title: strings( + "Mkv requires characters known to be variable. Check the matrix or choose Mk if it matches how your data were collected." + ), details: issue, strings: strings) + } + if workspace.settings.conditioning == "informative", + let issue = workspace.report?.informativeError + { + DiagnosticMessage( + title: strings( + workspace.report?.partitions?.contains(where: { $0.ordering == .ordered }) == true + ? "Informative-only coding is not available for ordered characters. Keep the coding consistent with how your matrix was collected." + : "Informative-only coding requires at least two states each shared by two or more taxa. Check the matrix and how its characters were selected." + ), details: issue, strings: strings) + } } } + } LabPanel { @@ -301,6 +308,8 @@ struct ReviewView: View { .foregroundStyle(Lab.secondary) }.padding(.top, 16) + if let metadata = report.mixed { MixedSourcesSection(metadata: metadata, strings: strings) } + LabPanel { VStack(spacing: 0) { HStack(spacing: 13) { @@ -317,15 +326,21 @@ struct ReviewView: View { .font(.system(size: 11)).foregroundStyle(Lab.secondary) } Spacer() - Text("NEXUS").font(.system(size: 10, design: .monospaced)).foregroundStyle(Lab.muted) + Text((report.inputFormat ?? "nexus").uppercased()).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" - ? "Mkv · variable characters" - : workspace.settings.conditioning == "informative" - ? "Mkparsinf · informative characters" : "Mk · all characters") + workspace.settings.characterModelLabel) + if workspace.settings.dataType == "mixed" { + row( + "Morphology/DNA rate ratio", workspace.settings.mixedRateDescription(strings: strings) + ) + row("Morphology conditioning", workspace.settings.morphologyConditioningLabel) + } if let partitions = report.partitions { row( "Alphabet choice", AnalysisSettings.partitioningLabel(workspace.settings.partitioning) @@ -343,13 +358,6 @@ struct ReviewView: View { if let prior = workspace.settings.clockSigmaPrior { row("Clock sigma prior", prior.description(strings: strings)) } - row( - "Tree prior", - workspace.settings.dating.estimatesProcess - ? "Fossilized birth–death · estimated parameters" - : workspace.settings.dating.enabled - ? "Fossilized birth–death · fixed process" : "Birth–death · all tips at height zero" - ) rule row( "Chain", 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/TreeFileView.swift b/apps/macos/Sources/RoveApp/TreeFileView.swift index 98aca51..694835b 100644 --- a/apps/macos/Sources/RoveApp/TreeFileView.swift +++ b/apps/macos/Sources/RoveApp/TreeFileView.swift @@ -26,7 +26,7 @@ struct TreeFileDetail: View { VStack(alignment: .leading, spacing: 14) { Text( strings( - "Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." + "Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." ) ) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) diff --git a/apps/macos/Sources/RoveApp/TreePriorView.swift b/apps/macos/Sources/RoveApp/TreePriorView.swift new file mode 100644 index 0000000..4e74122 --- /dev/null +++ b/apps/macos/Sources/RoveApp/TreePriorView.swift @@ -0,0 +1,73 @@ +import SwiftUI + +extension AnalysisSettings { + var treePriorLabel: String { + dating.enabled + ? "Fossilized birth-death" : treePrior == "yule" ? "Yule · pure birth" : "Birth-death" + } + + func treePriorDescription(strings: AppStrings) -> String { + if dating.enabled { + return strings(dating.estimatesProcess + ? "Fossilized birth–death · estimated parameters" + : "Fossilized birth–death · fixed process") + } + 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/Sources/RoveApp/WelcomeView.swift b/apps/macos/Sources/RoveApp/WelcomeView.swift index 9fe0139..f53ff82 100644 --- a/apps/macos/Sources/RoveApp/WelcomeView.swift +++ b/apps/macos/Sources/RoveApp/WelcomeView.swift @@ -38,6 +38,11 @@ struct WelcomeView: View { }.padding(.top, 1).padding(.bottom, 5) importCard + Button { + workspace.showingMixedImport = true + } label: { + Label(strings("Combine morphology and DNA"), systemImage: "square.stack.3d.up") + }.buttonStyle(LabButtonStyle(compact: true)) exampleCard treeCard @@ -57,12 +62,12 @@ struct WelcomeView: View { VStack(alignment: .leading, spacing: 9) { Text(strings(targeted ? "That's the one. Drop it here." : "Start with your matrix")) .font(Lab.display(23, weight: .semibold)).tracking(-0.4).foregroundStyle(Lab.ink) - Text(strings("Drop a NEXUS file here, or browse your Mac.")) + Text(strings("Drop a NEXUS or aligned FASTA file here, or browse your Mac.")) .font(.system(size: 12)).foregroundStyle(Lab.secondary) HStack(spacing: 8) { Text(".nex").font(.system(size: 10, design: .monospaced)) - Text(".nexus").font(.system(size: 10, design: .monospaced)) - Text(strings("· Morphological characters")).font(.system(size: 10)) + Text(".nexus · .fasta").font(.system(size: 10, design: .monospaced)) + Text(strings("· Morphology or aligned DNA")).font(.system(size: 10)) }.foregroundStyle(Lab.muted).padding(.top, 7) } Spacer(minLength: 4) @@ -102,7 +107,7 @@ struct WelcomeView: View { } isTargeted: { targeted = $0 } - .accessibilityLabel(strings("Open or drop a NEXUS matrix or tree file")) + .accessibilityLabel(strings("Open or drop a NEXUS matrix, tree file or aligned DNA in FASTA")) } private func headline(size: CGFloat) -> some View { diff --git a/apps/macos/Sources/RoveApp/Workspace.swift b/apps/macos/Sources/RoveApp/Workspace.swift index 69ddbc6..60f2c0e 100644 --- a/apps/macos/Sources/RoveApp/Workspace.swift +++ b/apps/macos/Sources/RoveApp/Workspace.swift @@ -12,6 +12,7 @@ enum WorkspacePage: String, CaseIterable { @MainActor @Observable final class Workspace { + var showingMixedImport = false var report: MatrixReport? var file: URL? var page = WorkspacePage.matrix @@ -125,11 +126,16 @@ final class Workspace { } } + func combineInput(_ request: MixedInputRequest) async throws { + try await request.execute(executable: executable) + } + func chooseFile() { guard !isRunning else { return } let panel = NSOpenPanel() - panel.title = strings("Choose a morphological matrix") - panel.message = strings("Open a NEXUS file. Your data stays on this Mac.") + panel.title = strings("Choose a matrix or DNA alignment") + panel.message = strings( + "Open a NEXUS matrix or aligned DNA in FASTA. Your data stays on this Mac.") panel.prompt = strings("Open matrix") panel.canChooseDirectories = false panel.allowsMultipleSelection = false @@ -156,14 +162,14 @@ final class Workspace { defer { if scoped { url.stopAccessingSecurityScopedResource() } } do { guard url.isFileURL else { - throw ImportError.message("Choose a local NEXUS file from your Mac.") + throw ImportError.message("Choose a local NEXUS or aligned FASTA file from your Mac.") } let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) guard values.isRegularFile == true else { - throw ImportError.message("Choose a NEXUS file, rather than a folder.") + throw ImportError.message("Choose a NEXUS or aligned FASTA file, rather than a folder.") } // A tree sample is not a matrix: it goes to the summary sheet instead. - if try await Task.detached { try Self.holdsTrees(url) }.value { + if try await Task.detached(operation: { try Self.holdsTrees(url) }).value { guard importID == id else { return } guard !preserveSettings else { throw ImportError.message("The matrix could not be read.") @@ -181,8 +187,16 @@ final class Workspace { let imported = try await MatrixInspector.inspect( url, gapsAsMissing: gaps, partitioning: partitioning, executable: executable) guard importID == id else { return } + if preserveSettings && settings.dataType != (imported.dataType ?? "standard") { + throw ImportError.message("The saved data type does not match the input.") + } if !preserveSettings { settings = AnalysisSettings() + settings.dataType = imported.dataType ?? "standard" + if imported.isDNA { + settings.conditioning = "none" + settings.partitioning = "declared" + } monophyly = [] outgroup = nil } @@ -223,8 +237,9 @@ final class Workspace { nonisolated static func holdsTrees(_ url: URL) throws -> Bool { let handle = try FileHandle(forReadingFrom: url) defer { try? handle.close() } - let head = String(decoding: try handle.read(upToCount: 256 * 1024) ?? Data(), as: UTF8.self) - .lowercased().replacing(/\[[^\]]*\]/, with: " ") + let raw = String(decoding: try handle.read(upToCount: 256 * 1024) ?? Data(), as: UTF8.self) + if raw.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("{") { return false } + let head = raw.lowercased().replacing(/\[[^\]]*\]/, with: " ") let trees = head.firstRange(of: /begin\s+trees\s*;/)?.lowerBound let characters = head.firstRange(of: /begin\s+(characters|data)\s*;/)?.lowerBound guard let trees else { return false } @@ -414,6 +429,10 @@ final class Workspace { matrix, gapsAsMissing: draft.settings.gapsAsMissing, partitioning: draft.settings.partitioning, executable: executable) guard imported.inputSha256 == draft.matrixSHA256 else { throw RunFailure.changedInput } + guard (imported.dataType ?? "standard") == draft.settings.dataType else { + throw ImportError.message("The saved data type does not match the input.") + } + guard imported.mixed == draft.mixedInput else { throw RunFailure.changedInput } try draft.validateTaxa(imported.allTaxa) guard importID == id else { return } run = nil @@ -537,10 +556,19 @@ final class Workspace { var predictiveChecks: [String: PredictiveCheckModel] = [:] var marginalEstimates: [String: MarginalLikelihoodModel] = [:] var runComparisons: [String: RunComparisonModel] = [:] + var runAssessments: [String: RunAssessmentModel] = [:] var toolsBusy: Bool { predictiveChecks.values.contains(where: \.busy) || marginalEstimates.values.contains(where: \.busy) || runComparisons.values.contains(where: \.busy) + || runAssessments.values.contains(where: \.busy) + } + + func runAssessment(for entry: HistoryEntry) -> RunAssessmentModel { + if let model = runAssessments[entry.id] { return model } + let model = RunAssessmentModel(entry: entry, executable: executable) + runAssessments[entry.id] = model + return model } func predictiveCheck(for entry: HistoryEntry) -> PredictiveCheckModel { diff --git a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift index 336762d..ea19d1d 100644 --- a/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift +++ b/apps/macos/Tests/RoveAppTests/AdvancedOptionsTests.swift @@ -18,7 +18,10 @@ struct AdvancedOptionsTests { let matrix = URL(fileURLWithPath: "/tmp/m.nex") let output = URL(fileURLWithPath: "/tmp/out") let plain = try settings.arguments(matrix: matrix, output: output) - for flag in ["--sample-from-prior", "--no-tuning", "--weight", "--tuning", "--min-ess", "--checkpoint-every"] { + for flag in [ + "--sample-from-prior", "--no-tuning", "--weight", "--tuning", "--min-ess", + "--checkpoint-every", + ] { #expect(!plain.contains(flag)) } #expect(!settings.usesAdvancedOptions) @@ -39,7 +42,9 @@ struct AdvancedOptionsTests { "--chains", "2", "--stop-when-converged", "--min-ess", "300.0", "--max-rhat", "1.02", "--check-every", "5000", "--checkpoint-every", "20000", "--sample-from-prior", ] - let schedule = ["--no-tuning", "--weight", "gamma_shape_scale=3.0", "--tuning", "subtree_slide=0.00076"] + let schedule = [ + "--no-tuning", "--weight", "gamma_shape_scale=3.0", "--tuning", "subtree_slide=0.00076", + ] #expect(arguments.indices.contains { arguments[$0...].starts(with: sampling) }) #expect(arguments.suffix(schedule.count).elementsEqual(schedule)) #expect(try settings.modelArguments().suffix(schedule.count).elementsEqual(schedule)) @@ -63,7 +68,9 @@ struct AdvancedOptionsTests { #expect(settings.validationError != nil) settings.weights = [MoveOverride(move: "node_height", value: -1)] #expect(settings.validationError != nil) - settings.weights = [MoveOverride(move: "node_height", value: 2), MoveOverride(move: "node_height", value: 3)] + settings.weights = [ + MoveOverride(move: "node_height", value: 2), MoveOverride(move: "node_height", value: 3), + ] #expect(settings.validationError != nil) settings.weights = ProposalSchedule.presets[1].weights #expect(settings.validationError == nil) @@ -82,7 +89,7 @@ struct AdvancedOptionsTests { #expect(settings.validationError != nil) settings.checkpointEvery = 3_000 #expect(settings.validationError == nil) - #expect(ProposalSchedule.moves.count == 22 && Set(ProposalSchedule.moves).count == 22) + #expect(ProposalSchedule.moves.count == 25 && Set(ProposalSchedule.moves).count == 25) #expect(ProposalSchedule.tunable.isSubset(of: ProposalSchedule.moves)) } @@ -96,6 +103,7 @@ struct AdvancedOptionsTests { dating: dating) } #expect(issue("birth_difference_scale") != nil && issue("relative_death_scale") != nil) + #expect(issue("narrow_exchange_rates") != nil) #expect(issue("clock_rate_scale") != nil) #expect(issue("tip_age") == nil) dating.clock = .estimated @@ -109,6 +117,48 @@ struct AdvancedOptionsTests { #expect(issue("birth_difference_scale") == nil && issue("fbd_birth_scale") != nil) } + @Test @MainActor func jointExchangePersistsRunsAndResumesFromHistory() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-joint-exchange-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let matrix = root.appendingPathComponent("fixtures/reference/20x50/matrix.nex") + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + var settings = AnalysisSettings() + settings.steps = 2_000 + settings.sampleEvery = 10 + settings.weights = [MoveOverride(move: "narrow_exchange_rates", value: 10)] + #expect(settings.validationError == nil) + #expect(try settings.modelArguments().contains("narrow_exchange_rates=10.0")) + settings.clock = "strict" + #expect(settings.validationError != nil) + settings.clock = "reference" + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings, outgroup: "T20") + #expect(draft.formatVersion == 9) + let file = parent.appendingPathComponent("setup.rove.json") + try draft.write(to: file) + #expect(try AnalysisDraft.read(file).settings == settings) + let directory = parent.appendingPathComponent("run") + let request = RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft) + let worker = RunProcess() + let paused = await worker.execute(request) { event in + if event.event == "started" { worker.pause() } + } + #expect(paused.status == .paused) + #expect(HistoryEntry.read(directory).checkpoint != nil) + let resumed = RunRequest( + id: UUID(), executable: engine, directory: directory, draft: draft, resume: true) + #expect(await RunProcess().execute(resumed) { _ in }.status == .completed) + let record = try EngineRecord.verify(directory: directory, draft: draft) + #expect(record.moves?.first(where: { $0.name == "narrow_exchange_rates" })?.weight == 10) + #expect(HistoryEntry.read(directory).draft?.settings.weights == settings.weights) + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + json["formatVersion"] = 8 + try JSONSerialization.data(withJSONObject: json).write(to: file) + #expect(throws: (any Error).self) { try AnalysisDraft.read(file) } + } + @Test @MainActor func groupRunsVerifyWithScheduleOverrides() async throws { let folder = FileManager.default.temporaryDirectory.appendingPathComponent( "rove-advanced-group-\(UUID())") @@ -135,7 +185,10 @@ struct AdvancedOptionsTests { #expect(chain.moves?.first { $0.name == "gamma_shape_scale" }?.weight == 3) var changed = settings changed.tuningValues = [MoveOverride(move: "tree_scale", value: 0.5)] - #expect(!chain.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed), seed: chain.settings.seed)) + #expect( + !chain.matches( + AnalysisDraft(matrix: matrix, report: report, settings: changed), seed: chain.settings.seed) + ) #expect(HistoryEntry.read(directory).status == .completed) } @@ -198,10 +251,16 @@ struct AdvancedOptionsTests { #expect(record.moves?.first { $0.name == "tree_scale" }?.initialTuning == 0.24) var changed = settings changed.weights = [MoveOverride(move: "gamma_shape_scale", value: 0.1)] - #expect(!record.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly))) + #expect( + !record.matches( + AnalysisDraft( + matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly))) changed = settings changed.sampleFromPrior = false - #expect(!record.matches(AnalysisDraft(matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly))) + #expect( + !record.matches( + AnalysisDraft( + matrix: matrix, report: report, settings: changed, monophyly: request.draft.monophyly))) #expect(entry.draft?.settings.advancedRows(strings: AppStrings(language: .english)).count == 5) let summary = TreeSummaryModel(directory: directory, executable: engine) diff --git a/apps/macos/Tests/RoveAppTests/AnalysisTests.swift b/apps/macos/Tests/RoveAppTests/AnalysisTests.swift index ec48455..e04abaf 100644 --- a/apps/macos/Tests/RoveAppTests/AnalysisTests.swift +++ b/apps/macos/Tests/RoveAppTests/AnalysisTests.swift @@ -209,7 +209,7 @@ struct AnalysisTests { #expect(workspace.report?.inputSha256 == original.inputSha256) workspace.load(URL(string: "https://example.invalid/matrix.nex")!) try await finishImport(workspace) - #expect(workspace.error == "Choose a local NEXUS file from your Mac.") + #expect(workspace.error == "Choose a local NEXUS or aligned FASTA file from your Mac.") #expect(workspace.report?.inputSha256 == original.inputSha256) workspace.load(root.appendingPathComponent("fixtures/validation/missing/matrix.nex")) try await finishImport(workspace) diff --git a/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift b/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift new file mode 100644 index 0000000..e177389 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift @@ -0,0 +1,73 @@ +import AppKit +import SwiftUI +import Testing + +@testable import RoveApp + +struct AssessmentPreviewTests { + @Test @MainActor func renderAssessmentAndPairedDistribution() async throws { + guard ProcessInfo.processInfo.environment["CI"] == nil else { return } + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent() + let output = root.appendingPathComponent(".local/ui/assessment") + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + _ = NSApplication.shared + NSApp.appearance = NSAppearance(named: .darkAqua) + Lab.registerFonts() + let suite = "rove-assessment-preview-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppPreferences(defaults: defaults, preferredLanguages: ["en-US"]) + let engine = root.appendingPathComponent("target/release/rove") + let matrix = root.appendingPathComponent("fixtures/reference/20x50/matrix.nex") + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + var settings = AnalysisSettings() + settings.steps = 1000 + settings.sampleEvery = 10 + let directory = output.appendingPathComponent("run-\(UUID())") + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings) + #expect( + await RunProcess().execute( + RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft) + ) { _ in }.status == .completed) + let entry = HistoryEntry.read(directory) + let workspace = Workspace(executable: engine, preferences: preferences) + let predictive = workspace.predictiveCheck(for: entry) + predictive.replicates = "30" + predictive.start() + await predictive.waitForExit() + let saved = try #require(predictive.predictions.first) + let review = workspace.runAssessment(for: entry) + review.start() + await review.waitForExit() + #expect(review.error == nil, Comment(rawValue: review.details ?? "")) + for language in [AppLanguage.english, .portuguese] { + preferences.language = language + try await render( + RunAssessmentView(workspace: workspace, entry: entry), name: "review", height: 950) + try await render( + PredictiveReportView(prediction: saved, strings: preferences.strings), name: "prediction", + height: 850) + + @MainActor func render(_ content: V, name: String, height: CGFloat) async throws { + let view = NSHostingView( + rootView: content.padding(24).background(Lab.background) + .foregroundStyle(Lab.ink).frame(width: 820, height: height, alignment: .topLeading)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 820, height: height), styleMask: [.borderless], + backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = view + window.orderBack(nil) + try await Task.sleep(for: .milliseconds(500)) + view.layoutSubtreeIfNeeded() + let bitmap = try #require(view.bitmapImageRepForCachingDisplay(in: view.bounds)) + view.cacheDisplay(in: view.bounds, to: bitmap) + try #require(bitmap.representation(using: .png, properties: [:])).write( + to: output.appendingPathComponent("\(name)-\(language.rawValue).png")) + window.close() + } + } + } +} diff --git a/apps/macos/Tests/RoveAppTests/CheckpointTests.swift b/apps/macos/Tests/RoveAppTests/CheckpointTests.swift index dbf7aaa..3875159 100644 --- a/apps/macos/Tests/RoveAppTests/CheckpointTests.swift +++ b/apps/macos/Tests/RoveAppTests/CheckpointTests.swift @@ -41,6 +41,13 @@ struct CheckpointTests { let continued = await RunProcess().execute(resumed) { _ in } #expect(continued.status == .completed, "\(String(describing: continued))") #expect(HistoryEntry.read(directory).status == .completed) + let review = try await AssessmentRequest( + entry: HistoryEntry.read(directory), executable: engine, + output: parent.appendingPathComponent("review-\(chains)"), options: AssessmentOptions(), + export: false + ) + .execute(with: EngineTool()) + #expect(review.sections.first(where: { $0.id == "completion" })?.status == "passed") let fullDirectory = parent.appendingPathComponent("full-\(chains)") let full = RunRequest(id: UUID(), executable: engine, directory: fullDirectory, draft: draft) let complete = await RunProcess().execute(full) { _ in } diff --git a/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift b/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift index dd29ff1..5959ee5 100644 --- a/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift +++ b/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift @@ -4,6 +4,33 @@ import Testing @testable import RoveApp struct ClockSigmaPriorTests { + @Test func densityPreviewMatchesIndependentGammaSpecialCases() throws { + let exponential = ClockSigmaPrior(shape: 1, scale: 2) + for x in [0.0, 0.1, 1.0, 5.0, 20.0] { + let actual = try #require(exponential.logDensity(at: x)) + #expect(abs(exp(actual) - 0.5 * exp(-x / 2)) < 1e-14) + } + let prior = ClockSigmaPrior.reference + #expect(prior.mean == 1) + #expect(abs(prior.standardDeviation - sqrt(0.2)) < 1e-14) + for x in [0.1, 0.8, 1.0, 2.0] { + let direct = pow(x, 4) * exp(-x / 0.2) / (24 * pow(0.2, 5)) + #expect(abs(exp(try #require(prior.logDensity(at: x))) - direct) < 1e-12) + } + let curve = try #require(prior.curve) + let integral = zip(curve.points, curve.points.dropFirst()).reduce(0.0) { sum, pair in + sum + (pair.1.sigma - pair.0.sigma) * (pair.0.density + pair.1.density) / 2 + } + let u = curve.upperBound / prior.scale + let exact = 1 - exp(-u) * (1 + u + u * u / 2 + u * u * u / 6 + pow(u, 4) / 24) + #expect(abs(integral - exact) < 1e-5) + let singular = ClockSigmaPrior(shape: 0.5, scale: 1) + #expect(singular.logDensity(at: 0) == .infinity) + #expect(singular.curve?.points.allSatisfy { $0.sigma > 0 && $0.density.isFinite } == true) + #expect(ClockSigmaPrior(shape: 5, scale: 1e-100).curve == nil) + #expect(ClockSigmaPrior(shape: -1, scale: 1).curve == nil) + } + @Test func priorSettingsRoundTripAndLegacyDefaults() throws { var settings = AnalysisSettings() #expect(settings.clockSigmaPrior == .reference) diff --git a/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift b/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift index 61c4c36..4a96dd8 100644 --- a/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift +++ b/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift @@ -29,6 +29,8 @@ struct FeedbackPreviewTests { workspace.settings.apply(SamplingPreset(millions: 30)) workspace.settings.checkpointEvery = 50_000 workspace.settings.chains = 2 + workspace.settings.clockSigmaShape = "2.5" + workspace.settings.clockSigmaScale = "0.4" let run = AnalysisRun( request: RunRequest( id: UUID(), executable: engine, directory: output, @@ -57,12 +59,31 @@ struct FeedbackPreviewTests { .foregroundStyle(Lab.ink), name: "run", width: 820, height: 1300) try await render( SetupView(workspace: workspace).padding(28).background(Lab.background).foregroundStyle( - Lab.ink), name: "setup", width: 820, height: 2350) + Lab.ink), name: "setup", width: 820, height: 2850) + try await render( + ClockSigmaPriorChart(prior: .reference, strings: strings).padding(24) + .background(Lab.background).foregroundStyle(Lab.ink), + name: "sigma-prior", width: 620, height: 280) + try await render( + RootingSection(workspace: workspace).padding(24).background(Lab.background) + .foregroundStyle(Lab.ink), name: "rooting-compact", width: 620, height: 540) + let exporter = root.appendingPathComponent("fixtures/synthetic/exporter_labels.nex") + let exporterReport = try await MatrixInspector.inspect( + exporter, gapsAsMissing: false, partitioning: "labels", executable: engine) + let imported = Workspace(executable: engine, preferences: preferences) + imported.report = exporterReport + imported.file = exporter + imported.settings.partitioning = "labels" + try await render( + MatrixView(workspace: imported, report: exporterReport).padding(24) + .background(Lab.background).foregroundStyle(Lab.ink), + name: "observation-review", width: 820, height: 1250) @MainActor func render(_ content: V, name: String, width: CGFloat, height: CGFloat) async throws { - let view = NSHostingView(rootView: content) + let view = NSHostingView( + rootView: content.frame(width: width, height: height, alignment: .topLeading)) let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.borderless], backing: .buffered, defer: false) diff --git a/apps/macos/Tests/RoveAppTests/MixedTests.swift b/apps/macos/Tests/RoveAppTests/MixedTests.swift new file mode 100644 index 0000000..3b1911d --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/MixedTests.swift @@ -0,0 +1,171 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct MixedTests { + 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") + } + @MainActor private func wait(_ workspace: Workspace) async throws { + for _ in 0..<1000 { + if !workspace.loading { return } + try await Task.sleep(for: .milliseconds(10)) + } + throw ImportError.message("Mixed import did not finish") + } + + @Test @MainActor func combinedSourcesSettingsAndValidationPersist() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-mixed-import-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let suite = "rove-mixed-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let workspace = Workspace(executable: engine, preferences: AppPreferences(defaults: defaults)) + let matrix = parent.appendingPathComponent("combined.mixed.json") + try await workspace.combineInput( + MixedInputRequest( + morphology: root.appendingPathComponent("fixtures/validation/mixed/morphology.nex"), + dna: root.appendingPathComponent("fixtures/validation/dna/complete.fasta"), output: matrix, + missingTaxa: "reject")) + workspace.open(matrix) + try await wait(workspace) + #expect(workspace.error == nil) + #expect(workspace.report?.isMixed == true && workspace.settings.dataType == "mixed") + #expect(workspace.settings.mixedRateError != nil) + workspace.settings.morphologyRateMode = "estimate" + workspace.settings.morphologyRateLogSD = "0,8" + #expect(workspace.issue == nil) + let report = try #require(workspace.report) + #expect(report.mixed?.sources.map(\.dataType) == ["standard", "dna"]) + let draft = AnalysisDraft( + matrix: matrix, report: report, settings: workspace.settings, outgroup: "Epsilon five") + #expect(draft.formatVersion == 12) + let file = parent.appendingPathComponent("mixed.rove.json") + try draft.write(to: file) + workspace.loadSetup(file) + try await wait(workspace) + #expect(workspace.error == nil && workspace.report?.mixed == draft.mixedInput) + #expect(workspace.settings.morphologyLogSDValue == 0.8 && workspace.outgroup == "Epsilon five") + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + json["formatVersion"] = 11 + try JSONSerialization.data(withJSONObject: json).write(to: file) + #expect(throws: (any Error).self) { try AnalysisDraft.read(file) } + workspace.settings.morphologyRateLogSD = "0" + #expect(workspace.settings.validationError != nil) + workspace.settings.morphologyRateMode = "fixed" + workspace.settings.weights = [MoveOverride(move: "morphology_rate_scale", value: 1)] + #expect(workspace.settings.validationError != nil) + } + + @Test @MainActor func mixedRunsResumePredictEstimateImportAndExport() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-mixed-run-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let matrix = parent.appendingPathComponent("combined.mixed.json") + try await MixedInputRequest( + morphology: root.appendingPathComponent("fixtures/validation/mixed/morphology.nex"), + dna: root.appendingPathComponent("fixtures/validation/dna/complete.fasta"), output: matrix, + missingTaxa: "reject" + ).execute(executable: engine) + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + for mode in ["fixed", "estimate", "dated"] { + var settings = AnalysisSettings() + settings.dataType = "mixed" + settings.morphologyRateMode = mode == "fixed" ? "fixed" : "estimate" + settings.morphologyRate = "2.5" + settings.morphologyRateLogSD = "0.7" + settings.clock = mode == "fixed" ? "strict" : "reference" + settings.chains = mode == "fixed" ? 1 : 2 + settings.steps = 2000 + settings.sampleEvery = 100 + if mode == "estimate" { + settings.treePrior = "yule" + settings.birthRateUpper = "4" + } + if mode == "dated" { + settings.dating.enabled = true + settings.dating.birthRate = "0.8" + settings.dating.deathRate = "0.3" + settings.dating.fossilSamplingRate = "0.2" + settings.dating.presentSampling = "0.7" + settings.dating.origin = "4" + settings.dating.clockRate = "0.1" + settings.dating.clockPriorMean = "0.1" + settings.dating.ages = Dictionary( + uniqueKeysWithValues: report.allTaxa.map { ($0, TipAgeInput()) }) + settings.dating.ages["Beta two"] = TipAgeInput(kind: .fixed, fixed: "0.4") + } + let draft = AnalysisDraft( + matrix: matrix, report: report, settings: settings, outgroup: "Epsilon five") + let directory = parent.appendingPathComponent(mode) + let worker = RunProcess() + let paused = await worker.execute( + RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft) + ) { event in + if event.event == "started" { worker.pause() } + } + #expect(paused.status == .paused) + #expect( + await RunProcess().execute( + RunRequest( + id: UUID(), executable: engine, directory: directory, draft: draft, resume: true) + ) { _ in }.status == .completed) + let record = try EngineRecord.verify(directory: directory, draft: draft) + #expect(record.model.mixedModel?.matches(settings) == true) + let entry = HistoryEntry.read(directory) + #expect(entry.draft?.mixedInput == report.mixed) + let imported = try await CommandLineImport.prepare( + directory.appendingPathComponent("results"), matrix: matrix, under: parent, + executable: engine) + #expect( + HistoryEntry.read(imported).draft?.settings.morphologyRateMode + == settings.morphologyRateMode) + let prediction = PredictiveCheckModel(entry: entry, executable: engine) + prediction.replicates = "2" + prediction.start() + await prediction.waitForExit() + #expect(prediction.error == nil, Comment(rawValue: prediction.details ?? "")) + let saved = try #require(prediction.predictions.first) + let replicate = try await MatrixInspector.inspect( + saved.directory.appendingPathComponent("matrices/replicate-00001.mixed.json"), + gapsAsMissing: false, executable: engine) + #expect(replicate.isMixed && replicate.partitions?.last?.states == 4) + 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 ?? "")) + #expect(try #require(marginal.estimates.first).matches(draft)) + var changed = settings + changed.morphologyRateLogSD = "0.9" + changed.morphologyRate = "3" + #expect(!record.model.dataModelMatches(changed)) + for include in [false, true] { + let output = parent.appendingPathComponent("export-\(mode)-\(include)") + _ = try await AssessmentRequest( + entry: entry, executable: engine, output: output, + options: AssessmentOptions(includeMatrix: include), export: true + ).execute(with: EngineTool()) + #expect( + FileManager.default.fileExists( + atPath: output.appendingPathComponent("matrix.mixed.json").path) == include) + if include { + #expect( + try Data(contentsOf: output.appendingPathComponent("matrix.mixed.json")) + == Data(contentsOf: matrix)) + } + } + } + } +} diff --git a/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift b/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift index 610da67..6149cf2 100644 --- a/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift +++ b/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift @@ -67,6 +67,12 @@ struct ModelToolsTests { #expect(model.error == nil, Comment(rawValue: model.details ?? "")) #expect(model.completed == 5) let saved = try #require(model.predictions.first) + let distributions = try PredictiveDistribution.read(saved) + #expect(distributions.count == 5) + for distribution in distributions { + #expect(distribution.differences.count + distribution.undefined == 5) + #expect(distribution.bins.map(\.count).reduce(0, +) == distribution.differences.count) + } // 2,000 steps sampled every 100 give 21 samples; 10% burn-in discards 2. let source = saved.report.source #expect( diff --git a/apps/macos/Tests/RoveAppTests/NucleotideTests.swift b/apps/macos/Tests/RoveAppTests/NucleotideTests.swift new file mode 100644 index 0000000..7383707 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/NucleotideTests.swift @@ -0,0 +1,160 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct NucleotideTests { + 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") + } + + @MainActor private func waitForImport(_ workspace: Workspace) async throws { + for _ in 0..<1000 { + if !workspace.loading { return } + try await Task.sleep(for: .milliseconds(10)) + } + throw ImportError.message("DNA import did not finish") + } + + @Test @MainActor func importChoosesJc69AndPersistsItsDataIdentity() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-dna-import-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let suite = "rove-dna-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let workspace = Workspace(executable: engine, preferences: AppPreferences(defaults: defaults)) + let matrix = root.appendingPathComponent("fixtures/validation/dna/matrix.fasta") + workspace.load(matrix) + try await waitForImport(workspace) + #expect(workspace.error == nil) + #expect(workspace.report?.dataType == "dna" && workspace.report?.inputFormat == "fasta") + #expect(workspace.report?.allTaxa.first == "Alpha one") + #expect(workspace.settings.dataType == "dna" && workspace.settings.conditioning == "none") + #expect(workspace.settings.partitioning == "declared" && workspace.issue != nil) + workspace.settings.gapsAsMissing = true + workspace.reloadGapPolicy() + try await waitForImport(workspace) + #expect(workspace.issue == nil) + let report = try #require(workspace.report) + #expect(report.partitions?.first?.states == 4) + let draft = AnalysisDraft( + matrix: matrix, report: report, settings: workspace.settings, outgroup: "Epsilon five") + #expect(draft.formatVersion == 11) + let file = parent.appendingPathComponent("dna.rove.json") + try draft.write(to: file) + workspace.loadSetup(file) + try await waitForImport(workspace) + #expect(workspace.error == nil && workspace.settings.dataType == "dna") + #expect(workspace.outgroup == "Epsilon five") + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + json["formatVersion"] = 10 + try JSONSerialization.data(withJSONObject: json).write(to: file) + #expect(throws: (any Error).self) { try AnalysisDraft.read(file) } + workspace.settings.conditioning = "variable" + #expect(workspace.settings.validationError != nil) + workspace.settings.conditioning = "none" + workspace.settings.partitioning = "observed" + #expect(workspace.settings.validationError != nil) + workspace.load(root.appendingPathComponent("fixtures/reference/20x50/matrix.nex")) + try await waitForImport(workspace) + #expect( + workspace.settings.dataType == "standard" && workspace.settings.conditioning == "variable") + } + + @Test @MainActor func dnaRunsResumeSummarizePredictAndEstimate() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-dna-run-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + for clock in ["strict", "reference"] { + let ambiguous = clock == "reference" + let matrix = root.appendingPathComponent( + "fixtures/validation/dna/" + (ambiguous ? "matrix.nex" : "complete.fasta")) + let report = try await MatrixInspector.inspect( + matrix, gapsAsMissing: ambiguous, executable: engine) + var settings = AnalysisSettings() + settings.dataType = "dna" + settings.conditioning = "none" + settings.partitioning = "declared" + settings.gapsAsMissing = ambiguous + settings.clock = clock + settings.steps = 2_000 + settings.sampleEvery = 100 + settings.chains = ambiguous ? 2 : 1 + if ambiguous { + settings.treePrior = "yule" + settings.birthRateUpper = "4" + } + let draft = AnalysisDraft( + matrix: matrix, report: report, settings: settings, outgroup: "Epsilon five") + let directory = parent.appendingPathComponent(clock) + let worker = RunProcess() + let request = RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft) + let paused = await worker.execute(request) { event in + if event.event == "started" { worker.pause() } + } + #expect(paused.status == .paused) + 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.dataType == "dna" && record.model.substitutionModel == "jc69") + #expect(record.model.conditioningLabel == "JC69") + let entry = HistoryEntry.read(directory) + #expect(entry.draft?.settings.dataType == "dna") + let imported = try await CommandLineImport.prepare( + directory.appendingPathComponent("results"), matrix: matrix, under: parent, + executable: engine) + #expect(HistoryEntry.read(imported).draft?.formatVersion == 11) + + let summaryDirectory = + ambiguous ? directory.appendingPathComponent("results/chain-01") : directory + let summary = TreeSummaryModel(directory: summaryDirectory, executable: engine) + summary.start() + await summary.waitForExit() + #expect(summary.error == nil, Comment(rawValue: summary.details ?? "")) + #expect(summary.summaries.count == 1) + + let prediction = PredictiveCheckModel(entry: entry, executable: engine) + prediction.replicates = "2" + prediction.start() + await prediction.waitForExit() + if ambiguous { + #expect(prediction.error != nil && prediction.predictions.isEmpty) + #expect(prediction.details?.contains("observation model") == true) + } else { + #expect(prediction.error == nil, Comment(rawValue: prediction.details ?? "")) + let saved = try #require(prediction.predictions.first) + let replicate = try String( + contentsOf: saved.directory.appendingPathComponent("matrices/replicate-00001.nex"), + encoding: .utf8) + #expect(replicate.contains("DATATYPE=DNA")) + #expect( + FileManager.default.fileExists( + atPath: saved.directory.appendingPathComponent("source/matrix.fasta").path)) + } + 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 saved = try #require(marginal.estimates.first) + #expect(saved.matches(draft) && saved.record.model.substitutionModel == "jc69") + var changed = settings + changed.dataType = "standard" + #expect( + !record.matches( + AnalysisDraft(matrix: matrix, report: report, settings: changed, outgroup: "Epsilon five") + )) + } + } +} diff --git a/apps/macos/Tests/RoveAppTests/PreviewTests.swift b/apps/macos/Tests/RoveAppTests/PreviewTests.swift index 36bef9d..e38c4f3 100644 --- a/apps/macos/Tests/RoveAppTests/PreviewTests.swift +++ b/apps/macos/Tests/RoveAppTests/PreviewTests.swift @@ -5,6 +5,131 @@ import Testing @testable import RoveApp struct PreviewTests { + @Test @MainActor func renderMixedSourcesAndRates() 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/mixed") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + _ = NSApplication.shared + NSApp.appearance = NSAppearance(named: .darkAqua) + Lab.registerFonts() + let suite = "rove-mixed-preview-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppPreferences(defaults: defaults) + let engine = root.appendingPathComponent("target/release/rove") + let workspace = Workspace(executable: engine, preferences: preferences) + let matrix = root.appendingPathComponent("fixtures/validation/mixed/study.mixed.json") + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + workspace.file = matrix + workspace.report = report + workspace.settings.dataType = "mixed" + workspace.settings.morphologyRateMode = "estimate" + workspace.settings.morphologyRateLogSD = "0.7" + let metadata = try #require(report.mixed) + let view = NSHostingView( + rootView: + VStack(spacing: 20) { + MixedSourcesSection(metadata: metadata, strings: workspace.strings) + MixedRateSection(workspace: workspace) + }.padding(24).frame(width: 740, height: 660).background(Lab.background)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 740, height: 660), styleMask: [.borderless], + backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = view + window.orderBack(nil) + for language in [AppLanguage.english, .portuguese] { + preferences.language = language + // Refresh the value-only source summary when the locale changes. + view.rootView = VStack(spacing: 20) { + MixedSourcesSection(metadata: metadata, strings: workspace.strings) + MixedRateSection(workspace: workspace) + }.padding(24).frame(width: 740, height: 660).background(Lab.background) + try await capture( + view, to: directory.appendingPathComponent("sources-rates-\(language.rawValue).png")) + } + window.close() + } + + @Test @MainActor func renderNucleotideImportAndReview() 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/dna") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + _ = NSApplication.shared + NSApp.appearance = NSAppearance(named: .darkAqua) + Lab.registerFonts() + let suite = "rove-dna-preview-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppPreferences(defaults: defaults) + let engine = root.appendingPathComponent("target/release/rove") + let workspace = Workspace(executable: engine, preferences: preferences) + let matrix = root.appendingPathComponent("fixtures/validation/dna/matrix.fasta") + workspace.file = matrix + workspace.report = try await MatrixInspector.inspect( + matrix, gapsAsMissing: true, executable: engine) + workspace.settings.dataType = "dna" + workspace.settings.conditioning = "none" + workspace.settings.partitioning = "declared" + workspace.settings.gapsAsMissing = true + for page in [WorkspacePage.matrix, .review] { + workspace.page = page + let view = NSHostingView(rootView: RootView(workspace: workspace)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 1080, height: 900), + 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("\(page)-\(language.rawValue).png")) + } + window.close() + } + } + + @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 new file mode 100644 index 0000000..6b74077 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift @@ -0,0 +1,111 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct RunAssessmentTests { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + private var engine: URL { root.appendingPathComponent("target/release/rove") } + + @Test @MainActor func reviewPersistsAndExportReopensWithVerifiedFiles() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-review-\(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; FORMAT SYMBOLS=\"01\"; MATRIX A 0000 B 0011 C 1100 D 1111; END;" + .write(to: matrix, atomically: true, encoding: .utf8) + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + for chains in [1, 2] { + var settings = AnalysisSettings() + settings.steps = 100 + settings.sampleEvery = 10 + settings.chains = chains + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings) + let directory = parent.appendingPathComponent("run-\(chains)") + let result = await RunProcess().execute( + RunRequest( + id: UUID(), executable: engine, + directory: directory, draft: draft) + ) { _ in } + #expect(result.status == .completed) + let entry = HistoryEntry.read(directory) + let model = RunAssessmentModel(entry: entry, executable: engine) + model.options.burnin = "20" + model.start() + await model.waitForExit() + #expect(model.error == nil, Comment(rawValue: model.details ?? "")) + let review = try #require(model.report) + #expect(review.burninPercent == 20 && !review.convergenceCertified) + #expect(review.sections.first(where: { $0.id == "completion" })?.status == "passed") + #expect( + review.sections.first(where: { $0.id == "agreement" })?.status + == (chains == 1 ? "unavailable" : "attention")) + let restored = RunAssessmentModel(entry: entry, executable: engine) + await restored.load() + #expect(restored.options.burnin == "20" && restored.report?.chainCount == chains) + let package = parent.appendingPathComponent("package-\(chains)") + model.options.includeMatrix = chains == 2 + model.start(exportTo: package) + await model.waitForExit() + #expect(model.error == nil, Comment(rawValue: model.details ?? "")) + #expect(model.exported == package) + #expect( + FileManager.default.fileExists(atPath: package.appendingPathComponent("matrix.nex").path) + == (chains == 2)) + #expect(HistoryEntry.read(package.appendingPathComponent("run")).status == .completed) + let manifest = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: package.appendingPathComponent("manifest.json"))) as? [String: Any] + ) + let files = try #require(manifest["files"] as? [[String: Any]]) + for file in files { + let path = try #require(file["path"] as? String) + let hash = try #require(file["sha256"] as? String) + #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) + let changed = RunAssessmentModel(entry: entry, executable: engine) + changed.start() + await changed.waitForExit() + #expect(changed.report?.originalMatrixStatus == "changed") + changed.options.includeMatrix = true + let rejected = parent.appendingPathComponent("rejected") + changed.start(exportTo: rejected) + await changed.waitForExit() + #expect(changed.error != nil && !FileManager.default.fileExists(atPath: rejected.path)) + } + + @Test func histogramIncludesEveryPairAndHandlesConstantDifferences() { + let constant = PredictiveDistribution(name: "example", differences: [0, 0, 0], undefined: 2) + #expect(constant.bins.count == 1 && constant.bins[0].count == 3) + let spread = PredictiveDistribution( + name: "example", differences: [-2, -1, 0, 1, 4], undefined: 0) + #expect(spread.bins.map(\.count).reduce(0, +) == 5) + #expect(PredictiveDistribution(name: "undefined", differences: [], undefined: 2).bins.isEmpty) + } +} 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/.vitepress/config.mjs b/docs/.vitepress/config.mjs index 8d5999c..3e6c7bc 100644 --- a/docs/.vitepress/config.mjs +++ b/docs/.vitepress/config.mjs @@ -35,6 +35,8 @@ const locales = { referenceModel: 'The reference model', treePriors: 'Tree priors', nexus: 'Reading NEXUS', + dna: 'Aligned DNA · JC69', + mixedData: 'Morphology + DNA', fixtures: 'Synthetic matrices', outline: 'On this page', edit: 'Edit this page on GitHub', @@ -69,6 +71,8 @@ const locales = { referenceModel: 'O modelo de referência', treePriors: 'Priors de árvore', nexus: 'Lendo NEXUS', + dna: 'DNA alinhado · JC69', + mixedData: 'Morfologia + DNA', fixtures: 'Matrizes sintéticas', outline: 'Nesta página', edit: 'Editar esta página no GitHub', @@ -120,6 +124,8 @@ const locales = { referenceModel: 'El modelo de referencia', treePriors: 'Priors de árbol', nexus: 'Lectura de NEXUS', + dna: 'ADN alineado · JC69', + mixedData: 'Morfología + ADN', fixtures: 'Matrices sintéticas', outline: 'En esta página', edit: 'Editar esta página en GitHub', @@ -171,6 +177,8 @@ const locales = { referenceModel: '参考模型', treePriors: '树先验', nexus: '读取 NEXUS', + dna: '已比对 DNA · JC69', + mixedData: '形态 + DNA', fixtures: '合成矩阵', outline: '本页目录', edit: '在 GitHub 上编辑此页', @@ -200,7 +208,7 @@ const locales = { function themeFor(locale) { const prefix = locale.dir ? `/${locale.dir}` : '' const { ui } = locale - const { guide, roadmap, project, code, what, macPreview, runFiles, design, kernel, sampler, characterSelection, macBenchmark, orderedCharacters, posteriorPrediction, tipDating, modelComparison, referenceModel, treePriors, nexus, fixtures, outline, edit, message, copyright, ...labels } = ui + const { guide, roadmap, project, code, what, macPreview, runFiles, design, kernel, sampler, characterSelection, macBenchmark, orderedCharacters, posteriorPrediction, tipDating, modelComparison, referenceModel, treePriors, nexus, dna, mixedData, fixtures, outline, edit, message, copyright, ...labels } = ui return { nav: [ { text: guide, link: `${prefix}/guide/`, activeMatch: `${prefix}/guide/(?!roadmap)` }, @@ -232,6 +240,8 @@ function themeFor(locale) { { text: referenceModel, link: `${prefix}/guide/reference-model` }, { text: treePriors, link: `${prefix}/guide/tree-priors` }, { text: nexus, link: `${prefix}/guide/nexus` }, + { text: dna, link: `${prefix}/guide/dna` }, + { text: mixedData, link: `${prefix}/guide/mixed-data` }, { text: fixtures, link: `${prefix}/guide/fixtures` } ] } diff --git a/docs/es/guide/dna.md b/docs/es/guide/dna.md new file mode 100644 index 0000000..bb1d4d4 --- /dev/null +++ b/docs/es/guide/dna.md @@ -0,0 +1,60 @@ +--- +description: "ADN alineado en NEXUS y FASTA bajo JC69, con ambigüedades y tratamiento explícito de gaps." +--- + +# ADN alineado con JC69 + +[Morfología y ADN combinados](./mixed-data.md). + +Abra una matriz NEXUS `DATATYPE=DNA` o un FASTA ya alineado. La app selecciona +**DNA · JC69**, mantiene A/C/G/T posibles en cada sitio e incluye sitios +constantes. Rove no alinea, recorta ni ensambla lecturas. `sample`, `inspect` +y `marginal` aceptan el mismo archivo: + +```sh +rove sample alignment.fasta --output dna-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --gaps missing +``` + +Elija `--gaps missing` solo si los gaps no deben aportar información de estado; +por defecto se rechazan. `?` es faltante, `R` permite A/G, `Y` C/T y los otros +códigos IUPAC mantienen sus estados posibles; `N` permite los cuatro. Son +máscaras de verosimilitud con unos, no probabilidades fraccionarias ni estados +adicionales. El polimorfismo entre paréntesis se conserva pero no se analiza. +ADN usa `--conditioning none --partitioning declared`; se rechazan Mkv, +Mkparsinf y la recodificación morfológica solicitados explícitamente. + +FASTA admite secuencias en varias líneas de igual longitud positiva. El primer +identificador tras `>`, hasta el espacio, nombra el taxón; se ignora la descripción +según la [convención FASTA](https://www.ncbi.nlm.nih.gov/genbank/fastaformat/). +Se aplica la convención NEXUS existente: guiones bajos pasan a espacios, las +duplicaciones ignoran mayúsculas ASCII y se conserva el resto de la grafía. +Revise los nombres mostrados antes de enraizar o combinar datos. Los originales +no cambian. En NEXUS DNA las bases no distinguen mayúsculas, el alfabeto es +A/C/G/T fijo y el gap predeterminado es `-`; `SYMBOLS="ACGT"` es opcional. +Se rechazan alfabetos propios, RESPECTCASE, ADN ordenado, ARN, proteínas y +directivas no admitidas. `MISSING=N` declara N como faltante. Se admiten los +mismos diseños secuenciales/intercalados que para morfología. + +JC69 fija frecuencias 1/4 y tasas de intercambio iguales, normalizadas a una +sustitución esperada por sitio: `Pii(t)=1/4+3/4 exp(−4t/3)` y +`Pij(t)=1/4−1/4 exp(−4t/3)` entre bases diferentes. Los controles existentes +ofrecen reloj estricto o relajado lognormal, categorías gamma, raíz y priors +de árbol admitidos. No se aplica corrección morfológica de selección. HKY y GTR no están disponibles. El análisis combinado tiene un flujo propio. + +Configuraciones de formato 11, historial, registros y checkpoints conservan +ADN/JC69 y la política de gaps; apps anteriores rechazan estas configuraciones. +Se pueden importar ejecuciones CLI al historial. Modelos incompatibles no se +combinan para convergencia. Árboles, diagnósticos y estimaciones marginales +conservan el modelo. Pruebas cortas verifican integración, no convergencia. +La predicción requiere bases individuales o faltantes; la incertidumbre IUPAC +necesita un modelo de observación y se rechaza en simulación. Las réplicas se +escriben como NEXUS DNA. La exportación guarda los bytes originales en +`matrix.fasta` o `matrix.nex`. La inclusión es explícita y también controla +las copias originales guardadas por las verificaciones predictivas. + +`fixtures/validation/dna` incluye datos sintéticos, suma analítica independiente +de estados internos, seis estados fijos BEAST.base 2.7.8, frecuencias simuladas +y reanudación exacta. Con iguales tasas de categoría, las diferencias absolutas +de log verosimilitud son menores que 1e-10. Para cuantiles gamma independientes +se usa tolerancia 1e-7; la aproximación AS91 de BEAST difiere menos de 3e-8 en +las tasas de estos estados. No es una comparación de velocidad. diff --git a/docs/es/guide/macos-preview.md b/docs/es/guide/macos-preview.md index 30d24df..a428773 100644 --- a/docs/es/guide/macos-preview.md +++ b/docs/es/guide/macos-preview.md @@ -474,3 +474,36 @@ El plan ofrece 1, 10, 20, 30, 50 y 100 millones de pasos, con intervalos de 100, Durante la ejecución, **Estimated time to step limit** y **Time per million steps** usan diferencias recientes de pasos y tiempo activo del motor. Primero se recogen al menos tres intervalos que cubran diez segundos, y luego se usan hasta ocho intervalos recientes. Cada cadena se mide por separado; la estimación del grupo es el mayor tiempo restante. Reanudar inicia una medición nueva que excluye el tiempo en pausa. Las estimaciones desaparecen al detener o terminar. La carga del procesador puede cambiar el ritmo. La predicción corresponde al límite de pasos, no a la convergencia; la parada automática puede terminar antes. **What are these files?** en Resultados y History abre una explicación sin conexión. La [guía de la carpeta](./run-files) muestra los archivos y el recorrido desde la traza hasta el árbol anotado. + +### Orientación visual del modelo + +El panel de enraizamiento dibuja la división impuesta: el terminal elegido a un lado y un grupo colapsado con todos los demás al otro. No estima longitudes de ramas, relaciones internas ni estados ancestrales. El recorrido inicial emplea la misma terminología. + +Abre **Clock sigma prior** para ver cómo cambia la densidad gamma con Alpha y Beta, en la parametrización forma/escala. La línea discontinua marca la esperanza del prior; también se muestra su desviación estándar. El rango dibujado no es un intervalo de credibilidad. Con forma menor que uno, la densidad diverge en cero y la curva comienza por encima de cero. Las escalas numéricas extremas pueden no tener vista gráfica; esto no altera el prior del motor. + +La duración estimada corresponde al límite solicitado de pasos y usa el tiempo activo reciente del motor. No predice cuándo se establecerá la convergencia. Los controles de selección de caracteres y datación explican sus supuestos junto a la validación; estas explicaciones no demuestran adecuación para un estudio concreto. + +## Revisión de evidencias y paquetes de reproducción + +En **History → Evidence review**, elija el porcentaje de burn-in y actualice la revisión. `assessments/review-…/assessment.json` guarda una instantánea fechada con huellas SHA-256, registros originales, diagnósticos por cadena, una comparación nueva y rutas de informes de árboles y predictivos correspondientes. Actualice después de generar otros informes. El burn-in y la opción de incluir la matriz se guardan localmente junto a la ejecución. + +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 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: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Incluir explícitamente una matriz original coincidente: +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/mixed-data.md b/docs/es/guide/mixed-data.md new file mode 100644 index 0000000..9a32e30 --- /dev/null +++ b/docs/es/guide/mixed-data.md @@ -0,0 +1,75 @@ +--- +description: "Combine morfología y ADN alineado con fuentes, correspondencia de taxones y tasas relativas explícitas." +--- + +# Morfología y ADN juntos + +Elija **Combine morphology and DNA** en la pantalla inicial del Mac. Seleccione +una matriz morfológica NEXUS STANDARD y ADN alineado NEXUS/FASTA, revise la +política de taxones ausentes y guarde una entrada `.mixed.json`. En la CLI: + +```sh +rove combine --morphology morphology.nex --dna alignment.fasta --missing-taxa reject --output study.mixed.json +rove sample study.mixed.json --output combined-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --morphology-rate estimate --morphology-rate-log-sd 1 +``` + +El manifiesto incorpora los textos UTF-8 originales y sus hashes SHA-256; no +sigue rutas externas y funciona después de mover las fuentes. No sobrescribe +archivos existentes. Se verifican formato, versión, tipos y hashes al importar. +Contiene datos de investigación: compartirlo requiere permiso para distribuir +ambas fuentes. + +Los taxones coinciden por **nombre normalizado exacto**, no por posición de +fila. Se aplica la conversión existente de guiones bajos a espacios. `reject` +exige los mismos taxones. `--missing-taxa missing` conserva su unión y completa +las ausencias con datos faltantes; la app muestra los taxones ausentes por fuente. +Deben compartir al menos dos taxones. Las diferencias solo de mayúsculas se +rechazan; revise otras diferencias de escritura antes de considerarlas ausencias +biológicas. Las celdas faltantes no aportan información de estado; los gaps +mantienen `--gaps reject|missing`. Rove no alinea secuencias. + +Cada bloque conserva alfabeto, orden, etiquetas y observaciones. La morfología +admite alfabetos observados, declarados o completos mediante etiquetas, caracteres +ordenados/no ordenados y `--conditioning none|variable|informative`. Estas +opciones afectan **solo a la morfología**. El ADN usa JC69 sin condicionamiento, +las cuatro bases y todos los sitios, incluidos los constantes. La ambigüedad +IUPAC representa bases posibles; el polimorfismo verdadero sigue rechazándose. + +Ambos bloques comparten topología, tiempos de ramas, reloj estricto o lognormal +y forma gamma cuando está habilitada. Las categorías se integran por sitio. +No hay relojes ni formas gamma independientes por bloque. El ADN fija la tasa +relativa en 1. Todas las particiones morfológicas usan un multiplicador positivo +común `r`: distancia `tiempo × tasa de rama × r`; el ADN usa `tiempo × tasa de rama`. +Esto fija la escala relativa, sin convertir longitudes no datadas en edades de +calendario. La datación fósil conserva su reloj global y calibraciones explícitas. + +Seleccione el modelo de tasa: + +- `--morphology-rate 2.5` fija la razón en ese valor positivo. +- `--morphology-rate estimate --morphology-rate-log-sd s` estima con + `log(r) ~ Normal(0, s²)`. Si se omite, la desviación del log es 1; la mediana + es 1 y la media `exp(s²/2)`. Evalúe la sensibilidad a esta premisa. + +El log prior normalizado es +`−log(r) − log(s) − log(2π)/2 − (log(r)/s)²/2`. +La propuesta usa `f ~ Uniform(a, 1/a)` y log de razón de Hastings `−log(f)`. +`morphology_rate_scale` tiene peso inicial 3 al estimar y no está disponible para +una razón fija. El estado se guarda en `trace.log` y checkpoints. La log +verosimilitud suma ambos bloques, con la corrección morfológica elegida. Los +priors se cuentan una vez y el prior relativo está normalizado para estimación marginal. + +Las configuraciones de formato 12 conservan fuentes, política de taxones y tasas. +Revisión, historial, importación CLI, comparaciones, reanudación y estimaciones +marginales verifican esa identidad. La predicción reconstruye la razón muestreada +y genera réplicas `.mixed.json`, con alfabetos y máscaras de datos faltantes por +bloque. Incertidumbre y polimorfismo requieren un modelo de observación para +simular. Incluir la matriz al exportar es explícito, también para las copias +originales guardadas por la predicción. Las simulaciones son sintéticas, no sustitutos +de las observaciones. + +La validación incluye 36 estados fijos BEAST.base 2.7.8 + MM 1.2.1, sumas +independientes de particiones, cuadratura del prior y muestreo estacionario, +restricciones, recálculo de caché, reanudación exacta, predicción y ejecución +nativa. La tolerancia 1e-7 incluye aproximaciones independientes de cuantiles +gamma. Datos y generador: `fixtures/validation/mixed` y `tools/beast/MixedStates.java`. +Son controles de corrección, no certificación de convergencia ni mediciones de velocidad. diff --git a/docs/es/guide/nexus.md b/docs/es/guide/nexus.md index 0e261a6..078c655 100644 --- a/docs/es/guide/nexus.md +++ b/docs/es/guide/nexus.md @@ -4,6 +4,8 @@ description: "Leer matrices NEXUS morfológicas en Rust, preservar la semántica # Lectura de NEXUS morfológico +También se admite ADN alineado en NEXUS y FASTA con [JC69](./dna). Las reglas morfológicas siguientes describen matrices `STANDARD`. + `nexus::parse` lee una cadena UTF-8 en una `data::Matrix`. Preserva el orden de los taxones, el alfabeto de estados declarado, las etiquetas de caracteres y de estados, y cada celda observada. No tiene dependencias en tiempo de ejecución y no invoca a BEAST. Prueba la matriz de referencia incluida desde la raíz del repositorio: @@ -39,7 +41,7 @@ Con `TAXLABELS`, las filas devueltas siguen el orden declarado aunque las filas Los valores por defecto son estados sin distinción de mayúsculas y minúsculas, símbolo de faltante `?`, ningún símbolo de gap y filas secuenciales. Por tanto, `-` no es un gap salvo que se declare con `GAP=-`. Los símbolos de estado, de faltante y de gap deben ser distintos bajo la política de mayúsculas elegida. -Los tipos de datos moleculares o continuos, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, los rangos de estados, las frecuencias/recuentos, `ELIMINATE`, las matrices múltiples y los comandos no admitidos se rechazan. `SETS`, las directivas no admitidas de `ASSUMPTIONS` y los bloques específicos de aplicaciones también se rechazan: sus particiones, pesos, orden o exclusiones no deben desaparecer en la importación. El análisis sintáctico de XML queda fuera de esta API. +Los tipos de datos de ARN, proteínas o continuos, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, los rangos de estados, las frecuencias/recuentos, `ELIMINATE`, las matrices múltiples y los comandos no admitidos se rechazan. `SETS`, las directivas no admitidas de `ASSUMPTIONS` y los bloques específicos de aplicaciones también se rechazan: sus particiones, pesos, orden o exclusiones no deben desaparecer en la importación. El análisis sintáctico de XML queda fuera de esta API. ## Observaciones y verosimilitudes de los terminales diff --git a/docs/es/guide/reference-model.md b/docs/es/guide/reference-model.md index 02ef62a..993d9bf 100644 --- a/docs/es/guide/reference-model.md +++ b/docs/es/guide/reference-model.md @@ -4,6 +4,8 @@ description: "El modelo independiente del XML suministrado: categorías gamma, t # El modelo de referencia +También se admite ADN alineado en NEXUS y FASTA con [JC69](./dna) + `rove sample --model reference` ejecuta el modelo probabilístico del XML 20 × 50 suministrado, sin BEAST. Usa el mismo Mk binario, la corrección Mkv por defecto, el prior de nacimiento–muerte y las convenciones de parámetros. @@ -181,3 +183,62 @@ de modelos conservan el prior; comparar cadenas exige priors iguales. Registros antiguos usan 5 y 0,2. Las configuraciones personalizadas del app usan formato 6 para que versiones antiguas no ignoren la elección. Véase [Priors de árbol](./tree-priors) para la decisión sobre modelos de árbol. + +## Intercambio conjunto opcional de topología y tasas + +`--weight narrow_exchange_rates=10` activa una propuesta experimental junto con las existentes. Su peso predeterminado es cero y no tiene parámetro de ajuste. En el app, use **Advanced sampling → Try joint topology/rate exchange**; el peso inicial 10 es editable. La selección se conserva en el formato 9 de configuración, revisión, historial, registros y checkpoints. Por ahora requiere reloj relajado sin datación; se rechazan reloj estricto y datación antes del muestreo. Es una propuesta independiente, no todo BEAST ORC. No se ha demostrado una mejora de velocidad o mezcla para morfología; las mediciones comparativas de [#97](https://github.com/getcortexlabs/rove/issues/97) siguen aplazadas. + +Sea `G` un nodo interno con hijo interno. Elija `G` uniformemente entre los `C(T)` nodos elegibles, tome su hijo más antiguo `P` y el más reciente `U`, y elija un hijo `X` de `P` con probabilidad 1/2. Intercambie `X` y `U` sin cambiar alturas ni raíz, preservando las distancias de entrada: + +```text +rX' = rX (hP − hX) / (hG − hX) +rU' = rU (hG − hU) / (hP − hU) +J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)] +log Hastings = log C(T) − log C(T') + log J +``` + +Se exigen duraciones y tasas positivas y finitas, y `hP > hU`. Los límites inválidos y desbordamientos se rechazan antes de modificar el estado. La inversa elige los mismos `G` y `P` y devuelve `U` intercambiándolo con `X`; su probabilidad es `1 / (2 C(T'))` frente a `1 / (2 C(T))`. Como las alturas no cambian, el jacobiano continuo es el producto de ambos factores de escala. Las tasas siguen indexadas por los nodos de entrada, incluso cuando la raíz no es el último nodo. Restricciones y rechazos usan la restauración exacta habitual. Preservar estas distancias no preserva la verosimilitud: cambia la topología. + +Las pruebas cubren inversión, jacobiano numérico completo, selección directa/inversa enumerada, distribuciones conocidas de topologías uniformes y tasas lognormales independientes, restricciones, verosimilitud recalculada frente a caché, índices de raíz, checkpoints exactos, cancelación/reanudación nativa y muestras idénticas en portable/ARM. No sustituyen estudios de posterior y rendimiento. Véase [Douglas, Zhang y Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322). + +## 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/dna.md b/docs/guide/dna.md new file mode 100644 index 0000000..3d764e7 --- /dev/null +++ b/docs/guide/dna.md @@ -0,0 +1,63 @@ +--- +description: "Aligned NEXUS and FASTA DNA under JC69, with explicit ambiguity and gap handling." +--- + +# Aligned DNA with JC69 + +[Mixed morphology and DNA](./mixed-data.md). + +Open a NEXUS `DATATYPE=DNA` matrix or an aligned FASTA file in the Mac app. +Import selects **DNA · JC69**, keeps all four A/C/G/T states at every site, +and includes constant sites. Rove does not align, trim or assemble reads. +The same input works with `sample`, `inspect` and `marginal`: + +```sh +rove sample alignment.fasta --output dna-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --gaps missing +``` + +Choose `--gaps missing` only when gaps should contribute no state information. +The default rejects gaps. `?` is missing; `R` permits A/G, `Y` C/T, and the +other IUPAC ambiguity codes retain their allowed states. `N` permits all four. +These are likelihood masks of ones, not fractional probabilities or extra +states. Parenthesized polymorphism is preserved but unsupported for inference. +DNA defaults to `--conditioning none --partitioning declared`; explicitly +requesting Mkv, Mkparsinf or morphological alphabet recoding is rejected. + +FASTA sequences may wrap across lines and must have equal nonzero lengths. +The first whitespace-delimited identifier after `>` names the taxon; the +remaining description is ignored, following the [FASTA header convention](https://www.ncbi.nlm.nih.gov/genbank/fastaformat/). +Rove's existing NEXUS naming convention also applies to FASTA: underscores +become spaces, names are checked for duplicates ignoring ASCII case, and +spelling otherwise remains intact. Review the displayed terminal names before +rooting or matching datasets. Original files remain unchanged. + +For NEXUS DNA, bases are case insensitive, the alphabet is fixed A/C/G/T, and +the default gap symbol is `-`. Optional `SYMBOLS="ACGT"` is accepted; custom +alphabets, RESPECTCASE, ordered DNA, RNA/protein datatypes and unsupported +NEXUS directives are rejected. `MISSING=N` explicitly makes N missing. +The same supported sequential/interleaved layout rules apply as for morphology. + +JC69 fixes frequencies at 1/4 and exchangeabilities equal, normalized to one +expected substitution per site: `Pii(t)=1/4+3/4 exp(−4t/3)` and +`Pij(t)=1/4−1/4 exp(−4t/3)` for different bases. Strict and lognormal relaxed +clocks, gamma categories, rooting and supported tree priors use the existing +controls. DNA has no morphology ascertainment correction. HKY and GTR are not available. Combined morphology/DNA has its own explicit workflow. + +Format-11 app setups, History, run records and checkpoints preserve DNA/JC69 +identity and the chosen gap policy. Older apps reject these setups. CLI runs +can be imported into History; incompatible models cannot be pooled for +convergence. Trees, diagnostics and marginal estimates retain the fitted +model. Short execution tests demonstrate integration, not posterior convergence. +Posterior prediction currently accepts single bases and missing cells; IUPAC +uncertainty requires an observation model and is rejected for simulation. +Replicates are emitted as DNA NEXUS. Reproducibility exports retain original +input bytes as `matrix.fasta` or `matrix.nex`. Inclusion remains explicit and +also governs original copies saved by predictive checks. + +Validation uses synthetic fixtures in `fixtures/validation/dna`, independent +summation of internal states under the analytical JC69 probabilities, six fixed +states from BEAST.base 2.7.8, simulation frequencies and exact checkpoint replay. +With identical category rates, absolute log-likelihood differences are below +1e-10. With independently computed gamma quantiles, the test tolerance is +1e-7; BEAST's AS91 approximation differs by less than 3e-8 in category rates +on these states. This is numerical validation, not a speed comparison. diff --git a/docs/guide/macos-preview.md b/docs/guide/macos-preview.md index 4bf2830..d0b27b8 100644 --- a/docs/guide/macos-preview.md +++ b/docs/guide/macos-preview.md @@ -462,3 +462,36 @@ The exploration plan offers 1, 10, 20, 30, 50 and 100 million steps, paired with During a run, **Estimated time to step limit** and **Time per million steps** use recent step and engine active-time differences. Rove first collects at least three intervals spanning ten seconds, then uses up to eight recent intervals. Each chain is measured separately; the group estimate is the longest remaining time. Pausing and resuming starts a fresh measurement without counting paused time. Estimates disappear when stopping or finished. CPU load can change the pace. This predicts the requested step limit, not convergence; automatic stopping may finish earlier. **What are these files?** in Results and History opens an offline explanation. See the [run-folder guide](./run-files) for the file map and a worked path from trace to annotated tree. + +### Visual model guidance + +The rooting panel draws the actual constrained split: the selected terminal on one side and a collapsed group containing every other terminal on the other. It does not estimate branch lengths, internal relationships or ancestral states. Onboarding uses the same rooting terminology. + +Expand **Clock sigma prior** to see the Gamma shape/scale density update as Alpha and Beta change. A dashed line marks the prior expectation; the panel also shows its standard deviation. The plotted range is a display window, not a credible interval. For shape below one, the density diverges at zero and the plotted curve starts above zero. Extreme numerical scales may have no graphical preview; this does not change the engine's prior. + +The run-time estimate predicts the requested step limit from recent active engine time. It does not predict when convergence will be established. Character-selection and fossil-dating controls explain their assumptions alongside their validation messages; these explanations do not establish that a model fits a particular study. + +## Evidence review and reproducibility packages + +In **History → Evidence review**, choose the burn-in percentage and refresh the review. The saved `assessments/review-…/assessment.json` is a dated snapshot with source SHA-256 fingerprints, the original run records, within-chain diagnostics, a fresh chain comparison and matching tree/predictive report paths. Refresh after generating new reports. The burn-in choice and matrix-inclusion option are saved locally beside the run. + +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 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: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Explicitly include a matching original matrix: +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/mixed-data.md b/docs/guide/mixed-data.md new file mode 100644 index 0000000..188b79f --- /dev/null +++ b/docs/guide/mixed-data.md @@ -0,0 +1,79 @@ +--- +description: "Combine morphological characters and aligned DNA with explicit sources, taxon matching and relative rates." +--- + +# Morphology and DNA together + +Choose **Combine morphology and DNA** on the Mac welcome screen. Select one +STANDARD morphological NEXUS matrix and one aligned DNA NEXUS/FASTA file, review +the missing-taxon policy, and save a new `.mixed.json` input. The same operation +is available in the CLI: + +```sh +rove combine --morphology morphology.nex --dna alignment.fasta --missing-taxa reject --output study.mixed.json +rove sample study.mixed.json --output combined-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --morphology-rate estimate --morphology-rate-log-sd 1 +``` + +The manifest embeds both original UTF-8 texts and their SHA-256 fingerprints; +it never follows external source paths. It can be reopened after the originals +move. Existing output files are not overwritten. The format/version, source +types and hashes are checked on every import. The file contains research data; +keep it private unless sharing the two original datasets is permitted. + +Taxa match by **exact normalized name**, not row position. Existing NEXUS/FASTA +underscore-to-space normalization applies. The default `reject` requires the +same taxa. Explicit `--missing-taxa missing` keeps their union and fills cells +for absent taxa with missing data; the app lists these taxa for each source. +At least two taxa must occur in both blocks. Case-only name disagreements are +rejected. Review other spelling differences before treating them as biological +absences. Missing cells contribute no state information; gaps retain their +separate `--gaps reject|missing` policy. No sequences are aligned automatically. + +Each block retains its own alphabet, character order, labels and observations. +Morphology supports observed, declared or complete labeled alphabets, ordered +and unordered models, and `--conditioning none|variable|informative`. These +choices apply **only to morphology**. DNA uses unconditioned JC69, all four +A/C/G/T states and all sites, including constants. IUPAC ambiguity is a mask of +possible bases. Unsupported true polymorphism still rejects inference. + +Both blocks share topology, branch times, the strict or lognormal branch clock, +and the gamma-shape parameter when enabled. Categories are integrated separately +at each site. Independent block clocks or separate gamma shapes are not offered. +DNA fixes the relative rate at 1. Every morphological partition uses a common +positive multiplier `r`, so its branch distance is `time × branch-rate × r`. +The DNA block uses `time × branch-rate`. This fixes the relative-rate scale; +it does not turn undated branch lengths into calendar ages. Fossil dating retains +its explicit global clock and calibration settings. + +Choose the rate model explicitly in the app or CLI: + +- `--morphology-rate 2.5` fixes the ratio to that positive value. +- `--morphology-rate estimate --morphology-rate-log-sd s` estimates it with + `log(r) ~ Normal(0, s²)`. The default log-SD is 1 when omitted; the median is 1 + and the mean is `exp(s²/2)`. This assumption needs sensitivity assessment. + +The normalized log prior is +`−log(r) − log(s) − log(2π)/2 − (log(r)/s)²/2`. +A scale proposal uses a factor `f ~ Uniform(a, 1/a)` and log Hastings ratio +`−log(f)`. The `morphology_rate_scale` move defaults to weight 3 for estimation +and is unavailable for a fixed ratio. Its state is recorded in `trace.log` and +checkpoints. Likelihood equals the sum of the two blocks' log likelihoods, +including the selected morphological ascertainment correction. Priors are +counted once; the relative-rate prior is normalized for marginal estimation. + +Format-12 app setups preserve source provenance, taxon policy and rate choices. +Review, History, CLI import, comparisons, resume and marginal estimates verify +that identity. Predictive checks reconstruct the sampled ratio and emit typed +`.mixed.json` replicates, retaining per-block alphabets and missing masks. +Prediction still rejects uncertainty/polymorphism until a suitable observation +model exists. Matrix inclusion in reproducibility exports is explicit and also +covers original copies kept by predictive checks. Exported simulations are +synthetic; they do not replace the original observations. + +Validation includes 36 fixed states from BEAST.base 2.7.8 + MM 1.2.1, independent +partition sums, normalized-prior quadrature and stationary sampling, constraints, +cache recomputation, exact checkpoint replay, prediction and native execution. +The reference likelihood tolerance is 1e-7, including independent gamma-quantile +approximations. Fixtures and generator are in `fixtures/validation/mixed` and +`tools/beast/MixedStates.java`. These are correctness checks, not convergence +certification or comparative speed measurements. diff --git a/docs/guide/nexus.md b/docs/guide/nexus.md index 339913e..23d1bda 100644 --- a/docs/guide/nexus.md +++ b/docs/guide/nexus.md @@ -4,6 +4,8 @@ description: "Read morphological NEXUS matrices in Rust, preserve observation se # Reading morphological NEXUS +Aligned DNA in NEXUS and FASTA is also supported under [JC69](./dna). The morphology rules below describe `STANDARD` matrices. + `nexus::parse` reads a UTF-8 string into a `data::Matrix`. It preserves taxon order, the declared state alphabet, character and state labels, and every observed cell. It has no runtime dependencies and does not invoke BEAST. Try the supplied reference matrix from the repository root: @@ -39,7 +41,7 @@ With `TAXLABELS`, returned rows follow the declared order even if matrix rows ap Defaults are case-insensitive states, missing symbol `?`, no gap symbol, and sequential rows. Thus `-` is not a gap unless declared with `GAP=-`. State, missing and gap symbols must be distinct under the chosen case policy. -Molecular or continuous datatypes, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, state ranges, frequencies/counts, `ELIMINATE`, multiple matrices and unsupported commands are rejected. `SETS`, unsupported `ASSUMPTIONS` directives and application-specific blocks are also rejected: their partitions, weights, ordering or exclusions must not disappear on import. XML parsing is outside this API. +RNA, protein or continuous datatypes, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, state ranges, frequencies/counts, `ELIMINATE`, multiple matrices and unsupported commands are rejected. `SETS`, unsupported `ASSUMPTIONS` directives and application-specific blocks are also rejected: their partitions, weights, ordering or exclusions must not disappear on import. XML parsing is outside this API. ## Observations and tip likelihoods diff --git a/docs/guide/reference-model.md b/docs/guide/reference-model.md index d88c130..5ffc0e3 100644 --- a/docs/guide/reference-model.md +++ b/docs/guide/reference-model.md @@ -4,6 +4,8 @@ description: "The standalone model of the supplied BEAST XML: gamma categories, # The reference model +Aligned DNA in NEXUS and FASTA is also supported under [JC69](./dna) + `rove sample --model reference` runs the probability model of the supplied 20 × 50 XML without BEAST. It uses the same binary Mk model, Mkv conditioning by default, birth–death prior and parameter conventions. The default @@ -172,3 +174,63 @@ preserve the chosen prior; chain comparisons require matching priors. `scale`, alongside the readable description. Legacy records use 5 and 0.2. Custom app setups use format 6 so older apps cannot silently ignore the choice. See [Tree priors](./tree-priors) for the separate decision about tree models. + +## Optional joint topology/rate exchange + +`--weight narrow_exchange_rates=10` enables an experimental proposal alongside the existing moves. It has zero weight by default and no tuning parameter. In the native app, use **Advanced sampling → Try joint topology/rate exchange**; its initial weight is 10 and remains editable. The choice is preserved in setup format 9, review, history, run records and checkpoints. Only an undated relaxed clock is currently supported; dated and strict-clock use is rejected before sampling. This is one independently implemented proposal, not the full BEAST ORC suite. No morphology speed or mixing benefit has been established; comparative measurements in [#97](https://github.com/getcortexlabs/rove/issues/97) remain deferred. + +Let `G` be an internal node with an internal child. Choose `G` uniformly from the `C(T)` such nodes, take its older child `P` and younger child `U`, and choose either child `X` of `P` with probability 1/2. Exchange `X` and `U`, keeping heights and the root unchanged. Preserve the incoming distance of each reattached subtree with: + +```text +rX' = rX (hP − hX) / (hG − hX) +rU' = rU (hG − hU) / (hP − hU) +J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)] +log Hastings = log C(T) − log C(T') + log J +``` + +Positive finite durations/rates and `hP > hU` are required. Boundary/overflow proposals fail before mutation. The reverse chooses the same `G` and `P` and exchanges `U` back with `X`; its probability is `1 / (2 C(T'))`, compared with `1 / (2 C(T))` forward. The continuous map leaves heights unchanged, so the Jacobian is the product of the two rate scale factors. Rates remain attached to node-indexed incoming branches, including the special slot when the root is not the last node. Constraints and likelihood/prior rejection use the normal exact restoration path. Preserving the reattached distances does not preserve the likelihood: the topology changes. + +Tests cover the inverse, full numerical Jacobian, enumerated forward/reverse choices, known uniform-topology/independent-lognormal targets, constraint rejection, fresh versus cached likelihood, different root indices, exact checkpoint replay, native cancellation/resumption and identical portable/ARM samples. These correctness checks do not replace posterior and performance studies. Related joint-proposal methods are described by [Douglas, Zhang and Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322). + +## 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/dna.md b/docs/pt-BR/guide/dna.md new file mode 100644 index 0000000..0c070a8 --- /dev/null +++ b/docs/pt-BR/guide/dna.md @@ -0,0 +1,64 @@ +--- +description: "DNA alinhado em NEXUS e FASTA com JC69, ambiguidades e tratamento explícito de gaps." +--- + +# DNA alinhado com JC69 + +[Morfologia e DNA combinados](./mixed-data.md). + +Abra no app uma matriz NEXUS `DATATYPE=DNA` ou um arquivo FASTA já alinhado. +A importação seleciona **DNA · JC69**, mantém A/C/G/T possíveis em cada sítio +e inclui sítios constantes. Rove não alinha, recorta ou monta leituras. +O mesmo arquivo funciona com `sample`, `inspect` e `marginal`: + +```sh +rove sample alignment.fasta --output dna-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --gaps missing +``` + +Escolha `--gaps missing` somente quando gaps não devem informar o estado. +O padrão rejeita gaps. `?` é ausente; `R` permite A/G, `Y` C/T, e os demais +códigos IUPAC mantêm seus estados possíveis. `N` permite os quatro. São +máscaras de verossimilhança com valores um, não probabilidades fracionadas +nem estados adicionais. Polimorfismo entre parênteses é preservado, mas não +aceito na inferência. DNA usa `--conditioning none --partitioning declared`; +Mkv, Mkparsinf e recodificação morfológica explícitos são rejeitados. + +Sequências FASTA podem ocupar várias linhas e devem ter comprimentos iguais +e positivos. O primeiro identificador após `>`, até o primeiro espaço, nomeia +o táxon; a descrição restante é ignorada, conforme a [convenção de cabeçalho FASTA](https://www.ncbi.nlm.nih.gov/genbank/fastaformat/). +A convenção NEXUS já usada pelo Rove também vale para FASTA: sublinhados viram +espaços, duplicatas são verificadas sem diferenciar maiúsculas ASCII e o resto +da grafia é mantido. Confira os nomes exibidos antes de escolher a raiz ou +combinar dados. Os arquivos originais não são alterados. + +Em NEXUS DNA, bases não distinguem maiúsculas, o alfabeto é A/C/G/T fixo e o +gap padrão é `-`. `SYMBOLS="ACGT"` é aceito; alfabetos próprios, RESPECTCASE, +DNA ordenado, RNA, proteínas e diretivas NEXUS não suportadas são rejeitados. +`MISSING=N` declara N como ausente. Valem as mesmas regras de linhas +sequenciais ou intercaladas já suportadas para morfologia. + +JC69 fixa frequências em 1/4 e taxas de troca iguais, normalizadas para uma +substituição esperada por sítio: `Pii(t)=1/4+3/4 exp(−4t/3)` e +`Pij(t)=1/4−1/4 exp(−4t/3)` entre bases diferentes. Os controles existentes +servem para relógios estrito e relaxado lognormal, categorias gama, raiz e +priors de árvore suportados. Não há correção morfológica de seleção de +caracteres. HKY e GTR não estão disponíveis. A análise combinada tem um fluxo próprio. + +Configurações de formato 11, Histórico, registros e checkpoints preservam +DNA/JC69 e o tratamento de gaps. Apps antigos rejeitam essas configurações. +É possível importar execuções CLI no Histórico; modelos incompatíveis não +são agrupados para avaliar convergência. Árvores, diagnósticos e estimativas +marginais mantêm o modelo ajustado. Testes curtos verificam integração, não +convergência posterior. A predição aceita bases individuais e células +ausentes; ambiguidades IUPAC precisam de modelo de observação e são recusadas +na simulação. Réplicas saem em NEXUS DNA. A exportação reprodutível mantém os +bytes originais em `matrix.fasta` ou `matrix.nex`. A inclusão continua explícita +e também controla cópias originais guardadas pelas verificações preditivas. + +As fixtures sintéticas em `fixtures/validation/dna` validam a soma independente +dos estados internos pela fórmula de JC69, seis estados fixos do BEAST.base +2.7.8, frequências simuladas e retomada exata. Com as mesmas taxas de categoria, +as diferenças absolutas de log-verossimilhança são menores que 1e-10. Com +quantis gama calculados separadamente, a tolerância é 1e-7; a aproximação AS91 +do BEAST difere menos de 3e-8 nas taxas desses estados. É validação numérica, +sem comparação de velocidade. diff --git a/docs/pt-BR/guide/macos-preview.md b/docs/pt-BR/guide/macos-preview.md index 00fa48b..e5f2a15 100644 --- a/docs/pt-BR/guide/macos-preview.md +++ b/docs/pt-BR/guide/macos-preview.md @@ -478,3 +478,36 @@ O plano oferece 1, 10, 20, 30, 50 e 100 milhões de passos, com intervalos de 10 Durante a execução, **Tempo estimado até o limite de passos** e **Tempo por milhão de passos** usam diferenças recentes de passos e de tempo ativo do motor. O Rove primeiro coleta pelo menos três intervalos cobrindo dez segundos e depois usa até oito intervalos recentes. Cada cadeia é medida separadamente; a estimativa do grupo é o maior tempo restante. Retomar depois de uma pausa inicia uma nova medição, sem contar o tempo parado. As estimativas desaparecem ao interromper ou concluir. A carga do processador pode mudar o ritmo. A previsão é até o limite de passos, não até a convergência; a parada automática pode encerrar antes. **O que são estes arquivos?**, nos resultados e no Histórico, abre uma explicação offline. O [guia da pasta da execução](./run-files) mostra os arquivos e o caminho do traço até a árvore anotada. + +### Orientação visual sobre o modelo + +O painel de enraizamento desenha a divisão imposta: o terminal escolhido de um lado e um grupo recolhido com todos os demais do outro. Ele não estima comprimentos de ramos, relações internas ou estados ancestrais. O tour usa a mesma terminologia de enraizamento. + +Abra **Prior do sigma do relógio** para ver a densidade gamma mudar com Alpha e Beta, na parametrização forma/escala. Uma linha tracejada marca a esperança do prior; o painel também mostra o desvio padrão. O trecho desenhado não é um intervalo de credibilidade. Com forma menor que um, a densidade diverge em zero e a curva começa acima de zero. Escalas numéricas extremas podem não ter prévia gráfica; isso não muda o prior do motor. + +A previsão de duração estima o limite de passos solicitado usando o tempo ativo recente do motor. Ela não prevê quando a convergência será estabelecida. As opções de seleção de caracteres e datação explicam suas hipóteses junto das mensagens de validação; essas explicações não demonstram adequação a um estudo específico. + +## Revisão das evidências e pacotes de reprodução + +Em **Histórico → Revisão das evidências**, escolha o burn-in e atualize a revisão. O arquivo `assessments/review-…/assessment.json` registra uma fotografia datada com identificadores SHA-256 das fontes, registros originais, diagnósticos por cadeia, uma comparação nova entre cadeias e caminhos dos relatórios de árvores e preditivos correspondentes. Atualize após gerar novos relatórios. O burn-in e a opção de incluir a matriz ficam salvos localmente junto à execução. + +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 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: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Incluir explicitamente uma matriz original correspondente: +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/mixed-data.md b/docs/pt-BR/guide/mixed-data.md new file mode 100644 index 0000000..24a3ebd --- /dev/null +++ b/docs/pt-BR/guide/mixed-data.md @@ -0,0 +1,75 @@ +--- +description: "Combine morfologia e DNA alinhado com fontes, correspondência de táxons e taxas relativas explícitas." +--- + +# Morfologia e DNA juntos + +Escolha **Combinar morfologia e DNA** na tela inicial do Mac. Selecione uma matriz +morfológica NEXUS STANDARD e DNA alinhado em NEXUS/FASTA, confira a política para +táxons ausentes e salve uma entrada `.mixed.json`. Na CLI: + +```sh +rove combine --morphology morphology.nex --dna alignment.fasta --missing-taxa reject --output study.mixed.json +rove sample study.mixed.json --output combined-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --morphology-rate estimate --morphology-rate-log-sd 1 +``` + +O manifesto incorpora os textos UTF-8 originais e seus hashes SHA-256, sem seguir +caminhos externos. Continua utilizável se os originais mudarem de lugar. Não +sobrescreve arquivos existentes e verifica formato, versão, tipos e hashes ao +abrir. O arquivo contém dados de pesquisa: sua distribuição exige a mesma +permissão necessária para compartilhar as duas fontes. + +Os táxons correspondem pelo **nome normalizado exato**, nunca pela posição das +linhas. Vale a conversão existente de sublinhados para espaços. `reject` exige +os mesmos táxons. A escolha explícita `--missing-taxa missing` mantém a união e +preenche ausências com dados faltantes; o app lista os táxons ausentes por fonte. +São necessários ao menos dois táxons compartilhados. Diferenças apenas de +maiúsculas/minúsculas são rejeitadas. Confira outras diferenças de escrita antes +de tratá-las como ausências biológicas. Células faltantes não informam estados; +gaps mantêm a política separada `--gaps reject|missing`. O Rove não alinha sequências. + +Cada bloco preserva alfabeto, ordem, rótulos e observações. A morfologia admite +alfabetos observados, declarados ou completos pelos rótulos, caracteres ordenados +ou não e `--conditioning none|variable|informative`. Essas escolhas valem **só +para a morfologia**. O DNA usa JC69 sem correção de amostragem, quatro bases e +todos os sítios, inclusive constantes. Ambiguidades IUPAC são máscaras de bases +possíveis; polimorfismos verdadeiros continuam impedindo a inferência. + +Os blocos compartilham topologia, tempos dos ramos, relógio estrito ou lognormal +e parâmetro de forma gama quando habilitado. As categorias são integradas por +sítio. Não há relógios ou formas gama independentes por bloco. O DNA fixa a taxa +relativa em 1. Todas as partições morfológicas usam um multiplicador positivo +comum `r`: distância `tempo × taxa do ramo × r`; no DNA, `tempo × taxa do ramo`. +Isso define a escala relativa, sem transformar comprimentos não datados em +idades de calendário. A datação fóssil mantém relógio global e calibrações explícitos. + +Escolha o modelo de taxa no app ou na CLI: + +- `--morphology-rate 2.5` fixa a razão nesse valor positivo. +- `--morphology-rate estimate --morphology-rate-log-sd s` estima a razão com + `log(r) ~ Normal(0, s²)`. O desvio padrão do log é 1 se omitido; a mediana é 1 + e a média é `exp(s²/2)`. Avalie a sensibilidade a essa premissa. + +O log prior normalizado é +`−log(r) − log(s) − log(2π)/2 − (log(r)/s)²/2`. +A proposta de escala usa `f ~ Uniform(a, 1/a)` e log da razão de Hastings +`−log(f)`. O movimento `morphology_rate_scale` tem peso inicial 3 na estimação +e não está disponível com razão fixa. O estado fica no `trace.log` e no +checkpoint. A log verossimilhança é a soma dos blocos, com a correção de +amostragem escolhida para a morfologia. Os priors entram uma vez; o prior da +razão é normalizado para a estimativa marginal. + +Setups de formato 12 preservam fontes, política de táxons e taxas. Revisão, +histórico, importação da CLI, comparação, retomada e estimativas marginais +conferem essa identidade. A predição reconstrói a razão amostrada e gera réplicas +`.mixed.json`, com alfabetos por bloco e máscaras de dados faltantes. Incerteza +e polimorfismo ainda exigem um modelo de observação para simulação. A inclusão +da matriz na exportação é explícita, inclusive para cópias originais guardadas +pela predição. As simulações exportadas são sintéticas e não substituem as observações. + +A validação inclui 36 estados fixos BEAST.base 2.7.8 + MM 1.2.1, soma independente +dos blocos, quadratura do prior e amostragem estacionária, restrições, recálculo +do cache, retomada exata, predição e execução nativa. A tolerância é 1e-7, +incluindo aproximações independentes dos quantis gama. Dados e gerador estão em +`fixtures/validation/mixed` e `tools/beast/MixedStates.java`. São testes de +correção, sem certificação de convergência ou comparação de velocidade. diff --git a/docs/pt-BR/guide/nexus.md b/docs/pt-BR/guide/nexus.md index ba407b8..2501a0f 100644 --- a/docs/pt-BR/guide/nexus.md +++ b/docs/pt-BR/guide/nexus.md @@ -4,6 +4,8 @@ description: "Leia matrizes NEXUS morfológicas em Rust, preserve a semântica d # Lendo NEXUS morfológico +DNA alinhado em NEXUS e FASTA também é aceito com [JC69](./dna). As regras morfológicas abaixo descrevem matrizes `STANDARD`. + `nexus::parse` lê uma string UTF-8 e produz uma `data::Matrix`. Ele preserva a ordem dos táxons, o alfabeto de estados declarado, os rótulos de caracteres e de estados e cada célula observada. Não tem dependências em tempo de execução e não invoca o BEAST. Experimente a matriz de referência fornecida, a partir da raiz do repositório: @@ -39,7 +41,7 @@ Com `TAXLABELS`, as linhas devolvidas seguem a ordem declarada mesmo que as linh Sem declaração em contrário, os estados não distinguem maiúsculas de minúsculas, o símbolo de faltante é `?`, não há símbolo de gap e as linhas são sequenciais. Assim, `-` não é um gap a menos que seja declarado com `GAP=-`. Os símbolos de estado, de faltante e de gap devem ser distintos sob a política de maiúsculas e minúsculas escolhida. -Tipos de dados moleculares ou contínuos, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, intervalos de estados, frequências/contagens, `ELIMINATE`, múltiplas matrizes e comandos não suportados são rejeitados. `SETS`, diretivas não suportadas de `ASSUMPTIONS` e blocos específicos de aplicativos também são rejeitados: suas partições, pesos, ordenação ou exclusões não devem desaparecer na importação. O parsing de XML está fora desta API. +Tipos de dados de RNA, proteínas ou contínuos, `TOKENS`, `TRANSPOSE`, `NOLABELS`, `EQUATE`, `MATCHCHAR`, intervalos de estados, frequências/contagens, `ELIMINATE`, múltiplas matrizes e comandos não suportados são rejeitados. `SETS`, diretivas não suportadas de `ASSUMPTIONS` e blocos específicos de aplicativos também são rejeitados: suas partições, pesos, ordenação ou exclusões não devem desaparecer na importação. O parsing de XML está fora desta API. ## Observações e verossimilhanças dos terminais diff --git a/docs/pt-BR/guide/reference-model.md b/docs/pt-BR/guide/reference-model.md index 46d1652..e89fd90 100644 --- a/docs/pt-BR/guide/reference-model.md +++ b/docs/pt-BR/guide/reference-model.md @@ -4,6 +4,8 @@ description: "O modelo independente do XML fornecido: categorias gama, taxas log # O modelo de referência +DNA alinhado em NEXUS e FASTA também é aceito com [JC69](./dna) + `rove sample --model reference` executa o modelo probabilístico do XML 20 × 50 fornecido, sem o BEAST. Usa o mesmo Mk binário, a correção Mkv por padrão, o prior de nascimento–morte e as convenções dos parâmetros. A opção @@ -180,3 +182,64 @@ preservam o prior; comparar cadeias exige priors iguais. `run.json` registra Registros antigos usam 5 e 0,2. Configurações personalizadas do app usam formato 6 para impedir que apps antigos ignorem a escolha. Veja [Priors de árvore](./tree-priors) para a decisão separada sobre modelos de árvore. + +## Troca conjunta opcional de topologia e taxas + +`--weight narrow_exchange_rates=10` ativa uma proposta experimental junto às existentes. Seu peso padrão é zero e não há parâmetro de ajuste do passo. No app, use **Amostragem avançada → Experimentar troca conjunta de topologia e taxas**; o peso inicial é 10 e permanece editável. A escolha fica no formato 9 de configuração, revisão, histórico, registros e checkpoints. Por enquanto, exige relógio relaxado sem datação; relógio estrito e datação são recusados antes da amostragem. É uma proposta implementada independentemente, não o conjunto completo do BEAST ORC. Nenhum ganho de velocidade ou mistura para morfologia foi demonstrado; as medições comparativas da [#97](https://github.com/getcortexlabs/rove/issues/97) continuam adiadas. + +Seja `G` um nó interno com filho interno. Escolha `G` uniformemente entre os `C(T)` nós assim definidos, tome seu filho mais antigo `P` e o mais recente `U`, e escolha um dos filhos `X` de `P` com probabilidade 1/2. Troque `X` e `U`, mantendo alturas e raiz. Preserve a distância de entrada de cada subárvore realocada: + +```text +rX' = rX (hP − hX) / (hG − hX) +rU' = rU (hG − hU) / (hP − hU) +J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)] +log Hastings = log C(T) − log C(T') + log J +``` + +Durações e taxas devem ser positivas e finitas, com `hP > hU`. Limites inválidos ou overflow são rejeitados antes da alteração. O reverso escolhe os mesmos `G` e `P` e troca `U` de volta com `X`; sua probabilidade é `1 / (2 C(T'))`, contra `1 / (2 C(T))` na ida. A transformação contínua preserva alturas, portanto o jacobiano é o produto dos dois fatores de escala das taxas. As taxas continuam associadas aos ramos de entrada indexados por nó, incluindo o índice especial quando a raiz não é o último nó. Restrições e rejeições pela verossimilhança/prior usam a restauração exata normal. Preservar as distâncias dos ramos realocados não preserva a verossimilhança, pois a topologia muda. + +Os testes cobrem inversão, jacobiano numérico completo, escolhas de ida/volta enumeradas, alvos conhecidos de topologias uniformes e taxas lognormais independentes, rejeição por restrições, verossimilhança recalculada versus cache, diferentes índices de raiz, checkpoints exatos, cancelamento/retomada no app e amostras idênticas nos backends portátil/ARM. Esses testes de correção não substituem estudos de posterior e desempenho. Métodos relacionados são descritos por [Douglas, Zhang e Bouckaert (2021)](https://doi.org/10.1371/journal.pcbi.1008322). + +## 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/dna.md b/docs/zh-CN/guide/dna.md new file mode 100644 index 0000000..9acb570 --- /dev/null +++ b/docs/zh-CN/guide/dna.md @@ -0,0 +1,48 @@ +--- +description: "使用 JC69 分析 NEXUS 和 FASTA 中已比对的 DNA,明确处理模糊碱基与缺口。" +--- + +# 使用 JC69 分析已比对 DNA + +[联合分析形态与 DNA](./mixed-data.md). + +在应用中打开 NEXUS `DATATYPE=DNA` 矩阵或已比对的 FASTA 文件。导入自动选择 +**DNA · JC69**,每个位点保留 A/C/G/T 四个可能状态,并保留恒定位点。 +Rove 不执行序列比对、裁剪或测序读段组装。相同输入可用于 `sample`、`inspect` +及 `marginal`: + +```sh +rove sample alignment.fasta --output dna-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --gaps missing +``` + +仅在缺口不应提供状态信息时选择 `--gaps missing`;默认拒绝缺口。`?` 表示缺失, +`R` 允许 A/G,`Y` 允许 C/T,其他 IUPAC 代码保留其可能状态,`N` 允许全部四种。 +这些是取值为一的似然掩码,不是分数概率或额外状态。括号内的多态被保留,但 +不能用于推断。DNA 默认使用 `--conditioning none --partitioning declared`; +显式请求 Mkv、Mkparsinf 或形态学状态重编码会被拒绝。 + +FASTA 序列可跨行,必须非空且等长。按照 [FASTA 标题约定](https://www.ncbi.nlm.nih.gov/genbank/fastaformat/), +`>` 后到首个空白之前的标识符是分类单元名称,其余描述被忽略。Rove 现有的 +NEXUS 命名规则也适用于 FASTA:下划线转换为空格,重复检查忽略 ASCII 大小写, +其余拼写不变。定根或匹配数据前请核对界面显示的名称;原始文件不会修改。 +NEXUS DNA 碱基不区分大小写,固定为 A/C/G/T,默认缺口为 `-`,可选 +`SYMBOLS="ACGT"`。自定义字母表、RESPECTCASE、有序 DNA、RNA、蛋白质及不支持 +的指令均被拒绝。`MISSING=N` 可显式将 N 定义为缺失。支持与形态学相同的顺序 +或带标签交错布局。 + +JC69 固定各碱基频率为 1/4,交换率相等,并归一化为每个位点一次预期替换: +`Pii(t)=1/4+3/4 exp(−4t/3)`,不同碱基为 `Pij(t)=1/4−1/4 exp(−4t/3)`。 +现有控件提供严格或对数正态松弛时钟、伽马类别、定根及支持的树先验。DNA 不使用 +形态学取样校正。目前不支持 HKY 或 GTR。形态与 DNA 联合分析有单独的明确流程。 + +格式 11 的设置、历史、运行记录和检查点保存 DNA/JC69 及缺口策略,旧版应用会 +拒绝这些设置。命令行运行可导入历史;不兼容模型不能合并做收敛比较。树、诊断和 +边际似然估计保留拟合模型。短执行测试验证集成,不证明后验收敛。后验预测目前 +要求单个碱基或缺失单元;IUPAC 不确定观测需要明确的观测模型,模拟时会拒绝。 +模拟副本使用 DNA NEXUS。复现导出将原始输入字节保存在 `matrix.fasta` 或 `matrix.nex` 中。 +矩阵须显式选择才会导出,此选项同样控制预测检查保存的原始矩阵副本。 + +`fixtures/validation/dna` 包含合成数据、独立解析内部状态求和、BEAST.base 2.7.8 +的六个固定状态、模拟频率与精确续跑测试。使用相同类别率时,对数似然绝对误差 +小于 1e-10;分别计算伽马分位数时采用 1e-7 容差,BEAST 的 AS91 近似在这些状态 +的类别率差异小于 3e-8。这是数值验证,不是性能比较。 diff --git a/docs/zh-CN/guide/macos-preview.md b/docs/zh-CN/guide/macos-preview.md index abb17dc..7fb7a44 100644 --- a/docs/zh-CN/guide/macos-preview.md +++ b/docs/zh-CN/guide/macos-preview.md @@ -375,3 +375,36 @@ History 中已完成的运行包含 **Can the model reproduce the matrix?** 面 运行中,**Estimated time to step limit** 和 **Time per million steps** 根据近期步数及引擎有效运行时间的差值计算。先收集至少三个、跨度不少于十秒的间隔,之后最多使用最近八个间隔。各链分别估计,链组采用最长剩余时间。恢复运行时重新测量,不计暂停时间。停止或结束后不再显示估计。CPU 负载可能改变速度。估计的是达到请求步数上限的时间,不是收敛时间;自动停止可能提前结束。 结果和 History 中的 **What are these files?** 提供离线说明。[运行文件夹指南](./run-files)展示文件结构及从轨迹到注释树的操作示例。 + +### 模型的可视化说明 + +定根面板显示实际施加的分割:一侧是所选末端,另一侧是包含其余所有末端的折叠类群。示意图不估计枝长、内部关系或祖先状态。初始引导使用一致的定根术语。 + +展开 **Clock sigma prior**,可查看 Gamma 密度随 Alpha 和 Beta 的变化,参数化为形状/尺度。虚线标示先验期望值,同时显示标准差。绘图范围不是可信区间。形状参数小于 1 时,密度在零处发散,因此曲线从大于零的位置开始。极端数值尺度可能无法绘图,但不会改变引擎使用的先验。 + +运行时间预测根据近期引擎活动时间估计达到所请求步数上限的时间,不预测何时能够确认收敛。性状选择和化石定年控件在验证信息旁解释相应假设;这些解释本身不能证明模型适合某项研究。 + +## 证据审查与可复现数据包 + +在 **History → Evidence review** 中选择预热比例并刷新审查。`assessments/review-…/assessment.json` 保存带时间戳的快照,包括源文件 SHA-256、原始运行记录、链内诊断、新计算的链间比较,以及匹配的树和后验预测报告路径。生成新报告后请刷新。预热比例和是否包含矩阵的选项保存在运行目录旁。 + +运行完成、标量采样、独立链一致性、树证据和预测证据分别显示状态。标量标准为每条链至少保留 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** 且指纹匹配时才包含原矩阵。审查会标明原矩阵已更改或不可用。不复制未知相邻文件、以前的审查或比较报告引用的外部数据源。导出保留记录中的路径和分类单元名称,拒绝结果文件内部的符号链接和现有目标,检查复制过程中源文件是否变化,并保持原件不变。数据包不包含可执行文件:精确恢复需要有效检查点以及原可执行文件、输入和模型身份;复用配置前请检查路径。 + +引擎提供相同操作: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# 明确包含指纹匹配的原矩阵: +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/mixed-data.md b/docs/zh-CN/guide/mixed-data.md new file mode 100644 index 0000000..2b98024 --- /dev/null +++ b/docs/zh-CN/guide/mixed-data.md @@ -0,0 +1,62 @@ +--- +description: "在明确数据来源、分类单元匹配和相对速率的前提下联合分析形态与已比对 DNA。" +--- + +# 联合分析形态与 DNA + +在 Mac 欢迎页选择 **Combine morphology and DNA**,指定一个 STANDARD 形态 +NEXUS 文件及一个已比对的 DNA NEXUS/FASTA 文件,检查缺失分类单元的处理方式, +保存新的 `.mixed.json` 输入。CLI 对应操作: + +```sh +rove combine --morphology morphology.nex --dna alignment.fasta --missing-taxa reject --output study.mixed.json +rove sample study.mixed.json --output combined-run --seed 42 --steps 30000000 --sample-every 3000 --model reference --morphology-rate estimate --morphology-rate-log-sd 1 +``` + +清单内嵌两个原始 UTF-8 文本及其 SHA-256 指纹,不读取外部源路径。原文件移位后 +仍可使用。不会覆盖现有输出;每次导入都检查格式、版本、数据类型和指纹。 +清单包含研究数据,只有获准分享两个原始数据集时才应分发。 + +分类单元按**标准化后的完整名称精确匹配**,不按行位置匹配。现有的下划线转空格 +规则仍然适用。默认 `reject` 要求两组分类单元相同;显式选择 +`--missing-taxa missing` 保留并集,为某来源没有的分类单元填入缺失数据,应用会 +逐来源列出它们。至少需要两个共同分类单元。仅大小写不同的名称会被拒绝; +其他拼写差异也应先核对,不能直接视为生物学缺失。缺失单元不提供状态信息; +gap 保持独立的 `--gaps reject|missing` 策略。Rove 不自动进行序列比对。 + +每个数据块保留自己的字母表、字符顺序、标签和观测。形态支持观察、声明或完整 +状态标签定义的字母表、有序/无序模型和 `--conditioning none|variable|informative`。 +这些选项**仅作用于形态**。DNA 使用无条件 JC69、完整四种碱基及全部位点,包括 +常量位点。IUPAC 歧义表示可能碱基的掩码;真正的多态性仍会阻止推断。 + +两个数据块共享拓扑、分支时间、严格或对数正态分支时钟,以及启用时的 gamma +形状参数。速率类别在各位点分别积分。不提供按块独立的时钟或 gamma 形状。 +DNA 相对速率固定为 1;所有形态分区共用正乘数 `r`,距离为 +`时间 × 分支速率 × r`,DNA 则为 `时间 × 分支速率`。这确定相对尺度,并不把 +未定年的分支长度变成日历年龄。化石定年继续使用明确的全局时钟及校准设置。 + +必须明确选择速率模型: + +- `--morphology-rate 2.5` 将比率固定在该正值。 +- `--morphology-rate estimate --morphology-rate-log-sd s` 使用 + `log(r) ~ Normal(0, s²)` 估计比率。省略时,对数标准差为 1;中位数为 1, + 均值为 `exp(s²/2)`。应评估结果对这一假设的敏感性。 + +标准化对数先验为 +`−log(r) − log(s) − log(2π)/2 − (log(r)/s)²/2`。 +尺度提议使用 `f ~ Uniform(a, 1/a)`,对数 Hastings 比为 `−log(f)`。 +估计时 `morphology_rate_scale` 默认权重为 3;比率固定时不可使用该提议。 +状态保存在 `trace.log` 和检查点中。联合对数似然为两块之和,其中形态使用选定 +的抽样校正。先验只计一次,相对速率先验经过标准化,可用于边际似然估计。 + +格式 12 的应用配置保留来源、分类单元策略和速率选项。复核、历史、CLI 导入、 +比较、恢复和边际估计均核验该身份。预测检验重建抽样时的比率,输出带类型的 +`.mixed.json` 重复数据,保留各块字母表和缺失掩码。模拟歧义或多态性观测仍需 +明确的观测模型。导出是否包含原矩阵必须显式选择;此选择也适用于预测检验 +保存的原始副本。导出的模拟数据是合成数据,不能替代原始观测。 + +验证包括 BEAST.base 2.7.8 + MM 1.2.1 的 36 个固定状态、独立分区求和、先验 +积分和稳态抽样、约束、缓存重算、精确检查点恢复、预测及原生应用执行。 +参考似然容差为 1e-7,包含独立 gamma 分位数算法的近似差异。数据和生成器位于 +`fixtures/validation/mixed` 与 `tools/beast/MixedStates.java`。这些是正确性检查, +不是收敛认证或速度比较。 diff --git a/docs/zh-CN/guide/nexus.md b/docs/zh-CN/guide/nexus.md index 65cbbaa..84b8bd3 100644 --- a/docs/zh-CN/guide/nexus.md +++ b/docs/zh-CN/guide/nexus.md @@ -4,6 +4,8 @@ description: "在 Rust 中读取形态学 NEXUS 矩阵,保留观测语义, # 读取形态学 NEXUS +也支持通过 [JC69](./dna) 分析 NEXUS 和 FASTA 中已比对的 DNA。以下形态学规则描述 `STANDARD` 矩阵。 + `nexus::parse` 把一个 UTF-8 字符串读入 `data::Matrix`。它保留分类单元的顺序、声明的状态字母表、性状标签和状态标签,以及每一个观测单元格。它没有运行时依赖,也不会调用 BEAST。 在代码仓库根目录下试试随附的参考矩阵: @@ -39,7 +41,7 @@ cargo run --release --example read_nexus -- fixtures/reference/20x50/matrix.nex 默认值是:状态不区分大小写,缺失符号为 `?`,没有缺口符号,顺序行。因此除非用 `GAP=-` 声明,`-` 不是缺口。在所选的大小写策略下,状态、缺失和缺口符号必须互不相同。 -分子或连续数据类型、`TOKENS`、`TRANSPOSE`、`NOLABELS`、`EQUATE`、`MATCHCHAR`、状态范围、频率/计数、`ELIMINATE`、多个矩阵和不支持的命令都会被拒绝。`SETS`、不支持的 `ASSUMPTIONS` 指令和应用程序特有的块同样会被拒绝:它们的分区、权重、排序或排除项不能在导入时消失。XML 解析不在这个 API 的范围内。 +RNA、蛋白质或连续数据类型、`TOKENS`、`TRANSPOSE`、`NOLABELS`、`EQUATE`、`MATCHCHAR`、状态范围、频率/计数、`ELIMINATE`、多个矩阵和不支持的命令都会被拒绝。`SETS`、不支持的 `ASSUMPTIONS` 指令和应用程序特有的块同样会被拒绝:它们的分区、权重、排序或排除项不能在导入时消失。XML 解析不在这个 API 的范围内。 ## 观测与末端节点似然 diff --git a/docs/zh-CN/guide/reference-model.md b/docs/zh-CN/guide/reference-model.md index e72c1e3..685f5b2 100644 --- a/docs/zh-CN/guide/reference-model.md +++ b/docs/zh-CN/guide/reference-model.md @@ -4,6 +4,8 @@ description: "独立运行所提供 XML 的概率模型:gamma 类别、显式 # 参考模型 +也支持通过 [JC69](./dna) 分析 NEXUS 和 FASTA 中已比对的 DNA + `rove sample --model reference` 无需 BEAST 即可运行所提供 20 × 50 XML 的概率模型。 它使用相同的二态 Mk、默认的 Mkv 校正、生灭先验和参数约定。默认选项 `--model strict` 保留先前的单速率类别、严格时钟配置。两个配置都可用 @@ -137,3 +139,52 @@ CLI 在 `--model reference` 下接受 `--clock-sigma-shape 2.5 --clock-sigma-sca `run.json` 中的 `clock_sigma_prior_parameters` 记录数值 `shape` 和 `scale`,并保留文字说明。 旧记录按 5 和 0.2 解释。自定义应用设置使用格式 6,防止旧应用忽略设置。 树模型的独立决策见[树先验](./tree-priors)。 + +## 可选的拓扑与速率联合交换 + +`--weight narrow_exchange_rates=10` 在现有提议之外启用一项实验性提议。默认权重为零,没有步长调节参数。原生应用中使用 **Advanced sampling → Try joint topology/rate exchange**,初始权重为 10,可继续编辑。选项保存在格式 9 的配置、审查、历史、运行记录和检查点中。目前仅支持无定年的松弛钟;严格钟和定年分析会在采样前被拒绝。这是独立实现的一项提议,并非完整 BEAST ORC 套件。尚未证明形态数据上的速度或混合收益;[#97](https://github.com/getcortexlabs/rove/issues/97) 的比较测量仍然推迟。 + +设 `G` 为具有内部子节点的内部节点。从这样的 `C(T)` 个节点中均匀选择 `G`,取其较老子节点 `P` 和较年轻子节点 `U`,再以 1/2 概率选择 `P` 的一个子节点 `X`。交换 `X` 和 `U`,保持高度及根不变,并保持两个重接子树的入枝距离: + +```text +rX' = rX (hP − hX) / (hG − hX) +rU' = rU (hG − hU) / (hP − hU) +J = [(hP − hX) / (hG − hX)] [(hG − hU) / (hP − hU)] +log Hastings = log C(T) − log C(T') + log J +``` + +持续时间和速率必须为正且有限,并满足 `hP > hU`。无效边界或溢出在修改前拒绝。逆映射选择相同的 `G`、`P`,将 `U` 与 `X` 换回;逆向概率为 `1 / (2 C(T'))`,正向为 `1 / (2 C(T))`。连续映射不改变高度,因此雅可比是两个速率缩放因子的乘积。速率仍对应节点索引的入枝,包括根不是最后节点时的特殊槽位。约束与似然/先验拒绝沿用精确恢复路径。保留重接枝距离并不保留似然,因为拓扑改变了。 + +测试覆盖逆映射、完整数值雅可比、枚举的正反选择、已知均匀拓扑与独立对数正态速率目标、约束拒绝、重新计算与缓存似然、不同根索引、精确检查点回放、原生取消/恢复,以及 portable/ARM 后端样本一致性。这些正确性测试不能替代后验及性能研究。相关方法见 [Douglas、Zhang 与 Bouckaert(2021)](https://doi.org/10.1371/journal.pcbi.1008322)。 + +## 可选的 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/dna/README.md b/fixtures/validation/dna/README.md new file mode 100644 index 0000000..6d786a1 --- /dev/null +++ b/fixtures/validation/dna/README.md @@ -0,0 +1,29 @@ +# Synthetic aligned DNA + +All sequences here are synthetic and redistributable. The `matrix` pair has +identical observations in FASTA and NEXUS, including constant sites, R/Y/N +ambiguity, missing cells and a gap. The `complete` pair uses only A/C/G/T and +can also exercise posterior prediction. FASTA descriptions are ignored and +underscores in identifiers follow Rove's existing NEXUS-to-space convention. + +`DnaStates.java` exports six fixed states from BEAST.base 2.7.8 with +`java.only=true`, `scaling=always`, `useAmbiguities=true`, strict clock rate 1, +height increments 0.001/0.05/1.7, and one/four gamma categories (shape 0.7). +The TSV includes the actual category rates. Jar fingerprints are recorded in +`provenance.json`. The engine does not depend on BEAST or Java. + +Reproduce using a local pinned BEAST package directory and launcher: + +```sh +javac --release 17 -cp /path/BEAST.base.jar:/path/launcher.jar -d /tmp/rove-dna tools/beast/DnaStates.java +java -Dbeast.user.package.dir=/path/packages -cp /tmp/rove-dna:/path/BEAST.base.jar:/path/launcher.jar DnaStates /tmp/dna.tsv +``` + +`tests/dna.rs` independently enumerates internal states with JC69's closed-form +transition probabilities. Fixed-rate kernel comparisons use absolute 1e-10 +log-likelihood tolerance. Shape-based comparisons allow 1e-7 because BEAST's +AS91 gamma quantiles have lower precision (already tested in `tests/rates.rs`); +these category rates differ by less than 3e-8. Tests also cover IUPAC masks, +constant sites, gaps, model identity, rejection of unsupported options, +simulation frequencies, cache correctness, and exact checkpoint continuation. +No benchmark or mixing comparison is included. diff --git a/fixtures/validation/dna/beast-2.7.8.tsv b/fixtures/validation/dna/beast-2.7.8.tsv new file mode 100644 index 0000000..b5045cb --- /dev/null +++ b/fixtures/validation/dna/beast-2.7.8.tsv @@ -0,0 +1,7 @@ +height_step categories shape log_likelihood category_rates +0.001 1 0.7 -122.35230897918072 1.0 +0.001 4 0.7 -118.12409765723184 0.0740142904547853,0.39882196965807243,1.0144203406595267,2.512743399227616 +0.05 1 0.7 -70.6609811523506 1.0 +0.05 4 0.7 -69.7788071553649 0.0740142904547853,0.39882196965807243,1.0144203406595267,2.512743399227616 +1.7 1 0.7 -77.55658051402887 1.0 +1.7 4 0.7 -69.06440091712855 0.0740142904547853,0.39882196965807243,1.0144203406595267,2.512743399227616 diff --git a/fixtures/validation/dna/complete.fasta b/fixtures/validation/dna/complete.fasta new file mode 100644 index 0000000..6adf6ff --- /dev/null +++ b/fixtures/validation/dna/complete.fasta @@ -0,0 +1,10 @@ +>Alpha_one synthetic alignment +AACGTACGTAAC +>Beta_two synthetic alignment +AATGTCATACGT +>Gamma_three synthetic alignment +ACCGTGGTAAGT +>Delta_four synthetic alignment +AGCGTTACTCGT +>Epsilon_five synthetic alignment +ATCGTCGTACGT diff --git a/fixtures/validation/dna/complete.nex b/fixtures/validation/dna/complete.nex new file mode 100644 index 0000000..641747d --- /dev/null +++ b/fixtures/validation/dna/complete.nex @@ -0,0 +1,12 @@ +#NEXUS +BEGIN DATA; +DIMENSIONS NTAX=5 NCHAR=12; +FORMAT DATATYPE=DNA MISSING=? GAP=-; +MATRIX +'Alpha_one' AACGTACGTAAC +'Beta_two' AATGTCATACGT +'Gamma_three' ACCGTGGTAAGT +'Delta_four' AGCGTTACTCGT +'Epsilon_five' ATCGTCGTACGT +; +END; diff --git a/fixtures/validation/dna/matrix.fasta b/fixtures/validation/dna/matrix.fasta new file mode 100644 index 0000000..8c18bc0 --- /dev/null +++ b/fixtures/validation/dna/matrix.fasta @@ -0,0 +1,10 @@ +>Alpha_one synthetic alignment +AACGTRYN?-AC +>Beta_two synthetic alignment +AATGTCATACGT +>Gamma_three synthetic alignment +ACCGTGGTAAGT +>Delta_four synthetic alignment +AGCGTTACTCGT +>Epsilon_five synthetic alignment +ATCGTCGTACGT diff --git a/fixtures/validation/dna/matrix.nex b/fixtures/validation/dna/matrix.nex new file mode 100644 index 0000000..d01ef3a --- /dev/null +++ b/fixtures/validation/dna/matrix.nex @@ -0,0 +1,12 @@ +#NEXUS +BEGIN DATA; +DIMENSIONS NTAX=5 NCHAR=12; +FORMAT DATATYPE=DNA MISSING=? GAP=-; +MATRIX +'Alpha_one' AACGTRYN?-AC +'Beta_two' AATGTCATACGT +'Gamma_three' ACCGTGGTAAGT +'Delta_four' AGCGTTACTCGT +'Epsilon_five' ATCGTCGTACGT +; +END; diff --git a/fixtures/validation/dna/provenance.json b/fixtures/validation/dna/provenance.json new file mode 100644 index 0000000..dc10dde --- /dev/null +++ b/fixtures/validation/dna/provenance.json @@ -0,0 +1,8 @@ +{ + "reference": "BEAST.base 2.7.8", + "java": "Temurin 17.0.15", + "jar_sha256": "7e2133989c1cc0a8d78e23917db90e86236e0b4f17213c5d439bfd908c93a359", + "launcher_sha256": "7d51654fd80dd4c32f64e02b02ca90aa6387c2c9837761befe665ff730a5dc01", + "generator": "tools/beast/DnaStates.java", + "scope": "6 fixed synthetic JC69 states, with ambiguities and missing gaps; strict clock and 1/4 gamma categories; no MCMC or timing" +} diff --git a/fixtures/validation/mixed/README.md b/fixtures/validation/mixed/README.md new file mode 100644 index 0000000..f384784 --- /dev/null +++ b/fixtures/validation/mixed/README.md @@ -0,0 +1,26 @@ +# Combined morphology and DNA reference + +Synthetic five-taxon, six-character binary morphology plus the twelve-site +`../dna/complete.fasta` alignment. `study.mixed.json` embeds their original UTF-8 +contents and SHA-256 digests; no private matrices are used. + +`beast-2.7.8.tsv` contains 36 states from BEAST.base 2.7.8 + MM 1.2.1: +ladder internal heights 1–4 times `height_step`, contemporaneous tips, strict +branch clock, morphology/DNA rate ratios 0.2/1/3.5, 1/4 gamma categories with +shape 0.7, and unconditioned/variable/informative morphology (codes 0/1/2). +DNA is always unconditioned JC69. Columns list both likelihood components and +their sum. The Java oracle enumerates excluded binary columns for ascertainment; +it does not use Rove's likelihood or informative-probability implementation. + +Reproduce with `tools/beast/MixedStates.java`, Java 17, the pinned BEAST.base jar, +MM addon jar and `launcher.jar` on the classpath. Set `beast.user.package.dir` to +the corresponding package directory; pass the destination TSV as the only +argument. `provenance.json` records versions and SHA-256 hashes. This is a +fixed-state reference, not a runtime dependency or performance measurement. + +`cargo test --test mixed` checks the reference at tolerance 1e-7 (including gamma +quantile approximation differences), independent component sums, a normalized +lognormal rate prior and stationary simulation, taxon matching and missing +masks, cache recomputation and exact state replay. CLI/native tests additionally +exercise combined-source creation, settings/history, resume, predictive checks, +marginal estimates and explicit original-input export consent. diff --git a/fixtures/validation/mixed/beast-2.7.8.tsv b/fixtures/validation/mixed/beast-2.7.8.tsv new file mode 100644 index 0000000..9529d5c --- /dev/null +++ b/fixtures/validation/mixed/beast-2.7.8.tsv @@ -0,0 +1,37 @@ +height_step categories conditioning morphology_rate morphology_log_likelihood dna_log_likelihood joint_log_likelihood +0.01 1 0 0.2 -72.23834653311707 -108.22032095561926 -180.45866748873632 +0.01 1 0 1.0 -53.305252020442566 -108.22032095561926 -161.52557297606182 +0.01 1 0 3.5 -39.42716140743076 -108.22032095561926 -147.64748236305002 +0.01 1 1 0.2 -50.683431268236745 -108.22032095561926 -158.903752223856 +0.01 1 1 1.0 -41.00822811883559 -108.22032095561926 -149.22854907445486 +0.01 1 1 3.5 -33.47713133449607 -108.22032095561926 -141.69745229011534 +0.01 1 2 0.2 -39.32739576674117 -108.22032095561926 -147.54771672236043 +0.01 1 2 1.0 -30.752736363607 -108.22032095561926 -138.97305731922626 +0.01 1 2 3.5 -25.54299669915799 -108.22032095561926 -133.76331765477724 +0.01 4 0 0.2 -68.58078744384419 -103.04014588390791 -171.62093332775208 +0.01 4 0 1.0 -50.10859677214491 -103.04014588390791 -153.14874265605283 +0.01 4 0 3.5 -37.47903432223957 -103.04014588390791 -140.5191802061475 +0.01 4 1 0.2 -46.938301657932286 -103.04014588390791 -149.97844754184018 +0.01 4 1 1.0 -37.409121237576386 -103.04014588390791 -140.4492671214843 +0.01 4 1 3.5 -30.440870914881263 -103.04014588390791 -133.48101679878917 +0.01 4 2 0.2 -35.84132069339124 -103.04014588390791 -138.88146657729914 +0.01 4 2 1.0 -28.035577789078115 -103.04014588390791 -131.07572367298602 +0.01 4 2 3.5 -23.728222973208933 -103.04014588390791 -126.76836885711684 +0.2 1 0 0.2 -38.049830803836606 -77.23682091426558 -115.28665171810218 +0.2 1 0 1.0 -24.944721195066627 -77.23682091426558 -102.18154210933221 +0.2 1 0 3.5 -21.172190036488978 -77.23682091426558 -98.40901095075455 +0.2 1 1 0.2 -32.68036359223835 -77.23682091426558 -109.91718450650393 +0.2 1 1 1.0 -23.977465271308986 -77.23682091426558 -101.21428618557457 +0.2 1 1 3.5 -20.757315114855494 -77.23682091426558 -97.99413602912108 +0.2 1 2 0.2 -25.0844528605704 -77.23682091426558 -102.32127377483599 +0.2 1 2 1.0 -20.48680089674887 -77.23682091426558 -97.72362181101445 +0.2 1 2 3.5 -18.268889397756254 -77.23682091426558 -95.50571031202183 +0.2 4 0 0.2 -36.318463378885404 -74.85257919265459 -111.17104257154 +0.2 4 0 1.0 -26.487663557388167 -74.85257919265459 -101.34024275004276 +0.2 4 0 3.5 -23.20572075648014 -74.85257919265459 -98.05829994913472 +0.2 4 1 0.2 -29.76626490664969 -74.85257919265459 -104.61884409930428 +0.2 4 1 1.0 -23.87082369633542 -74.85257919265459 -98.72340288899001 +0.2 4 1 3.5 -21.96043394850193 -74.85257919265459 -96.81301314115652 +0.2 4 2 0.2 -23.35558099923931 -74.85257919265459 -98.2081601918939 +0.2 4 2 1.0 -20.01082173285269 -74.85257919265459 -94.86340092550728 +0.2 4 2 3.5 -18.853822870231497 -74.85257919265459 -93.70640206288608 diff --git a/fixtures/validation/mixed/morphology.nex b/fixtures/validation/mixed/morphology.nex new file mode 100644 index 0000000..f4abc86 --- /dev/null +++ b/fixtures/validation/mixed/morphology.nex @@ -0,0 +1,12 @@ +#NEXUS +BEGIN DATA; +DIMENSIONS NTAX=5 NCHAR=6; +FORMAT DATATYPE=STANDARD SYMBOLS="01" MISSING=?; +MATRIX +Alpha_one 010101 +Beta_two 101010 +Gamma_three 011001 +Delta_four 100110 +Epsilon_five 110011 +; +END; diff --git a/fixtures/validation/mixed/provenance.json b/fixtures/validation/mixed/provenance.json new file mode 100644 index 0000000..4783872 --- /dev/null +++ b/fixtures/validation/mixed/provenance.json @@ -0,0 +1,9 @@ +{ + "reference": "BEAST.base 2.7.8 + MM 1.2.1", + "java": "Temurin 17.0.15", + "jar_sha256": "7e2133989c1cc0a8d78e23917db90e86236e0b4f17213c5d439bfd908c93a359", + "launcher_sha256": "7d51654fd80dd4c32f64e02b02ca90aa6387c2c9837761befe665ff730a5dc01", + "generator": "tools/beast/MixedStates.java", + "scope": "36 fixed shared-tree Mk/Mkv/Mkparsinf + JC69 states, 1/4 gamma categories, morphology/DNA rate ratios 0.2/1/3.5; no MCMC or timing", + "mm_sha256": "78f02140b79f8061cbfacfe73600d6ecc2660af00d852a125bda2c683c595a68" +} diff --git a/fixtures/validation/mixed/study.mixed.json b/fixtures/validation/mixed/study.mixed.json new file mode 100644 index 0000000..24d36a2 --- /dev/null +++ b/fixtures/validation/mixed/study.mixed.json @@ -0,0 +1,19 @@ +{ + "format": "rove-mixed", + "missing_taxa": "reject", + "sources": [ + { + "content": "#NEXUS\nBEGIN DATA;\nDIMENSIONS NTAX=5 NCHAR=6;\nFORMAT DATATYPE=STANDARD SYMBOLS=\"01\" MISSING=?;\nMATRIX\nAlpha_one 010101\nBeta_two 101010\nGamma_three 011001\nDelta_four 100110\nEpsilon_five 110011\n;\nEND;\n", + "data_type": "standard", + "name": "morphology.nex", + "sha256": "4fa36f553bc61733cddb668d92fca0bcca3b43d2d2dbab440d5c0666d232d08c" + }, + { + "content": ">Alpha_one synthetic alignment\nAACGTACGTAAC\n>Beta_two synthetic alignment\nAATGTCATACGT\n>Gamma_three synthetic alignment\nACCGTGGTAAGT\n>Delta_four synthetic alignment\nAGCGTTACTCGT\n>Epsilon_five synthetic alignment\nATCGTCGTACGT\n", + "data_type": "dna", + "name": "complete.fasta", + "sha256": "52f795b2fa66cb4fe54df6114e1a9fb217f72f2dcad1e6ef7cd3c169fafbbad3" + } + ], + "version": 1 +} 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/alignment.rs b/src/alignment.rs new file mode 100644 index 0000000..d3d0a3b --- /dev/null +++ b/src/alignment.rs @@ -0,0 +1,154 @@ +//! Aligned DNA import. FASTA identifiers are the first whitespace-delimited +//! token after `>`; underscores become spaces as in Rove's NEXUS reader. +//! Descriptions do not become taxon names. No alignment, +//! trimming, state recoding or substitution-model inference is performed. +use std::collections::HashSet; + +use crate::data::{Cell, DataType, Matrix}; +use crate::model::CharacterOrdering; +use crate::nexus::{self, Error}; + +pub fn is_fasta(input: &str) -> bool { + input + .trim_start_matches('\u{feff}') + .trim_start() + .starts_with('>') +} + +pub fn parse(input: &str) -> Result { + let input = input.trim_start_matches('\u{feff}'); + if input.trim_start().starts_with('{') { + crate::mixed::parse(input).map_err(|message| Error { + line: 1, + column: 1, + message, + }) + } else if is_fasta(input) { + fasta(input) + } else { + nexus::parse(input) + } +} + +/// IUPAC ambiguity is a set of possible states, not polymorphism or a vector +/// of normalized probabilities. N permits all four states. +pub(crate) fn dna_cell(symbol: char) -> Option { + let states: &[usize] = match symbol.to_ascii_uppercase() { + 'A' => &[0], + 'C' => &[1], + 'G' => &[2], + 'T' => &[3], + 'R' => &[0, 2], + 'Y' => &[1, 3], + 'S' => &[1, 2], + 'W' => &[0, 3], + 'K' => &[2, 3], + 'M' => &[0, 1], + 'B' => &[1, 2, 3], + 'D' => &[0, 2, 3], + 'H' => &[0, 1, 3], + 'V' => &[0, 1, 2], + 'N' => &[0, 1, 2, 3], + _ => return None, + }; + Some(if states.len() == 1 { + Cell::State(states[0]) + } else { + Cell::Uncertain(states.to_vec()) + }) +} + +fn fasta(input: &str) -> Result { + let mut taxa = Vec::new(); + let mut rows: Vec> = Vec::new(); + let mut seen = HashSet::new(); + let mut length = None; + let error = |line, column, message: String| Error { + line, + column, + message, + }; + for (index, line) in input.lines().enumerate() { + let line_number = index + 1; + let line = line.trim(); + if line.is_empty() { + continue; + } + if let Some(header) = line.strip_prefix('>') { + if rows.last().is_some_and(Vec::is_empty) { + return Err(error(line_number, 1, "FASTA sequence is empty".into())); + } + if let Some(row) = rows.last() { + let expected = *length.get_or_insert(row.len()); + if row.len() != expected { + return Err(error( + line_number, + 1, + "FASTA sequences must already be aligned to the same length".into(), + )); + } + } + let name = header.split_whitespace().next().ok_or_else(|| { + error( + line_number, + 1, + "FASTA needs a nonempty sequence identifier".into(), + ) + })?; + // Match Rove's existing NEXUS/BEAST naming convention. + let name = name.replace('_', " "); + if name.trim().is_empty() { + return Err(error( + line_number, + 1, + "FASTA identifier is empty after NEXUS name normalization".into(), + )); + } + if !seen.insert(name.to_ascii_lowercase()) { + return Err(error( + line_number, + 1, + format!("duplicate FASTA identifier {name:?}"), + )); + } + taxa.push(name.to_owned()); + rows.push(Vec::new()); + } else { + let row = rows.last_mut().ok_or_else(|| { + error( + line_number, + 1, + "FASTA sequence appears before its header".into(), + ) + })?; + for (column, symbol) in line.chars().enumerate() { + if symbol.is_ascii_whitespace() { + continue; + } + row.push(match symbol { + '?' => Cell::Missing, '-' => Cell::Gap, + _ => dna_cell(symbol).ok_or_else(|| error(line_number, column+1, format!("unsupported DNA symbol {symbol:?}; use A/C/G/T, IUPAC ambiguity, ? or -")))?, + }); + } + } + } + let nchar = rows.first().map_or(0, Vec::len); + if nchar == 0 || rows.iter().any(|r| r.len() != nchar) { + return Err(error( + input.lines().count().max(1), + 1, + "FASTA sequences must be nonempty and aligned to the same length".into(), + )); + } + Ok(Matrix { + data_type: DataType::Dna, + blocks: Vec::new(), + mixed: None, + taxa, + rows, + symbols: vec!['A', 'C', 'G', 'T'], + character_labels: vec![None; nchar], + state_labels: vec![Vec::new(); nchar], + ordering: vec![CharacterOrdering::Unordered; nchar], + }) +} diff --git a/src/bin/rove/assessment.rs b/src/bin/rove/assessment.rs new file mode 100644 index 0000000..f14713a --- /dev/null +++ b/src/bin/rove/assessment.rs @@ -0,0 +1,433 @@ +//! Evidence review and local reproducibility packages. No convergence certificate. +use std::collections::{BTreeMap, HashSet}; +use std::error::Error; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rove::summary::Burnin; +use serde_json::{Value, json}; + +use super::{compare, diagnose, events::Cancellation, sha256, summarize}; + +type Result = std::result::Result>; + +struct Output(PathBuf, bool); +impl Drop for Output { + fn drop(&mut self) { + if !self.1 { + let _ = fs::remove_dir_all(&self.0); + } + } +} + +fn write(path: &Path, value: &Value) -> Result<()> { + fs::write(path, serde_json::to_vec_pretty(value)?)?; + Ok(()) +} + +fn check(cancel: &dyn Fn() -> bool) -> Result<()> { + if cancel() { + Err("assessment/export cancelled".into()) + } else { + Ok(()) + } +} + +fn inventory(root: &Path, cancel: &dyn Fn() -> bool) -> Result> { + fn visit( + root: &Path, + relative: &Path, + depth: usize, + out: &mut BTreeMap, + cancel: &dyn Fn() -> bool, + ) -> Result<()> { + check(cancel)?; + if depth > 16 || out.len() >= 100_000 { + return Err("run archive exceeds file/depth limit".into()); + } + 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()); + } + if meta.is_file() { + out.insert(relative.to_owned(), sha256::file(&path)?); + } else if meta.is_dir() { + for child in fs::read_dir(path)? { + visit( + root, + &relative.join(child?.file_name()), + depth + 1, + out, + cancel, + )?; + } + } else { + return Err("run archive contains a non-regular file".into()); + } + Ok(()) + } + let mut files = BTreeMap::new(); + // Export only Rove-owned records and derived-result folders, not neighboring research files. + for child in fs::read_dir(root)? { + let child = child?; + let name = child.file_name(); + let text = name.to_str().ok_or("non-UTF-8 run filename")?; + if matches!( + text, + "results" + | "run.json" + | "trace.log" + | "trees.nexus" + | "setup.rove.json" + | "session.json" + | "engine.stderr.log" + | "events.jsonl" + | "dating.json" + | "comparison.json" + | "checkpoint.json" + | "diagnostics" + | "comparisons" + | "predictions" + | "summaries" + | "marginal" + ) || (text.starts_with("checkpoint-") && text.ends_with(".bin")) + || (text.starts_with("chain-") && text[6..].parse::().is_ok()) + { + visit(root, Path::new(&name), 0, &mut files, cancel)?; + } + } + Ok(files) +} + +fn section(id: &str, status: &str, message: &str) -> Value { + json!({"id":id, "status":status, "message":message}) +} + +fn assess( + root: &Path, + burnin: u8, + files: &BTreeMap, + cancel: &dyn Fn() -> bool, +) -> Result { + let engine = if root.join("results/run.json").exists() { + root.join("results") + } else { + root.to_owned() + }; + let record = summarize::record(&engine.join("run.json"))?; + let grouped = record["kind"] == "independent_chains"; + let directories = if grouped { + let n = record["chain_count"] + .as_u64() + .filter(|n| (2..=16).contains(n)) + .ok_or("invalid chain count")?; + (1..=n) + .map(|i| engine.join(format!("chain-{i:02}"))) + .collect::>() + } else { + vec![engine.clone()] + }; + let mut sections = Vec::new(); + let mut diagnostics = Vec::new(); + let mut completed = record["status"] == "completed"; + if root.join("session.json").exists() { + let session = summarize::record(&root.join("session.json"))?; + completed &= session["status"] == "completed" && session["exitCode"] == 0; + } + for directory in &directories { + match diagnose::inspect( + &directory.join("trace.log"), + Burnin::Percent(burnin), + cancel, + ) { + Ok(mut value) => { + completed &= value["source"]["completion"] == "completed"; + if let Some(columns) = value["columns"].as_array_mut() { + for column in columns { + column.as_object_mut().unwrap().remove("points"); + } + } + diagnostics.push(value); + } + Err(error) => { + check(cancel)?; + completed = false; + diagnostics.push(json!({"source":{"path":directory.join("trace.log")},"error":error.to_string()})); + } + } + } + let comparison = (|| -> Result { + let records = compare::compatible_records(&directories)?; + let first = &records[0]; + if grouped { + let children = record["chains"] + .as_array() + .ok_or("missing group chain records")?; + if children.len() != directories.len() { + return Err("group chain count mismatch".into()); + } + for (i, child) in children.iter().enumerate() { + if child["index"] != i + 1 + || child["directory"] != format!("chain-{:02}", i + 1) + || child["seed"] != records[i]["settings"]["seed"] + || records[i]["input"]["sha256"] != record["input"]["sha256"] + || records[i]["settings"]["steps"] != record["settings"]["steps"] + || records[i]["settings"]["sample_every"] != record["settings"]["sample_every"] + { + return Err("group metadata disagrees with a chain".into()); + } + } + } + let constraints: Vec> = + serde_json::from_value(first["model"]["monophyly"].clone())?; + compare::summarize( + &directories, + burnin as usize, + &constraints, + first["model"].get("dating"), + cancel, + false, + ) + })(); + let (comparison, consistent) = match comparison { + Ok(value) => (value, true), + Err(error) => { + check(cancel)?; + (json!({"error":error.to_string()}), false) + } + }; + completed &= consistent && diagnostics.iter().all(|d| d.get("error").is_none()); + sections.push(section("completion", if completed {"passed"} else {"attention"}, + if completed {"Recorded steps and sample files agree. Completion is not convergence."} else {"The run is unfinished, incomplete or inconsistent. Review the source records and errors."})); + let enough = comparison["retained_per_chain"].as_u64().unwrap_or(0) >= 1000; + let scalar_pass = completed + && enough + && comparison["statistics"].as_array().is_some_and(|columns| { + columns.iter().any(|v| v["fixed_by_model"] != true) + && columns.iter().all(|v| { + v["fixed_by_model"] == true + || (v["ess"].as_array().is_some_and(|values| { + values + .iter() + .all(|x| x.as_f64().is_some_and(|x| x >= 200.0)) + }) && v["lag_limit_reached"] + .as_array() + .is_some_and(|values| values.iter().all(|x| x == false))) + }) + }); + sections.push(section("sampling", if !consistent {"unavailable"} else if scalar_pass {"passed"} else {"attention"}, + "Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not.")); + sections.push(section("agreement", if !consistent || directories.len() == 1 {"unavailable"} else if completed && compare::thresholds_met(&comparison, 200.0, 1.01) {"passed"} else {"attention"}, + "Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence.")); + let mut summaries = Vec::new(); + let mut predictions = Vec::new(); + for relative in files.keys() { + check(cancel)?; + let name = relative.file_name().and_then(|s| s.to_str()).unwrap_or(""); + if !matches!(name, "summary.json" | "predictive.json") { + continue; + } + let value = match summarize::record(&root.join(relative)) { + Ok(v) => v, + Err(_) => continue, + }; + // Presence is not adequacy: only list reports whose recorded source hashes match this snapshot. + let matched = directories.iter().any(|directory| { + let prefix = directory.strip_prefix(root).unwrap(); + let trees = files.get(&prefix.join("trees.nexus")); + if name == "summary.json" { + value["status"] == "completed" + && trees.is_some_and(|h| value["source"]["sha256"] == *h) + } else { + value["status"] == "completed" + && value["method"] == "posterior-predictive-paired-v1" + && trees.is_some_and(|h| value["source"]["trees_sha256"] == *h) + && files + .get(&prefix.join("trace.log")) + .is_some_and(|h| value["source"]["trace_sha256"] == *h) + && files + .get(&prefix.join("run.json")) + .is_some_and(|h| value["source"]["run_sha256"] == *h) + } + }); + if matched { + if name == "summary.json" { + summaries.push(relative); + } else { + predictions.push(relative); + } + } + } + sections.push(section("trees", if summaries.is_empty() {"unavailable"} else {"review_required"}, + "Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space.")); + sections.push(section("prediction", if predictions.is_empty() {"unavailable"} else {"review_required"}, + "Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy.")); + let input = if grouped { + summarize::record(&directories[0].join("run.json")) + .ok() + .map(|v| v["input"].clone()) + .unwrap_or(Value::Null) + } else { + record["input"].clone() + }; + let input_status = input["path"] + .as_str() + .map(|p| match sha256::file(Path::new(p)) { + Ok(h) if input["sha256"] == h => "matches", + Ok(_) => "changed", + Err(_) => "unavailable", + }) + .unwrap_or("unavailable"); + Ok( + json!({"schema_version":1,"kind":"run_assessment","rove_version":env!("CARGO_PKG_VERSION"), + "created_unix_seconds":SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(), + "source":root,"chain_count":directories.len(),"burnin_percent":burnin, + "input":input,"original_matrix_status":input_status,"run_record":record, + "criteria":{"minimum_retained_per_chain":1000,"min_ess_per_chain":200,"max_rhat":1.01}, + "sections":sections,"diagnostics":diagnostics,"comparison":comparison, + "tree_reports":summaries,"predictive_reports":predictions,"convergence_certified":false, + "source_files":files.iter().map(|(p,h)|json!({"path":p,"sha256":h})).collect::>()}), + ) +} + +pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { + let mut input = None; + let mut output = None; + let mut matrix = None; + let mut burnin = 10u8; + let mut cancel_on_close = false; + let mut seen = HashSet::new(); + let mut args = arguments.iter(); + while let Some(arg) = args.next() { + if arg.starts_with("--") && !seen.insert(arg) { + return Err(format!("duplicate option {arg}").into()); + } + match arg.as_str() { + "--output" => { + output = Some(PathBuf::from( + args.next().ok_or("missing output directory")?, + )) + } + "--include-matrix" if export => { + matrix = Some(PathBuf::from(args.next().ok_or("missing matrix path")?)) + } + "--burnin-percent" => burnin = args.next().ok_or("missing burn-in")?.parse()?, + "--cancel-on-stdin-close" => cancel_on_close = true, + path if !path.starts_with('-') && input.is_none() => input = Some(PathBuf::from(path)), + _ => return Err(format!("unsupported assessment/export argument {arg}").into()), + } + } + if burnin >= 100 { + return Err("burn-in must be between 0 and 99 percent".into()); + } + let root = input.ok_or("missing run directory")?.canonicalize()?; + let output = output.ok_or("missing --output new directory")?; + let parent = output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let output = parent + .canonicalize()? + .join(output.file_name().ok_or("invalid output directory")?); + 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() { + return Err("output directory already exists".into()); + } + let cancellation = Cancellation::watch_stdin(cancel_on_close); + let cancel = || cancellation.requested(); + let before = inventory(&root, &cancel)?; + let report = assess(&root, burnin, &before, &cancel)?; + fs::create_dir(&output)?; + let mut guard = Output(output.clone(), false); + 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.*. + // 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" || n == "matrix.fasta" || n == "matrix.mixed.json" + }) && 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)?; + if sha256::file(&target)? != *hash { + return Err("source changed while exporting".into()); + } + entries.push(json!({"path":Path::new("run").join(relative),"sha256":hash,"bytes":fs::metadata(&target)?.len()})); + } + if let Some(source) = matrix.as_ref() { + let hash = sha256::file(source)?; + if report["input"]["sha256"] != hash { + return Err("included matrix does not match the run fingerprint".into()); + } + let raw = fs::read(source)?; + let name = if report["run_record"]["model"]["data_type"] == "mixed" { + "matrix.mixed.json" + } else if rove::alignment::is_fasta(std::str::from_utf8(&raw)?) { + "matrix.fasta" + } else { + "matrix.nex" + }; + drop(raw); + let target = output.join(name); + fs::copy(source, &target)?; + if sha256::file(&target)? != hash { + return Err("matrix changed while exporting".into()); + } + entries.push(json!({"path":name,"sha256":hash,"bytes":fs::metadata(target)?.len()})); + } + entries.push(json!({"path":"assessment.json","sha256":sha256::file(&output.join("assessment.json"))?,"bytes":fs::metadata(output.join("assessment.json"))?.len()})); + write( + &output.join("manifest.json"), + &json!({"schema_version":1,"kind":"rove_reproducibility_package", + "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."}), + )?; + } + if inventory(&root, &cancel)? != before { + return Err( + "run files changed during assessment/export; retry after the run finishes".into(), + ); + } + check(&cancel)?; + guard.1 = true; + Ok(()) +} diff --git a/src/bin/rove/combine.rs b/src/bin/rove/combine.rs new file mode 100644 index 0000000..8cd2ba9 --- /dev/null +++ b/src/bin/rove/combine.rs @@ -0,0 +1,44 @@ +use std::{collections::HashMap, error::Error, fs, io::Write, path::Path}; + +const USAGE: &str = "usage: rove combine --morphology --dna --output [--missing-taxa reject|missing]"; + +pub(super) fn run(arguments: &[String]) -> Result<(), Box> { + let mut options = HashMap::new(); + let mut args = arguments.iter(); + while let Some(key) = args.next() { + if !matches!( + key.as_str(), + "--morphology" | "--dna" | "--output" | "--missing-taxa" + ) { + return Err(USAGE.into()); + } + let value = args.next().ok_or(USAGE)?; + if options.insert(key.as_str(), value.as_str()).is_some() { + return Err("duplicate combine option".into()); + } + } + let morphology = Path::new(options.get("--morphology").ok_or(USAGE)?); + let dna = Path::new(options.get("--dna").ok_or(USAGE)?); + let output = Path::new(options.get("--output").ok_or(USAGE)?); + let morph_text = fs::read_to_string(morphology)?; + let dna_text = fs::read_to_string(dna)?; + let filename = |path: &Path| { + path.file_name() + .and_then(|s| s.to_str()) + .map(String::from) + .ok_or("source needs a UTF-8 filename") + }; + let text = rove::mixed::manifest( + (&filename(morphology)?, &morph_text), + (&filename(dna)?, &dna_text), + options.get("--missing-taxa").copied().unwrap_or("reject"), + )?; + // Validate completely before creating a new output; never overwrite a source. + let mut file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(output)?; + file.write_all(text.as_bytes())?; + file.sync_all()?; + Ok(()) +} diff --git a/src/bin/rove/compare.rs b/src/bin/rove/compare.rs index 234725f..b063710 100644 --- a/src/bin/rove/compare.rs +++ b/src/bin/rove/compare.rs @@ -271,10 +271,27 @@ pub(super) fn run(arguments: &[String]) -> Result<(), Box> { "compare needs 2 to 16 run directories and burn-in from 0 to 99 percent".into(), ); } + let records = compatible_records(&directories)?; + let first = &records[0]; + let constraints: Vec> = + serde_json::from_value(first["model"]["monophyly"].clone())?; + let summary = summarize( + &directories, + burnin, + &constraints, + first["model"].get("dating"), + &|| false, + true, + )?; + println!("{}", serde_json::to_string_pretty(&summary)?); + Ok(()) +} + +pub(super) fn compatible_records(directories: &[PathBuf]) -> Result, Box> { let records = directories .iter() .map(|d| -> Result> { - let mut record: Value = serde_json::from_slice(&fs::read(d.join("run.json"))?)?; + let mut record = super::summarize::record(&d.join("run.json"))?; // Records before configurable sigma priors used the reference prior. if record["model"] .get("clock_sigma_prior_parameters") @@ -294,28 +311,18 @@ pub(super) fn run(arguments: &[String]) -> Result<(), Box> { Ok(record) }) .collect::, _>>()?; - let first = &records[0]; + let first = records.first().ok_or("no chain directories")?; let mut seeds = std::collections::HashSet::new(); for record in &records { if record["input"]["sha256"] != first["input"]["sha256"] + || record["input"]["gaps"] != first["input"]["gaps"] || record["model"] != first["model"] || !seeds.insert(record["settings"]["seed"].as_u64().ok_or("missing seed")?) { return Err("comparison requires the same input and model, with distinct seeds".into()); } } - let constraints: Vec> = - serde_json::from_value(first["model"]["monophyly"].clone())?; - let summary = summarize( - &directories, - burnin, - &constraints, - first["model"].get("dating"), - &|| false, - true, - )?; - println!("{}", serde_json::to_string_pretty(&summary)?); - Ok(()) + Ok(records) } #[cfg(test)] diff --git a/src/bin/rove/inspect.rs b/src/bin/rove/inspect.rs index 71424fe..e67df6a 100644 --- a/src/bin/rove/inspect.rs +++ b/src/bin/rove/inspect.rs @@ -5,7 +5,6 @@ use std::io::Write; use rove::ascertainment::{VariableCharacters, validate_informative}; use rove::data::{Cell, GapTreatment, Matrix}; use rove::mcmc::{Conditioning, Sampler, Settings}; -use rove::nexus; use super::partitions::{self, Partitioning}; use super::{Json, is_plain_label, sha256}; @@ -50,18 +49,26 @@ fn report(data: &Matrix, bytes: &[u8], gaps: GapTreatment, partitioning: Partiti .map_or(Json::Null, |p| partitions::describe(p)); let (patterns, mut sampler_error, variable_error, informative_error) = match compressed { Ok(partitions) => { - let settings = Settings { + let mut settings = Settings { conditioning: Conditioning::None, ..Settings::default() }; + if data.data_type() == rove::data::DataType::Mixed { + settings.set_morphology_rate(rove::mcmc::RelativeRate { + value: 1.0, + log_sd: None, + }); + } let sampler_error = Sampler::new(&partitions, &settings, 1) .err() .map(|e| e.to_string()); let variable_error = partitions .iter() + .filter(|p| p.data_type() != rove::data::DataType::Dna) .find_map(|p| VariableCharacters::new(p).err().map(|e| e.to_string())); let informative_error = partitions .iter() + .filter(|p| p.data_type() != rove::data::DataType::Dna) .find_map(|p| validate_informative(p).err().map(|e| e.to_string())); ( Json::Integer(partitions.iter().map(|p| p.weights().len() as u64).sum()), @@ -119,6 +126,11 @@ fn report(data: &Matrix, bytes: &[u8], gaps: GapTreatment, partitioning: Partiti } } Json::Object(vec![ + ( + "mixed", + data.mixed_metadata() + .map_or(Json::Null, |m| Json::Value(m.json())), + ), ("schema_version", Json::Integer(1)), ("input_sha256", Json::text(sha256::hex(bytes))), ("taxon_count", Json::Integer(data.taxa().len() as u64)), @@ -127,7 +139,25 @@ fn report(data: &Matrix, bytes: &[u8], gaps: GapTreatment, partitioning: Partiti Json::Integer(data.character_count() as u64), ), ("pattern_count", patterns), - ("partitioning", Json::text(partitioning.name())), + ("data_type", Json::text(data.data_type().name())), + ( + "input_format", + Json::text(if data.data_type() == rove::data::DataType::Mixed { + "mixed" + } else if rove::alignment::is_fasta(&String::from_utf8_lossy(bytes)) { + "fasta" + } else { + "nexus" + }), + ), + ( + "partitioning", + Json::text(if data.data_type() == rove::data::DataType::Dna { + "declared" + } else { + partitioning.name() + }), + ), ("partitions", description), ("missing_count", Json::Integer(missing)), ("gap_count", Json::Integer(gap_count)), @@ -221,7 +251,7 @@ pub(super) fn run(arguments: &[String]) -> Result<(), Box> { } } let bytes = fs::read(&arguments[0])?; - let data = nexus::parse(std::str::from_utf8(&bytes)?)?; + let data = rove::alignment::parse(std::str::from_utf8(&bytes)?)?; let mut text = String::new(); report(&data, &bytes, gaps, partitioning).write(&mut text, 0); writeln!(std::io::stdout().lock(), "{text}")?; diff --git a/src/bin/rove/main.rs b/src/bin/rove/main.rs index 46e9a59..1a09554 100644 --- a/src/bin/rove/main.rs +++ b/src/bin/rove/main.rs @@ -1,5 +1,7 @@ +mod assessment; mod benchmark; mod checkpoint; +mod combine; mod compare; mod dating; mod diagnose; @@ -26,13 +28,16 @@ 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::{Backend, nexus}; +use rove::speciation::TreePrior; +use rove::{Backend, alignment}; const USAGE: &str = "usage: rove sample --output --seed --steps --sample-every [--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 ] + [--morphology-rate estimate|] [--morphology-rate-log-sd ] [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--chains <1..16>] [--burnin-percent <0..99>] @@ -45,12 +50,18 @@ const USAGE: &str = [--monophyly ]... [--gaps reject|missing] [--model strict|reference] [--conditioning variable|informative|none] [--clock-sigma-shape ] [--clock-sigma-scale ] - [--partitioning observed|declared|labels] [--dating ] + [--tree-prior birth-death|yule] [--birth-rate-upper ] + [--morphology-rate estimate|] [--morphology-rate-log-sd ] + [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--print-every ] [--cancel-on-stdin-close] [--expect-input-sha256 ] + rove combine --morphology --dna --output [--missing-taxa reject|missing] rove benchmark [--cancel-on-stdin-close] rove compare ... [--burnin-percent <0..99>] + rove assess --output [--burnin-percent <0..99>] + rove export-run --output [--burnin-percent <0..99>] + [--include-matrix ] [--cancel-on-stdin-close] rove inspect [--gaps reject|missing] [--partitioning observed|declared|labels] rove inspect-tree rove diagnose --burnin-percent <0..99> [--output ] @@ -95,8 +106,13 @@ struct Options { gaps: GapTreatment, partitioning: Partitioning, conditioning: Conditioning, + conditioning_explicit: bool, + partitioning_explicit: bool, + morphology_rate: Option, 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)>, @@ -131,9 +147,13 @@ fn parse_options(arguments: &[String]) -> Result { let mut gaps = GapTreatment::Reject; let mut partitioning = Partitioning::Observed; let mut conditioning = Conditioning::Variable; + let mut morphology_rate = None; + let mut morphology_log_sd = None; 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(); @@ -205,6 +225,14 @@ fn parse_options(arguments: &[String]) -> Result { sigma_scale = parsed; } } + "--morphology-rate" => morphology_rate = Some(value(argument)?), + "--morphology-rate-log-sd" => { + morphology_log_sd = Some( + value(argument)? + .parse::() + .map_err(|_| "morphology log-SD needs a number")?, + ) + } "--events-json" => events_json = true, "--cancel-on-stdin-close" => cancel_on_stdin_close = true, "--expect-input-sha256" => { @@ -282,6 +310,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 @@ -322,6 +362,37 @@ 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 morphology_rate = match morphology_rate.as_deref() { + None if morphology_log_sd.is_some() => { + return Err("--morphology-rate-log-sd requires --morphology-rate estimate".into()); + } + None => None, + Some("estimate") => Some(rove::mcmc::RelativeRate { + value: 1.0, + log_sd: Some(morphology_log_sd.unwrap_or(1.0)), + }), + Some(value) if morphology_log_sd.is_none() => Some(rove::mcmc::RelativeRate { + value: value + .parse() + .map_err(|_| "--morphology-rate needs estimate or a positive number")?, + log_sd: None, + }), + _ => return Err("--morphology-rate-log-sd requires --morphology-rate estimate".into()), + }; + if let Some(rate) = morphology_rate { + rate.validate().map_err(|e| e.to_string())?; + } let options = Options { command, powers: match command { @@ -352,8 +423,13 @@ fn parse_options(arguments: &[String]) -> Result { gaps, partitioning, conditioning, + conditioning_explicit: seen.contains("--conditioning"), + partitioning_explicit: seen.contains("--partitioning"), reference_model, + morphology_rate, clock_sigma_prior, + tree_prior, + birth_rate_upper, sample_from_prior, tuning, tuning_values, @@ -590,7 +666,27 @@ fn configure(options: &mut Options) -> Result> { return Err("the matrix fingerprint changed; inspect and review the input again".into()); } options.expected_input = Some(input.clone()); - let data = nexus::parse(std::str::from_utf8(&bytes)?)?; + let data = alignment::parse(std::str::from_utf8(&bytes)?)?; + if data.data_type() == rove::data::DataType::Dna { + if options.conditioning_explicit && options.conditioning != Conditioning::None { + return Err( + "DNA JC69 uses all aligned sites; Mkv/Mkparsinf conditioning is not supported" + .into(), + ); + } + if options.partitioning_explicit + && !matches!(options.partitioning, partitions::Partitioning::Declared) + { + return Err( + "DNA JC69 fixes all four A/C/G/T states; use --partitioning declared".into(), + ); + } + options.conditioning = Conditioning::None; + options.partitioning = partitions::Partitioning::Declared; + } + if (data.data_type() == rove::data::DataType::Mixed) != options.morphology_rate.is_some() { + return Err("mixed morphology/DNA requires --morphology-rate estimate or an explicit positive fixed value; this option does not apply to homogeneous inputs".into()); + } let patterns = options.partitioning.compress(&data, options.gaps)?; let taxa = data.taxa(); if let Some(name) = taxa.iter().find(|name| !is_plain_label(name)) { @@ -607,7 +703,8 @@ fn configure(options: &mut Options) -> Result> { let wanted = name.replace('_', " "); let tip = taxa .iter() - .position(|taxon| *taxon == wanted) + .position(|taxon| taxon == name) + .or_else(|| taxa.iter().position(|taxon| *taxon == wanted)) .ok_or_else(|| format!("--monophyly names unknown taxon {name:?}"))?; tips.push(tip); } @@ -630,6 +727,14 @@ 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); + } + if let Some(rate) = options.morphology_rate { + settings.set_morphology_rate(rate); + } for &(kind, weight) in &options.weights { if let Some(entry) = settings.weights.iter_mut().find(|(k, _)| *k == kind) { entry.1 = weight; @@ -651,7 +756,7 @@ fn input_json( data: &rove::data::Matrix, patterns: &[rove::data::Patterns], ) -> Json { - Json::Object(vec![ + let mut fields = vec![ ("path", Json::text(options.matrix.display().to_string())), ("sha256", Json::text(input)), ("taxa", Json::Integer(data.taxa().len() as u64)), @@ -667,7 +772,11 @@ fn input_json( GapTreatment::Missing => "missing", }), ), - ]) + ]; + if let Some(mixed) = data.mixed_metadata() { + fields.push(("mixed", Json::Value(mixed.json()))); + } + Json::Object(fields) } fn model_json( @@ -676,33 +785,43 @@ fn model_json( patterns: &[rove::data::Patterns], taxa: &[String], ) -> Json { + let dna = patterns + .iter() + .all(|p| p.data_type() == rove::data::DataType::Dna); let conditioning = match settings.conditioning { Conditioning::Variable => "variable characters (Mkv)", Conditioning::Informative => "parsimony-informative characters (Mkparsinf)", + Conditioning::None if dna => "none (JC69)", 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)), ( "substitution", - Json::text( - if patterns - .iter() - .any(|p| p.ordering() == rove::model::CharacterOrdering::Ordered) - { - if options.reference_model { - "Ordered/unordered models per partition, equal frequencies, four shared midpoint gamma categories normalized to mean one" - } else { - "Ordered/unordered models per partition, equal frequencies, one rate category" - } - } else if options.reference_model { - "Mk per partition, equal frequencies, four shared midpoint gamma categories normalized to mean one" + Json::text(if settings.morphology_rate.is_some() { + "Morphology Mk/ordered per partition and DNA JC69, shared topology/clock/gamma shape, DNA relative rate one" + } else if dna { + if options.reference_model { + "JC69 DNA, fixed A/C/G/T frequencies 1/4, four shared midpoint gamma categories normalized to mean one" } else { - "Mk per partition, equal frequencies, one rate category" - }, - ), + "JC69 DNA, fixed A/C/G/T frequencies 1/4, one rate category" + } + } else if patterns + .iter() + .any(|p| p.ordering() == rove::model::CharacterOrdering::Ordered) + { + if options.reference_model { + "Ordered/unordered models per partition, equal frequencies, four shared midpoint gamma categories normalized to mean one" + } else { + "Ordered/unordered models per partition, equal frequencies, one rate category" + } + } else if options.reference_model { + "Mk per partition, equal frequencies, four shared midpoint gamma categories normalized to mean one" + } else { + "Mk per partition, equal frequencies, one rate category" + }), ), ( "preset", @@ -816,6 +935,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" }, @@ -823,7 +944,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)) @@ -831,7 +952,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)") @@ -842,7 +963,44 @@ fn model_json( "monophyly", Json::List(settings.monophyly.iter().map(|c| names(c)).collect()), ), - ]) + ]; + if let Some(rate) = settings.morphology_rate { + fields.extend([ + ("data_type", Json::text("mixed")), + ("substitution_model", Json::text("mk+jc69")), + ("mixed_model", Json::Value(serde_json::json!({ + "topology":"shared", "branch_clock":"shared", "gamma_shape":"shared", + "dna_rate":1.0, "morphology_rate":rate.value, + "morphology_rate_prior":rate.log_sd.map(|s| serde_json::json!({"distribution":"lognormal","log_mean":0.0,"log_sd":s})), + "morphology_conditioning": match settings.conditioning {Conditioning::None=>"none",Conditioning::Variable=>"variable",Conditioning::Informative=>"informative"}, + "dna_conditioning":"none" + }))), + ]); + } else if dna { + fields.extend([ + ("data_type", Json::text("dna")), + ("substitution_model", Json::text("jc69")), + ]); + } + 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 { @@ -1137,11 +1295,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", @@ -1241,7 +1415,12 @@ fn run_chain( fn main() { let arguments: Vec = std::env::args().skip(1).collect(); - let result = if arguments.first().is_some_and(|a| a == "benchmark") { + let result = if arguments + .first() + .is_some_and(|a| a == "assess" || a == "export-run") + { + assessment::run(&arguments[1..], arguments[0] == "export-run").map(|_| true) + } else if arguments.first().is_some_and(|a| a == "benchmark") { benchmark::run(&arguments[1..]) } else if arguments.first().is_some_and(|a| a == "predict") { predict::run(&arguments[1..]).map(|_| true) @@ -1253,6 +1432,8 @@ fn main() { inspect_tree::run(&arguments[1..]).map(|_| true) } else if arguments.first().is_some_and(|a| a == "summarize") { summarize::run(&arguments[1..]).map(|_| true) + } else if arguments.first().is_some_and(|a| a == "combine") { + combine::run(&arguments[1..]).map(|_| true) } else if arguments.first().is_some_and(|a| a == "inspect") { inspect::run(&arguments[1..]).map(|_| true) } else { diff --git a/src/bin/rove/partitions.rs b/src/bin/rove/partitions.rs index 61966a2..12de61d 100644 --- a/src/bin/rove/partitions.rs +++ b/src/bin/rove/partitions.rs @@ -47,7 +47,7 @@ pub(super) fn describe(partitions: &[Patterns]) -> Json { partitions .iter() .map(|p| { - Json::Object(vec![ + let mut fields = vec![ ("ordering", Json::text(p.ordering().name())), ("states", Json::Integer(p.symbols().len() as u64)), ("characters", Json::Integer(p.sites().len() as u64)), @@ -70,7 +70,11 @@ pub(super) fn describe(partitions: &[Patterns]) -> Json { .collect(), ), ), - ]) + ]; + if p.data_type() == rove::data::DataType::Dna { + fields.push(("data_type", Json::text("dna"))); + } + Json::Object(fields) }) .collect(), ) diff --git a/src/bin/rove/predict.rs b/src/bin/rove/predict.rs index 2ff5187..740ca3b 100644 --- a/src/bin/rove/predict.rs +++ b/src/bin/rove/predict.rs @@ -235,7 +235,13 @@ pub(super) fn run(args: &[String]) -> Result<()> { if record["input"]["sha256"] != sha256::hex(&input) { return Err("matrix fingerprint differs from the fitted input".into()); } - let data = rove::nexus::parse(std::str::from_utf8(&input)?)?; + let data = rove::alignment::parse(std::str::from_utf8(&input)?)?; + let recorded_type = record["model"]["data_type"].as_str().unwrap_or("standard"); + if recorded_type != data.data_type().name() + || (recorded_type == "dna" && record["model"]["substitution_model"] != "jc69") + { + return Err("recorded data type or substitution model differs from the input".into()); + } let gaps = match record["input"]["gaps"].as_str() { Some("reject") => GapTreatment::Reject, Some("missing") => GapTreatment::Missing, @@ -253,7 +259,7 @@ pub(super) fn run(args: &[String]) -> Result<()> { return Err("fitted partitions disagree with the input".into()); } let conditioning = match record["model"]["conditioning"].as_str() { - Some("none (Mk)") => Conditioning::None, + Some("none (Mk)" | "none (JC69)") => Conditioning::None, Some("variable characters (Mkv)") => Conditioning::Variable, Some("parsimony-informative characters (Mkparsinf)") => Conditioning::Informative, _ => return Err("unknown ascertainment conditioning".into()), @@ -292,10 +298,82 @@ 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()); } - let design = Design::new(&data, &partitions, gaps, conditioning)?; + let mixed_rate = if recorded_type == "mixed" { + if record["model"]["substitution_model"] != "mk+jc69" + || record["input"]["mixed"] + != data + .mixed_metadata() + .ok_or("missing mixed provenance")? + .json() + { + return Err("mixed model or source provenance mismatch".into()); + } + let m = &record["model"]["mixed_model"]; + if m["topology"] != "shared" + || m["branch_clock"] != "shared" + || m["gamma_shape"] != "shared" + || m["dna_rate"] != 1.0 + || m["dna_conditioning"] != "none" + { + return Err("unsupported mixed linkage or DNA conditioning".into()); + } + let expected = match conditioning { + Conditioning::None => "none", + Conditioning::Variable => "variable", + Conditioning::Informative => "informative", + }; + if m["morphology_conditioning"] != expected { + return Err("mixed conditioning mismatch".into()); + } + let prior = &m["morphology_rate_prior"]; + let log_sd = if prior.is_null() { + None + } else { + if prior["distribution"] != "lognormal" || prior["log_mean"] != 0.0 { + return Err("unsupported morphology rate prior".into()); + } + Some( + prior["log_sd"] + .as_f64() + .ok_or("missing morphology rate log-SD")?, + ) + }; + let rate = rove::mcmc::RelativeRate { + value: m["morphology_rate"] + .as_f64() + .ok_or("missing morphology rate")?, + log_sd, + }; + rate.validate()?; + Some(rate) + } else { + None + }; + let mut design = Design::new(&data, &partitions, gaps, conditioning)?; if data.character_count().saturating_mul(replicates) > 2_000_000 || data .character_count() @@ -313,7 +391,14 @@ pub(super) fn run(args: &[String]) -> Result<()> { fs::create_dir(output.join("source"))?; fs::create_dir(output.join("matrices"))?; fs::write(output.join("source/run.json"), &record_bytes)?; - fs::write(output.join("source/matrix.nex"), &input)?; + let matrix_copy = if recorded_type == "mixed" { + "matrix.mixed.json" + } else if rove::alignment::is_fasta(std::str::from_utf8(&input)?) { + "matrix.fasta" + } else { + "matrix.nex" + }; + fs::write(output.join("source").join(matrix_copy), &input)?; let trace_hash = copy( &source.join("trace.log"), &output.join("source/trace.log"), @@ -387,6 +472,20 @@ pub(super) fn run(args: &[String]) -> Result<()> { Settings::default() } }; + if let Some(mut rate) = mixed_rate { + let value = column(&trace, "morphology_rate", row)?; + if rate.log_sd.is_none() && value != rate.value { + return Err("fixed morphology rate disagrees with trace".into()); + } + rate.value = value; + settings.set_morphology_rate(rate); + design.set_morphology_rate(value)?; + } + 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 { @@ -472,14 +571,19 @@ pub(super) fn run(args: &[String]) -> Result<()> { b.surprise )?; } - let filename = format!("matrices/replicate-{replica:05}.nex"); + let extension = if recorded_type == "mixed" { + "mixed.json" + } else { + "nex" + }; + let filename = format!("matrices/replicate-{replica:05}.{extension}"); let text = to_nexus(&simulated); fs::write(output.join(&filename), &text)?; writeln!( details, "{}", json!({"replicate":replica,"source_sample_index":row,"state":trace.states[row],"seed":simulation_seed, - "matrix":filename,"matrix_sha256":sha256::hex(text.as_bytes()),"gamma_shape":rates.gamma.as_ref().map(|g|g.shape()), + "morphology_rate":check.morphology_rate(),"matrix":filename,"matrix_sha256":sha256::hex(text.as_bytes()),"gamma_shape":rates.gamma.as_ref().map(|g|g.shape()), "observed":stats(&observed),"simulated":stats(&comparison),"reconstructed_likelihood_difference":delta}) )?; done += 1; diff --git a/src/bin/rove/sha256.rs b/src/bin/rove/sha256.rs index 4a2a5a8..1fbffad 100644 --- a/src/bin/rove/sha256.rs +++ b/src/bin/rove/sha256.rs @@ -1,150 +1 @@ -//! SHA-256 (FIPS 180-4), to identify inputs and the executable in run metadata. - -const K: [u32; 64] = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, -]; - -#[derive(Clone)] -pub struct Digest { - state: [u32; 8], - pending: Vec, - bytes: u64, -} -impl Digest { - pub fn new() -> Self { - Self { - state: [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, - 0x5be0cd19, - ], - pending: Vec::with_capacity(64), - bytes: 0, - } - } - pub fn update(&mut self, mut data: &[u8]) { - self.bytes += data.len() as u64; - if !self.pending.is_empty() { - let take = (64 - self.pending.len()).min(data.len()); - self.pending.extend_from_slice(&data[..take]); - data = &data[take..]; - if self.pending.len() == 64 { - let block: [u8; 64] = self.pending.as_slice().try_into().unwrap(); - self.compress(&block); - self.pending.clear(); - } - } - while data.len() >= 64 { - self.compress(&data[..64]); - data = &data[64..]; - } - self.pending.extend_from_slice(data); - } - pub fn finish(mut self) -> String { - let bits = self.bytes * 8; - let mut padding = vec![0x80]; - while (self.pending.len() + padding.len()) % 64 != 56 { - padding.push(0); - } - padding.extend_from_slice(&bits.to_be_bytes()); - self.update(&padding); - self.state - .iter() - .map(|word| format!("{word:08x}")) - .collect() - } - fn compress(&mut self, block: &[u8]) { - let mut w = [0u32; 64]; - for (word, bytes) in w.iter_mut().zip(block.chunks_exact(4)) { - *word = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); - } - for i in 16..64 { - let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); - let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] - .wrapping_add(s0) - .wrapping_add(w[i - 7]) - .wrapping_add(s1); - } - let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state; - for (k, word) in K.iter().zip(w) { - let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); - let choice = (e & f) ^ (!e & g); - let t1 = h - .wrapping_add(s1) - .wrapping_add(choice) - .wrapping_add(*k) - .wrapping_add(word); - let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); - let majority = (a & b) ^ (a & c) ^ (b & c); - let t2 = s0.wrapping_add(majority); - (h, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2)); - } - for (value, add) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) { - *value = value.wrapping_add(add); - } - } -} -pub fn hex(data: &[u8]) -> String { - let mut digest = Digest::new(); - digest.update(data); - digest.finish() -} - -pub fn file(path: &std::path::Path) -> std::io::Result { - use std::io::Read; - let mut input = std::fs::File::open(path)?; - let mut digest = Digest::new(); - let mut bytes = [0; 65536]; - loop { - let count = input.read(&mut bytes)?; - if count == 0 { - break; - } - digest.update(&bytes[..count]); - } - Ok(digest.finish()) -} - -#[cfg(test)] -mod tests { - use super::{Digest, hex}; - - #[test] - fn streaming_chunks_match_one_shot() { - let data = vec![37; 131_073]; - for size in [1, 7, 63, 64, 65, 65536] { - let mut digest = Digest::new(); - for chunk in data.chunks(size) { - digest.update(chunk); - } - assert_eq!(digest.finish(), hex(&data)); - } - } - - #[test] - fn matches_the_standard_test_vectors() { - assert_eq!( - hex(b""), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - assert_eq!( - hex(b"abc"), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - assert_eq!( - hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" - ); - assert_eq!( - hex(&[b'a'; 1000]), - "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" - ); - } -} +pub use rove::fingerprint::*; diff --git a/src/data.rs b/src/data.rs index e740d5d..a8e47ad 100644 --- a/src/data.rs +++ b/src/data.rs @@ -1,10 +1,27 @@ -//! Morphological observations and lossless compression within model partitions. +//! Morphological and nucleotide observations, compressed within model partitions. use crate::model::CharacterOrdering; use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::ops::Range; +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum DataType { + Standard, + Dna, + Mixed, +} + +impl DataType { + pub fn name(self) -> &'static str { + match self { + Self::Standard => "standard", + Self::Dna => "dna", + Self::Mixed => "mixed", + } + } +} + /// State indices refer to the matrix's declared alphabet, including unobserved states. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Cell { @@ -17,6 +34,9 @@ pub enum Cell { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Matrix { + pub(crate) data_type: DataType, + pub(crate) blocks: Vec, + pub(crate) mixed: Option, pub(crate) taxa: Vec, pub(crate) symbols: Vec, pub(crate) rows: Vec>, @@ -41,11 +61,42 @@ pub enum CompressionError { Gap { taxon: String, site: usize }, Polymorphism { taxon: String, site: usize }, OrderedAlphabet { site: usize }, + DnaModel, +} + +impl CompressionError { + fn offset(self, offset: usize) -> Self { + match self { + Self::StateCount { site } => Self::StateCount { + site: site + offset, + }, + Self::StateLabels { site } => Self::StateLabels { + site: site + offset, + }, + Self::ExcludedState { site, symbol } => Self::ExcludedState { + site: site + offset, + symbol, + }, + Self::Gap { site, taxon } => Self::Gap { + site: site + offset, + taxon, + }, + Self::Polymorphism { site, taxon } => Self::Polymorphism { + site: site + offset, + taxon, + }, + Self::OrderedAlphabet { site } => Self::OrderedAlphabet { + site: site + offset, + }, + other => other, + } + } } impl fmt::Display for CompressionError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::DnaModel => f.write_str("DNA requires the complete A/C/G/T alphabet and unordered JC69; morphology's state recoding and ordering do not apply"), Self::StateLabels { site } => write!( f, "character {} needs at least two state labels for labeled-alphabet partitioning; declare every possible state in SYMBOLS order or choose another explicit alphabet", @@ -89,6 +140,7 @@ impl std::error::Error for CompressionError {} /// Observed patterns from one partition, numbered by first occurrence. #[derive(Clone, Debug, PartialEq)] pub struct Patterns { + data_type: DataType, ordering: CharacterOrdering, sites: Vec, symbols: Vec, @@ -106,6 +158,79 @@ pub struct CharacterSet { } impl Matrix { + pub fn data_type(&self) -> DataType { + self.data_type + } + + pub fn mixed_metadata(&self) -> Option<&crate::mixed::Metadata> { + self.mixed.as_ref() + } + + /// Source-local alphabets and cell indices, reconstructed from current cells. + pub fn component_matrices(&self) -> Vec { + self.blocks + .iter() + .map(|block| { + let map: Vec<_> = self + .symbols + .iter() + .map(|s| block.symbols.iter().position(|x| x == s)) + .collect(); + let recode = |c: &Cell| match c { + Cell::State(s) => Cell::State(map[*s].expect("block alphabet")), + Cell::Uncertain(v) => Cell::Uncertain( + v.iter().map(|s| map[*s].expect("block alphabet")).collect(), + ), + Cell::Polymorphic(v) => Cell::Polymorphic( + v.iter().map(|s| map[*s].expect("block alphabet")).collect(), + ), + other => other.clone(), + }; + let range = block.start..block.start + block.characters; + Matrix { + data_type: block.data_type, + blocks: Vec::new(), + mixed: None, + taxa: self.taxa.clone(), + symbols: block.symbols.clone(), + rows: self + .rows + .iter() + .map(|r| r[range.clone()].iter().map(recode).collect()) + .collect(), + character_labels: self.character_labels[range.clone()].to_vec(), + state_labels: self.state_labels[range.clone()].to_vec(), + ordering: self.ordering[range].to_vec(), + } + }) + .collect() + } + + fn compress_components( + &self, + gaps: GapTreatment, + mode: u8, + ) -> Result, CompressionError> { + let mut output = Vec::new(); + for (block, component) in self.blocks.iter().zip(self.component_matrices()) { + let parts = if component.data_type == DataType::Dna || mode == 0 { + component.compress( + std::slice::from_ref(&(0..component.character_count())), + gaps, + ) + } else if mode == 1 { + component.partition_by_states(gaps) + } else { + component.partition_by_labels(gaps) + }; + for mut part in parts.map_err(|e| e.offset(block.start))? { + part.sites.iter_mut().for_each(|s| *s += block.start); + output.push(part); + } + } + Ok(output) + } + pub fn taxa(&self) -> &[String] { &self.taxa } @@ -152,6 +277,12 @@ impl Matrix { partitions: &[Range], gaps: GapTreatment, ) -> Result, CompressionError> { + if self.data_type == DataType::Mixed { + if partitions.len() != 1 || partitions[0] != (0..self.character_count()) { + return Err(CompressionError::InvalidPartitions); + } + return self.compress_components(gaps, 0); + } let mut end = 0; for sites in partitions { if sites.start != end || sites.is_empty() || sites.end > self.character_count() { @@ -184,6 +315,12 @@ impl Matrix { &self, gaps: GapTreatment, ) -> Result, CompressionError> { + if self.data_type == DataType::Mixed { + return self.compress_components(gaps, 1); + } + if self.data_type == DataType::Dna { + return self.compress(std::slice::from_ref(&(0..self.character_count())), gaps); + } // Mk needs at least two states, so a binary declared alphabet leaves // no state-count ambiguity even when a character is constant or missing. if self.symbols.len() == 2 { @@ -232,6 +369,12 @@ impl Matrix { &self, gaps: GapTreatment, ) -> Result, CompressionError> { + if self.data_type == DataType::Mixed { + return self.compress_components(gaps, 2); + } + if self.data_type == DataType::Dna { + return Err(CompressionError::DnaModel); + } let mut groups = BTreeMap::>::new(); for (site, labels) in self.state_labels.iter().enumerate() { if labels.len() < 2 || labels.len() > self.symbols.len() { @@ -256,10 +399,54 @@ impl Matrix { partitions: &[CharacterSet], gaps: GapTreatment, ) -> Result, CompressionError> { + if self.data_type == DataType::Mixed { + if partitions + .iter() + .any(|p| p.sites.is_empty() || p.sites.windows(2).any(|s| s[0] >= s[1])) + { + return Err(CompressionError::InvalidPartitions); + } + if partitions + .iter() + .flat_map(|p| &p.sites) + .any(|s| *s >= self.character_count()) + { + return Err(CompressionError::InvalidPartitions); + } + let mut output = Vec::new(); + for (block, component) in self.blocks.iter().zip(self.component_matrices()) { + let sets: Vec<_> = partitions + .iter() + .filter_map(|p| { + let sites: Vec<_> = p + .sites + .iter() + .filter(|s| **s >= block.start && **s < block.start + block.characters) + .map(|s| s - block.start) + .collect(); + (!sites.is_empty()).then(|| CharacterSet { + sites, + symbols: p.symbols.clone(), + }) + }) + .collect(); + for mut p in component + .compress_sets(&sets, gaps) + .map_err(|e| e.offset(block.start))? + { + p.sites.iter_mut().for_each(|s| *s += block.start); + output.push(p); + } + } + return Ok(output); + } self.validate_observations(gaps)?; let mut covered = vec![false; self.character_count()]; let mut mapped = Vec::new(); for partition in partitions { + if self.data_type == DataType::Dna && partition.symbols != ['A', 'C', 'G', 'T'] { + return Err(CompressionError::DnaModel); + } let states = partition .symbols .iter() @@ -317,6 +504,9 @@ impl Matrix { } fn validate_observations(&self, gaps: GapTreatment) -> Result<(), CompressionError> { + if self.data_type == DataType::Dna && self.ordering.contains(&CharacterOrdering::Ordered) { + return Err(CompressionError::DnaModel); + } // Validate before allocating partials so unsupported observations cannot // produce a partially usable likelihood input. for (taxon, row) in self.taxa.iter().zip(&self.rows) { @@ -408,6 +598,7 @@ impl Matrix { }) .collect(); Patterns { + data_type: self.data_type, ordering: self.ordering[sites[0].0], sites: sites.iter().map(|(site, _)| *site).collect(), symbols: sites[0].1.iter().map(|&s| self.symbols[s]).collect(), @@ -423,6 +614,10 @@ impl Matrix { } impl Patterns { + pub fn data_type(&self) -> DataType { + self.data_type + } + pub fn ordering(&self) -> CharacterOrdering { self.ordering } diff --git a/src/fingerprint.rs b/src/fingerprint.rs new file mode 100644 index 0000000..0f9edfc --- /dev/null +++ b/src/fingerprint.rs @@ -0,0 +1,156 @@ +//! SHA-256 (FIPS 180-4), to identify inputs and the executable in run metadata. + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +#[derive(Clone)] +pub struct Digest { + state: [u32; 8], + pending: Vec, + bytes: u64, +} +impl Default for Digest { + fn default() -> Self { + Self::new() + } +} + +impl Digest { + pub fn new() -> Self { + Self { + state: [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, + 0x5be0cd19, + ], + pending: Vec::with_capacity(64), + bytes: 0, + } + } + pub fn update(&mut self, mut data: &[u8]) { + self.bytes += data.len() as u64; + if !self.pending.is_empty() { + let take = (64 - self.pending.len()).min(data.len()); + self.pending.extend_from_slice(&data[..take]); + data = &data[take..]; + if self.pending.len() == 64 { + let block: [u8; 64] = self.pending.as_slice().try_into().unwrap(); + self.compress(&block); + self.pending.clear(); + } + } + while data.len() >= 64 { + self.compress(&data[..64]); + data = &data[64..]; + } + self.pending.extend_from_slice(data); + } + pub fn finish(mut self) -> String { + let bits = self.bytes * 8; + let mut padding = vec![0x80]; + while (self.pending.len() + padding.len()) % 64 != 56 { + padding.push(0); + } + padding.extend_from_slice(&bits.to_be_bytes()); + self.update(&padding); + self.state + .iter() + .map(|word| format!("{word:08x}")) + .collect() + } + fn compress(&mut self, block: &[u8]) { + let mut w = [0u32; 64]; + for (word, bytes) in w.iter_mut().zip(block.chunks_exact(4)) { + *word = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state; + for (k, word) in K.iter().zip(w) { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choice = (e & f) ^ (!e & g); + let t1 = h + .wrapping_add(s1) + .wrapping_add(choice) + .wrapping_add(*k) + .wrapping_add(word); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(majority); + (h, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2)); + } + for (value, add) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *value = value.wrapping_add(add); + } + } +} +pub fn hex(data: &[u8]) -> String { + let mut digest = Digest::new(); + digest.update(data); + digest.finish() +} + +pub fn file(path: &std::path::Path) -> std::io::Result { + use std::io::Read; + let mut input = std::fs::File::open(path)?; + let mut digest = Digest::new(); + let mut bytes = [0; 65536]; + loop { + let count = input.read(&mut bytes)?; + if count == 0 { + break; + } + digest.update(&bytes[..count]); + } + Ok(digest.finish()) +} + +#[cfg(test)] +mod tests { + use super::{Digest, hex}; + + #[test] + fn streaming_chunks_match_one_shot() { + let data = vec![37; 131_073]; + for size in [1, 7, 63, 64, 65, 65536] { + let mut digest = Digest::new(); + for chunk in data.chunks(size) { + digest.update(chunk); + } + assert_eq!(digest.finish(), hex(&data)); + } + } + + #[test] + fn matches_the_standard_test_vectors() { + assert_eq!( + hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + assert_eq!( + hex(&[b'a'; 1000]), + "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index c80385f..eae5e0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,12 +1,15 @@ +pub mod alignment; pub mod ascertainment; mod checkpoint; pub mod data; pub mod dating; pub mod diagnostics; +pub mod fingerprint; mod kernel; mod layout; pub mod marginal; pub mod mcmc; +pub mod mixed; pub mod model; pub mod nexus; pub mod predictive; diff --git a/src/mcmc/checkpoint.rs b/src/mcmc/checkpoint.rs index 6584c7b..342cd91 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"ROVECP09"; impl Sampler { /// Saves a between-proposals state, including the live likelihood buffers. @@ -59,9 +59,14 @@ impl Sampler { write_f64(&mut out, v)?; } } + if let Some(rate) = self.morphology_rate { + write_f64(&mut out, rate)?; + } + 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, @@ -185,8 +190,20 @@ impl Sampler { None }; let mut initial = settings.clone(); + if let Some(rate) = &mut initial.morphology_rate { + let value = read_f64(&mut input)?; + if rate.log_sd.is_none() && value != rate.value { + return Err(invalid()); + } + rate.value = value; + } 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, @@ -240,6 +257,7 @@ impl Sampler { if input.position() != bytes.len() as u64 { return Err(invalid()); } + sampler.morphology_rate_model = settings.morphology_rate; sampler.steps = steps; sampler.tunable_proposals = tunable_proposals; Ok(sampler) @@ -249,6 +267,10 @@ impl Sampler { fn write_partitions(out: &mut impl Write, patterns: &[Patterns]) -> io::Result<()> { write_u64(out, patterns.len() as u64)?; for partition in patterns { + write_u64( + out, + u64::from(partition.data_type() == crate::data::DataType::Dna), + )?; write_u64( out, u64::from(partition.ordering() == crate::model::CharacterOrdering::Ordered), @@ -303,6 +325,7 @@ mod tests { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 10.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); } let mut chain = Sampler::new(&patterns, &settings, 42).unwrap(); diff --git a/src/mcmc/coupled.rs b/src/mcmc/coupled.rs index 08c53e4..f04bf70 100644 --- a/src/mcmc/coupled.rs +++ b/src/mcmc/coupled.rs @@ -4,6 +4,58 @@ use crate::rates::RelaxedClock; use crate::tree::Tree; +/// Exchange a child of `parent` with its uncle, preserving each reattached +/// subtree's incoming rate × duration. Heights and the root stay fixed. +/// The involution scales two rates by old/new durations; its Jacobian is +/// their product. The caller adds the forward/reverse node-selection ratio. +pub(super) fn exchange_rates( + tree: &mut Tree, + clock: &mut RelaxedClock, + parent: usize, + child: usize, + uncle: usize, +) -> Option { + let grandparent = tree.parent(parent)?; + if tree.parent(child) != Some(parent) + || tree.parent(uncle) != Some(grandparent) + || uncle == parent + || tree.height(uncle) >= tree.height(parent) + || tree.height(child) >= tree.height(parent) + { + return None; + } + let branches = [child, uncle]; + let durations = [ + tree.height(grandparent) - tree.height(child), + tree.height(parent) - tree.height(uncle), + ]; + let mut proposed = [0.0; 2]; + let mut jacobian = 0.0; + for i in 0..2 { + let old = tree.branch_length(branches[i]); + if old <= 0.0 || durations[i] <= 0.0 { + return None; + } + let log_ratio = old.ln() - durations[i].ln(); + proposed[i] = (clock.branch_rate(branches[i], tree.root()).ln() + log_ratio).exp(); + if !proposed[i].is_finite() || proposed[i] <= 0.0 { + return None; + } + jacobian += log_ratio; + } + tree.replace_child(parent, child, uncle); + tree.replace_child(grandparent, uncle, child); + for i in 0..2 { + let index = if branches[i] == tree.nodes() - 1 { + tree.root() + } else { + branches[i] + }; + clock.set_rate(index, proposed[i]); + } + Some(jacobian) +} + /// Change one internal height, preserving rate × duration on incident branches. /// For a symmetric height draw, the Hastings factor is the product of old/new /// branch durations. The root has two incident branches; other nodes have three. @@ -209,6 +261,175 @@ mod tests { determinant(matrix) } + #[test] + fn exchange_is_an_involution_with_correct_rate_slots_and_jacobian() { + for root_last in [false, true] { + let (original, parent, child, uncle) = if root_last { + ( + Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((3, 4)), + Some((0, 1)), + Some((6, 2)), + Some((7, 5)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.6, 1.0, 1.5], + ) + .unwrap(), + 7, + 6, + 5, + ) + } else { + ( + Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((6, 8)), + Some((7, 2)), + Some((0, 1)), + Some((3, 4)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.5, 1.0, 0.6, 0.2], + ) + .unwrap(), + 6, + 7, + 8, + ) + }; + let original_clock = + RelaxedClock::new(0.7, vec![0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]).unwrap(); + let mut tree = original.clone(); + let mut clock = original_clock.clone(); + let h = exchange_rates(&mut tree, &mut clock, parent, child, uncle).unwrap(); + tree.validate().unwrap(); + assert_eq!(tree.root(), original.root()); + for node in 0..tree.nodes() { + near( + tree.branch_length(node) * clock.branch_rate(node, tree.root()), + original.branch_length(node) + * original_clock.branch_rate(node, original.root()), + 1e-13, + ); + } + // Continuous coordinates include all internal heights and all + // rates. Height derivatives enter off-diagonal blocks only. + let mut x = (tree.tips()..tree.nodes()) + .map(|i| original.height(i)) + .collect::>(); + x.extend(original_clock.rates()); + let numerical = numerical_jacobian(&x, |values| { + let mut t = original.clone(); + for i in t.tips()..t.nodes() { + t.set_height(i, values[i - t.tips()]); + } + let mut c = RelaxedClock::new(0.7, values[4..].to_vec()).unwrap(); + exchange_rates(&mut t, &mut c, parent, child, uncle).unwrap(); + let mut y = values[..4].to_vec(); + y.extend(c.rates()); + y + }); + near(h.exp(), numerical, 1e-7); + near( + h + exchange_rates(&mut tree, &mut clock, parent, uncle, child).unwrap(), + 0.0, + 1e-13, + ); + assert_eq!(tree, original); + for (a, b) in clock.rates().iter().zip(original_clock.rates()) { + near(*a, *b, 1e-13); + } + // Invalid ancestry and singular support leave every coordinate intact. + let saved = clock.clone(); + assert!(exchange_rates(&mut tree, &mut clock, parent, uncle, child).is_none()); + assert_eq!(tree, original); + assert_eq!(clock, saved); + } + } + + #[test] + fn joint_exchange_preserves_uniform_topologies_and_independent_lognormal_rates() { + let mut random = Random::new(97001); + let mut t = tree(true); + let mut clock = RelaxedClock::new(0.7, vec![1.0; 4]).unwrap(); + let mut counts = [0usize; 3]; + let mut log_sums = [0.0; 3]; + let mut squares = 0.0; + let mut n = 0usize; + let mut birth = crate::speciation::BirthDeath { + birth_difference: 1.0, + relative_death: 0.5, + } + .into(); + for step in 0..250_000 { + if random.uniform() < 0.15 { + // Exact independent conditional draws for a known target. + t.set_height(3, 0.05 + 0.9 * random.uniform()); + for i in 0..4 { + clock.set_rate(i, (0.7 * random.normal() - 0.245).exp()); + } + } else { + let mut proposal = t.clone(); + let mut rates = crate::rates::RateVariation { + clock: Some(clock.clone()), + ..Default::default() + }; + let h = super::super::Move::NarrowExchangeRates + .propose( + &mut proposal, + &mut birth, + &mut rates, + 1000.0, + None, + &mut random, + ) + .unwrap(); + let c = rates.clock.unwrap(); + let alpha = c.log_rate_prior() - clock.log_rate_prior() + h; + if alpha >= 0.0 || random.uniform() < alpha.exp() { + t = proposal; + clock = c; + } + } + if step >= 10_000 { + let (a, b) = t.children(t.root()).unwrap(); + let outside = if a < 3 { a } else { b }; + counts[outside] += 1; + for rate in clock.rates() { + log_sums[outside] += rate.ln() / 4.0; + squares += (rate.ln() + 0.245).powi(2) / 4.0; + } + n += 1; + } + } + for i in 0..3 { + near(counts[i] as f64 / n as f64, 1.0 / 3.0, 0.015); + near(log_sums[i] / counts[i] as f64, -0.245, 0.025); + } + near(squares / n as f64, 0.49, 0.025); + } + + #[test] + fn exchange_overflow_is_rejected_before_mutating_rates_or_topology() { + let mut t = tree(true); + let mut c = RelaxedClock::new(0.7, vec![0.8, 1.3, 1e308, 0.4]).unwrap(); + let old_t = t.clone(); + let old_c = c.clone(); + assert!(exchange_rates(&mut t, &mut c, 3, 0, 2).is_none()); + assert_eq!(t, old_t); + assert_eq!(c, old_c); + } + #[test] fn augmented_jacobians_match_finite_differences() { // These maps include the reverse auxiliary variable. Differentiating diff --git a/src/mcmc/mod.rs b/src/mcmc/mod.rs index 6dee067..503454c 100644 --- a/src/mcmc/mod.rs +++ b/src/mcmc/mod.rs @@ -12,6 +12,8 @@ mod checkpoint; mod coupled; mod moves; +mod relative; +pub use relative::RelativeRate; pub mod output; use std::fmt; @@ -23,7 +25,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}; @@ -34,6 +36,7 @@ pub enum Error { /// A tree needs at least two taxa. TooFewTaxa(usize), Dating(String), + Model(String), /// Mk needs at least two states. States(usize), /// Partitions must be nonempty and contain the same taxa in the same order. @@ -61,7 +64,7 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Dating(error) => f.write_str(error), + Self::Dating(error) | Self::Model(error) => f.write_str(error), Self::Rates(error) => error.fmt(f), Self::RateMove(kind) => write!(f, "{} needs its rate model to be enabled", kind.name()), Self::Power(power) => { @@ -118,10 +121,22 @@ pub enum Conditioning { Informative, } +impl Conditioning { + /// Nucleotide sites are always unconditioned in a mixed analysis. + pub fn for_data(self, data_type: crate::data::DataType) -> Self { + if data_type == crate::data::DataType::Dna { + Self::None + } else { + self + } + } +} + #[derive(Clone, Debug, PartialEq)] pub struct Settings { pub dating: Option, pub conditioning: Conditioning, + pub morphology_rate: Option, /// Four midpoint gamma categories, starting at this shape; None uses one rate. pub gamma_shape: Option, /// Explicit lognormal branch rates, starting at 0.5 with this sigma. @@ -139,6 +154,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)>, @@ -159,6 +175,7 @@ impl Default for Settings { Self { dating: None, conditioning: Conditioning::Variable, + morphology_rate: None, gamma_shape: None, clock_sigma: None, clock_sigma_prior: crate::rates::SigmaPrior::default(), @@ -166,6 +183,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 +208,37 @@ impl Default for Settings { } impl Settings { + pub fn set_morphology_rate(&mut self, rate: RelativeRate) { + self.morphology_rate = Some(rate); + self.weights + .retain(|(m, _)| *m != Move::MorphologyRateScale); + if rate.log_sd.is_some() { + self.weights.push((Move::MorphologyRateScale, 3.0)); + } + } + + /// 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() @@ -293,7 +342,9 @@ impl Likelihood { backend: Backend, tree: &Tree, rates: &RateVariation, + multiplier: f64, ) -> Result { + let conditioning = conditioning.for_data(patterns.data_type()); let states = patterns.symbols().len(); let model = Mk::uniform(states); let variable = match conditioning { @@ -346,7 +397,8 @@ impl Likelihood { order: Vec::with_capacity(tree.nodes()), }; for node in tree.postorder() { - let distance = tree.branch_length(node) * rates.branch_rate(node, tree.root()); + let distance = + tree.branch_length(node) * rates.branch_rate(node, tree.root()) * multiplier; for (category, &rate) in rates.category_rates().iter().enumerate() { likelihood.core.set_node_distance( node, @@ -366,7 +418,13 @@ impl Likelihood { /// Recomputes the branches that differ from `before`, and the partials of /// their ancestors. - fn update(&mut self, tree: &Tree, before: &Tree, rates: &RateVariation) -> f64 { + fn update( + &mut self, + tree: &Tree, + before: &Tree, + rates: &RateVariation, + multiplier: f64, + ) -> f64 { #[cfg(feature = "profile-sampler")] let _profile = crate::profiling::enter(crate::profiling::Phase::LikelihoodUpdate); let dirty = &mut self.dirty; @@ -375,7 +433,8 @@ impl Likelihood { if node == tree.root() { continue; } - let distance = tree.branch_length(node) * rates.branch_rate(node, tree.root()); + let distance = + tree.branch_length(node) * rates.branch_rate(node, tree.root()) * multiplier; let unchanged = rates.category_rates().iter().enumerate().all(|(c, r)| { self.core.node_distance(node, c) == category_distance(distance, *r) @@ -453,11 +512,13 @@ pub struct Sampler { tree: Tree, rates: RateVariation, stored_rates: RateVariation, - birth_death: BirthDeath, + speciation: SpeciationState, stored_tree: Tree, likelihoods: Vec, patterns: Vec, conditioning: Conditioning, + morphology_rate_model: Option, + morphology_rate: Option, backend: Backend, posterior: Posterior, operators: Vec, @@ -548,6 +609,35 @@ 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 + .iter() + .all(|p| p.data_type() == crate::data::DataType::Dna) + && settings.conditioning != Conditioning::None + { + return Err(Error::Model( + "DNA JC69 requires unconditioned aligned sites".into(), + )); + } + let mixed = patterns + .iter() + .any(|p| p.data_type() == crate::data::DataType::Dna) + && patterns + .iter() + .any(|p| p.data_type() == crate::data::DataType::Standard); + if mixed != settings.morphology_rate.is_some() { + return Err(Error::Model("mixed morphology/DNA requires an explicit relative-rate model; homogeneous data does not use one".into())); + } + if let Some(rate) = settings.morphology_rate { + rate.validate()?; + } if patterns.is_empty() || patterns.iter().any(|p| p.tip_partials().len() != tips) { return Err(Error::Partitions); } @@ -596,6 +686,26 @@ impl Sampler { return Err(Error::Rates(rates::Error::BranchRates)); } for &(kind, weight) in &settings.weights { + if kind == Move::MorphologyRateScale + && weight > 0.0 + && settings.morphology_rate.is_none_or(|r| r.log_sd.is_none()) + { + return Err(Error::RateMove(kind)); + } + 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())); + } if weight > 0.0 && kind.changes_fbd() && settings @@ -633,6 +743,7 @@ impl Sampler { | Move::NodeTimeRates | Move::RootTimeRates | Move::ClockSigmaRates + | Move::NarrowExchangeRates ) && rates.clock.is_none())) { return Err(Error::RateMove(kind)); @@ -648,6 +759,18 @@ impl Sampler { return Err(Error::Weights); } for &(kind, value) in &settings.tuning_values { + if kind == Move::MorphologyRateScale + && settings.morphology_rate.is_none_or(|r| r.log_sd.is_none()) + { + return Err(Error::Tuning(kind)); + } + 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, @@ -689,7 +812,16 @@ impl Sampler { } else { patterns .iter() - .map(|p| Likelihood::new(p, settings.conditioning, settings.backend, &tree, &rates)) + .map(|p| { + Likelihood::new( + p, + settings.conditioning, + settings.backend, + &tree, + &rates, + partition_multiplier(p, settings.morphology_rate.map(|r| r.value)), + ) + }) .collect::, _>>()? }; let mut sampler = Self { @@ -699,10 +831,17 @@ 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, + morphology_rate_model: settings.morphology_rate, + morphology_rate: settings.morphology_rate.map(|r| r.value), backend: settings.backend, posterior: Posterior { likelihood: 0.0, @@ -736,6 +875,15 @@ impl Sampler { self.dating.as_ref() } + pub fn morphology_rate(&self) -> Option { + self.morphology_rate + } + + pub fn morphology_rate_log_prior(&self) -> f64 { + self.morphology_rate_model + .map_or(0.0, |m| m.log_density(self.morphology_rate.unwrap())) + } + pub fn rates(&self) -> &RateVariation { &self.rates } @@ -748,8 +896,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 { @@ -781,10 +935,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() @@ -794,7 +949,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| { @@ -803,7 +958,9 @@ impl Sampler { self.rates.mean.unwrap_or(1.0), self.fbd.unwrap(), ) - }), + }) + self + .morphology_rate_model + .map_or(0.0, |m| m.log_density(self.morphology_rate.unwrap())), gamma_prior: self.rates.gamma.as_ref().map_or(0.0, GammaRates::log_prior), clock_rate_prior: self .rates @@ -838,6 +995,7 @@ impl Sampler { self.backend, &self.tree, &self.rates, + partition_multiplier(patterns, self.morphology_rate), )? .evaluate(self.tree.root(), &self.rates); } @@ -852,8 +1010,9 @@ 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; + let stored_morphology_rate = self.morphology_rate; self.stored_tree.clone_from(&self.tree); self.stored_rates.clone_from(&self.rates); for likelihood in &mut self.likelihoods { @@ -862,7 +1021,14 @@ impl Sampler { correction.store(); } } - let proposal = if kind.changes_fbd() { + let proposal = if kind == Move::MorphologyRateScale { + moves::scale( + self.morphology_rate.as_mut().unwrap(), + f64::MAX, + self.operators[index].tuning.unwrap(), + &mut self.random, + ) + } else if kind.changes_fbd() { let dating = self.dating.as_ref().unwrap(); dating.process_priors.and_then(|p| { p.propose( @@ -880,7 +1046,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, @@ -902,7 +1068,15 @@ impl Sampler { } else if proposed.prior().is_finite() { self.likelihoods .iter_mut() - .map(|l| l.update(&self.tree, &self.stored_tree, &self.rates)) + .zip(&self.patterns) + .map(|(l, p)| { + l.update( + &self.tree, + &self.stored_tree, + &self.rates, + partition_multiplier(p, self.morphology_rate), + ) + }) .sum() } else { f64::NEG_INFINITY @@ -922,8 +1096,9 @@ 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; + self.morphology_rate = stored_morphology_rate; std::mem::swap(&mut self.rates, &mut self.stored_rates); for likelihood in &mut self.likelihoods { likelihood.core.restore(); @@ -989,6 +1164,14 @@ impl Sampler { } } +fn partition_multiplier(pattern: &Patterns, morphology_rate: Option) -> f64 { + if pattern.data_type() == crate::data::DataType::Standard { + morphology_rate.unwrap_or(1.0) + } else { + 1.0 + } +} + /// Sorted, distinct tip indices for each constraint, if they are valid and /// pairwise nested or disjoint. fn check_constraints(constraints: &[Vec], tips: usize) -> Result>, Error> { diff --git a/src/mcmc/moves.rs b/src/mcmc/moves.rs index 9abd43e..d8a65de 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)] @@ -46,10 +46,15 @@ pub enum Move { RootTimeRates, /// Scale clock sigma while preserving standardized log branch rates. ClockSigmaRates, + /// Narrow exchange with compensation of the two reattached branch rates. + NarrowExchangeRates, + /// Scale the pure-birth rate of a Yule prior. + BirthRateScale, + MorphologyRateScale, } impl Move { - pub const ALL: [Move; 22] = [ + pub const ALL: [Move; 25] = [ Move::FbdBirthScale, Move::FbdDeathScale, Move::FbdSamplingScale, @@ -72,6 +77,9 @@ impl Move { Move::NodeTimeRates, Move::RootTimeRates, Move::ClockSigmaRates, + Move::NarrowExchangeRates, + Move::BirthRateScale, + Move::MorphologyRateScale, ]; pub fn name(self) -> &'static str { @@ -98,6 +106,9 @@ impl Move { Self::NodeTimeRates => "node_time_rates", Self::RootTimeRates => "root_time_rates", Self::ClockSigmaRates => "clock_sigma_rates", + Self::NarrowExchangeRates => "narrow_exchange_rates", + Self::BirthRateScale => "birth_rate_scale", + Self::MorphologyRateScale => "morphology_rate_scale", } } @@ -114,6 +125,8 @@ impl Move { | Self::RootScale | Self::TreeScale | Self::BirthDifferenceScale + | Self::BirthRateScale + | Self::MorphologyRateScale | Self::RelativeDeathScale | Self::RootTimeRates => Some(0.75), Self::GammaShapeScale @@ -148,6 +161,7 @@ impl Move { | Self::TreeScale | Self::NodeTimeRates | Self::RootTimeRates + | Self::NarrowExchangeRates ) } @@ -156,6 +170,7 @@ impl Move { || matches!( self, Self::ClockRateScale + | Self::MorphologyRateScale | Self::GammaShapeScale | Self::BranchRateScale | Self::ClockSigmaRates @@ -165,7 +180,11 @@ impl Move { pub fn changes_topology(self) -> bool { matches!( self, - Self::SubtreeSlide | Self::NarrowExchange | Self::WideExchange | Self::WilsonBalding + Self::SubtreeSlide + | Self::NarrowExchange + | Self::WideExchange + | Self::WilsonBalding + | Self::NarrowExchangeRates ) } @@ -180,7 +199,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, @@ -193,19 +212,37 @@ impl Move { | Self::FbdSamplingScale | Self::FbdRhoLogit | Self::FbdOriginScale + | Self::MorphologyRateScale | Self::TipAge => None, // Dating proposals are handled by the sampler. Self::ClockRateScale => scale(rates.mean.as_mut()?, f64::MAX, tuning, random), Self::NodeHeight => node_height(tree, random), Self::SubtreeSlide => subtree_slide(tree, tuning, random), Self::NarrowExchange => narrow_exchange(tree, random), + Self::NarrowExchangeRates => { + narrow_exchange_with_rates(tree, Some(rates.clock.as_mut()?), random) + } Self::WideExchange => wide_exchange(tree, random), Self::WilsonBalding => wilson_balding(tree, random), Self::RootScale => root_scale(tree, tuning, random), 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); @@ -317,7 +354,7 @@ fn tree_scale(tree: &mut Tree, factor: f64, random: &mut Random) -> Option Some((internal - 2.0) * f.ln()) } -fn scale(value: &mut f64, upper: f64, factor: f64, random: &mut Random) -> Option { +pub(super) fn scale(value: &mut f64, upper: f64, factor: f64, random: &mut Random) -> Option { if *value == 0.0 { return None; } @@ -418,6 +455,14 @@ fn subtree_slide(tree: &mut Tree, size: f64, random: &mut Random) -> Option } fn narrow_exchange(tree: &mut Tree, random: &mut Random) -> Option { + narrow_exchange_with_rates(tree, None, random) +} + +fn narrow_exchange_with_rates( + tree: &mut Tree, + clock: Option<&mut crate::rates::RelaxedClock>, + random: &mut Random, +) -> Option { let internal = tree.nodes() - tree.tips(); if internal <= 1 { return None; @@ -446,9 +491,14 @@ fn narrow_exchange(tree: &mut Tree, random: &mut Random) -> Option { let (a, b) = tree.children(parent)?; let before = count(tree); let child = if random.coin() { a } else { b }; - tree.replace_child(parent, child, uncle); - tree.replace_child(grandparent, uncle, child); - Some((before as f64 / count(tree) as f64).ln()) + let jacobian = if let Some(clock) = clock { + coupled::exchange_rates(tree, clock, parent, child, uncle)? + } else { + tree.replace_child(parent, child, uncle); + tree.replace_child(grandparent, uncle, child); + 0.0 + }; + Some((before as f64 / count(tree) as f64).ln() + jacobian) } fn wide_exchange(tree: &mut Tree, random: &mut Random) -> Option { @@ -600,7 +650,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 { @@ -639,6 +690,51 @@ mod tests { (observed + unobserved) / 2.0 } + #[test] + fn joint_exchange_selection_ratio_matches_enumerated_reverse_choices() { + let mut tree = Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((0, 1)), + Some((5, 2)), + Some((6, 3)), + Some((7, 4)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8], + ) + .unwrap(); + let choices = |tree: &Tree| { + (tree.tips()..tree.nodes()) + .filter(|&parent| { + tree.parent(parent).is_some() + && tree.height(parent) > tree.height(tree.sibling(parent)) + }) + .count() + * 2 + }; + let mut random = Random::new(97002); + let mut changed_selection = false; + for _ in 0..2000 { + let before = tree.clone(); + let mut clock = crate::rates::RelaxedClock::new(0.7, vec![1.0; 8]).unwrap(); + let h = super::narrow_exchange_with_rates(&mut tree, Some(&mut clock), &mut random) + .unwrap(); + let ratio = (choices(&before) as f64 / choices(&tree) as f64).ln(); + changed_selection |= ratio != 0.0; + let jacobian = (0..tree.nodes()) + .filter(|&i| i != tree.root()) + .map(|i| before.branch_length(i).ln() - tree.branch_length(i).ln()) + .sum::(); + assert!((h - ratio - jacobian).abs() < 1e-13); + tree.validate().unwrap(); + } + assert!(changed_selection); + } + /// The subtree slide mixes slowest; dropping either of its counts raises /// its distance to about 0.026 at 6.4 million steps, against 0.009. #[test] diff --git a/src/mcmc/output.rs b/src/mcmc/output.rs index c0f9525..1b0f630 100644 --- a/src/mcmc/output.rs +++ b/src/mcmc/output.rs @@ -26,6 +26,8 @@ pub struct TraceWriter { dated: bool, ages: usize, process: bool, + yule: bool, + mixed: bool, } impl TraceWriter { @@ -38,6 +40,8 @@ impl TraceWriter { dated: rates.mean.is_some(), ages: 0, process: false, + yule: false, + mixed: false, } } @@ -45,6 +49,8 @@ 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.mixed = sampler.morphology_rate().is_some(); + writer.yule = sampler.tree_prior() == crate::speciation::TreePrior::Yule; writer } @@ -55,6 +61,8 @@ 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, + sampler.morphology_rate().is_some(), ) } @@ -63,7 +71,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, false) } fn header( @@ -72,6 +80,8 @@ impl TraceWriter { rates: &RateVariation, ages: usize, process: bool, + yule: bool, + mixed: bool, ) -> io::Result { for comment in comments { writeln!(out, "# {comment}")?; @@ -81,6 +91,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"))?; } @@ -99,6 +114,9 @@ impl TraceWriter { "\tfbd_birth_rate\tfbd_death_rate\tfbd_fossil_sampling_rate\tfbd_present_sampling\tfbd_origin" )?; } + if mixed { + write!(out, "\tmorphology_rate\tmorphology_rate_prior")?; + } for tip in 0..ages { write!(out, "\ttip_age_{}", tip + 1)?; } @@ -110,6 +128,8 @@ impl TraceWriter { dated: rates.mean.is_some(), ages, process, + yule, + mixed, }) } @@ -119,9 +139,11 @@ impl TraceWriter { let posterior = sampler.posterior(); let birth_death = sampler.birth_death(); let tree = sampler.tree(); - if self.gamma != sampler.rates().gamma.is_some() + if self.mixed != sampler.morphology_rate().is_some() + || 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 +152,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 - sampler.morphology_rate_log_prior() + } else { + birth_death.unwrap().relative_death + } + )?; + } + write!( + self.out, + "\t{}\t{}", tree.height(tree.root()), tree.tree_length() )?; @@ -166,6 +198,13 @@ impl TraceWriter { p.birth, p.death, p.fossil_sampling, p.present_sampling, p.origin )?; } + if let Some(rate) = sampler.morphology_rate() { + write!( + self.out, + "\t{rate}\t{}", + sampler.morphology_rate_log_prior() + )?; + } for tip in 0..self.ages { write!(self.out, "\t{}", tree.height(tip))?; } diff --git a/src/mcmc/relative.rs b/src/mcmc/relative.rs new file mode 100644 index 0000000..cd43c73 --- /dev/null +++ b/src/mcmc/relative.rs @@ -0,0 +1,40 @@ +//! A morphology/DNA rate ratio. DNA fixes the reference rate at one. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RelativeRate { + /// Fixed value or the estimated rate's starting value. + pub value: f64, + /// None fixes the rate; Some(s) uses log(rate) ~ Normal(0, s²). + pub log_sd: Option, +} +impl RelativeRate { + pub fn validate(self) -> Result<(), super::Error> { + if !self.value.is_finite() + || self.value <= 0.0 + || self.log_sd.is_some_and(|s| !s.is_finite() || s <= 0.0) + { + return Err(super::Error::Model( + "morphology rate and lognormal log-SD must be positive and finite".into(), + )); + } + Ok(()) + } + /// Normalized density with respect to d(rate), including its Jacobian. + pub fn log_density(self, rate: f64) -> f64 { + if !rate.is_finite() || rate <= 0.0 { + return f64::NEG_INFINITY; + } + match self.log_sd { + None => { + if rate == self.value { + 0.0 + } else { + f64::NEG_INFINITY + } + } + Some(s) => { + let z = rate.ln(); + -z - s.ln() - 0.5 * (2.0 * std::f64::consts::PI).ln() - 0.5 * (z / s).powi(2) + } + } + } +} diff --git a/src/mixed.rs b/src/mixed.rs new file mode 100644 index 0000000..fca0ab2 --- /dev/null +++ b/src/mixed.rs @@ -0,0 +1,203 @@ +//! Self-contained morphology/DNA sources with explicit taxon matching. +use crate::data::{Cell, DataType, Matrix}; +use serde_json::{Value, json}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Block { + pub data_type: DataType, + pub start: usize, + pub characters: usize, + pub symbols: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Source { + pub name: String, + pub sha256: String, + pub data_type: DataType, + pub missing_taxa: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Metadata { + pub missing_taxa_policy: String, + pub sources: Vec, +} + +impl Metadata { + pub fn json(&self) -> Value { + json!({"missing_taxa_policy": self.missing_taxa_policy, + "taxon_matching": "exact normalized names; source order does not determine correspondence", + "sources": self.sources.iter().map(|s| json!({"name":s.name,"sha256":s.sha256, + "data_type":s.data_type.name(),"missing_taxa":s.missing_taxa})).collect::>()}) + } +} + +fn fields(value: &Value, keys: &[&str]) -> Result<(), String> { + let object = value + .as_object() + .ok_or("mixed manifest must contain objects")?; + if object.len() != keys.len() || keys.iter().any(|k| !object.contains_key(*k)) { + return Err(format!( + "mixed manifest requires exactly these fields: {}", + keys.join(", ") + )); + } + Ok(()) +} + +/// Every source is embedded verbatim. No filesystem paths are followed on import. +pub fn manifest( + morphology: (&str, &str), + dna: (&str, &str), + missing: &str, +) -> Result { + let source = |(name, text): (&str, &str), data_type: &str| { + json!({ + "name": name, "data_type":data_type, "sha256":crate::fingerprint::hex(text.as_bytes()), "content":text}) + }; + let value = json!({"format":"rove-mixed", "version":1,"missing_taxa":missing, + "sources":[source(morphology,"standard"),source(dna,"dna")]}); + let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())? + "\n"; + parse(&text)?; + Ok(text) +} + +pub fn parse(input: &str) -> Result { + let value: Value = + serde_json::from_str(input).map_err(|e| format!("invalid mixed manifest: {e}"))?; + fields(&value, &["format", "version", "missing_taxa", "sources"])?; + if value["format"] != "rove-mixed" || value["version"] != 1 { + return Err("unsupported mixed manifest format/version".into()); + } + let policy = value["missing_taxa"] + .as_str() + .ok_or("missing taxon policy")?; + if !matches!(policy, "reject" | "missing") { + return Err("missing_taxa must be reject or missing".into()); + } + let sources = value["sources"] + .as_array() + .filter(|v| v.len() == 2) + .ok_or("mixed input needs exactly one morphology source followed by one DNA source")?; + let mut matrices = Vec::new(); + let mut metadata = Metadata { + missing_taxa_policy: policy.into(), + sources: Vec::new(), + }; + for (source, expected) in sources.iter().zip([DataType::Standard, DataType::Dna]) { + fields(source, &["name", "data_type", "sha256", "content"])?; + let text = source["content"].as_str().ok_or("missing source text")?; + // Reject nested manifests before dispatching to the input parser. + if text + .trim_start_matches('\u{feff}') + .trim_start() + .starts_with('{') + { + return Err("nested mixed manifests are unsupported".into()); + } + let hash = crate::fingerprint::hex(text.as_bytes()); + if source["sha256"] != hash { + return Err("embedded source fingerprint does not match its bytes".into()); + } + let name = source["name"] + .as_str() + .filter(|s| !s.trim().is_empty() && !s.contains(['/', '\\', '\n', '\r'])) + .ok_or("source name must be a nonempty filename")?; + let matrix = crate::alignment::parse(text).map_err(|e| format!("{name}: {e}"))?; + if matrix.data_type() != expected || source["data_type"] != expected.name() { + return Err(format!("{name}: expected {} data", expected.name())); + } + metadata.sources.push(Source { + name: name.into(), + sha256: hash, + data_type: expected, + missing_taxa: Vec::new(), + }); + matrices.push(matrix); + } + let mut taxa = matrices[0].taxa.clone(); + let shared = matrices[1].taxa.iter().filter(|t| taxa.contains(t)).count(); + if shared < 2 { + return Err("mixed sources must share at least two exactly matching taxon names".into()); + } + for taxon in &matrices[1].taxa { + if !taxa.contains(taxon) { + if taxa.iter().any(|t| t.eq_ignore_ascii_case(taxon)) { + return Err(format!( + "taxon spelling differs between sources: {taxon:?}; match normalized names exactly" + )); + } + taxa.push(taxon.clone()); + } + } + for (matrix, source) in matrices.iter_mut().zip(&mut metadata.sources) { + source.missing_taxa = taxa + .iter() + .filter(|t| !matrix.taxa.contains(t)) + .cloned() + .collect(); + if policy == "reject" && !source.missing_taxa.is_empty() { + return Err(format!( + "{} lacks taxa: {}; choose missing explicitly to retain them", + source.name, + source.missing_taxa.join(", ") + )); + } + matrix.rows = taxa + .iter() + .map(|t| { + matrix.taxa.iter().position(|name| name == t).map_or_else( + || vec![Cell::Missing; matrix.character_count()], + |i| matrix.rows[i].clone(), + ) + }) + .collect(); + matrix.taxa = taxa.clone(); + } + let mut result = Matrix { + data_type: DataType::Mixed, + blocks: Vec::new(), + mixed: Some(metadata), + rows: vec![Vec::new(); taxa.len()], + taxa, + symbols: Vec::new(), + character_labels: Vec::new(), + state_labels: Vec::new(), + ordering: Vec::new(), + }; + for matrix in matrices { + let start = result.character_count(); + let mut map = Vec::new(); + for symbol in &matrix.symbols { + let index = result + .symbols + .iter() + .position(|s| s == symbol) + .unwrap_or_else(|| { + result.symbols.push(*symbol); + result.symbols.len() - 1 + }); + map.push(index); + } + let recode = |cell: Cell| match cell { + Cell::State(s) => Cell::State(map[s]), + Cell::Uncertain(v) => Cell::Uncertain(v.into_iter().map(|s| map[s]).collect()), + Cell::Polymorphic(v) => Cell::Polymorphic(v.into_iter().map(|s| map[s]).collect()), + other => other, + }; + result.blocks.push(Block { + data_type: matrix.data_type, + start, + characters: matrix.character_count(), + symbols: matrix.symbols, + }); + result.character_labels.extend(matrix.character_labels); + result.state_labels.extend(matrix.state_labels); + result.ordering.extend(matrix.ordering); + for (out, row) in result.rows.iter_mut().zip(matrix.rows) { + out.extend(row.into_iter().map(recode)); + } + } + Ok(result) +} diff --git a/src/nexus/matrix.rs b/src/nexus/matrix.rs index 5b09382..c7c3a70 100644 --- a/src/nexus/matrix.rs +++ b/src/nexus/matrix.rs @@ -182,6 +182,12 @@ fn symbols(token: &Token, format: &Format) -> Result, Error> { Ok(Cell::Missing) } else if format.gap.is_some_and(|g| format.equal(g, symbol)) { Ok(Cell::Gap) + } else if format.data_type == crate::data::DataType::Dna { + crate::alignment::dna_cell(symbol).ok_or_else(|| { + token.error(format!( + "unsupported DNA symbol {symbol:?}; use A/C/G/T or IUPAC ambiguity codes" + )) + }) } else if let Some(state) = format.state(symbol) { Ok(Cell::State(state)) } else { diff --git a/src/nexus/mod.rs b/src/nexus/mod.rs index b989571..aa86905 100644 --- a/src/nexus/mod.rs +++ b/src/nexus/mod.rs @@ -1,4 +1,4 @@ -//! A strict subset of morphological NEXUS. See the NEXUS guide for supported syntax. +//! NEXUS STANDARD morphology and aligned DNA. See the NEXUS guide for supported syntax. mod assumptions; mod lexer; @@ -7,7 +7,7 @@ mod matrix; use std::collections::HashSet; use std::fmt; -use crate::data::Matrix; +use crate::data::{DataType, Matrix}; use lexer::{Kind, Token}; /// A source location uses one-based lines and columns. @@ -30,7 +30,7 @@ impl fmt::Display for Error { impl std::error::Error for Error {} -/// Read one STANDARD matrix without invoking BEAST or inferring a model alphabet +/// Read one STANDARD or DNA matrix without invoking BEAST or inferring a model alphabet /// from observed states. Unsupported analysis directives produce an error. pub fn parse(input: &str) -> Result { let tokens = lexer::lex(input)?; @@ -90,7 +90,15 @@ pub fn parse(input: &str) -> Result { ))); } } - matrix.ok_or_else(|| header.error("no DATA or CHARACTERS matrix found")) + let matrix = matrix.ok_or_else(|| header.error("no DATA or CHARACTERS matrix found"))?; + if matrix.data_type() == DataType::Dna + && matrix + .ordering() + .contains(&crate::model::CharacterOrdering::Ordered) + { + return Err(header.error("ordered characters are not supported for DNA JC69")); + } + Ok(matrix) } struct Commands<'a> { @@ -241,6 +249,7 @@ fn parse_taxa(commands: &mut Commands<'_>, block: &Token) -> Result, } struct Format { + data_type: DataType, symbols: Vec, missing: char, gap: Option, @@ -251,6 +260,7 @@ struct Format { impl Default for Format { fn default() -> Self { Self { + data_type: DataType::Standard, symbols: vec!['0', '1'], missing: '?', gap: None, @@ -285,9 +295,14 @@ fn format(tokens: &[&Token]) -> Result { return Err(key.error("duplicate FORMAT option")); } if key.is("DATATYPE") { - if !assignment(tokens, &mut i, key)?.is("STANDARD") { - return Err(key.error("only DATATYPE=STANDARD is supported")); - } + let value = assignment(tokens, &mut i, key)?; + result.data_type = if value.is("STANDARD") { + DataType::Standard + } else if value.is("DNA") { + DataType::Dna + } else { + return Err(key.error("only DATATYPE=STANDARD or DNA is supported")); + }; } else if key.is("RESPECTCASE") { result.respect_case = true; } else if key.is("LABELS") || key.is("NOTOKENS") { @@ -326,6 +341,29 @@ fn format(tokens: &[&Token]) -> Result { return Err(key.error(format!("unsupported FORMAT option {}", key.text))); } } + if result.data_type == DataType::Dna { + if result.respect_case + || (seen.contains("SYMBOLS") && result.symbols != ['A', 'C', 'G', 'T']) + { + return Err(tokens[0].error( + "DNA uses case-insensitive A/C/G/T states; omit RESPECTCASE and custom SYMBOLS", + )); + } + result.symbols = vec!['A', 'C', 'G', 'T']; + if !seen.contains("GAP") { + result.gap = Some('-'); + } + if (crate::alignment::dna_cell(result.missing).is_some() + && !result.missing.eq_ignore_ascii_case(&'N')) + || result + .gap + .is_some_and(|gap| crate::alignment::dna_cell(gap).is_some()) + { + return Err(tokens[0].error( + "DNA gap symbols cannot replace IUPAC codes; only N may also be declared missing", + )); + } + } if result.symbols.len() < 2 || result.symbols.iter().any(|&s| !valid_symbol(s)) { return Err(tokens[0] .error("SYMBOLS must contain at least two valid single-character ASCII states")); @@ -416,6 +454,9 @@ fn parse_data( (names, rows) }; let mut data = Matrix { + data_type: fmt.data_type, + blocks: Vec::new(), + mixed: None, taxa: names, rows, symbols: fmt.symbols.clone(), diff --git a/src/predictive/mod.rs b/src/predictive/mod.rs index 6bf41bf..7ebb42a 100644 --- a/src/predictive/mod.rs +++ b/src/predictive/mod.rs @@ -14,7 +14,7 @@ use crate::model::{CharacterOrdering, Mk, Ordered}; use crate::random::Random; use crate::rates::RateVariation; use crate::tree::Tree; -use crate::{LikelihoodCore, Scaling, nexus}; +use crate::{LikelihoodCore, Scaling}; #[derive(Debug)] pub struct Error(pub String); @@ -31,6 +31,7 @@ pub struct Design { sets: Vec, gaps: GapTreatment, conditioning: Conditioning, + morphology_rate: f64, } impl Design { @@ -40,6 +41,11 @@ impl Design { gaps: GapTreatment, conditioning: Conditioning, ) -> Result { + if matrix.data_type() == crate::data::DataType::Dna && conditioning != Conditioning::None { + return Err(Error( + "DNA JC69 requires unconditioned aligned sites".into(), + )); + } if matrix.taxa().len() < 2 || matrix.taxa().len().saturating_mul(matrix.character_count()) > 8_000_000 { @@ -76,9 +82,10 @@ impl Design { sets, gaps, conditioning, + morphology_rate: 1.0, }; for p in design.compress(matrix)? { - match conditioning { + match conditioning.for_data(p.data_type()) { Conditioning::None => {} Conditioning::Variable => { crate::ascertainment::VariableCharacters::new(&p) @@ -93,6 +100,29 @@ impl Design { Ok(design) } + pub fn set_morphology_rate(&mut self, rate: f64) -> Result<()> { + if !rate.is_finite() + || rate <= 0.0 + || (self.original.data_type() != crate::data::DataType::Mixed && rate != 1.0) + { + return Err(Error( + "relative morphology rate requires mixed input and a positive finite value".into(), + )); + } + self.morphology_rate = rate; + Ok(()) + } + + fn rates_for(&self, rates: &RateVariation, data_type: crate::data::DataType) -> RateVariation { + let mut result = rates.clone(); + if self.original.data_type() == crate::data::DataType::Mixed + && data_type == crate::data::DataType::Standard + { + result.mean = Some(rates.mean.unwrap_or(1.0) * self.morphology_rate); + } + result + } + pub fn original(&self) -> &Matrix { &self.original } @@ -101,7 +131,9 @@ impl Design { } pub fn compress(&self, matrix: &Matrix) -> Result> { - if matrix.taxa() != self.original.taxa() + if matrix.blocks != self.original.blocks + || matrix.data_type() != self.original.data_type() + || matrix.taxa() != self.original.taxa() || matrix.symbols() != self.original.symbols() || matrix.ordering() != self.original.ordering() || matrix.character_count() != self.original.character_count() @@ -145,14 +177,14 @@ impl Design { let order = tree.postorder(); for partition in self.compress(&self.original)? { let k = partition.symbols().len(); - let matrices = transitions(tree, rates, k, partition.ordering())?; - let symbols: Vec<_> = partition - .symbols() - .iter() - .map(|s| self.original.symbols().iter().position(|c| c == s).unwrap()) - .collect(); + let rates = self.rates_for(rates, partition.data_type()); + let matrices = transitions(tree, &rates, k, partition.ordering())?; let mut counts = vec![0; k]; - for &site in partition.sites() { + for (&site, alphabet) in partition.sites().iter().zip(partition.state_symbols()) { + let symbols: Vec<_> = alphabet + .iter() + .map(|s| self.original.symbols().iter().position(|c| c == s).unwrap()) + .collect(); let mut accepted = false; for attempt in 0..max_attempts { if attempt % 128 == 0 && cancel() { @@ -171,7 +203,7 @@ impl Design { for &state in &states[..tree.tips()] { counts[state] += 1; } - accepted = match self.conditioning { + accepted = match self.conditioning.for_data(partition.data_type()) { Conditioning::None => true, Conditioning::Variable => counts.iter().filter(|&&n| n > 0).count() > 1, Conditioning::Informative => { @@ -197,7 +229,8 @@ impl Design { } // Exercise the same parser and frozen-alphabet compression used for // exported replicates; losing a state must never shrink the model. - let parsed = nexus::parse(&to_nexus(&result)).map_err(|e| Error(e.to_string()))?; + let parsed = + crate::alignment::parse(&to_input(&result)).map_err(|e| Error(e.to_string()))?; self.compress(&parsed)?; Ok(parsed) } @@ -213,6 +246,7 @@ impl Design { let parts = self.compress(matrix)?; let mut characters = vec![CharacterStatistics::default(); matrix.character_count()]; for p in parts { + let rates = self.rates_for(rates, p.data_type()); if cancel() { return Err(Error("posterior prediction cancelled".into())); } @@ -344,17 +378,49 @@ fn draw(probabilities: &[f64], random: &mut Random) -> usize { probabilities.len() - 1 } -/// A complete NEXUS matrix, including the original declared alphabet, labels, -/// character order and missing/gap mask. Explicit model alphabets live in the -/// predictive report and must be reused when fitting exported replicates. +/// Compatibility entry point for `to_input`: NEXUS for homogeneous data, +/// a typed manifest for mixed data. Alphabets, labels, ordering and missing masks +/// are retained. Frozen model alphabets live in the predictive report and must +/// be reused when fitting exported replicates. pub fn to_nexus(matrix: &Matrix) -> String { + to_input(matrix) +} + +/// NEXUS for homogeneous data, a self-contained typed manifest for mixed data. +pub fn to_input(matrix: &Matrix) -> String { + if matrix.data_type() == crate::data::DataType::Mixed { + let meta = matrix.mixed_metadata().expect("validated mixed matrix"); + let mut components = matrix.component_matrices(); + for (part, source) in components.iter_mut().zip(&meta.sources) { + let kept: Vec<_> = part + .taxa + .iter() + .enumerate() + .filter(|(_, t)| !source.missing_taxa.contains(t)) + .map(|(i, _)| i) + .collect(); + part.rows = kept.iter().map(|i| part.rows[*i].clone()).collect(); + part.taxa = kept.iter().map(|i| part.taxa[*i].clone()).collect(); + } + return crate::mixed::manifest( + ("morphology.nex", &to_input(&components[0])), + ("dna.nex", &to_input(&components[1])), + &meta.missing_taxa_policy, + ) + .expect("validated mixed matrix serialization"); + } fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', "''")) } let mut out = format!( - "#NEXUS\nBEGIN DATA;\nDIMENSIONS NTAX={} NCHAR={};\nFORMAT DATATYPE=STANDARD SYMBOLS=\"{}\" MISSING=? GAP=-;\n", + "#NEXUS\nBEGIN DATA;\nDIMENSIONS NTAX={} NCHAR={};\nFORMAT DATATYPE={} SYMBOLS=\"{}\" MISSING=? GAP=-;\n", matrix.taxa().len(), matrix.character_count(), + if matrix.data_type() == crate::data::DataType::Dna { + "DNA" + } else { + "STANDARD" + }, matrix.symbols().iter().collect::() ); let mut labels = Vec::new(); 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 new file mode 100644 index 0000000..04981d7 --- /dev/null +++ b/tests/assessment_cli.rs @@ -0,0 +1,284 @@ +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn call(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_rove")) + .args(args) + .output() + .unwrap() +} +fn good(output: Output) { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} +fn read(path: impl AsRef) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() +} +fn fixture(name: &str, chains: &str) -> PathBuf { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + fs::write(root.join("matrix.nex"), "#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=4; FORMAT SYMBOLS=\"01\"; MATRIX A 0000 B 0011 C 1100 D 1111; END;").unwrap(); + good(call(&[ + "sample", + root.join("matrix.nex").to_str().unwrap(), + "--output", + root.join("run").to_str().unwrap(), + "--seed", + "42", + "--steps", + "100", + "--sample-every", + "10", + "--chains", + chains, + ])); + root +} +fn assess(root: &Path, name: &str) -> Value { + good(call(&[ + "assess", + root.join("run").to_str().unwrap(), + "--output", + root.join(name).to_str().unwrap(), + ])); + read(root.join(name).join("assessment.json")) +} +fn status<'a>(report: &'a Value, id: &str) -> &'a Value { + &report["sections"] + .as_array() + .unwrap() + .iter() + .find(|v| v["id"] == id) + .unwrap()["status"] +} + +#[test] +fn review_distinguishes_finished_short_single_chain_from_convergence() { + let root = fixture("assessment-single", "1"); + let report = assess(&root, "review"); + assert_eq!(status(&report, "completion"), "passed"); + assert_eq!(status(&report, "sampling"), "attention"); + assert_eq!(status(&report, "agreement"), "unavailable"); + assert_eq!(status(&report, "prediction"), "unavailable"); + assert_eq!(report["convergence_certified"], false); + assert_eq!(report["original_matrix_status"], "matches"); + let log = root.join("run/trace.log"); + let original = fs::read_to_string(&log).unwrap(); + fs::write( + &log, + original + .lines() + .take(original.lines().count() - 1) + .collect::>() + .join("\n") + + "\n", + ) + .unwrap(); + let bad = assess(&root, "truncated"); + assert_eq!(status(&bad, "completion"), "attention"); + assert!( + bad["diagnostics"][0]["error"] + .as_str() + .unwrap() + .contains("truncated") + ); +} + +#[test] +fn chain_group_checks_child_identity_before_assessing_agreement() { + let root = fixture("assessment-group", "2"); + let report = assess(&root, "review"); + assert_eq!(status(&report, "completion"), "passed"); + assert_eq!(status(&report, "agreement"), "attention"); + let file = root.join("run/chain-02/run.json"); + let mut record = read(&file); + record["model"]["partitioning"] = Value::String("declared".into()); + fs::write(file, serde_json::to_vec(&record).unwrap()).unwrap(); + let incompatible = assess(&root, "mixed"); + assert_eq!(status(&incompatible, "agreement"), "unavailable"); + assert_eq!(status(&incompatible, "completion"), "attention"); +} + +#[test] +fn archive_preserves_sources_and_requires_explicit_matching_matrix() { + let root = fixture("assessment-export", "1"); + let original = fs::read(root.join("run/trace.log")).unwrap(); + good(call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap(), + ])); + let manifest = read(root.join("package/manifest.json")); + assert_eq!(manifest["matrix_included"], false); + assert!(!root.join("package/matrix.nex").exists()); + assert_eq!( + fs::read(root.join("package/run/trace.log")).unwrap(), + original + ); + assert_eq!(fs::read(root.join("run/trace.log")).unwrap(), original); + assert!( + manifest["files"] + .as_array() + .unwrap() + .iter() + .all(|v| v["sha256"].as_str().unwrap().len() == 64) + ); + good(call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("with-matrix").to_str().unwrap(), + "--include-matrix", + root.join("matrix.nex").to_str().unwrap(), + ])); + assert_eq!( + fs::read(root.join("with-matrix/matrix.nex")).unwrap(), + fs::read(root.join("matrix.nex")).unwrap() + ); + fs::write(root.join("matrix.nex"), "changed").unwrap(); + let changed = assess(&root, "changed"); + assert_eq!(changed["original_matrix_status"], "changed"); + let failed = call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("rejected").to_str().unwrap(), + "--include-matrix", + root.join("matrix.nex").to_str().unwrap(), + ]); + assert!(!failed.status.success()); + assert!(!root.join("rejected").exists()); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap() + ]) + .status + .success() + ); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("run/nested").to_str().unwrap() + ]) + .status + .success() + ); +} + +#[test] +fn reports_require_matching_source_fingerprints() { + let root = fixture("assessment-reports", "1"); + fs::create_dir(root.join("run/summaries")).unwrap(); + good(call(&[ + "summarize", + root.join("run/trees.nexus").to_str().unwrap(), + "--output", + root.join("run/summaries/first").to_str().unwrap(), + "--burnin-percent", + "10", + "--heights", + "keep", + ])); + let report = assess(&root, "review"); + assert_eq!(status(&report, "trees"), "review_required"); + let file = root.join("run/summaries/first/summary.json"); + let mut summary = read(&file); + summary["source"]["sha256"] = Value::String("0".repeat(64)); + fs::write(&file, serde_json::to_vec(&summary).unwrap()).unwrap(); + let changed = assess(&root, "changed"); + assert_eq!(status(&changed, "trees"), "unavailable"); +} + +#[cfg(unix)] +#[test] +fn exports_reject_symlinked_artifacts() { + let root = fixture("assessment-symlinks", "1"); + fs::create_dir(root.join("run/predictions")).unwrap(); + std::os::unix::fs::symlink(root.join("matrix.nex"), root.join("run/predictions/linked")) + .unwrap(); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap() + ]) + .status + .success() + ); + 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..29de554 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"]); } @@ -354,3 +358,121 @@ fn restarting_keeps_the_diagnostic_stopping_history() { } } } + +#[test] +fn dna_formats_resume_to_identical_samples() { + for (format, matrix) in [ + ( + "nexus", + include_str!("../fixtures/validation/dna/matrix.nex"), + ), + ( + "fasta", + include_str!("../fixtures/validation/dna/matrix.fasta"), + ), + ] { + for chains in [1, 4] { + let root = scratch(&format!("checkpoint-dna-{format}-{chains}")); + fs::write(root.join("matrix.nex"), matrix).unwrap(); + let configured = |name: &str| { + let mut cmd = command(&root, name, chains); + cmd.args(["--gaps", "missing", "--monophyly", "Alpha_one,Beta_two"]); + cmd + }; + assert!( + configured("full") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap() + .success() + ); + interrupt(configured("paused"), 230, false); + let outcome = Command::new(BIN) + .args(["sample", "--resume"]) + .arg(root.join("paused")) + .output() + .unwrap(); + assert!( + outcome.status.success(), + "{}", + String::from_utf8_lossy(&outcome.stderr) + ); + for c in 0..chains { + let member = if chains == 1 { + String::new() + } else { + format!("chain-{:02}", c + 1) + }; + for file in ["trace.log", "trees.nexus"] { + assert_eq!( + content(&root.join("full").join(&member).join(file)), + content(&root.join("paused").join(&member).join(file)) + ); + } + } + } + } +} + +#[test] +fn mixed_fixed_and_estimated_rates_resume_identically() { + let matrix = rove::mixed::manifest( + ( + "morphology.nex", + include_str!("../fixtures/validation/mixed/morphology.nex"), + ), + ( + "dna.fasta", + include_str!("../fixtures/validation/dna/complete.fasta"), + ), + "reject", + ) + .unwrap(); + for rate in ["2.5", "estimate"] { + for chains in [1, 4] { + let root = scratch(&format!("checkpoint-mixed-{rate}-{chains}")); + fs::write(root.join("matrix.nex"), &matrix).unwrap(); + let configured = |name: &str| { + let mut cmd = command(&root, name, chains); + cmd.args([ + "--morphology-rate", + rate, + "--monophyly", + "Alpha_one,Beta_two", + ]); + cmd + }; + let full = configured("full").output().unwrap(); + assert!( + full.status.success(), + "{}", + String::from_utf8_lossy(&full.stderr) + ); + interrupt(configured("paused"), 230, false); + let resumed = Command::new(BIN) + .args(["sample", "--resume"]) + .arg(root.join("paused")) + .output() + .unwrap(); + assert!( + resumed.status.success(), + "{}", + String::from_utf8_lossy(&resumed.stderr) + ); + for c in 0..chains { + let member = if chains == 1 { + String::new() + } else { + format!("chain-{:02}", c + 1) + }; + for file in ["trace.log", "trees.nexus"] { + assert_eq!( + content(&root.join("full").join(&member).join(file)), + content(&root.join("paused").join(&member).join(file)) + ); + } + } + } + } +} diff --git a/tests/dating.rs b/tests/dating.rs index bb30192..c537000 100644 --- a/tests/dating.rs +++ b/tests/dating.rs @@ -42,6 +42,20 @@ fn settings(dating: Dating, prior: bool) -> Settings { s } +#[test] +fn experimental_joint_exchange_is_not_enabled_for_dated_runs() { + let mut s = Settings::reference(); + s.set_dating(model(&[(0.0, 0.0), (0.2, 0.4), (0.0, 0.0)])); + s.weights.push((Move::NarrowExchangeRates, 10.0)); + assert!( + Sampler::new(patterns(3), &s, 97) + .err() + .unwrap() + .to_string() + .contains("restricted to undated") + ); +} + #[test] fn fixed_densities_match_beast_sa() { for row in include_str!("../fixtures/validation/dating/beast-sa-2.1.1.tsv") diff --git a/tests/dna.rs b/tests/dna.rs new file mode 100644 index 0000000..db4ce86 --- /dev/null +++ b/tests/dna.rs @@ -0,0 +1,326 @@ +use rove::alignment; +use rove::data::{Cell, CharacterSet, DataType, GapTreatment, Matrix}; +use rove::mcmc::{Conditioning, Sampler, Settings}; +use rove::predictive::Design; +use rove::rates::RateVariation; +use rove::tree::Tree; +use rove::{Backend, nexus}; + +const FASTA: &str = include_str!("../fixtures/validation/dna/matrix.fasta"); +const NEXUS: &str = include_str!("../fixtures/validation/dna/matrix.nex"); + +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 aligned_formats_preserve_iupac_identity_and_the_complete_alphabet() { + let fasta = alignment::parse(FASTA).unwrap(); + let nexus = alignment::parse(NEXUS).unwrap(); + assert_eq!(fasta, nexus); + assert_eq!(fasta.data_type(), DataType::Dna); + assert_eq!(fasta.taxa()[0], "Alpha one"); + assert_eq!(fasta.rows()[0][5], Cell::Uncertain(vec![0, 2])); + assert_eq!(fasta.rows()[0][6], Cell::Uncertain(vec![1, 3])); + assert_eq!(fasta.rows()[0][7], Cell::Uncertain(vec![0, 1, 2, 3])); + assert_eq!(fasta.rows()[0][8], Cell::Missing); + assert_eq!(fasta.rows()[0][9], Cell::Gap); + assert!(fasta.partition_by_states(GapTreatment::Reject).is_err()); + let parts = fasta.partition_by_states(GapTreatment::Missing).unwrap(); + assert_eq!(parts.len(), 1); + assert_eq!(parts[0].symbols(), ['A', 'C', 'G', 'T']); + assert_eq!(parts[0].weights().iter().sum::(), 12); + // The first, constant-A column still has four states in the model. + assert!( + parts[0] + .state_symbols() + .iter() + .all(|s| s == &['A', 'C', 'G', 'T']) + ); + assert!( + fasta + .compress_sets( + &[CharacterSet { + sites: (0..12).collect(), + symbols: vec!['A', 'C'] + }], + GapTreatment::Missing + ) + .is_err() + ); + assert!(fasta.partition_by_labels(GapTreatment::Missing).is_err()); + assert_eq!( + nexus::parse(&rove::predictive::to_nexus(&fasta)).unwrap(), + fasta + ); + assert!(Sampler::new(&parts, &Settings::default(), 1).is_err()); + let every = alignment::parse(">A\nacgtryswkmbdhvn\n>B\nACGTRYSWKMBDHVN\n").unwrap(); + assert_eq!(every.rows()[0], every.rows()[1]); + for (i, states) in [ + vec![0, 2], + vec![1, 3], + vec![1, 2], + vec![0, 3], + vec![2, 3], + vec![0, 1], + vec![1, 2, 3], + vec![0, 2, 3], + vec![0, 1, 3], + vec![0, 1, 2], + vec![0, 1, 2, 3], + ] + .into_iter() + .enumerate() + { + assert_eq!(every.rows()[0][i + 4], Cell::Uncertain(states)); + } + let missing_n = NEXUS.replace("MISSING=?", "MISSING=N").replace("?", "N"); + assert_eq!( + nexus::parse(&missing_n).unwrap().rows()[0][7], + Cell::Missing + ); +} + +#[test] +fn malformed_alignments_and_unsupported_models_are_rejected() { + for text in [ + ">a\nAC\n>b\nA\n", + ">a\n>b\nAC\n", + ">\nAC\n", + ">a\nAC\n>A other\nAG\n", + ">a\nACU\n", + ">___\nAC\n", + ">a\nAC.\n", + ">a\nAC0\n", + ] { + assert!(alignment::parse(text).is_err(), "{text}"); + } + for option in [ + "DATATYPE=RNA", + "DATATYPE=PROTEIN", + "DATATYPE=DNA SYMBOLS=\"AG\"", + "DATATYPE=DNA RESPECTCASE", + "DATATYPE=DNA GAP=R", + "DATATYPE=DNA MISSING=A", + ] { + let text = NEXUS.replace("DATATYPE=DNA", option); + assert!(nexus::parse(&text).is_err(), "{option}"); + } + assert!( + nexus::parse(&(NEXUS.to_owned() + "BEGIN ASSUMPTIONS; OPTIONS DEFTYPE=ORD; END;")).is_err() + ); + let data = alignment::parse(FASTA).unwrap(); + let parts = data.partition_by_states(GapTreatment::Missing).unwrap(); + let error = Design::new(&data, &parts, GapTreatment::Missing, Conditioning::None) + .err() + .unwrap(); + assert!(error.to_string().contains("observation model")); +} + +/// Sum all internal states explicitly, using the analytical JC69 transition +/// probabilities. This does not use pruning, the kernel or Mk's transition code. +fn brute_force(matrix: &Matrix, tree: &Tree) -> f64 { + let transition = |a, b, distance: f64| { + let decay = (-4.0 * distance / 3.0).exp(); + if a == b { + 0.25 + 0.75 * decay + } else { + 0.25 - 0.25 * decay + } + }; + let mut log_likelihood = 0.0; + for site in 0..matrix.character_count() { + let mut probability = 0.0; + for code in 0..4usize.pow((tree.tips() - 1) as u32) { + let mut remaining = code; + let mut states = vec![0; tree.nodes()]; + for state in &mut states[tree.tips()..] { + *state = remaining % 4; + remaining /= 4; + } + let mut term = 0.25; + for node in 0..tree.nodes() { + let Some(parent) = tree.parent(node) else { + continue; + }; + let distance = tree.branch_length(node); + term *= if node >= tree.tips() { + transition(states[parent], states[node], distance) + } else { + (0..4) + .filter(|s| match &matrix.rows()[node][site] { + Cell::State(x) => x == s, + Cell::Uncertain(xs) => xs.contains(s), + Cell::Missing | Cell::Gap => true, + Cell::Polymorphic(_) => unreachable!(), + }) + .map(|s| transition(states[parent], s, distance)) + .sum::() + }; + } + probability += term; + } + log_likelihood += probability.ln(); + } + log_likelihood +} + +#[test] +fn fixed_states_match_analytical_enumeration_and_pinned_beast() { + let data = alignment::parse(FASTA).unwrap(); + let patterns = data.partition_by_states(GapTreatment::Missing).unwrap(); + for row in include_str!("../fixtures/validation/dna/beast-2.7.8.tsv") + .lines() + .skip(1) + { + let values: Vec = row + .split('\t') + .take(4) + .map(|x| x.parse().unwrap()) + .collect(); + let tree = ladder(5, values[0]); + for backend in Backend::ALL.into_iter().filter(|b| b.is_available()) { + let settings = Settings { + conditioning: Conditioning::None, + gamma_shape: (values[1] == 4.0).then_some(values[2]), + backend, + ..Settings::default() + }; + let chain = Sampler::with_tree(&patterns, &settings, tree.clone(), 1).unwrap(); + let actual = chain.posterior().likelihood; + // Use BEAST's actual category rates to isolate pruning from the + // known AS91 inverse-gamma approximation difference (rates.rs). + let reference_rates: Vec = row + .split('\t') + .nth(4) + .unwrap() + .split(',') + .map(|x| x.parse().unwrap()) + .collect(); + let partition = &patterns[0]; + let mut core = rove::LikelihoodCore::mk( + &rove::model::Mk::uniform(4), + partition.weights().len(), + reference_rates.len(), + tree.nodes(), + rove::Scaling::Always, + ); + core.set_backend(backend); + for (tip, partials) in partition.tip_partials().iter().enumerate() { + core.set_tip_partials(tip, partials); + } + for node in tree.postorder() { + for (category, rate) in reference_rates.iter().enumerate() { + core.set_node_distance(node, category, tree.branch_length(node) * rate); + } + if let Some((a, b)) = tree.children(node) { + core.calculate_partials(a, b, node); + } + } + core.integrate_partials( + tree.root(), + &vec![1.0 / reference_rates.len() as f64; reference_rates.len()], + ); + let exact: f64 = core + .calculate_log_likelihoods(&[0.25; 4]) + .iter() + .zip(partition.weights()) + .map(|(ll, weight)| ll * *weight as f64) + .sum(); + assert!( + (exact - values[3]).abs() < 1e-10, + "fixed category rates: {row}: {exact}" + ); + if values[1] == 4.0 { + for (actual, expected) in chain + .rates() + .gamma + .as_ref() + .unwrap() + .rates() + .iter() + .zip(reference_rates) + { + assert!((actual - expected).abs() < 3e-8); + } + } + assert!( + (actual - values[3]).abs() < if values[1] == 1.0 { 1e-10 } else { 1e-7 }, + "{row}: {actual}" + ); + if values[1] == 1.0 { + assert!((actual - brute_force(&data, &tree)).abs() < 1e-10); + } + } + } +} + +#[test] +fn relaxed_dna_cache_and_checkpoint_keep_exact_model_identity() { + let data = alignment::parse(FASTA).unwrap(); + let patterns = data.partition_by_states(GapTreatment::Missing).unwrap(); + let settings = Settings { + conditioning: Conditioning::None, + tuning_delay: 10, + monophyly: vec![vec![0, 1]], + ..Settings::reference() + }; + let mut chain = Sampler::new(&patterns, &settings, 932).unwrap(); + for i in 0..1000 { + chain.step(); + if i % 20 == 0 { + assert!((chain.posterior().total() - chain.recompute().unwrap().total()).abs() < 1e-10); + } + } + let checkpoint = chain.checkpoint(&settings).unwrap(); + let mut resumed = Sampler::resume(&patterns, &settings, &checkpoint).unwrap(); + for _ in 0..500 { + assert_eq!(chain.step(), resumed.step()); + assert_eq!(chain.posterior(), resumed.posterior()); + assert_eq!(chain.tree(), resumed.tree()); + assert_eq!(chain.rates(), resumed.rates()); + } + let standard = + nexus::parse(&NEXUS.replace("DATATYPE=DNA", "DATATYPE=STANDARD SYMBOLS=\"ACGTRYN\"")) + .unwrap(); + let other = standard + .compress(std::slice::from_ref(&(0..12)), GapTreatment::Missing) + .unwrap(); + assert!(Sampler::resume(&other, &settings, &checkpoint).is_err()); +} + +#[test] +fn predictive_jc69_simulation_preserves_identity_and_expected_frequencies() { + let sequence = "A".repeat(5000); + let data = alignment::parse(&format!(">A\n{sequence}\n>B\n{sequence}\n")).unwrap(); + let patterns = data.partition_by_states(GapTreatment::Reject).unwrap(); + let design = Design::new(&data, &patterns, GapTreatment::Reject, Conditioning::None).unwrap(); + let tree = ladder(2, 0.25); + let simulated = design + .simulate(&tree, &RateVariation::default(), 82, 1, &|| false) + .unwrap(); + assert_eq!(simulated.data_type(), DataType::Dna); + let mut counts = [0; 4]; + let mut same = 0; + for site in 0..5000 { + let Cell::State(state) = simulated.rows()[0][site] else { + panic!("non-base") + }; + counts[state] += 1; + same += usize::from(simulated.rows()[0][site] == simulated.rows()[1][site]); + } + for count in counts { + assert!((count as f64 / 5000.0 - 0.25).abs() < 0.025); + } + let expected = 0.25 + 0.75 * (-4.0f64 * 0.5 / 3.0).exp(); + assert!((same as f64 / 5000.0 - expected).abs() < 0.025); + let text = rove::predictive::to_nexus(&simulated); + assert!(text.contains("DATATYPE=DNA")); + assert_eq!(nexus::parse(&text).unwrap(), simulated); +} diff --git a/tests/dna_cli.rs b/tests/dna_cli.rs new file mode 100644 index 0000000..5c64397 --- /dev/null +++ b/tests/dna_cli.rs @@ -0,0 +1,175 @@ +use serde_json::Value; +use std::fs; +use std::path::Path; +use std::process::Command; + +const BIN: &str = env!("CARGO_BIN_EXE_rove"); + +#[test] +fn dna_defaults_are_recorded_and_morphological_options_are_rejected() { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("dna-cli"); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let matrix = root.join("matrix.fasta"); + fs::write( + &matrix, + include_str!("../fixtures/validation/dna/matrix.fasta"), + ) + .unwrap(); + let sample = |name: &str, extra: &[&str]| { + Command::new(BIN) + .arg("sample") + .arg(&matrix) + .arg("--output") + .arg(root.join(name)) + .args([ + "--seed", + "42", + "--steps", + "200", + "--sample-every", + "10", + "--gaps", + "missing", + ]) + .args(extra) + .output() + .unwrap() + }; + let valid = sample("run", &["--monophyly", "Alpha_one,Beta_two"]); + assert!( + valid.status.success(), + "{}", + String::from_utf8_lossy(&valid.stderr) + ); + let record: Value = + serde_json::from_slice(&fs::read(root.join("run/run.json")).unwrap()).unwrap(); + assert_eq!(record["model"]["data_type"], "dna"); + assert_eq!(record["model"]["substitution_model"], "jc69"); + assert_eq!(record["model"]["conditioning"], "none (JC69)"); + assert_eq!(record["model"]["partitioning"], "declared"); + assert_eq!(record["model"]["partitions"][0]["states"], 4); + assert_eq!(record["model"]["monophyly"][0][0], "Alpha one"); + for options in [ + ["--conditioning", "variable"], + ["--conditioning", "informative"], + ["--partitioning", "observed"], + ["--partitioning", "labels"], + ] { + let rejected = sample("invalid", &options); + assert!(!rejected.status.success(), "{options:?}"); + assert!(!root.join("invalid").exists()); + } + let report = Command::new(BIN) + .arg("inspect") + .arg(&matrix) + .args(["--gaps", "missing"]) + .output() + .unwrap(); + assert!(report.status.success()); + let report: Value = serde_json::from_slice(&report.stdout).unwrap(); + assert_eq!(report["data_type"], "dna"); + assert_eq!(report["input_format"], "fasta"); + assert!(report["sampler_error"].is_null()); + + let destination = root.join("export"); + let export = Command::new(BIN) + .arg("export-run") + .arg(root.join("run")) + .arg("--output") + .arg(&destination) + .arg("--include-matrix") + .arg(&matrix) + .output() + .unwrap(); + assert!( + export.status.success(), + "{}", + String::from_utf8_lossy(&export.stderr) + ); + assert_eq!( + fs::read(destination.join("matrix.fasta")).unwrap(), + fs::read(matrix).unwrap() + ); + let exported: Value = + serde_json::from_slice(&fs::read(destination.join("run/run.json")).unwrap()).unwrap(); + assert_eq!(exported["model"], record["model"]); +} + +#[test] +fn fasta_predictive_source_copies_respect_export_inclusion() { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("dna-predict-export"); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let matrix = root.join("complete.fasta"); + fs::write( + &matrix, + include_str!("../fixtures/validation/dna/complete.fasta"), + ) + .unwrap(); + let run = root.join("run"); + let sample = Command::new(BIN) + .arg("sample") + .arg(&matrix) + .arg("--output") + .arg(&run) + .args(["--seed", "42", "--steps", "200", "--sample-every", "10"]) + .output() + .unwrap(); + assert!( + sample.status.success(), + "{}", + String::from_utf8_lossy(&sample.stderr) + ); + fs::create_dir(run.join("predictions")).unwrap(); + let prediction = run.join("predictions/check"); + let check = Command::new(BIN) + .arg("predict") + .arg(&run) + .arg("--matrix") + .arg(&matrix) + .arg("--output") + .arg(&prediction) + .args(["--replicates", "2", "--seed", "3", "--burnin-percent", "10"]) + .output() + .unwrap(); + assert!( + check.status.success(), + "{}", + String::from_utf8_lossy(&check.stderr) + ); + assert_eq!( + fs::read(prediction.join("source/matrix.fasta")).unwrap(), + fs::read(&matrix).unwrap() + ); + for include in [false, true] { + let destination = root.join(format!("export-{include}")); + let mut command = Command::new(BIN); + command + .arg("export-run") + .arg(&run) + .arg("--output") + .arg(&destination); + if include { + command.arg("--include-matrix").arg(&matrix); + } + let result = command.output().unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + assert_eq!(destination.join("matrix.fasta").exists(), include); + assert!( + !destination + .join("run/predictions/check/source/matrix.fasta") + .exists() + ); + assert!( + destination + .join("run/predictions/check/matrices/replicate-00001.nex") + .exists() + ); + } + assert!(prediction.join("source/matrix.fasta").exists()); +} 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/mixed.rs b/tests/mixed.rs new file mode 100644 index 0000000..26eefb9 --- /dev/null +++ b/tests/mixed.rs @@ -0,0 +1,336 @@ +use rove::{ + alignment, + data::{DataType, GapTreatment}, + mcmc::{Conditioning, Move, RelativeRate, Sampler, Settings}, + mixed, + predictive::Design, + tree::Tree, +}; +const MORPH: &str = include_str!("../fixtures/validation/mixed/morphology.nex"); +const DNA: &str = include_str!("../fixtures/validation/dna/complete.fasta"); +fn input(morph: &str, dna: &str, missing: &str) -> String { + mixed::manifest(("morphology.nex", morph), ("dna.fasta", dna), missing).unwrap() +} +fn ladder(step: f64) -> Tree { + Tree::new( + vec![ + None, + None, + None, + None, + None, + Some((0, 1)), + Some((5, 2)), + Some((6, 3)), + Some((7, 4)), + ], + vec![ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + step, + 2.0 * step, + 3.0 * step, + 4.0 * step, + ], + ) + .unwrap() +} +#[test] +fn sources_match_names_preserve_blocks_and_validate_fingerprints() { + let text = input(MORPH, DNA, "reject"); + let data = alignment::parse(&text).unwrap(); + assert_eq!(data.data_type(), DataType::Mixed); + assert_eq!(data.character_count(), 18); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0].data_type(), DataType::Standard); + assert_eq!(parts[1].data_type(), DataType::Dna); + assert_eq!(parts[1].sites(), &(6..18).collect::>()); + assert_eq!(parts[1].symbols(), ['A', 'C', 'G', 'T']); + let mut json: serde_json::Value = serde_json::from_str(&text).unwrap(); + json["sources"][0]["content"] = serde_json::json!(MORPH.replace("010101", "110101")); + assert!(alignment::parse(&json.to_string()).is_err()); + let reversed = DNA + .trim() + .split('>') + .filter(|x| !x.is_empty()) + .rev() + .map(|s| format!(">{s}\n")) + .collect::(); + let reordered = alignment::parse(&input(MORPH, &reversed, "reject")).unwrap(); + assert_eq!(data.rows(), reordered.rows()); + let missing = DNA.split(">Epsilon_five").next().unwrap().to_owned(); + assert!(mixed::manifest(("m.nex", MORPH), ("d.fa", &missing), "reject").is_err()); + let union = alignment::parse(&input(MORPH, &missing, "missing")).unwrap(); + assert_eq!( + union.mixed_metadata().unwrap().sources[1].missing_taxa, + ["Epsilon five"] + ); + assert!( + union.rows()[4][6..] + .iter() + .all(|c| matches!(c, rove::data::Cell::Missing)) + ); + let wrong = DNA.replace("Alpha_one", "alpha_one"); + assert!(mixed::manifest(("m.nex", MORPH), ("d.fa", &wrong), "missing").is_err()); + assert!(Sampler::new(&parts, &Settings::default(), 1).is_err()); +} +#[test] +fn joint_density_equals_independent_partitions_with_separate_conditioning() { + let data = alignment::parse(&input(MORPH, DNA, "reject")).unwrap(); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + let components = data.component_matrices(); + let morph = components[0] + .partition_by_states(GapTreatment::Reject) + .unwrap(); + let dna = components[1] + .partition_by_states(GapTreatment::Reject) + .unwrap(); + for conditioning in [ + Conditioning::None, + Conditioning::Variable, + Conditioning::Informative, + ] { + for ratio in [0.1, 1.0, 3.5] { + for reference in [false, true] { + let mut settings = if reference { + Settings::reference() + } else { + Settings::default() + }; + settings.conditioning = conditioning; + let a = Sampler::with_tree(&morph, &settings, ladder(0.1 * ratio), 7).unwrap(); + settings.conditioning = Conditioning::None; + let b = Sampler::with_tree(&dna, &settings, ladder(0.1), 7).unwrap(); + settings.conditioning = conditioning; + settings.set_morphology_rate(RelativeRate { + value: ratio, + log_sd: None, + }); + let joint = Sampler::with_tree(&parts, &settings, ladder(0.1), 7).unwrap(); + assert!( + (joint.posterior().likelihood + - a.posterior().likelihood + - b.posterior().likelihood) + .abs() + < 1e-10 + ); + } + } + } +} +#[test] +fn relative_rate_cache_and_exact_checkpoint_replay() { + let data = alignment::parse(&input(MORPH, DNA, "reject")).unwrap(); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + let mut settings = Settings::reference(); + settings.set_morphology_rate(RelativeRate { + value: 1.0, + log_sd: Some(0.8), + }); + settings.monophyly = vec![vec![0, 1]]; + let mut sampler = Sampler::new(&parts, &settings, 42).unwrap(); + for _ in 0..2000 { + sampler.step(); + assert!( + (sampler.posterior().likelihood - sampler.recompute().unwrap().likelihood).abs() < 1e-9 + ); + } + let saved = sampler.checkpoint(&settings).unwrap(); + let mut resumed = Sampler::resume(&parts, &settings, &saved).unwrap(); + for _ in 0..1000 { + assert_eq!(sampler.step(), resumed.step()); + assert_eq!(sampler.posterior(), resumed.posterior()); + assert_eq!(sampler.morphology_rate(), resumed.morphology_rate()); + } + settings.morphology_rate.as_mut().unwrap().log_sd = Some(0.9); + assert!(Sampler::resume(&parts, &settings, &saved).is_err()); +} +#[test] +fn normalized_relative_rate_prior_and_scale_stationarity() { + let data = alignment::parse(&input(MORPH, DNA, "reject")).unwrap(); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + let rate = RelativeRate { + value: 1.0, + log_sd: Some(0.7), + }; + let h = 12.0 / 10000.0; + let integral: f64 = (0..10000) + .map(|i| { + let z = -6.0 + (i as f64 + 0.5) * h; + (rate.log_density(z.exp()) + z).exp() * h + }) + .sum(); + assert!((integral - 1.0).abs() < 1e-12); + let mut settings = Settings { + sample_from_prior: true, + tuning: false, + ..Settings::default() + }; + settings.set_morphology_rate(rate); + settings.weights = vec![(Move::MorphologyRateScale, 1.0)]; + settings.tuning_values = vec![(Move::MorphologyRateScale, 0.35)]; + let mut sampler = Sampler::new(&parts, &settings, 78).unwrap(); + let (mut sum, mut squares) = (0.0, 0.0); + for i in 0..110000 { + sampler.step(); + if i >= 10000 { + let z = sampler.morphology_rate().unwrap().ln(); + sum += z; + squares += z * z; + } + } + assert!( + (sum / 100000.0).abs() < 0.035, + "mean={} second={}", + sum / 100000.0, + squares / 100000.0 + ); + assert!((squares / 100000.0 - 0.49).abs() < 0.035); +} +#[test] +fn prediction_preserves_models_masks_and_roundtrip_identity() { + let missing = DNA.split(">Epsilon_five").next().unwrap().to_owned(); + let data = alignment::parse(&input(MORPH, &missing, "missing")).unwrap(); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + let mut design = + Design::new(&data, &parts, GapTreatment::Reject, Conditioning::Variable).unwrap(); + design.set_morphology_rate(2.5).unwrap(); + let tree = ladder(0.05); + let rates = rove::rates::RateVariation::default(); + let simulated = design + .simulate(&tree, &rates, 23, 100000, &|| false) + .unwrap(); + let text = rove::predictive::to_input(&simulated); + let roundtrip = alignment::parse(&text).unwrap(); + assert_eq!(roundtrip.rows(), simulated.rows()); + assert_eq!( + roundtrip.mixed_metadata().unwrap().sources[1].missing_taxa, + ["Epsilon five"] + ); + assert_eq!( + design.compress(&roundtrip).unwrap()[1].symbols(), + ['A', 'C', 'G', 'T'] + ); + design + .statistics(&roundtrip, &tree, &rates, &|| false) + .unwrap(); +} + +#[test] +fn joint_states_match_pinned_beast_with_each_ascertainment_model() { + let data = alignment::parse(&input(MORPH, DNA, "reject")).unwrap(); + let parts = data.partition_by_states(GapTreatment::Reject).unwrap(); + for line in include_str!("../fixtures/validation/mixed/beast-2.7.8.tsv") + .lines() + .skip(1) + { + let values: Vec = line.split('\t').map(|v| v.parse().unwrap()).collect(); + let conditioning = [ + Conditioning::None, + Conditioning::Variable, + Conditioning::Informative, + ][values[2] as usize]; + for backend in rove::Backend::ALL.into_iter().filter(|b| b.is_available()) { + let mut settings = Settings { + conditioning, + backend, + gamma_shape: (values[1] == 4.0).then_some(0.7), + ..Settings::default() + }; + if settings.gamma_shape.is_some() { + settings.weights.push((Move::GammaShapeScale, 3.0)); + } + settings.set_morphology_rate(RelativeRate { + value: values[3], + log_sd: None, + }); + let sampler = Sampler::with_tree(&parts, &settings, ladder(values[0]), 42).unwrap(); + let error = (sampler.posterior().likelihood - values[6]).abs(); + assert!(error < 1e-7, "{line}: error={error}"); + } + } +} + +#[test] +fn mixed_multistate_ordering_labels_and_iupac_keep_source_semantics() { + let morph = "#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=3; FORMAT SYMBOLS=\"0123\"; STATELABELS 1 absent present, 2 zero one two three, 3 zero one two; MATRIX A 000 B 130 C 032 D 132; END; BEGIN ASSUMPTIONS; TYPESET * test = ORD: 3; END;"; + let dna = ">D\nAAAA\n>C\nCCCC\n>B\nGGGG\n>A\nTTTT\n"; + let matrix = alignment::parse(&input(morph, dna, "reject")).unwrap(); + for mode in [0, 1, 2] { + let parts = match mode { + 0 => matrix.partition_by_states(GapTreatment::Reject), + 1 => matrix.partition_by_labels(GapTreatment::Reject), + _ => matrix.compress(std::slice::from_ref(&(0..7)), GapTreatment::Reject), + } + .unwrap(); + let originals = match mode { + 0 => matrix.component_matrices()[0].partition_by_states(GapTreatment::Reject), + 1 => matrix.component_matrices()[0].partition_by_labels(GapTreatment::Reject), + _ => matrix.component_matrices()[0] + .compress(std::slice::from_ref(&(0..3)), GapTreatment::Reject), + } + .unwrap(); + assert_eq!(&parts[..parts.len() - 1], &originals); + let design = + Design::new(&matrix, &parts, GapTreatment::Reject, Conditioning::None).unwrap(); + let tree = Tree::new( + vec![ + None, + None, + None, + None, + Some((0, 1)), + Some((2, 3)), + Some((4, 5)), + ], + vec![0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.3], + ) + .unwrap(); + for seed in 0..16 { + let simulated = design + .simulate( + &tree, + &rove::rates::RateVariation::default(), + seed, + 1000, + &|| false, + ) + .unwrap(); + let frozen = design.compress(&simulated).unwrap(); + let layout = |patterns: &[rove::data::Patterns]| { + patterns + .iter() + .flat_map(|p| { + p.sites() + .iter() + .zip(p.state_symbols()) + .map(|(s, a)| (*s, (p.ordering(), a.clone(), p.data_type()))) + }) + .collect::>() + }; + assert_eq!(layout(&frozen), layout(&parts)); + } + } + let ambiguous = + alignment::parse(&input(morph, &dna.replace("TTTT", "RNY?"), "reject")).unwrap(); + let parts = ambiguous.partition_by_states(GapTreatment::Reject).unwrap(); + let mut settings = Settings::default(); + settings.set_morphology_rate(RelativeRate { + value: 1.0, + log_sd: None, + }); + assert!(Sampler::new(&parts, &settings, 1).is_ok()); + assert!( + Design::new( + &ambiguous, + &parts, + GapTreatment::Reject, + Conditioning::Variable + ) + .is_err() + ); +} diff --git a/tests/mixed_cli.rs b/tests/mixed_cli.rs new file mode 100644 index 0000000..2ee3c2f --- /dev/null +++ b/tests/mixed_cli.rs @@ -0,0 +1,153 @@ +use serde_json::Value; +use std::{fs, path::Path, process::Command}; +const BIN: &str = env!("CARGO_BIN_EXE_rove"); +#[test] +fn combine_is_explicit_self_contained_and_refuses_invalid_models_before_output() { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("mixed-cli"); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let morph = root.join("morph.nex"); + let dna = root.join("dna.fasta"); + let manifest = root.join("input.mixed.json"); + let morphology = include_str!("../fixtures/validation/mixed/morphology.nex"); + fs::write(&morph, morphology).unwrap(); + fs::write( + &dna, + include_str!("../fixtures/validation/dna/complete.fasta"), + ) + .unwrap(); + let combine = |output: &Path| { + Command::new(BIN) + .arg("combine") + .arg("--morphology") + .arg(&morph) + .arg("--dna") + .arg(&dna) + .arg("--output") + .arg(output) + .output() + .unwrap() + }; + assert!(combine(&manifest).status.success()); + assert!(!combine(&morph).status.success()); + assert_eq!(fs::read_to_string(&morph).unwrap(), morphology); + fs::remove_file(&morph).unwrap(); + fs::remove_file(&dna).unwrap(); + let inspect = Command::new(BIN) + .arg("inspect") + .arg(&manifest) + .output() + .unwrap(); + assert!(inspect.status.success()); + let report: Value = serde_json::from_slice(&inspect.stdout).unwrap(); + assert_eq!(report["data_type"], "mixed"); + assert_eq!(report["mixed"]["sources"][1]["name"], "dna.fasta"); + assert!(report["variable_error"].is_null()); + let sample = |name: &str, extra: &[&str]| { + Command::new(BIN) + .arg("sample") + .arg(&manifest) + .arg("--output") + .arg(root.join(name)) + .args(["--seed", "42", "--steps", "400", "--sample-every", "20"]) + .args(extra) + .output() + .unwrap() + }; + for args in [ + vec![], + vec!["--morphology-rate", "0"], + vec!["--morphology-rate", "NaN"], + vec!["--morphology-rate", "2", "--morphology-rate-log-sd", "1"], + vec![ + "--morphology-rate", + "2", + "--weight", + "morphology_rate_scale=1", + ], + ] { + let outcome = sample("invalid", &args); + assert!(!outcome.status.success(), "{args:?}"); + assert!(!root.join("invalid").exists()); + } + let run = sample( + "run", + &[ + "--morphology-rate", + "estimate", + "--morphology-rate-log-sd", + "0.7", + ], + ); + assert!( + run.status.success(), + "{}", + String::from_utf8_lossy(&run.stderr) + ); + let record: Value = + serde_json::from_slice(&fs::read(root.join("run/run.json")).unwrap()).unwrap(); + assert_eq!( + record["model"]["mixed_model"]["morphology_rate_prior"]["log_sd"], + 0.7 + ); + assert_eq!(record["input"]["mixed"], report["mixed"]); + let prediction = root.join("run/predictions/check"); + fs::create_dir_all(prediction.parent().unwrap()).unwrap(); + let outcome = Command::new(BIN) + .arg("predict") + .arg(root.join("run")) + .arg("--matrix") + .arg(&manifest) + .arg("--output") + .arg(&prediction) + .args([ + "--burnin-percent", + "10", + "--seed", + "21", + "--replicates", + "2", + ]) + .output() + .unwrap(); + assert!( + outcome.status.success(), + "{}", + String::from_utf8_lossy(&outcome.stderr) + ); + for include in [false, true] { + let output = root.join(format!("export-{include}")); + let mut command = Command::new(BIN); + command + .arg("export-run") + .arg(root.join("run")) + .arg("--output") + .arg(&output); + if include { + command.arg("--include-matrix").arg(&manifest); + } + let outcome = command.output().unwrap(); + assert!( + outcome.status.success(), + "{}", + String::from_utf8_lossy(&outcome.stderr) + ); + assert_eq!(output.join("matrix.mixed.json").exists(), include); + assert!( + !output + .join("run/predictions/check/source/matrix.mixed.json") + .exists() + ); + assert!( + output + .join("run/predictions/check/matrices/replicate-00001.mixed.json") + .exists() + ); + if include { + assert_eq!( + fs::read(output.join("matrix.mixed.json")).unwrap(), + fs::read(&manifest).unwrap() + ); + } + } +} diff --git a/tests/nexus.rs b/tests/nexus.rs index 666383b..6908fa6 100644 --- a/tests/nexus.rs +++ b/tests/nexus.rs @@ -342,7 +342,7 @@ fn malformed_data_produces_located_errors() { #[test] fn unsupported_semantics_are_rejected_instead_of_ignored() { for option in [ - "DATATYPE=DNA", + "DATATYPE=PROTEIN", "TOKENS", "TRANSPOSE", "NOLABELS", diff --git a/tests/rates.rs b/tests/rates.rs index fcd78a3..00348f4 100644 --- a/tests/rates.rs +++ b/tests/rates.rs @@ -121,6 +121,11 @@ fn invalid_rate_states_are_rejected() { ..Settings::default() }; assert!(Sampler::new(small(), &settings, 1).is_err()); + let settings = Settings { + weights: vec![(Move::NarrowExchangeRates, 1.0)], + ..Settings::default() + }; + assert!(Sampler::new(small(), &settings, 1).is_err()); } #[test] @@ -203,6 +208,7 @@ fn rate_moves_and_root_changes_restore_all_cached_values() { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 5.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); let mut chain = Sampler::new(&patterns, &settings, 29).unwrap(); let mut root_changes = 0; @@ -242,6 +248,7 @@ fn rate_moves_and_root_changes_restore_all_cached_values() { Move::NodeTimeRates, Move::RootTimeRates, Move::ClockSigmaRates, + Move::NarrowExchangeRates, ] { let operator = chain.operators().iter().find(|o| o.kind == kind).unwrap(); assert!( @@ -267,6 +274,7 @@ fn relaxed_clock_backends_give_identical_samples() { (Move::NodeTimeRates, 10.0), (Move::RootTimeRates, 5.0), (Move::ClockSigmaRates, 10.0), + (Move::NarrowExchangeRates, 10.0), ]); Sampler::new(&data, &settings, 21).unwrap() }) diff --git a/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/DnaStates.java b/tools/beast/DnaStates.java new file mode 100644 index 0000000..4fc74e8 --- /dev/null +++ b/tools/beast/DnaStates.java @@ -0,0 +1,59 @@ +import beast.base.evolution.alignment.Alignment; +import beast.base.evolution.alignment.Sequence; +import beast.base.evolution.branchratemodel.StrictClockModel; +import beast.base.evolution.likelihood.TreeLikelihood; +import beast.base.evolution.sitemodel.SiteModel; +import beast.base.evolution.substitutionmodel.JukesCantor; +import beast.base.evolution.tree.Node; +import beast.base.evolution.tree.Tree; +import beast.base.inference.parameter.RealParameter; +import java.io.PrintStream; +import java.util.ArrayList; + +/** Synthetic DNA likelihood states for pinned BEAST.base 2.7.8; no MCMC. */ +public class DnaStates { + public static void main(String[] args) throws Exception { + System.setProperty("java.only", "true"); + beast.pkgmgmt.PackageManager.loadExternalJars(); + String[] names = {"Alpha_one", "Beta_two", "Gamma_three", "Delta_four", "Epsilon_five"}; + String[] rows = {"AACGTRYN?-AC", "AATGTCATACGT", "ACCGTGGTAAGT", "AGCGTTACTCGT", "ATCGTCGTACGT"}; + var sequences = new ArrayList(); + for (int i=0; i(); + for (int bits=0;bits<32;++bits) { + int ones = Integer.bitCount(bits); + if (conditioning == 1 && (ones==0 || ones==5) || conditioning==2 && (ones<2 || ones>3)) excluded.add(bits); + } + var sequences = new ArrayList(); + for (int t=0;t<5;++t) { + var row = new StringBuilder(dna ? DNA[t] : MORPH[t]); + if (!dna) for (int bits:excluded) row.append((bits>>t)&1); + Sequence sequence = new Sequence(); + sequence.initByName("taxon",NAMES[t],"value",row.toString(),"totalcount",dna?4:2); + sequences.add(sequence); + } + Alignment alignment = new Alignment(); + if (dna) alignment.initByName("sequence",sequences,"dataType","nucleotide"); + else { + StandardData type = new StandardData(); type.initByName("nrOfStates",2); + alignment.initByName("sequence",sequences,"userDataType",type,"ascertained",conditioning>0, + "excludefrom",conditioning>0?6:0,"excludeto",conditioning>0?6+excluded.size():0); + } + return alignment; + } + static double likelihood(Alignment data, Tree tree, boolean dna, int categories, double ratio) throws Exception { + SubstitutionModel model; + if (dna) { JukesCantor jc=new JukesCantor();jc.initAndValidate();model=jc; } + else { LewisMK mk=new LewisMK();mk.initByName("stateNumber",2);model=mk; } + SiteModel site=new SiteModel();site.initByName("substModel",model,"gammaCategoryCount",categories,"shape",new RealParameter("0.7")); + StrictClockModel clock=new StrictClockModel();clock.initByName("clock.rate",new RealParameter(Double.toString(ratio))); + TreeLikelihood likelihood=new TreeLikelihood();likelihood.initByName("tree",tree,"data",data,"siteModel",site,"branchRateModel",clock,"useAmbiguities",true,"scaling","always"); + return likelihood.calculateLogP(); + } + public static void main(String[] args) throws Exception { + System.setProperty("java.only","true");beast.pkgmgmt.PackageManager.loadExternalJars(); + try(PrintStream out=new PrintStream(args[0])) { + out.println("height_step\tcategories\tconditioning\tmorphology_rate\tmorphology_log_likelihood\tdna_log_likelihood\tjoint_log_likelihood"); + for(double step:new double[]{0.01,0.2}) for(int categories:new int[]{1,4}) for(int conditioning=0;conditioning<3;++conditioning) for(double ratio:new double[]{0.2,1.0,3.5}) { + Node[] nodes=new Node[9]; + for(int i=0;i<9;++i) {nodes[i]=new Node();nodes[i].setNr(i);nodes[i].setHeight(i<5?0:(i-4)*step);if(i<5)nodes[i].setID(NAMES[i]);} + nodes[5].addChild(nodes[0]);nodes[5].addChild(nodes[1]); + for(int i=6;i<9;++i){nodes[i].addChild(nodes[i-1]);nodes[i].addChild(nodes[i-4]);} + Tree tree=new Tree(nodes[8]); + double morph=likelihood(data(false,conditioning),tree,false,categories,ratio); + double dna=likelihood(data(true,0),tree,true,categories,1.0); + out.println(step+"\t"+categories+"\t"+conditioning+"\t"+ratio+"\t"+morph+"\t"+dna+"\t"+(morph+dna)); + } + } + } +} 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