diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index 3fd6cf3..4ec6790 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -23,6 +23,9 @@ struct MatrixReport: Decodable, Sendable { let unobservedCharacters: [Int]? let observationExamples: [ObservationExample]? let stateLabels: [[String]]? + var dataType: String? = nil + var inputFormat: String? = nil + var isDNA: Bool { dataType == "dna" } var allTaxa: [String] { taxonNames ?? taxa } var missingPercent: Double { @@ -33,7 +36,8 @@ 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"].contains(value.dataType ?? "standard"), + value.taxonCount > 0, value.characterCount > 0, value.cells.count == value.taxa.count, !value.cells.isEmpty, value.cells.allSatisfy({ $0.count == value.characterLabels.count }) else { @@ -245,6 +249,7 @@ enum ProposalSchedule { } struct AnalysisSettings: Codable, Equatable, Sendable { + var dataType = "standard" var dating = DatingSettings() var treePrior = "birth-death" var birthRateUpper = "1000" @@ -285,7 +290,8 @@ struct AnalysisSettings: Codable, Equatable, Sendable { } private enum CodingKeys: String, CodingKey { - case dating, treePrior, birthRateUpper, clock, clockSigmaShape, clockSigmaScale, conditioning, + 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, @@ -294,6 +300,7 @@ 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" 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" @@ -367,14 +374,26 @@ struct AnalysisSettings: Codable, Equatable, Sendable { return value } + var characterModelLabel: String { + if dataType == "dna" { return "DNA · JC69" } + return conditioning == "variable" + ? "Mkv · variable characters" + : conditioning == "informative" ? "Mkparsinf · informative characters" : "Mk · all characters" + } + var validationError: String? { - guard ["birth-death", "yule"].contains(treePrior), + guard ["standard", "dna"].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 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." @@ -509,18 +528,20 @@ struct AnalysisDraft: Codable, Sendable { monophyly: [[String]] = [], outgroup: String? = nil ) { formatVersion = - 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))) + 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 @@ -544,7 +565,8 @@ struct AnalysisDraft: Codable, Sendable { } func validate() throws { - guard (1...10).contains(formatVersion), + guard (1...11).contains(formatVersion), + formatVersion >= 11 || settings.dataType != "dna", formatVersion >= 10 || settings.treePrior != "yule", formatVersion >= 9 || !settings.usesJointExchange, formatVersion >= 8 || settings.partitioning != "labels", diff --git a/apps/macos/Sources/RoveApp/CommandLineImport.swift b/apps/macos/Sources/RoveApp/CommandLineImport.swift index 7deebfe..843f877 100644 --- a/apps/macos/Sources/RoveApp/CommandLineImport.swift +++ b/apps/macos/Sources/RoveApp/CommandLineImport.swift @@ -64,12 +64,12 @@ 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 + guard record.model.dataModelMatches(value) else { throw RunFailure.invalidCompletion } value.treePrior = record.model.treePriorKind ?? "birth-death" if value.treePrior == "yule" { guard let prior = record.model.birthRatePriorParameters, prior.valid else { diff --git a/apps/macos/Sources/RoveApp/HistoryView.swift b/apps/macos/Sources/RoveApp/HistoryView.swift index fcfe4da..6187a03 100644 --- a/apps/macos/Sources/RoveApp/HistoryView.swift +++ b/apps/macos/Sources/RoveApp/HistoryView.swift @@ -285,10 +285,7 @@ private struct HistoryDetail: View { 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( diff --git a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift index 1cecf22..dfaf545 100644 --- a/apps/macos/Sources/RoveApp/MarginalLikelihood.swift +++ b/apps/macos/Sources/RoveApp/MarginalLikelihood.swift @@ -105,8 +105,8 @@ 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.model.partitioning ?? "declared") == settings.partitioning && record.model.dating == dating && record.model.treePriorMatches(settings) && (settings.clock != "reference" diff --git a/apps/macos/Sources/RoveApp/MatrixView.swift b/apps/macos/Sources/RoveApp/MatrixView.swift index 41bd428..9847f6b 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,37 +45,42 @@ 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: 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." + 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) - .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) } + .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 { @@ -85,7 +92,9 @@ 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.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) @@ -151,14 +160,18 @@ 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) 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/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index c736c20..0296e58 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -1174,3 +1174,24 @@ "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"; 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 96ef39f..d43ba98 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -1174,3 +1174,24 @@ "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"; diff --git a/apps/macos/Sources/RoveApp/RootView.swift b/apps/macos/Sources/RoveApp/RootView.swift index dd7245c..59ec153 100644 --- a/apps/macos/Sources/RoveApp/RootView.swift +++ b/apps/macos/Sources/RoveApp/RootView.swift @@ -125,7 +125,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 +158,8 @@ struct RootView: View { } else { Text( strings( - "Declared states: %@ · morphological data", + 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/RunComparison.swift b/apps/macos/Sources/RoveApp/RunComparison.swift index b4b9093..c1aa0e1 100644 --- a/apps/macos/Sources/RoveApp/RunComparison.swift +++ b/apps/macos/Sources/RoveApp/RunComparison.swift @@ -151,6 +151,7 @@ final class RunComparisonModel { 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.settings.treePrior != "yule" || x.settings.yuleBirthRateUpper == y.settings.yuleBirthRateUpper, x.settings.sampleFromPrior == y.settings.sampleFromPrior, diff --git a/apps/macos/Sources/RoveApp/RunRecord.swift b/apps/macos/Sources/RoveApp/RunRecord.swift index 416d6b5..fd4cd76 100644 --- a/apps/macos/Sources/RoveApp/RunRecord.swift +++ b/apps/macos/Sources/RoveApp/RunRecord.swift @@ -48,6 +48,21 @@ 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 resolvedDataType: String { dataType ?? "standard" } + + func dataModelMatches(_ settings: AnalysisSettings) -> Bool { + resolvedDataType == settings.dataType + && (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 @@ -78,7 +93,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" @@ -124,12 +140,13 @@ 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.treePriorMatches(draft.settings) + && model.dataModelMatches(draft.settings) && input.gaps == (draft.settings.gapsAsMissing ? "missing" : "reject") && model.preset == draft.settings.clock && (model.preset != "reference" diff --git a/apps/macos/Sources/RoveApp/SetupView.swift b/apps/macos/Sources/RoveApp/SetupView.swift index 1b46e0a..2279a28 100644 --- a/apps/macos/Sources/RoveApp/SetupView.swift +++ b/apps/macos/Sources/RoveApp/SetupView.swift @@ -42,51 +42,56 @@ struct SetupView: View { 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 == "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 { @@ -318,16 +323,15 @@ 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 let partitions = report.partitions { row( "Alphabet choice", AnalysisSettings.partitioningLabel(workspace.settings.partitioning) @@ -345,13 +349,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/TreePriorView.swift b/apps/macos/Sources/RoveApp/TreePriorView.swift index 7d339a3..4e74122 100644 --- a/apps/macos/Sources/RoveApp/TreePriorView.swift +++ b/apps/macos/Sources/RoveApp/TreePriorView.swift @@ -7,6 +7,11 @@ extension AnalysisSettings { } 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:)) ?? "—") diff --git a/apps/macos/Sources/RoveApp/WelcomeView.swift b/apps/macos/Sources/RoveApp/WelcomeView.swift index 9fe0139..1ac988a 100644 --- a/apps/macos/Sources/RoveApp/WelcomeView.swift +++ b/apps/macos/Sources/RoveApp/WelcomeView.swift @@ -57,11 +57,11 @@ 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(".nexus · .fasta").font(.system(size: 10, design: .monospaced)) Text(strings("· Morphological characters")).font(.system(size: 10)) }.foregroundStyle(Lab.muted).padding(.top, 7) } @@ -102,7 +102,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 5314ea8..eb8efc9 100644 --- a/apps/macos/Sources/RoveApp/Workspace.swift +++ b/apps/macos/Sources/RoveApp/Workspace.swift @@ -128,8 +128,9 @@ final class Workspace { 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,11 +157,11 @@ 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 { @@ -181,8 +182,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 } @@ -414,6 +423,9 @@ 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.") + } try draft.validateTaxa(imported.allTaxa) guard importID == id else { return } run = nil 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/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 64fa5e4..ac958d2 100644 --- a/apps/macos/Tests/RoveAppTests/PreviewTests.swift +++ b/apps/macos/Tests/RoveAppTests/PreviewTests.swift @@ -5,6 +5,48 @@ import Testing @testable import RoveApp struct PreviewTests { + @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() diff --git a/docs/.vitepress/config.mjs b/docs/.vitepress/config.mjs index 8d5999c..dd0beea 100644 --- a/docs/.vitepress/config.mjs +++ b/docs/.vitepress/config.mjs @@ -35,6 +35,7 @@ const locales = { referenceModel: 'The reference model', treePriors: 'Tree priors', nexus: 'Reading NEXUS', + dna: 'Aligned DNA · JC69', fixtures: 'Synthetic matrices', outline: 'On this page', edit: 'Edit this page on GitHub', @@ -69,6 +70,7 @@ const locales = { referenceModel: 'O modelo de referência', treePriors: 'Priors de árvore', nexus: 'Lendo NEXUS', + dna: 'DNA alinhado · JC69', fixtures: 'Matrizes sintéticas', outline: 'Nesta página', edit: 'Editar esta página no GitHub', @@ -120,6 +122,7 @@ const locales = { referenceModel: 'El modelo de referencia', treePriors: 'Priors de árbol', nexus: 'Lectura de NEXUS', + dna: 'ADN alineado · JC69', fixtures: 'Matrices sintéticas', outline: 'En esta página', edit: 'Editar esta página en GitHub', @@ -171,6 +174,7 @@ const locales = { referenceModel: '参考模型', treePriors: '树先验', nexus: '读取 NEXUS', + dna: '已比对 DNA · JC69', fixtures: '合成矩阵', outline: '本页目录', edit: '在 GitHub 上编辑此页', @@ -200,7 +204,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, fixtures, outline, edit, message, copyright, ...labels } = ui return { nav: [ { text: guide, link: `${prefix}/guide/`, activeMatch: `${prefix}/guide/(?!roadmap)` }, @@ -232,6 +236,7 @@ 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: 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..ec70fee --- /dev/null +++ b/docs/es/guide/dna.md @@ -0,0 +1,59 @@ +--- +description: "ADN alineado en NEXUS y FASTA bajo JC69, con ambigüedades y tratamiento explícito de gaps." +--- + +# ADN alineado con JC69 + +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, +GTR y análisis mixto quedan fuera de esta entrega. + +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/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 426c40d..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. diff --git a/docs/guide/dna.md b/docs/guide/dna.md new file mode 100644 index 0000000..f858e9b --- /dev/null +++ b/docs/guide/dna.md @@ -0,0 +1,62 @@ +--- +description: "Aligned NEXUS and FASTA DNA under JC69, with explicit ambiguity and gap handling." +--- + +# Aligned DNA with JC69 + +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, GTR and +mixed-data inference are outside this delivery. + +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/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 d2c394c..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 diff --git a/docs/pt-BR/guide/dna.md b/docs/pt-BR/guide/dna.md new file mode 100644 index 0000000..c68b3f4 --- /dev/null +++ b/docs/pt-BR/guide/dna.md @@ -0,0 +1,62 @@ +--- +description: "DNA alinhado em NEXUS e FASTA com JC69, ambiguidades e tratamento explícito de gaps." +--- + +# DNA alinhado com JC69 + +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, GTR e inferência mista não fazem parte desta entrega. + +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/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 a6b6fa3..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 diff --git a/docs/zh-CN/guide/dna.md b/docs/zh-CN/guide/dna.md new file mode 100644 index 0000000..e40cae0 --- /dev/null +++ b/docs/zh-CN/guide/dna.md @@ -0,0 +1,46 @@ +--- +description: "使用 JC69 分析 NEXUS 和 FASTA 中已比对的 DNA,明确处理模糊碱基与缺口。" +--- + +# 使用 JC69 分析已比对 DNA + +在应用中打开 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 或混合数据推断。 + +格式 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/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 9bb68a5..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` 保留先前的单速率类别、严格时钟配置。两个配置都可用 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/src/alignment.rs b/src/alignment.rs new file mode 100644 index 0000000..8b43bda --- /dev/null +++ b/src/alignment.rs @@ -0,0 +1,146 @@ +//! 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 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, + 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 index ee10441..aeae64a 100644 --- a/src/bin/rove/assessment.rs +++ b/src/bin/rove/assessment.rs @@ -368,10 +368,12 @@ pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { let mut omitted_source_matrices = Vec::new(); for (relative, hash) in &before { check(&cancel)?; - // Predictive checks retain an exact original in source/matrix.nex. + // 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") + if relative + .file_name() + .is_some_and(|n| n == "matrix.nex" || n == "matrix.fasta") && relative .parent() .and_then(Path::file_name) @@ -393,14 +395,19 @@ pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { if report["input"]["sha256"] != hash { return Err("included matrix does not match the run fingerprint".into()); } - let target = output.join("matrix.nex"); + let raw = fs::read(source)?; + let name = 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":"matrix.nex","sha256":hash,"bytes":fs::metadata(target)?.len()}), - ); + 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( diff --git a/src/bin/rove/inspect.rs b/src/bin/rove/inspect.rs index 71424fe..e425d3a 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}; @@ -127,7 +126,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 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 +238,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 2fe92c5..26e5641 100644 --- a/src/bin/rove/main.rs +++ b/src/bin/rove/main.rs @@ -28,7 +28,7 @@ use rove::mcmc::output::{TraceWriter, TreeWriter, is_plain_label}; use rove::mcmc::{Conditioning, Move, Sampler, Settings}; use rove::rates::SigmaPrior; use rove::speciation::TreePrior; -use rove::{Backend, nexus}; +use rove::{Backend, alignment}; const USAGE: &str = "usage: rove sample --output --seed --steps --sample-every @@ -102,6 +102,8 @@ struct Options { gaps: GapTreatment, partitioning: Partitioning, conditioning: Conditioning, + conditioning_explicit: bool, + partitioning_explicit: bool, reference_model: bool, clock_sigma_prior: SigmaPrior, tree_prior: TreePrior, @@ -386,6 +388,8 @@ fn parse_options(arguments: &[String]) -> Result { gaps, partitioning, conditioning, + conditioning_explicit: seen.contains("--conditioning"), + partitioning_explicit: seen.contains("--partitioning"), reference_model, clock_sigma_prior, tree_prior, @@ -626,7 +630,24 @@ 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; + } let patterns = options.partitioning.compress(&data, options.gaps)?; let taxa = data.taxa(); if let Some(name) = taxa.iter().find(|name| !is_plain_label(name)) { @@ -643,7 +664,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); } @@ -717,9 +739,13 @@ 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()); @@ -728,22 +754,26 @@ fn model_json( ("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 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", @@ -886,6 +916,12 @@ fn model_json( Json::List(settings.monophyly.iter().map(|c| names(c)).collect()), ), ]; + 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")), 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 c594653..33a2875 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()), @@ -334,7 +340,12 @@ 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 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"), diff --git a/src/data.rs b/src/data.rs index e740d5d..723c8e7 100644 --- a/src/data.rs +++ b/src/data.rs @@ -1,10 +1,25 @@ -//! 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, +} + +impl DataType { + pub fn name(self) -> &'static str { + match self { + Self::Standard => "standard", + Self::Dna => "dna", + } + } +} + /// State indices refer to the matrix's declared alphabet, including unobserved states. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Cell { @@ -17,6 +32,7 @@ pub enum Cell { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Matrix { + pub(crate) data_type: DataType, pub(crate) taxa: Vec, pub(crate) symbols: Vec, pub(crate) rows: Vec>, @@ -41,11 +57,13 @@ pub enum CompressionError { Gap { taxon: String, site: usize }, Polymorphism { taxon: String, site: usize }, OrderedAlphabet { site: usize }, + DnaModel, } 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 +107,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 +125,10 @@ pub struct CharacterSet { } impl Matrix { + pub fn data_type(&self) -> DataType { + self.data_type + } + pub fn taxa(&self) -> &[String] { &self.taxa } @@ -184,6 +207,9 @@ impl Matrix { &self, gaps: GapTreatment, ) -> Result, CompressionError> { + 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 +258,9 @@ impl Matrix { &self, gaps: GapTreatment, ) -> Result, CompressionError> { + 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() { @@ -260,6 +289,9 @@ impl Matrix { 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 +349,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 +443,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 +459,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/lib.rs b/src/lib.rs index c80385f..93fe8aa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod alignment; pub mod ascertainment; mod checkpoint; pub mod data; diff --git a/src/mcmc/checkpoint.rs b/src/mcmc/checkpoint.rs index 080bb09..32090d0 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"ROVECP07"; +const MAGIC: &[u8; 8] = b"ROVECP08"; impl Sampler { /// Saves a between-proposals state, including the live likelihood buffers. @@ -256,6 +256,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), diff --git a/src/mcmc/mod.rs b/src/mcmc/mod.rs index ad2adf5..63610b0 100644 --- a/src/mcmc/mod.rs +++ b/src/mcmc/mod.rs @@ -34,6 +34,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 +62,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) => { @@ -580,6 +581,15 @@ impl Sampler { "Yule requires contemporaneous tips without fossil dating or calibrations".into(), )); } + if patterns + .iter() + .any(|p| p.data_type() == crate::data::DataType::Dna) + && settings.conditioning != Conditioning::None + { + return Err(Error::Model( + "DNA JC69 requires unconditioned aligned sites".into(), + )); + } if patterns.is_empty() || patterns.iter().any(|p| p.tip_partials().len() != tips) { return Err(Error::Partitions); } 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..e34518d 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,7 @@ fn parse_data( (names, rows) }; let mut data = Matrix { + data_type: fmt.data_type, taxa: names, rows, symbols: fmt.symbols.clone(), diff --git a/src/predictive/mod.rs b/src/predictive/mod.rs index 6bf41bf..88f2713 100644 --- a/src/predictive/mod.rs +++ b/src/predictive/mod.rs @@ -40,6 +40,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 { @@ -101,7 +106,8 @@ impl Design { } pub fn compress(&self, matrix: &Matrix) -> Result> { - if matrix.taxa() != self.original.taxa() + if 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() @@ -352,9 +358,14 @@ pub fn to_nexus(matrix: &Matrix) -> 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/tests/checkpoint.rs b/tests/checkpoint.rs index 9349e7d..ea191db 100644 --- a/tests/checkpoint.rs +++ b/tests/checkpoint.rs @@ -358,3 +358,59 @@ 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)) + ); + } + } + } + } +} 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/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/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