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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 30 additions & 8 deletions apps/macos/Sources/RoveApp/Analysis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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?
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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."
}
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
3 changes: 1 addition & 2 deletions apps/macos/Sources/RoveApp/HistoryView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
3 changes: 1 addition & 2 deletions apps/macos/Sources/RoveApp/MarginalLikelihoodView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
70 changes: 63 additions & 7 deletions apps/macos/Sources/RoveApp/MatrixView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
Expand All @@ -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)
Expand All @@ -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))
Expand Down Expand Up @@ -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)
}
}
}
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Original file line number Diff line number Diff line change
Expand Up @@ -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";
3 changes: 3 additions & 0 deletions apps/macos/Sources/RoveApp/SetupView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
77 changes: 77 additions & 0 deletions apps/macos/Tests/RoveAppTests/MatrixObservationTests.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading