diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index ec71ca3..96ac878 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -19,6 +19,10 @@ struct MatrixReport: Decodable, Sendable { let characterLabels: [String?] let cells: [[String]] let partitions: [CharacterPartition]? + let constantCharacters: [Int]? + let unobservedCharacters: [Int]? + let observationExamples: [ObservationExample]? + let stateLabels: [[String]]? var allTaxa: [String] { taxonNames ?? taxa } var missingPercent: Double { @@ -39,6 +43,13 @@ struct MatrixReport: Decodable, Sendable { } } +struct ObservationExample: Decodable, Sendable { + let taxon: String + let character: Int + let kind: String + let value: String +} + struct CharacterPartition: Decodable, Sendable { enum Ordering: String, Decodable, Sendable { case ordered, unordered } let ordering: Ordering? @@ -248,6 +259,14 @@ struct AnalysisSettings: Codable, Equatable, Sendable { init() {} + static func partitioningLabel(_ value: String) -> String { + switch value { + case "observed": "By observed states" + case "labels": "Complete state labels" + default: "Declared alphabet" + } + } + private enum CodingKeys: String, CodingKey { case dating, clock, clockSigmaShape, clockSigmaScale, conditioning, partitioning, steps, sampleEvery, seed, gapsAsMissing, chains, comparisonBurnin, backend, printEvery, @@ -320,7 +339,7 @@ struct AnalysisSettings: Codable, Equatable, Sendable { var validationError: String? { guard ["strict", "reference"].contains(clock), ["variable", "informative", "none"].contains(conditioning), - ["observed", "declared"].contains(partitioning) + ["observed", "declared", "labels"].contains(partitioning) else { return "This setup uses an unsupported model." } @@ -443,12 +462,14 @@ struct AnalysisDraft: Codable, Sendable { monophyly: [[String]] = [], outgroup: String? = nil ) { formatVersion = - settings.usesExecutionOptions - ? 7 - : settings.usesCustomSigmaPrior - ? 6 - : (settings.usesAdvancedOptions - ? 5 : (settings.dating.estimatesProcess ? 4 : (settings.dating.enabled ? 3 : 2))) + 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 @@ -472,7 +493,8 @@ struct AnalysisDraft: Codable, Sendable { } func validate() throws { - guard (1...7).contains(formatVersion), + guard (1...8).contains(formatVersion), + formatVersion >= 8 || settings.partitioning != "labels", formatVersion >= 7 || !settings.usesExecutionOptions, formatVersion >= 6 || !settings.usesCustomSigmaPrior, formatVersion >= 5 || !settings.usesAdvancedOptions, diff --git a/apps/macos/Sources/RoveApp/HistoryView.swift b/apps/macos/Sources/RoveApp/HistoryView.swift index e1c0be9..e922010 100644 --- a/apps/macos/Sources/RoveApp/HistoryView.swift +++ b/apps/macos/Sources/RoveApp/HistoryView.swift @@ -291,8 +291,7 @@ private struct HistoryDetail: View { field( "State partitions", strings( - draft.settings.partitioning == "observed" - ? "By observed states" : "Declared alphabet")) + AnalysisSettings.partitioningLabel(draft.settings.partitioning))) if entry.status != .modelSetup { field("Independent chains", String(draft.settings.chains)) field( diff --git a/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift b/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift index 0c1fd63..a1d8666 100644 --- a/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift +++ b/apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift @@ -189,8 +189,7 @@ struct MarginalLikelihoodView: View { + (model.clockSigmaPriorParameters ?? .reference).description(strings: strings) } if model.partitioning != own.record.model.partitioning { - let observed = model.partitioning == "observed" - text += " · " + strings(observed ? "By observed states" : "Declared alphabet") + text += " · " + strings(AnalysisSettings.partitioningLabel(model.partitioning ?? "declared")) } return text } diff --git a/apps/macos/Sources/RoveApp/MatrixView.swift b/apps/macos/Sources/RoveApp/MatrixView.swift index 1469b4d..53ae475 100644 --- a/apps/macos/Sources/RoveApp/MatrixView.swift +++ b/apps/macos/Sources/RoveApp/MatrixView.swift @@ -51,6 +51,7 @@ struct MatrixView: View { Picker(strings("State partitions"), selection: $workspace.settings.partitioning) { Text(strings("By observed states")).tag("observed") Text(strings("Declared alphabet")).tag("declared") + Text(strings("Complete state labels")).tag("labels") }.labelsHidden().frame(width: 210) .disabled(workspace.loading) .onChange(of: workspace.settings.partitioning) { workspace.reloadGapPolicy() } @@ -59,7 +60,9 @@ struct MatrixView: View { strings( workspace.settings.partitioning == "observed" ? "Characters are grouped by state count and ordering. Ordered characters keep intermediate states; binary alphabets keep both states." - : "Every character uses all states declared in SYMBOLS. Choose this only if they are possible for every character." + : 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) @@ -72,6 +75,31 @@ struct MatrixView: View { } } + if let constant = report.constantCharacters, !constant.isEmpty { + LabPanel { + VStack(alignment: .leading, spacing: 8) { + Text(strings("Characters with one observed state")).font( + .system(size: 13, weight: .semibold)) + Text(constant.map(String.init).joined(separator: ", ")) + .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)." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } + } + } + if let unobserved = report.unobservedCharacters, !unobserved.isEmpty { + Text( + strings( + "Characters without observed states: %@", + unobserved.map(String.init).joined(separator: ", ")) + ) + .font(.system(size: 11)).foregroundStyle(Lab.coral) + } + VStack(alignment: .leading, spacing: 0) { HStack { Text(strings("A closer look")).font(.system(size: 13, weight: .semibold)) @@ -112,12 +140,40 @@ struct MatrixView: View { }.font(.system(size: 11)).padding(.horizontal, 3) } if report.uncertainCount + report.polymorphicCount > 0 { - Text( - strings( - "Uncertain cells: %@ · polymorphic cells: %@", strings.number(report.uncertainCount), - strings.number(report.polymorphicCount)) - ) - .font(.system(size: 11)).foregroundStyle(Lab.secondary) + VStack(alignment: .leading, spacing: 8) { + Text( + strings( + "Uncertain cells: %@ · polymorphic cells: %@", strings.number(report.uncertainCount), + strings.number(report.polymorphicCount)) + ) + .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." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + Text( + strings( + "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) + if let examples = report.observationExamples, !examples.isEmpty { + DisclosureGroup(strings("Inspect ambiguous observations")) { + ForEach(Array(examples.enumerated()), id: \.offset) { _, example in + Text( + "\(example.taxon) · \(strings("Character %@", strings.number(example.character))) · \(example.value)" + ) + .font(.system(size: 11, design: .monospaced)).textSelection(.enabled) + } + Text( + strings("Up to 100 observations are listed; the counts include the full matrix.") + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + } + } + } } } } diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index 698cfc9..d58618d 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -1093,3 +1093,15 @@ "The next update comes to you." = "The next update comes to you."; "Check for signed updates from the Rove menu or Settings." = "Check for signed updates from the Rove menu or Settings."; "This first upgrade from 0.1.1 needs a manual DMG installation. After that, Rove can find and install updates itself. Active calculations delay installation; when your work finishes, you choose when to relaunch." = "This first upgrade from 0.1.1 needs a manual DMG installation. After that, Rove can find and install updates itself. Active calculations delay installation; when your work finishes, you choose when to relaunch."; + +// Matrix observation review. +"Complete state labels" = "Complete state 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." = "Use each state-label list as the complete possible alphabet, in SYMBOLS order. Choose this only if every character lists all its possible states."; +"Characters with one observed state" = "Characters with one observed state"; +"These characters remain in the matrix. Variable-only (Mkv) coding cannot include them. Review how characters were selected before choosing All characters (Mk)." = "These characters remain in the matrix. Variable-only (Mkv) coding cannot include them. Review how characters were selected before choosing All characters (Mk)."; +"Characters without observed states: %@" = "Characters without observed 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." = "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."; +"If your exporter uses braces for polymorphism, confirm the meaning before running. Reading the file does not resolve that scientific choice." = "If your exporter uses braces for polymorphism, confirm the meaning before running. Reading the file does not resolve that scientific choice."; +"Inspect ambiguous observations" = "Inspect ambiguous observations"; +"Up to 100 observations are listed; the counts include the full matrix." = "Up to 100 observations are listed; the counts include the full matrix."; +"Alphabet choice" = "Alphabet choice"; 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 5439d8a..4245cfb 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -1093,3 +1093,15 @@ "The next update comes to you." = "A próxima atualização vem até você."; "Check for signed updates from the Rove menu or Settings." = "Busque atualizações assinadas pelo menu do Rove ou pelas Configurações."; "This first upgrade from 0.1.1 needs a manual DMG installation. After that, Rove can find and install updates itself. Active calculations delay installation; when your work finishes, you choose when to relaunch." = "Esta primeira atualização da versão 0.1.1 precisa ser instalada pelo DMG. Depois disso, o Rove pode buscar e instalar as próximas. A instalação espera os cálculos terminarem; você escolhe quando reiniciar o app."; + +// Matrix observation review. +"Complete state labels" = "Rótulos de estados completos"; +"Use each state-label list as the complete possible alphabet, in SYMBOLS order. Choose this only if every character lists all its possible states." = "Use a lista de rótulos como o alfabeto completo de cada caráter, na ordem de SYMBOLS. Escolha esta opção somente se todos os estados possíveis estiverem listados."; +"Characters with one observed state" = "Caracteres com um estado observado"; +"These characters remain in the matrix. Variable-only (Mkv) coding cannot include them. Review how characters were selected before choosing All characters (Mk)." = "Esses caracteres continuam na matriz. A correção para caracteres variáveis (Mkv) não permite incluí-los. Confira como os caracteres foram selecionados antes de escolher Todos os caracteres (Mk)."; +"Characters without observed states: %@" = "Caracteres sem estados observados: %@"; +"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." = "Chaves como {01} significam estado 0 OU 1. Parênteses como (01) significam que ambos estão presentes. O Rove preserva essa diferença; o modelo atual não analisa polimorfismo verdadeiro."; +"If your exporter uses braces for polymorphism, confirm the meaning before running. Reading the file does not resolve that scientific choice." = "Se o programa que exportou a matriz usa chaves para polimorfismo, confirme o significado antes de executar. Ler o arquivo não resolve essa escolha científica."; +"Inspect ambiguous observations" = "Inspecionar observações ambíguas"; +"Up to 100 observations are listed; the counts include the full matrix." = "A lista mostra até 100 observações; as contagens incluem a matriz inteira."; +"Alphabet choice" = "Escolha do alfabeto"; diff --git a/apps/macos/Sources/RoveApp/SetupView.swift b/apps/macos/Sources/RoveApp/SetupView.swift index 16d770c..197ce10 100644 --- a/apps/macos/Sources/RoveApp/SetupView.swift +++ b/apps/macos/Sources/RoveApp/SetupView.swift @@ -327,6 +327,9 @@ struct ReviewView: View { : workspace.settings.conditioning == "informative" ? "Mkparsinf · informative characters" : "Mk · all characters") if let partitions = report.partitions { + row( + "Alphabet choice", AnalysisSettings.partitioningLabel(workspace.settings.partitioning) + ) row( "State partitions", partitions.map { diff --git a/apps/macos/Tests/RoveAppTests/MatrixObservationTests.swift b/apps/macos/Tests/RoveAppTests/MatrixObservationTests.swift new file mode 100644 index 0000000..3dcceb2 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/MatrixObservationTests.swift @@ -0,0 +1,77 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct MatrixObservationTests { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + private var engine: URL { root.appendingPathComponent("target/release/rove") } + + @Test @MainActor func labeledAlphabetsInspectRunAndPersistWithoutChangingInput() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-observations-\(UUID())") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let matrix = root.appendingPathComponent("fixtures/synthetic/exporter_labels.nex") + let original = try Data(contentsOf: matrix) + let observed = try await MatrixInspector.inspect( + matrix, gapsAsMissing: false, executable: engine) + #expect(observed.constantCharacters == [1]) + #expect(observed.unobservedCharacters == [4]) + #expect(observed.uncertainCount == 1 && observed.polymorphicCount == 0) + #expect(observed.observationExamples?.first?.taxon == "A") + #expect(observed.observationExamples?.first?.character == 3) + #expect(observed.samplerError != nil) + let report = try await MatrixInspector.inspect( + matrix, gapsAsMissing: false, partitioning: "labels", executable: engine) + #expect(report.samplerError == nil && report.variableError != nil) + #expect(report.partitions?.map(\.states) == [2, 3]) + #expect(report.stateLabels?[1] == ["small", "medium", "large"]) + var settings = AnalysisSettings() + settings.partitioning = "labels" + settings.conditioning = "none" + settings.steps = 100 + settings.sampleEvery = 10 + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings) + #expect(draft.formatVersion == 8) + let setup = directory.appendingPathComponent("saved.rove.json") + try draft.write(to: setup) + let restored = try AnalysisDraft.read(setup) + #expect(restored.settings == settings) + let request = RunRequest( + id: UUID(), executable: engine, directory: directory.appendingPathComponent("run"), + draft: restored) + let run = AnalysisRun(request: request) + run.start() + await run.waitForExit() + #expect(run.status == .completed, "\(run.result?.error ?? "unknown error")") + let entry = HistoryEntry.read(request.directory) + #expect(entry.draft?.settings.partitioning == "labels") + #expect(entry.status == .completed) + #expect(try Data(contentsOf: matrix) == original) + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: setup)) as? [String: Any]) + json["formatVersion"] = 7 + try JSONSerialization.data(withJSONObject: json).write(to: setup) + #expect(throws: (any Error).self) { try AnalysisDraft.read(setup) } + } + + @Test func truePolymorphismIsVisibleAndBlocksInference() async throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-polymorphism-\(UUID()).nex") + defer { try? FileManager.default.removeItem(at: file) } + let source = try String( + contentsOf: root.appendingPathComponent( + "fixtures/synthetic/exporter_labels.nex"), encoding: .utf8) + try source.replacingOccurrences(of: "{01}", with: "(01)").write( + to: file, atomically: true, encoding: .utf8) + let report = try await MatrixInspector.inspect( + file, gapsAsMissing: false, partitioning: "labels", executable: engine) + #expect(report.polymorphicCount == 1 && report.uncertainCount == 0) + #expect(report.observationExamples?.first?.value == "(01)") + #expect(report.samplerError?.contains("polymorphism") == true) + } +} diff --git a/docs/es/guide/nexus.md b/docs/es/guide/nexus.md index 6cdc01c..0e261a6 100644 --- a/docs/es/guide/nexus.md +++ b/docs/es/guide/nexus.md @@ -32,7 +32,7 @@ Una entrada inválida o no admitida devuelve `nexus::Error` con línea y columna | Filas secuenciales | Filas con nombre, con espacios en blanco opcionales entre celdas y saltos de línea dentro de la fila. | | Filas intercaladas | Cada página repite todas las etiquetas de taxones en el mismo orden. Cada fila ocupa una línea, con el mismo número de caracteres dentro de una página. El ancho de las páginas puede variar. Las líneas en blanco son opcionales. No se admiten páginas de continuación sin etiquetas. | | Nombres | Nombres entre comillas simples, apóstrofos duplicados y nombres sin comillas. Los guiones bajos se convierten en espacios. La comparación y la detección de duplicados ignoran la distinción entre mayúsculas y minúsculas ASCII; los nombres devueltos conservan su escritura. | -| Etiquetas | `CHARLABELS` con exactamente `NCHAR` nombres; `STATELABELS` y `CHARSTATELABELS` indexados. Las etiquetas descriptivas de estados no reducen el alfabeto declarado. | +| Etiquetas | `CHARLABELS` con exactamente `NCHAR` nombres; `STATELABELS` y `CHARSTATELABELS` indexados. Las etiquetas son descriptivas salvo que se elija explícitamente `--partitioning labels`. | | Comentarios | Comentarios anidados entre corchetes, incluidos comentarios dentro de palabras. Se aceptan finales de línea LF, CRLF y CR. | Con `TAXLABELS`, las filas devueltas siguen el orden declarado aunque las filas de la matriz aparezcan en otro orden. En caso contrario, la primera página de la matriz define el orden. @@ -88,10 +88,20 @@ Las pruebas leen ambos [fixtures de 20 × 50](./fixtures), reconstruyen sus colu Los caracteres ordenados conservan estados intermedios y forman particiones separadas por ordenación; consulta [caracteres ordenados](./ordered-characters). -Un alfabeto declarado de dos estados conserva ambos, incluso en caracteres constantes o totalmente ausentes. Para caracteres no ordenados con un alfabeto mayor, una columna con menos de dos estados observados/posibles no determina su modelo y se rechaza en la partición automática. Usa `CharacterSet { sites, symbols }` con `Matrix::compress_sets`, o `--partitioning declared` si todos los estados de la matriz son posibles para cada carácter. `CHARSTATELABELS` sigue siendo descriptivo y no define estos alfabetos. Los bloques NEXUS `SETS` siguen rechazándose. +Un alfabeto declarado de dos estados conserva ambos, incluso en caracteres constantes o totalmente ausentes. Para caracteres no ordenados con un alfabeto mayor, una columna con menos de dos estados observados/posibles no determina su modelo y se rechaza en la partición automática. Usa `CharacterSet { sites, symbols }` con `Matrix::compress_sets`, o `--partitioning declared` si todos los estados de la matriz son posibles para cada carácter. `CHARSTATELABELS` es descriptivo por defecto; el uso explícito de etiquetas como alfabeto se explica abajo. Los bloques NEXUS `SETS` siguen rechazándose. `compress_sets` admite índices ordenados, no necesariamente contiguos, contados desde cero. Los conjuntos deben cubrir cada carácter exactamente una vez e incluir todos los estados observados/posibles. `Patterns::sites()` enumera las posiciones originales; `state_symbols()` registra las etiquetas originales de cada carácter en el orden del modelo. La compresión se realiza tras recodificar, dentro de cada partición, conservando el peso total. `rove inspect` y `rove sample` usan `--partitioning observed` por defecto; ambos aceptan `--partitioning declared`. La app permite elegirlo en **State partitions** y muestra el número de caracteres por partición. Los gaps siguen requiriendo una decisión explícita. Mkv rechaza cualquier carácter que pueda ser constante, aunque se conozca su número de estados. Cada partición tiene sus propios patrones constantes y corrección Mkv sobre el árbol, reloj y categorías gamma compartidos. `run.json` registra modo, ordenación, estados, índices contados desde uno, correspondencias y patrones observados. Los checkpoints conservan las cachés de todas las particiones. Doce casos de estado fijo, con tres escalas de longitud de rama, concuerdan con BEAST 2.7.8 / MM 1.2.1 con diferencia absoluta máxima de log-verosimilitud de `1,34e-9`; consulta el [caso de validación](https://github.com/getcortexlabs/rove/tree/main/fixtures/validation/multistate). + +## Revisar etiquetas y observaciones exportadas + +Se acepta una coma final en `CHARSTATELABELS` y `STATELABELS`. Las entradas vacías intermedias siguen siendo errores. La importación conserva las observaciones y el archivo original. + +`--partitioning labels` (Mac: **Complete state labels**) interpreta explícitamente la lista de cada carácter como su alfabeto posible completo, en el orden de `SYMBOLS`. Cada carácter debe enumerar al menos dos estados y todas sus observaciones deben estar incluidas. Se conservan los estados posibles no observados. Elige esta opción solo cuando las listas sean completas. El modo predeterminado `observed` no cambia. Las configuraciones con esta opción requieren el formato 8. + +La inspección informa `constant_characters` (un estado observado/posible), `unobserved_characters` (solo ausencias o gaps), `state_labels` y hasta 100 `observation_examples`; los índices empiezan en 1 y los recuentos abarcan toda la matriz. Un estado observado con celdas ausentes no determina esas celdas. No se elimina ningún carácter automáticamente. Mkv rechaza caracteres compatibles con una realización constante. Revisa la selección original de caracteres antes de elegir Mk sin condicionamiento. + +La app distingue `{01}` como incertidumbre (0 o 1) de `(01)` como polimorfismo (ambos presentes). Si el exportador usa llaves para polimorfismo verdadero, aclara su significado antes de analizar. El modelo actual no representa polimorfismo verdadero y la importación no lo convierte en incertidumbre. diff --git a/docs/guide/nexus.md b/docs/guide/nexus.md index 69d690d..339913e 100644 --- a/docs/guide/nexus.md +++ b/docs/guide/nexus.md @@ -32,7 +32,7 @@ Invalid or unsupported input returns `nexus::Error` with a one-based line, colum | Sequential rows | Named rows, with optional whitespace between cells and line wrapping. | | Interleaved rows | Every page repeats every taxon label in the same order. Each row occupies one line, with equal character counts within a page. Page widths may differ. Blank lines are optional. Unlabeled continuation pages are unsupported. | | Names | Single-quoted names, doubled apostrophes and unquoted names. Underscores become spaces. Matching and duplicate detection ignore ASCII case; returned names keep their spelling. | -| Labels | `CHARLABELS` with exactly `NCHAR` names; indexed `STATELABELS` and `CHARSTATELABELS`. Descriptive state labels do not reduce the declared alphabet. | +| Labels | `CHARLABELS` with exactly `NCHAR` names; indexed `STATELABELS` and `CHARSTATELABELS`. State labels are descriptive unless `--partitioning labels` is explicitly selected. | | Comments | Nested square-bracket comments, including comments inside words. LF, CRLF and CR line endings are accepted. | With `TAXLABELS`, returned rows follow the declared order even if matrix rows appear in another order. Otherwise, the first matrix page defines the order. @@ -88,10 +88,20 @@ Tests read both [20 × 50 fixtures](./fixtures), reconstruct their columns from Ordered characters instead preserve intermediate states and group separately by ordering; see [ordered characters](./ordered-characters). -A declared two-state alphabet keeps both states, including for constant or missing-only characters. For unordered characters with a larger alphabet, a column with fewer than two observed/possible states cannot determine its model: automatic partitioning rejects it. Use an explicit `CharacterSet { sites, symbols }` with `Matrix::compress_sets`, or `--partitioning declared` if the full matrix alphabet is possible for every character. `CHARSTATELABELS` remains descriptive and does not set these model alphabets. NEXUS `SETS` blocks are still rejected. +A declared two-state alphabet keeps both states, including for constant or missing-only characters. For unordered characters with a larger alphabet, a column with fewer than two observed/possible states cannot determine its model: automatic partitioning rejects it. Use an explicit `CharacterSet { sites, symbols }` with `Matrix::compress_sets`, or `--partitioning declared` if the full matrix alphabet is possible for every character. `CHARSTATELABELS` remains descriptive by default; explicit labeled-alphabet partitioning is described below. NEXUS `SETS` blocks are still rejected. `compress_sets` accepts sorted, non-contiguous, zero-based character indices. Sets must cover every character exactly once and include every observed/possible state. `Patterns::sites()` lists original matrix positions; `state_symbols()` records each character’s original labels in model-state order. Compression happens after recoding, within partitions, and preserves total character weight. `rove inspect` and `rove sample` default to `--partitioning observed`; both accept `--partitioning declared`. The Mac app exposes this choice under **State partitions** and shows each partition’s character count. Gaps still require explicit treatment. Mkv still rejects any character that could be constant, even if its state count is known. Each partition has its own constant patterns and Mkv correction on the shared tree, clock and gamma categories. `run.json` records the mode, ordering, state counts, one-based character indices, state mappings and observed pattern counts. Checkpoints preserve all partition caches. Twelve fixed-state cases, including three branch-length scales, match BEAST 2.7.8 / MM 1.2.1 with a maximum absolute log-likelihood difference of `1.34e-9`; see the [validation fixture](https://github.com/getcortexlabs/rove/tree/main/fixtures/validation/multistate). + +## Reviewing exporter labels and observations + +A final comma in `CHARSTATELABELS` or `STATELABELS` is accepted. Empty entries inside a list remain errors. Import preserves all observations and the original file. + +`--partitioning labels` (Mac: **Complete state labels**) explicitly treats each character's label list as its complete possible alphabet, in `SYMBOLS` order. Every character must list at least two states, and all observations must fit its alphabet. Unobserved possible states are retained. Choose this only when the lists are complete, not when they merely describe observed states. The default `observed` mode is unchanged. Saved setups using the new choice require format 8. + +Inspection reports one-based `constant_characters` (one state among observed/possible values), `unobserved_characters` (only missing or gaps), descriptive `state_labels`, and up to 100 `observation_examples`; counts cover the whole matrix. A single observed state with missing cells does not establish that unobserved cells have that state. These characters are never silently removed. Mkv still rejects any character compatible with a constant completion. Review the original character-selection process before choosing unconditioned Mk. + +The app explains `{01}` as uncertainty (0 or 1) and `(01)` as polymorphism (both present). If an exporter uses braces for actual polymorphism, resolve that meaning before inference. True polymorphism remains unsupported by the current observation model; importing it does not convert it to uncertainty. diff --git a/docs/pt-BR/guide/nexus.md b/docs/pt-BR/guide/nexus.md index be1430a..ba407b8 100644 --- a/docs/pt-BR/guide/nexus.md +++ b/docs/pt-BR/guide/nexus.md @@ -32,7 +32,7 @@ Entrada inválida ou não suportada devolve `nexus::Error` com linha e coluna co | Linhas sequenciais | Linhas nomeadas, com espaços em branco e quebras de linha opcionais entre as células. | | Linhas intercaladas | Cada página repete todos os rótulos de táxons na mesma ordem. Cada linha da matriz ocupa uma única linha de texto, com o mesmo número de caracteres dentro de uma página. As larguras das páginas podem diferir. Linhas em branco são opcionais. Páginas de continuação sem rótulos não são suportadas. | | Nomes | Nomes entre aspas simples, apóstrofos duplicados e nomes sem aspas. Sublinhados viram espaços. A correspondência e a detecção de duplicatas ignoram maiúsculas e minúsculas ASCII; os nomes devolvidos mantêm a grafia original. | -| Rótulos | `CHARLABELS` com exatamente `NCHAR` nomes; `STATELABELS` e `CHARSTATELABELS` indexados. Rótulos descritivos de estados não reduzem o alfabeto declarado. | +| Rótulos | `CHARLABELS` com exatamente `NCHAR` nomes; `STATELABELS` e `CHARSTATELABELS` indexados. Os rótulos são descritivos, exceto quando `--partitioning labels` é escolhido explicitamente. | | Comentários | Comentários aninhados entre colchetes, incluindo comentários dentro de palavras. Finais de linha LF, CRLF e CR são aceitos. | Com `TAXLABELS`, as linhas devolvidas seguem a ordem declarada mesmo que as linhas da matriz apareçam em outra ordem. Caso contrário, a primeira página da matriz define a ordem. @@ -88,10 +88,20 @@ Os testes leem as duas [fixtures 20 × 50](./fixtures), reconstroem suas colunas Caracteres ordenados preservam estados intermediários e formam partições separadas por ordenação; veja [caracteres ordenados](./ordered-characters). -Um alfabeto declarado de dois estados mantém ambos, inclusive em caracteres constantes ou só com dados ausentes. Para caracteres não ordenados com um alfabeto maior, uma coluna com menos de dois estados observados/possíveis não determina seu modelo: a partição automática a rejeita. Use `CharacterSet { sites, symbols }` com `Matrix::compress_sets`, ou `--partitioning declared` se todos os estados da matriz forem possíveis para cada caráter. `CHARSTATELABELS` continua descritivo e não define esses alfabetos. Blocos NEXUS `SETS` continuam rejeitados. +Um alfabeto declarado de dois estados mantém ambos, inclusive em caracteres constantes ou só com dados ausentes. Para caracteres não ordenados com um alfabeto maior, uma coluna com menos de dois estados observados/possíveis não determina seu modelo: a partição automática a rejeita. Use `CharacterSet { sites, symbols }` com `Matrix::compress_sets`, ou `--partitioning declared` se todos os estados da matriz forem possíveis para cada caráter. `CHARSTATELABELS` continua descritivo por padrão; o uso explícito dos rótulos como alfabeto está descrito abaixo. Blocos NEXUS `SETS` continuam rejeitados. `compress_sets` aceita índices de caracteres ordenados, não necessariamente contíguos, começando em zero. Os conjuntos devem cobrir cada caráter uma única vez e incluir todos os estados observados/possíveis. `Patterns::sites()` lista as posições originais; `state_symbols()` registra os símbolos originais de cada caráter na ordem do modelo. A compressão ocorre após a recodificação, dentro de cada partição, mantendo o peso total dos caracteres. `rove inspect` e `rove sample` usam `--partitioning observed` por padrão; ambos aceitam `--partitioning declared`. O app mostra essa escolha em **Partições por estados**, junto da quantidade de caracteres de cada partição. Lacunas continuam exigindo uma escolha explícita. Mkv ainda rejeita qualquer caráter que possa ser constante, mesmo que seu número de estados seja conhecido. Cada partição tem seus próprios padrões constantes e correção Mkv, compartilhando árvore, relógio e categorias gama. `run.json` registra modo, ordenação, número de estados, índices de caracteres começando em um, mapeamentos e quantidade de padrões observados. Os checkpoints preservam os caches de todas as partições. Doze casos com estado fixo, incluindo três escalas de comprimento de ramo, concordam com BEAST 2.7.8 / MM 1.2.1 com diferença absoluta máxima de log-verossimilhança de `1,34e-9`; veja o [caso de validação](https://github.com/getcortexlabs/rove/tree/main/fixtures/validation/multistate). + +## Conferir rótulos e observações dos exportadores + +Uma vírgula final em `CHARSTATELABELS` ou `STATELABELS` é aceita. Entradas vazias no meio da lista continuam sendo erros. A importação preserva as observações e o arquivo original. + +`--partitioning labels` (Mac: **Rótulos de estados completos**) usa explicitamente a lista de cada caráter como seu alfabeto possível completo, na ordem de `SYMBOLS`. Todos os caracteres precisam listar pelo menos dois estados, e suas observações devem caber nesse alfabeto. Estados possíveis não observados são mantidos. Escolha essa opção somente quando as listas forem completas, não quando apenas descreverem estados observados. O padrão `observed` permanece igual. Configurações com a nova opção exigem formato 8. + +A inspeção informa `constant_characters` (um estado entre os valores observados/possíveis), `unobserved_characters` (somente ausências ou lacunas), `state_labels` descritivos e até 100 `observation_examples`. Os índices começam em 1; as contagens cobrem toda a matriz. Um único estado observado com células ausentes não prova o estado dessas células. Nenhum caráter é removido automaticamente. Mkv continua rejeitando caracteres que possam ser constantes. Confira como os caracteres foram selecionados antes de escolher Mk sem condicionamento. + +O aplicativo explica `{01}` como incerteza (0 ou 1) e `(01)` como polimorfismo (ambos presentes). Se o exportador usa chaves para polimorfismo verdadeiro, esclareça esse significado antes da análise. O modelo atual não representa polimorfismo verdadeiro; a importação não o converte em incerteza. diff --git a/docs/zh-CN/guide/nexus.md b/docs/zh-CN/guide/nexus.md index 654df02..65cbbaa 100644 --- a/docs/zh-CN/guide/nexus.md +++ b/docs/zh-CN/guide/nexus.md @@ -32,7 +32,7 @@ cargo run --release --example read_nexus -- fixtures/reference/20x50/matrix.nex | 顺序行 | 带名字的行,单元格之间可以有空白,可以换行。 | | 交错行 | 每一页都以相同顺序重复每个分类单元的标签。每行占一行,同一页内各行的性状数相等。各页的宽度可以不同。空行可有可无。不支持没有标签的续页。 | | 名字 | 单引号括起的名字、双写的撇号和不带引号的名字。下划线变成空格。匹配和重复检测忽略 ASCII 大小写;返回的名字保留原有写法。 | -| 标签 | 恰好有 `NCHAR` 个名字的 `CHARLABELS`;带索引的 `STATELABELS` 和 `CHARSTATELABELS`。描述性的状态标签不会缩小声明的字母表。 | +| 标签 | 恰好有 `NCHAR` 个名字的 `CHARLABELS`;带索引的 `STATELABELS` 和 `CHARSTATELABELS`。状态标签默认仅用于描述;只有显式选择 `--partitioning labels` 才将其作为模型字母表。 | | 注释 | 嵌套的方括号注释,包括词内的注释。接受 LF、CRLF 和 CR 换行。 | 有 `TAXLABELS` 时,返回的行遵循声明的顺序,即使矩阵中的行以另一种顺序出现。否则,由矩阵的第一页决定顺序。 @@ -88,10 +88,20 @@ assert_eq!(patterns.weights().iter().sum::(), 50); 有序性状会保留中间状态并按排序类型单独分区;参见[有序性状](./ordered-characters)。 -声明为二态的字母表保留两个状态,包括恒定或全缺失性状。对于字母表更大的无序性状,观测/可能状态不足两个的列无法确定其模型,自动分区会拒绝该列。可通过 `Matrix::compress_sets` 使用显式 `CharacterSet { sites, symbols }`,或在全部声明状态对每个性状都可能时使用 `--partitioning declared`。`CHARSTATELABELS` 仍只用于描述,不设置这些模型字母表。NEXUS `SETS` 块仍被拒绝。 +声明为二态的字母表保留两个状态,包括恒定或全缺失性状。对于字母表更大的无序性状,观测/可能状态不足两个的列无法确定其模型,自动分区会拒绝该列。可通过 `Matrix::compress_sets` 使用显式 `CharacterSet { sites, symbols }`,或在全部声明状态对每个性状都可能时使用 `--partitioning declared`。`CHARSTATELABELS` 默认仅用于描述;显式使用标签字母表的方式见下文。NEXUS `SETS` 块仍被拒绝。 `compress_sets` 接受从零开始、已排序但不必连续的性状索引。集合必须恰好覆盖每个性状一次,并包含全部观测/可能状态。`Patterns::sites()` 列出原矩阵位置;`state_symbols()` 按模型状态顺序记录每个性状的原始标签。重编码后在各分区内部压缩,保留性状总权重。 `rove inspect` 和 `rove sample` 默认使用 `--partitioning observed`,也接受 `--partitioning declared`。Mac 应用在 **State partitions** 中提供此选项并显示各分区的性状数量。gap 仍需明确处理。即使状态数已知,Mkv 也拒绝可能为恒定的性状。 各分区在共享的树、时钟和 gamma 类别上有各自的恒定模式及 Mkv 校正。`run.json` 记录模式、排序类型、状态数、从一开始的性状索引、状态映射和观测模式数。检查点保留全部分区缓存。十二个固定状态案例涵盖三种枝长尺度,与 BEAST 2.7.8 / MM 1.2.1 的对数似然最大绝对差为 `1.34e-9`;参见[验证数据](https://github.com/getcortexlabs/rove/tree/main/fixtures/validation/multistate)。 + +## 检查导出文件的标签和观测 + +允许 `CHARSTATELABELS` 和 `STATELABELS` 列表末尾有一个逗号。列表中间的空条目仍会报错。导入保留原始文件和全部观测。 + +`--partitioning labels`(Mac:**Complete state labels**)显式将每个性状的状态标签列表解释为完整的可能状态字母表,顺序与 `SYMBOLS` 一致。每个性状至少需要两个状态标签,所有观测必须包含在对应字母表内。未观测到的可能状态会被保留。只有确认标签列表完整时才选择此模式;默认的 `observed` 模式不变。使用新选项的保存设置要求格式 8。 + +检查结果提供从 1 开始的 `constant_characters`(观测/可能值只有一种状态)、`unobserved_characters`(只有缺失或 gap)、`state_labels` 和最多 100 个 `observation_examples`;总计覆盖整个矩阵。存在缺失单元时,单一已观测状态不能证明缺失单元的状态。程序不会自动删除性状。Mkv 仍拒绝可能为恒定的性状;选择不带校正的 Mk 前,应核实原始性状的选择过程。 + +应用区分 `{01}` 表示的不确定性(0 或 1)与 `(01)` 表示的多态性(两种状态同时存在)。如果导出程序用花括号表示真正的多态性,应在推断前确认含义。当前观测模型不支持真正的多态性,导入不会将它转换为不确定性。 diff --git a/fixtures/synthetic/exporter_labels.nex b/fixtures/synthetic/exporter_labels.nex new file mode 100644 index 0000000..e3e30b8 --- /dev/null +++ b/fixtures/synthetic/exporter_labels.nex @@ -0,0 +1,24 @@ +#NEXUS +[Synthetic exporter compatibility fixture; no private research observations.] +BEGIN TAXA; + DIMENSIONS NTAX=5; + TAXLABELS A B C D E; +END; +BEGIN CHARACTERS; + DIMENSIONS NCHAR=5; + FORMAT DATATYPE=STANDARD SYMBOLS="0 1 2 3 4 5 6 7 8 9" MISSING=?; + CHARSTATELABELS + 1 'constant character' / absent present, + 2 'three states' / small medium large, + 3 'uncertain observation' / absent present, + 4 'unobserved character' / absent present, + 5 'variable character' / absent present, + ; + MATRIX + A 10{01}?0 + B 110?1 + C 121?0 + D 10??1 + E 111?0 + ; +END; diff --git a/src/bin/rove/inspect.rs b/src/bin/rove/inspect.rs index 82df1bb..71424fe 100644 --- a/src/bin/rove/inspect.rs +++ b/src/bin/rove/inspect.rs @@ -10,8 +10,7 @@ use rove::nexus; use super::partitions::{self, Partitioning}; use super::{Json, is_plain_label, sha256}; -const USAGE: &str = - "usage: rove inspect [--gaps reject|missing] [--partitioning observed|declared]"; +const USAGE: &str = "usage: rove inspect [--gaps reject|missing] [--partitioning observed|declared|labels]"; const PREVIEW_TAXA: usize = 200; const PREVIEW_CHARACTERS: usize = 120; @@ -79,6 +78,46 @@ fn report(data: &Matrix, bytes: &[u8], gaps: GapTreatment, partitioning: Partiti )); } let optional = |value: Option| value.map_or(Json::Null, Json::text); + let mut constant = Vec::new(); + let mut unobserved = Vec::new(); + for site in 0..data.character_count() { + let mut states = std::collections::BTreeSet::new(); + for row in data.rows() { + match &row[site] { + Cell::State(state) => { + states.insert(*state); + } + Cell::Uncertain(values) | Cell::Polymorphic(values) => { + states.extend(values); + } + Cell::Missing | Cell::Gap => {} + } + } + if states.is_empty() { + unobserved.push(Json::Integer((site + 1) as u64)); + } + if states.len() == 1 { + constant.push(Json::Integer((site + 1) as u64)); + } + } + let mut observation_examples = Vec::new(); + for (taxon, row) in data.rows().iter().enumerate() { + for (site, cell) in row.iter().enumerate() { + let kind = match cell { + Cell::Uncertain(_) => "uncertain", + Cell::Polymorphic(_) => "polymorphic", + _ => continue, + }; + if observation_examples.len() < 100 { + observation_examples.push(Json::Object(vec![ + ("taxon", Json::text(&data.taxa()[taxon])), + ("character", Json::Integer((site + 1) as u64)), + ("kind", Json::text(kind)), + ("value", Json::text(cell_text(cell, data.symbols()))), + ])); + } + } + } Json::Object(vec![ ("schema_version", Json::Integer(1)), ("input_sha256", Json::text(sha256::hex(bytes))), @@ -94,6 +133,19 @@ fn report(data: &Matrix, bytes: &[u8], gaps: GapTreatment, partitioning: Partiti ("gap_count", Json::Integer(gap_count)), ("uncertain_count", Json::Integer(uncertain)), ("polymorphic_count", Json::Integer(polymorphic)), + ("constant_characters", Json::List(constant)), + ("unobserved_characters", Json::List(unobserved)), + ("observation_examples", Json::List(observation_examples)), + ( + "state_labels", + Json::List( + data.state_labels() + .iter() + .take(PREVIEW_CHARACTERS) + .map(|labels| Json::List(labels.iter().map(Json::text).collect())) + .collect(), + ), + ), ("sampler_error", optional(sampler_error)), ("variable_error", optional(variable_error)), ("informative_error", optional(informative_error)), diff --git a/src/bin/rove/main.rs b/src/bin/rove/main.rs index 9e367af..46e9a59 100644 --- a/src/bin/rove/main.rs +++ b/src/bin/rove/main.rs @@ -33,7 +33,7 @@ const USAGE: &str = [--monophyly ]... [--gaps reject|missing] [--model strict|reference] [--conditioning variable|informative|none] [--sample-from-prior] [--clock-sigma-shape ] [--clock-sigma-scale ] - [--partitioning observed|declared] [--dating ] + [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--chains <1..16>] [--burnin-percent <0..99>] [--stop-when-converged] [--min-ess ] [--max-rhat ] [--check-every ] @@ -45,13 +45,13 @@ const USAGE: &str = [--monophyly ]... [--gaps reject|missing] [--model strict|reference] [--conditioning variable|informative|none] [--clock-sigma-shape ] [--clock-sigma-scale ] - [--partitioning observed|declared] [--dating ] + [--partitioning observed|declared|labels] [--dating ] [--no-tuning] [--tuning =]... [--weight =]... [--backend portable|neon] [--print-every ] [--cancel-on-stdin-close] [--expect-input-sha256 ] rove benchmark [--cancel-on-stdin-close] rove compare ... [--burnin-percent <0..99>] - rove inspect [--gaps reject|missing] [--partitioning observed|declared] + rove inspect [--gaps reject|missing] [--partitioning observed|declared|labels] rove inspect-tree rove diagnose --burnin-percent <0..99> [--output ] rove summarize --output --burnin-percent <0..99> --heights keep|ca diff --git a/src/bin/rove/partitions.rs b/src/bin/rove/partitions.rs index a94e04d..61966a2 100644 --- a/src/bin/rove/partitions.rs +++ b/src/bin/rove/partitions.rs @@ -6,6 +6,7 @@ use super::Json; pub(super) enum Partitioning { Observed, Declared, + Labels, } impl Partitioning { @@ -13,7 +14,8 @@ impl Partitioning { match value { "observed" => Ok(Self::Observed), "declared" => Ok(Self::Declared), - _ => Err("--partitioning must be observed or declared".into()), + "labels" => Ok(Self::Labels), + _ => Err("--partitioning must be observed, declared or labels".into()), } } @@ -21,6 +23,7 @@ impl Partitioning { match self { Self::Observed => "observed", Self::Declared => "declared", + Self::Labels => "labels", } } @@ -31,6 +34,7 @@ impl Partitioning { ) -> Result, CompressionError> { match self { Self::Observed => data.partition_by_states(gaps), + Self::Labels => data.partition_by_labels(gaps), Self::Declared => { data.compress(std::slice::from_ref(&(0..data.character_count())), gaps) } diff --git a/src/data.rs b/src/data.rs index d6cf570..e740d5d 100644 --- a/src/data.rs +++ b/src/data.rs @@ -36,6 +36,7 @@ pub enum GapTreatment { pub enum CompressionError { InvalidPartitions, StateCount { site: usize }, + StateLabels { site: usize }, ExcludedState { site: usize, symbol: char }, Gap { taxon: String, site: usize }, Polymorphism { taxon: String, site: usize }, @@ -45,6 +46,11 @@ pub enum CompressionError { impl fmt::Display for CompressionError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + 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", + site + 1 + ), Self::OrderedAlphabet { site } => write!( f, "ordered character {} requires a contiguous alphabet in declared SYMBOLS order; intermediate states cannot be removed", @@ -219,6 +225,30 @@ impl Matrix { .collect()) } + /// Explicitly interpret state-label lists as complete per-character + /// alphabets in declared SYMBOLS order. This is an opt-in model choice; + /// ordinary import and observed partitioning keep labels descriptive. + pub fn partition_by_labels( + &self, + gaps: GapTreatment, + ) -> Result, CompressionError> { + let mut groups = BTreeMap::>::new(); + for (site, labels) in self.state_labels.iter().enumerate() { + if labels.len() < 2 || labels.len() > self.symbols.len() { + return Err(CompressionError::StateLabels { site }); + } + groups.entry(labels.len()).or_default().push(site); + } + let sets = groups + .into_iter() + .map(|(count, sites)| CharacterSet { + sites, + symbols: self.symbols[..count].to_vec(), + }) + .collect::>(); + self.compress_sets(&sets, gaps) + } + /// Compress explicit, possibly non-contiguous character sets. Their alphabets /// include any unobserved possible states. Every character must occur once. pub fn compress_sets( diff --git a/src/nexus/mod.rs b/src/nexus/mod.rs index 4a59738..b989571 100644 --- a/src/nexus/mod.rs +++ b/src/nexus/mod.rs @@ -449,7 +449,14 @@ fn apply_labels(data: &mut Matrix, commands: &[Vec<&Token>]) -> Result<(), Error } continue; } - for entry in command[1..].split(|t| t.punct(',')) { + // Several matrix exporters leave a separator after the last label. + // Accept that one separator, but not missing entries within the list. + let entries = if command.last().is_some_and(|t| t.punct(',')) { + &command[1..command.len() - 1] + } else { + &command[1..] + }; + for entry in entries.split(|t| t.punct(',')) { let first = entry .first() .ok_or_else(|| head.error("empty state-label entry"))?; diff --git a/tests/nexus.rs b/tests/nexus.rs index 4071521..666383b 100644 --- a/tests/nexus.rs +++ b/tests/nexus.rs @@ -5,6 +5,60 @@ use rove::{LikelihoodCore, Scaling, model::Mk, nexus}; const REFERENCE: &str = include_str!("../fixtures/reference/20x50/matrix.nex"); const CONTROL: &str = include_str!("../fixtures/synthetic/control_20x50.nex"); +#[test] +fn exporter_labels_preserve_observations_and_require_explicit_alphabets() { + let source = include_str!("../fixtures/synthetic/exporter_labels.nex"); + let data = nexus::parse(source).unwrap(); + assert_eq!(data.taxa().len(), 5); + assert_eq!(data.character_count(), 5); + assert_eq!(data.symbols().len(), 10); + assert_eq!( + data.character_labels()[0].as_deref(), + Some("constant character") + ); + assert_eq!(data.rows()[0][2], Cell::Uncertain(vec![0, 1])); + assert_eq!( + data.partition_by_states(GapTreatment::Reject), + Err(CompressionError::StateCount { site: 0 }) + ); + let partitions = data.partition_by_labels(GapTreatment::Reject).unwrap(); + assert_eq!(partitions.len(), 2); + assert_eq!(partitions[0].sites(), &[0, 2, 3, 4]); + assert_eq!(partitions[0].symbols().len(), 2); + assert_eq!(partitions[1].sites(), &[1]); + assert_eq!(partitions[1].symbols().len(), 3); + assert_eq!( + partitions.iter().flat_map(|p| p.weights()).sum::(), + 5 + ); + // A declared but unobserved state remains possible under this explicit choice. + assert_eq!(partitions[0].state_symbols()[0], ['0', '1']); + for ending in [",,\n ;", ",, ,\n ;"] { + assert!(nexus::parse(&source.replace(",\n ;", ending)).is_err()); + } + let outside = nexus::parse(&source.replace("A 10{01}?0", "A 12{02}?0")).unwrap(); + assert!(matches!( + outside.partition_by_labels(GapTreatment::Reject), + Err(CompressionError::ExcludedState { + site: 2, + symbol: '2' + }) + )); + let incomplete = nexus::parse(&source.replace("absent present", "present")).unwrap(); + assert_eq!( + incomplete.partition_by_labels(GapTreatment::Reject), + Err(CompressionError::StateLabels { site: 0 }) + ); +} + +#[test] +fn final_separator_in_statelabels_does_not_accept_missing_interior_entries() { + let source = "#NEXUS BEGIN DATA; DIMENSIONS NTAX=2 NCHAR=2; STATELABELS 1 a b, 2 c d,; MATRIX A 01 B 10; END;"; + assert_eq!(nexus::parse(source).unwrap().state_labels()[1], ["c", "d"]); + assert!(nexus::parse(&source.replace("b, 2", "b,, 2")).is_err()); + assert!(nexus::parse(&source.replace("1 a b, 2 c d,", ",")).is_err()); +} + fn document(ntax: usize, nchar: usize, format: &str, matrix: &str) -> String { format!( "#NEXUS\nBEGIN DATA;\nDIMENSIONS NTAX={ntax} NCHAR={nchar};\nFORMAT {format};\nMATRIX\n{matrix}\n; END;" @@ -349,7 +403,7 @@ fn inconsistent_declarations_are_rejected() { "CHARSTATELABELS 1 size / small medium large;", "CHARSTATELABELS 1 size, 1 shape;", "STATELABELS 1 small large, 1 short long;", - "STATELABELS 1 small large,;", + "STATELABELS 1 small large,,;", "DIMENSIONS NTAX=2 NCHAR=2;", ] { let text = format!("{prefix} {command} MATRIX A 01 B 10; END;"); diff --git a/tools/native/cli-parity.json b/tools/native/cli-parity.json index c89e92d..2088c25 100644 --- a/tools/native/cli-parity.json +++ b/tools/native/cli-parity.json @@ -113,7 +113,7 @@ }, "--partitioning": { "native": "apps/macos/Sources/RoveApp/MatrixView.swift", - "control": "Matrix import options" + "control": "Matrix import: observed states, declared alphabet or explicit complete state labels" }, "--powers": { "native": "apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift",