diff --git a/apps/macos/Sources/RoveApp/Analysis.swift b/apps/macos/Sources/RoveApp/Analysis.swift index 96ac878..5e22cec 100644 --- a/apps/macos/Sources/RoveApp/Analysis.swift +++ b/apps/macos/Sources/RoveApp/Analysis.swift @@ -551,7 +551,7 @@ enum GroupConstraints { static func validate(_ groups: [[String]], taxa: [String], outgroup: String? = nil) -> String? { let known = Set(taxa) if let outgroup, !known.contains(outgroup) || known.count < 3 { - return "Choose one outgroup from a matrix with at least three terminals." + return "Choose one rooting taxon from a matrix with at least three terminals." } var previous: [Set] = [] for group in groups { diff --git a/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift b/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift index 1c320b2..22c2067 100644 --- a/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift +++ b/apps/macos/Sources/RoveApp/ClockSigmaPrior.swift @@ -1,3 +1,4 @@ +import Charts import SwiftUI struct ClockSigmaPrior: Codable, Equatable, Sendable { @@ -8,6 +9,109 @@ struct ClockSigmaPrior: Codable, Equatable, Sendable { func description(strings: AppStrings) -> String { strings("Gamma · shape %@ · scale %@", String(shape), String(scale)) } + + var mean: Double { shape * scale } + var standardDeviation: Double { sqrt(shape) * scale } + + /// Shape/scale Gamma density; evaluate in scaled coordinates to avoid + /// subtracting the separate, large shape * log(scale) terms. + func logDensity(at sigma: Double) -> Double? { + guard shape.isFinite, scale.isFinite, shape > 0, scale > 0, + sigma.isFinite, sigma >= 0, lgamma(shape).isFinite + else { return nil } + if sigma == 0 { + if shape < 1 { return .infinity } + return shape == 1 ? -log(scale) : -.infinity + } + let value = sigma / scale + guard value.isFinite, value > 0 else { return nil } + let density = (shape - 1) * log(value) - value - lgamma(shape) - log(scale) + return density.isNaN ? nil : density + } + + struct Curve: Sendable { + struct Point: Identifiable, Sendable { + let id: Int + let sigma: Double + let density: Double + } + let points: [Point] + let upperBound: Double + } + + var curve: Curve? { + let upper = mean + 5 * standardDeviation + // The numerical prior may be valid at scales where a linear display + // cannot draw meaningful axes. Keep that limitation in the preview only. + guard upper.isFinite, upper >= 1e-12, upper <= 1e12, + mean.isFinite, mean > 0, shape > 0, scale > 0 + else { return nil } + let first = shape < 1 ? 1 : 0 + var points: [Curve.Point] = [] + for index in first...240 { + let sigma = upper * Double(index) / 240 + guard let logValue = logDensity(at: sigma) else { return nil } + let value = exp(logValue) + guard value.isFinite, value <= 1e12 else { return nil } + points.append(.init(id: index, sigma: sigma, density: value)) + } + guard points.contains(where: { $0.density > 0 }) else { return nil } + return Curve(points: points, upperBound: upper) + } +} + +struct ClockSigmaPriorChart: View { + let prior: ClockSigmaPrior + let strings: AppStrings + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + if let curve = prior.curve { + Chart { + ForEach(curve.points) { point in + LineMark( + x: .value("Sigma", point.sigma), + y: .value(strings("Prior density"), point.density) + ) + .foregroundStyle(Lab.lilac).lineStyle(StrokeStyle(lineWidth: 2)) + } + RuleMark(x: .value(strings("Expected sigma"), prior.mean)) + .foregroundStyle(Lab.accent).lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + } + .chartXScale(domain: 0...curve.upperBound) + .chartXAxisLabel("Sigma") + .chartYAxisLabel(strings("Prior density")) + .frame(height: 170) + .accessibilityLabel( + strings("Gamma prior for clock sigma; the dashed line marks its expectation.")) + } else { + Text(strings("The density preview is unavailable at this numerical scale.")) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } + if prior.mean.isFinite, prior.standardDeviation.isFinite { + Text( + strings( + "Expected sigma: %@ · standard deviation: %@", + number(prior.mean), number(prior.standardDeviation)) + ) + .font(.system(size: 11, weight: .medium)).foregroundStyle(Lab.accent) + } + if prior.shape < 1 { + Text(strings("The density grows without bound near zero; the curve starts above zero.")) + .font(.system(size: 10)).foregroundStyle(Lab.secondary) + } + Text( + strings( + "This is a prior preview, before seeing the data. The displayed range is not a credible interval." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + } + } + + private func number(_ value: Double) -> String { + value.formatted(.number.precision(.significantDigits(1...5)).locale(strings.locale)) + } } struct ClockSigmaPriorSection: View { @@ -39,6 +143,9 @@ struct ClockSigmaPriorSection: View { ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + if let prior = workspace.settings.clockSigmaPrior { + ClockSigmaPriorChart(prior: prior, strings: strings) + } if workspace.settings.clockSigmaPrior == nil { Text(strings("Use positive, finite shape and scale values for the clock sigma prior.")) .font(.system(size: 12)).foregroundStyle(Lab.accent) diff --git a/apps/macos/Sources/RoveApp/LaunchExperience.swift b/apps/macos/Sources/RoveApp/LaunchExperience.swift index afbd668..f9d5f53 100644 --- a/apps/macos/Sources/RoveApp/LaunchExperience.swift +++ b/apps/macos/Sources/RoveApp/LaunchExperience.swift @@ -99,7 +99,7 @@ struct RoveRelease: Identifiable { id: "morphology", symbol: "square.grid.3x3", title: "Bring all the little differences.", summary: "Morphological matrices, with two, three or more states.", detail: - "Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start.", + "Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start.", action: "Try the example", destination: .example), ReleaseHighlight( id: "history", symbol: "clock.arrow.circlepath", diff --git a/apps/macos/Sources/RoveApp/MatrixView.swift b/apps/macos/Sources/RoveApp/MatrixView.swift index 53ae475..41bd428 100644 --- a/apps/macos/Sources/RoveApp/MatrixView.swift +++ b/apps/macos/Sources/RoveApp/MatrixView.swift @@ -52,7 +52,7 @@ struct MatrixView: View { Text(strings("By observed states")).tag("observed") Text(strings("Declared alphabet")).tag("declared") Text(strings("Complete state labels")).tag("labels") - }.labelsHidden().frame(width: 210) + }.labelsHidden().frame(width: 260) .disabled(workspace.loading) .onChange(of: workspace.settings.partitioning) { workspace.reloadGapPolicy() } } @@ -66,6 +66,7 @@ struct MatrixView: View { ) ) .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) } @@ -88,6 +89,7 @@ struct MatrixView: View { ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) } } } @@ -153,12 +155,14 @@ struct MatrixView: View { ) ) .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." ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) if let examples = report.observationExamples, !examples.isEmpty { DisclosureGroup(strings("Inspect ambiguous observations")) { ForEach(Array(examples.enumerated()), id: \.offset) { _, example in @@ -275,9 +279,18 @@ private struct MatrixGrid: View { let name = report.characterLabels[selected.column] ?? strings("Character %@", strings.number(selected.column + 1)) - Text( - "\(report.taxa[selected.row]) · \(name) · \(report.cells[selected.row][selected.column])" - ) + VStack(alignment: .leading, spacing: 4) { + Text( + "\(report.taxa[selected.row]) · \(name) · \(report.cells[selected.row][selected.column])" + ) + if let labels = report.stateLabels, labels.indices.contains(selected.column) { + Text( + zip(report.symbols, labels[selected.column]) + .map { "\($0.0) = \($0.1)" }.joined(separator: " · ") + ) + .fixedSize(horizontal: false, vertical: true) + } + } } else { Text(strings("Click a cell to inspect it. Scroll to explore.")) } diff --git a/apps/macos/Sources/RoveApp/OnboardingView.swift b/apps/macos/Sources/RoveApp/OnboardingView.swift index 9639349..fb9b101 100644 --- a/apps/macos/Sources/RoveApp/OnboardingView.swift +++ b/apps/macos/Sources/RoveApp/OnboardingView.swift @@ -17,7 +17,7 @@ struct OnboardingView: View { private let descriptions = [ "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion.", "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything.", - "Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you.", + "Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you.", "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis.", ] @@ -179,7 +179,7 @@ struct OnboardingView: View { VStack(alignment: .leading, spacing: 10) { Label(strings("For the bundled example"), systemImage: "lightbulb") .font(.system(size: 12, weight: .medium)).foregroundStyle(Lab.ice) - Text(strings("Choose T20 as the outgroup. Check the remaining settings before starting.")) + Text(strings("Choose T20 as the taxon used for rooting. Check the remaining settings before starting.")) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) } }.padding(22).background(Lab.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 15)) diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index d58618d..aeeee12 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -298,7 +298,7 @@ "%@ on one side of the root; the other %@ terminals together on the other." = "%@ on one side of the root; the other %@ terminals together on the other."; "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup." = "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup."; "No outgroup selected. Any applied groups below still constrain the tree." = "No outgroup selected. Any applied groups below still constrain the tree."; -"Choose one outgroup from a matrix with at least three terminals." = "Choose one outgroup from a matrix with at least three terminals."; +"Choose one rooting taxon from a matrix with at least three terminals." = "Choose one rooting taxon from a matrix with at least three terminals."; "No groups applied. Root placement is unconstrained by groups." = "No groups applied. Root placement is unconstrained by groups."; "Applied groups" = "Applied groups"; "Support for an imposed group is not independent evidence from the characters." = "Support for an imposed group is not independent evidence from the characters."; @@ -618,7 +618,7 @@ "Your research.\nRoom to explore." = "Your research.\nRoom to explore."; "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion." = "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion."; "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything." = "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything."; -"Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you." = "Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you."; +"Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you." = "Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you."; "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis." = "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis."; "YOUR FIRST FIELD TRIP" = "YOUR FIRST FIELD TRIP"; "A SMALL INTRODUCTION" = "A SMALL INTRODUCTION"; @@ -637,7 +637,7 @@ "Illustration of a morphological matrix" = "Illustration of a morphological matrix"; "? means an unknown observation." = "? means an unknown observation."; "For the bundled example" = "For the bundled example"; -"Choose T20 as the outgroup. Check the remaining settings before starting." = "Choose T20 as the outgroup. Check the remaining settings before starting."; +"Choose T20 as the taxon used for rooting. Check the remaining settings before starting." = "Choose T20 as the taxon used for rooting. Check the remaining settings before starting."; "Check the sampling" = "Check the sampling"; "Useful samples matter more than step counts." = "Useful samples matter more than step counts."; "Explore the trees" = "Explore the trees"; @@ -655,7 +655,7 @@ "A small beginning, with room for big questions. Meet the tools already inside this beta." = "A small beginning, with room for big questions. Meet the tools already inside this beta."; "Bring all the little differences." = "Bring all the little differences."; "Morphological matrices, with two, three or more states." = "Morphological matrices, with two, three or more states."; -"Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start." = "Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start."; +"Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start." = "Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start."; "Good work deserves a save point." = "Good work deserves a save point."; "Find past runs. Pause a long analysis. Pick up where you left off." = "Find past runs. Pause a long analysis. Pick up where you left off."; "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input." = "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input."; @@ -950,7 +950,7 @@ "The tree file could not be opened." = "The tree file could not be opened."; "The tree file is no longer at its recorded path." = "The tree file is no longer at its recorded path."; "Trees from another program" = "Trees from another program"; -"Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." = "Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence."; +"Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." = "Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence."; "The tree file is no longer at its recorded path. Saved summaries stay available." = "The tree file is no longer at its recorded path. Saved summaries stay available."; "Summaries" = "Summaries"; "No summary yet. Summarize the file to build an annotated MCC tree." = "No summary yet. Summarize the file to build an annotated MCC tree."; @@ -1105,3 +1105,14 @@ "Inspect ambiguous observations" = "Inspect ambiguous observations"; "Up to 100 observations are listed; the counts include the full matrix." = "Up to 100 observations are listed; the counts include the full matrix."; "Alphabet choice" = "Alphabet choice"; + +// Visual model guidance. +"Prior density" = "Prior density"; +"Expected sigma" = "Expected sigma"; +"Gamma prior for clock sigma; the dashed line marks its expectation." = "Gamma prior for clock sigma; the dashed line marks its expectation."; +"The density preview is unavailable at this numerical scale." = "The density preview is unavailable at this numerical scale."; +"Expected sigma: %@ · standard deviation: %@" = "Expected sigma: %@ · standard deviation: %@"; +"The density grows without bound near zero; the curve starts above zero." = "The density grows without bound near zero; the curve starts above zero."; +"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "This is a prior preview, before seeing the data. The displayed range is not a credible interval."; +"Other %@ terminals" = "Other %@ terminals"; +"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here."; diff --git a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings index 4245cfb..da04537 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -298,7 +298,7 @@ "%@ on one side of the root; the other %@ terminals together on the other." = "%@ de um lado da raiz; os outros %@ terminais juntos do outro."; "The outgroup is a terminal, not the ancestor at the root. This choice constrains the ingroup; its support is imposed by the setup." = "O grupo externo é um terminal, não o ancestral na raiz. Esta escolha obriga os demais a formar um grupo; o suporte dele é imposto pela configuração."; "No outgroup selected. Any applied groups below still constrain the tree." = "Nenhum grupo externo selecionado. Os grupos aplicados abaixo continuam restringindo a árvore."; -"Choose one outgroup from a matrix with at least three terminals." = "Escolha um grupo externo de uma matriz com pelo menos três terminais."; +"Choose one rooting taxon from a matrix with at least three terminals." = "Escolha um táxon de enraizamento de uma matriz com pelo menos três terminais."; "No groups applied. Root placement is unconstrained by groups." = "Nenhum grupo aplicado. Não há restrição de grupos sobre a posição da raiz."; "Applied groups" = "Grupos aplicados"; "Support for an imposed group is not independent evidence from the characters." = "O suporte de um grupo imposto não é uma evidência independente dos caracteres."; @@ -618,7 +618,7 @@ "Your research.\nRoom to explore." = "Sua pesquisa.\nEspaço para explorar."; "Rove explores evolutionary relationships from morphological data. A native workspace, a Rust engine, and a curious little companion." = "O Rove explora relações evolutivas a partir de dados morfológicos. Um aplicativo nativo, um motor em Rust e um companheiro curioso."; "Rows are taxa. Columns are characters. Bring a NEXUS matrix and Rove will help you inspect the states and missing observations before you run anything." = "As linhas são táxons. As colunas são caracteres. Abra uma matriz NEXUS para conferir os estados e as observações ausentes antes de iniciar uma análise."; -"Review the model and choose your outgroup explicitly. It gives your analysis a rooting constraint; Rove never guesses one for you." = "Revise o modelo e escolha seu grupo externo. Ele define uma restrição para a raiz da análise; o Rove não faz essa escolha por você."; +"Review the model and choose a taxon for rooting explicitly. It constrains the root split; Rove never guesses that choice for you." = "Revise o modelo e escolha explicitamente um táxon para enraizamento. Ele restringe a divisão na raiz; o Rove não faz essa escolha por você."; "Follow the run, inspect its traces and explore the trees. History keeps your work together, with checkpoints for picking up a paused analysis." = "Acompanhe a execução, examine os traços e explore as árvores. O Histórico reúne seu trabalho e os pontos salvos para retomar análises pausadas."; "YOUR FIRST FIELD TRIP" = "SUA PRIMEIRA EXPLORAÇÃO"; "A SMALL INTRODUCTION" = "UMA BREVE APRESENTAÇÃO"; @@ -637,7 +637,7 @@ "Illustration of a morphological matrix" = "Ilustração de uma matriz morfológica"; "? means an unknown observation." = "? indica uma observação desconhecida."; "For the bundled example" = "No exemplo do aplicativo"; -"Choose T20 as the outgroup. Check the remaining settings before starting." = "Escolha T20 como grupo externo. Confira as outras opções antes de começar."; +"Choose T20 as the taxon used for rooting. Check the remaining settings before starting." = "Escolha T20 como táxon de enraizamento. Confira as outras opções antes de começar."; "Check the sampling" = "Confira a amostragem"; "Useful samples matter more than step counts." = "Amostras úteis valem mais do que contar passos."; "Explore the trees" = "Explore as árvores"; @@ -655,7 +655,7 @@ "A small beginning, with room for big questions. Meet the tools already inside this beta." = "Um pequeno começo, com espaço para grandes perguntas. Conheça as ferramentas que já estão neste beta."; "Bring all the little differences." = "Traga cada pequena diferença."; "Morphological matrices, with two, three or more states." = "Matrizes morfológicas com dois, três ou mais estados."; -"Import a NEXUS matrix, review its state partitions and choose the outgroup explicitly. The bundled 20 × 50 example is a good place to start." = "Importe uma matriz NEXUS, confira as partições por estados e escolha o grupo externo. O exemplo 20 × 50 do aplicativo é um bom ponto de partida."; +"Import a NEXUS matrix, review its state partitions and choose the taxon used for rooting explicitly. The bundled 20 × 50 example is a good place to start." = "Importe uma matriz NEXUS, confira as partições por estados e escolha explicitamente o táxon de enraizamento. O exemplo 20 × 50 do aplicativo é um bom ponto de partida."; "Good work deserves a save point." = "Bom trabalho merece um ponto salvo."; "Find past runs. Pause a long analysis. Pick up where you left off." = "Encontre análises anteriores, pause uma execução longa e retome de onde parou."; "History keeps the run configuration and output paths together. Checkpoints preserve the sampler state; resuming requires the same engine and original input." = "O Histórico reúne as configurações e os caminhos dos resultados. Os pontos salvos preservam o estado do amostrador; para retomar, use o mesmo motor e os dados originais."; @@ -950,7 +950,7 @@ "The tree file could not be opened." = "Não foi possível abrir o arquivo de árvores."; "The tree file is no longer at its recorded path." = "O arquivo de árvores não está mais no caminho registrado."; "Trees from another program" = "Árvores de outro programa"; -"Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." = "O Rove não rodou esta amostra aqui, então nenhum grupo externo é conhecido. Um resumo e suporte alto nos nós não comprovam convergência."; +"Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." = "O Rove não rodou esta amostra aqui, então a escolha de enraizamento é desconhecida. Um resumo e suporte alto nos nós não comprovam convergência."; "The tree file is no longer at its recorded path. Saved summaries stay available." = "O arquivo de árvores não está mais no caminho registrado. Os resumos salvos continuam disponíveis."; "Summaries" = "Resumos"; "No summary yet. Summarize the file to build an annotated MCC tree." = "Nenhum resumo ainda. Resuma o arquivo para construir uma árvore MCC anotada."; @@ -1105,3 +1105,14 @@ "Inspect ambiguous observations" = "Inspecionar observações ambíguas"; "Up to 100 observations are listed; the counts include the full matrix." = "A lista mostra até 100 observações; as contagens incluem a matriz inteira."; "Alphabet choice" = "Escolha do alfabeto"; + +// Visual model guidance. +"Prior density" = "Densidade do prior"; +"Expected sigma" = "Sigma esperado"; +"Gamma prior for clock sigma; the dashed line marks its expectation." = "Prior gamma do sigma do relógio; a linha tracejada marca sua esperança."; +"The density preview is unavailable at this numerical scale." = "A prévia da densidade não está disponível nessa escala numérica."; +"Expected sigma: %@ · standard deviation: %@" = "Sigma esperado: %@ · desvio padrão: %@"; +"The density grows without bound near zero; the curve starts above zero." = "A densidade cresce sem limite perto de zero; a curva começa acima de zero."; +"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "Esta é uma prévia do prior, antes de observar os dados. O intervalo exibido não é um intervalo de credibilidade."; +"Other %@ terminals" = "Outros %@ terminais"; +"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Diagrama da restrição. Os comprimentos dos ramos e as relações dentro do grupo recolhido não são estimados aqui."; diff --git a/apps/macos/Sources/RoveApp/RootingView.swift b/apps/macos/Sources/RoveApp/RootingView.swift index 7869435..4c0d2be 100644 --- a/apps/macos/Sources/RoveApp/RootingView.swift +++ b/apps/macos/Sources/RoveApp/RootingView.swift @@ -30,6 +30,7 @@ struct RootingSection: View { ) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) if let outgroup = workspace.outgroup { + RootingConstraintDiagram(taxon: outgroup, remaining: taxa.count - 1, strings: strings) HStack(alignment: .top, spacing: 12) { Image(systemName: "point.3.connected.trianglepath.dotted") .font(.system(size: 22)).foregroundStyle(Lab.ice).accessibilityHidden(true) @@ -46,6 +47,7 @@ struct RootingSection: View { ) ) .font(.system(size: 11)).foregroundStyle(Lab.secondary).lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) } }.padding(16).background(Lab.ice.opacity(0.045), in: RoundedRectangle(cornerRadius: 12)) } else { @@ -66,6 +68,61 @@ struct RootingSection: View { } } +struct RootingConstraintDiagram: View { + let taxon: String + let remaining: Int + let strings: AppStrings + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 14) { + Canvas { context, size in + var branches = Path() + branches.move(to: CGPoint(x: 10, y: 48)) + branches.addLine(to: CGPoint(x: 40, y: 48)) + branches.move(to: CGPoint(x: 40, y: 18)) + branches.addLine(to: CGPoint(x: 40, y: 76)) + branches.move(to: CGPoint(x: 40, y: 18)) + branches.addLine(to: CGPoint(x: size.width - 6, y: 18)) + branches.move(to: CGPoint(x: 40, y: 76)) + branches.addLine(to: CGPoint(x: 70, y: 76)) + context.stroke(branches, with: .color(Lab.ice), lineWidth: 2) + context.fill( + Path(ellipseIn: CGRect(x: 6, y: 44, width: 8, height: 8)), + with: .color(Lab.accent)) + var group = Path() + group.move(to: CGPoint(x: 70, y: 76)) + group.addLine(to: CGPoint(x: size.width - 6, y: 53)) + group.addLine(to: CGPoint(x: size.width - 6, y: 96)) + group.closeSubpath() + context.fill(group, with: .color(Lab.lilac.opacity(0.2))) + context.stroke(group, with: .color(Lab.lilac), lineWidth: 1.5) + }.frame(width: 140, height: 100).accessibilityHidden(true) + VStack(alignment: .leading, spacing: 0) { + Text(taxon).font(.system(size: 12, weight: .medium)).foregroundStyle(Lab.ice) + .frame(height: 36, alignment: .center) + Spacer(minLength: 0) + Text(strings("Other %@ terminals", strings.number(remaining))) + .font(.system(size: 12)).foregroundStyle(Lab.lilac) + .frame(height: 46, alignment: .center) + }.frame(height: 100) + } + Text( + strings( + "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel( + strings( + "%@ on one side of the root; the other %@ terminals together on the other.", taxon, + strings.number(remaining))) + } +} + struct ConstraintSummary: View { let outgroup: String? let taxa: [String]? diff --git a/apps/macos/Sources/RoveApp/TreeFileView.swift b/apps/macos/Sources/RoveApp/TreeFileView.swift index 98aca51..694835b 100644 --- a/apps/macos/Sources/RoveApp/TreeFileView.swift +++ b/apps/macos/Sources/RoveApp/TreeFileView.swift @@ -26,7 +26,7 @@ struct TreeFileDetail: View { VStack(alignment: .leading, spacing: 14) { Text( strings( - "Rove did not run this sample here, so no outgroup is known. A summary and high node support do not establish convergence." + "Rove did not run this sample here, so its rooting choice is unknown. A summary and high node support do not establish convergence." ) ) .font(.system(size: 12)).foregroundStyle(Lab.secondary).lineSpacing(4) diff --git a/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift b/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift index dd29ff1..5959ee5 100644 --- a/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift +++ b/apps/macos/Tests/RoveAppTests/ClockSigmaPriorTests.swift @@ -4,6 +4,33 @@ import Testing @testable import RoveApp struct ClockSigmaPriorTests { + @Test func densityPreviewMatchesIndependentGammaSpecialCases() throws { + let exponential = ClockSigmaPrior(shape: 1, scale: 2) + for x in [0.0, 0.1, 1.0, 5.0, 20.0] { + let actual = try #require(exponential.logDensity(at: x)) + #expect(abs(exp(actual) - 0.5 * exp(-x / 2)) < 1e-14) + } + let prior = ClockSigmaPrior.reference + #expect(prior.mean == 1) + #expect(abs(prior.standardDeviation - sqrt(0.2)) < 1e-14) + for x in [0.1, 0.8, 1.0, 2.0] { + let direct = pow(x, 4) * exp(-x / 0.2) / (24 * pow(0.2, 5)) + #expect(abs(exp(try #require(prior.logDensity(at: x))) - direct) < 1e-12) + } + let curve = try #require(prior.curve) + let integral = zip(curve.points, curve.points.dropFirst()).reduce(0.0) { sum, pair in + sum + (pair.1.sigma - pair.0.sigma) * (pair.0.density + pair.1.density) / 2 + } + let u = curve.upperBound / prior.scale + let exact = 1 - exp(-u) * (1 + u + u * u / 2 + u * u * u / 6 + pow(u, 4) / 24) + #expect(abs(integral - exact) < 1e-5) + let singular = ClockSigmaPrior(shape: 0.5, scale: 1) + #expect(singular.logDensity(at: 0) == .infinity) + #expect(singular.curve?.points.allSatisfy { $0.sigma > 0 && $0.density.isFinite } == true) + #expect(ClockSigmaPrior(shape: 5, scale: 1e-100).curve == nil) + #expect(ClockSigmaPrior(shape: -1, scale: 1).curve == nil) + } + @Test func priorSettingsRoundTripAndLegacyDefaults() throws { var settings = AnalysisSettings() #expect(settings.clockSigmaPrior == .reference) diff --git a/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift b/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift index 61c4c36..4a96dd8 100644 --- a/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift +++ b/apps/macos/Tests/RoveAppTests/FeedbackPreviewTests.swift @@ -29,6 +29,8 @@ struct FeedbackPreviewTests { workspace.settings.apply(SamplingPreset(millions: 30)) workspace.settings.checkpointEvery = 50_000 workspace.settings.chains = 2 + workspace.settings.clockSigmaShape = "2.5" + workspace.settings.clockSigmaScale = "0.4" let run = AnalysisRun( request: RunRequest( id: UUID(), executable: engine, directory: output, @@ -57,12 +59,31 @@ struct FeedbackPreviewTests { .foregroundStyle(Lab.ink), name: "run", width: 820, height: 1300) try await render( SetupView(workspace: workspace).padding(28).background(Lab.background).foregroundStyle( - Lab.ink), name: "setup", width: 820, height: 2350) + Lab.ink), name: "setup", width: 820, height: 2850) + try await render( + ClockSigmaPriorChart(prior: .reference, strings: strings).padding(24) + .background(Lab.background).foregroundStyle(Lab.ink), + name: "sigma-prior", width: 620, height: 280) + try await render( + RootingSection(workspace: workspace).padding(24).background(Lab.background) + .foregroundStyle(Lab.ink), name: "rooting-compact", width: 620, height: 540) + let exporter = root.appendingPathComponent("fixtures/synthetic/exporter_labels.nex") + let exporterReport = try await MatrixInspector.inspect( + exporter, gapsAsMissing: false, partitioning: "labels", executable: engine) + let imported = Workspace(executable: engine, preferences: preferences) + imported.report = exporterReport + imported.file = exporter + imported.settings.partitioning = "labels" + try await render( + MatrixView(workspace: imported, report: exporterReport).padding(24) + .background(Lab.background).foregroundStyle(Lab.ink), + name: "observation-review", width: 820, height: 1250) @MainActor func render(_ content: V, name: String, width: CGFloat, height: CGFloat) async throws { - let view = NSHostingView(rootView: content) + let view = NSHostingView( + rootView: content.frame(width: width, height: height, alignment: .topLeading)) let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.borderless], backing: .buffered, defer: false) diff --git a/docs/es/guide/macos-preview.md b/docs/es/guide/macos-preview.md index 30d24df..a71c70a 100644 --- a/docs/es/guide/macos-preview.md +++ b/docs/es/guide/macos-preview.md @@ -474,3 +474,11 @@ El plan ofrece 1, 10, 20, 30, 50 y 100 millones de pasos, con intervalos de 100, Durante la ejecución, **Estimated time to step limit** y **Time per million steps** usan diferencias recientes de pasos y tiempo activo del motor. Primero se recogen al menos tres intervalos que cubran diez segundos, y luego se usan hasta ocho intervalos recientes. Cada cadena se mide por separado; la estimación del grupo es el mayor tiempo restante. Reanudar inicia una medición nueva que excluye el tiempo en pausa. Las estimaciones desaparecen al detener o terminar. La carga del procesador puede cambiar el ritmo. La predicción corresponde al límite de pasos, no a la convergencia; la parada automática puede terminar antes. **What are these files?** en Resultados y History abre una explicación sin conexión. La [guía de la carpeta](./run-files) muestra los archivos y el recorrido desde la traza hasta el árbol anotado. + +### Orientación visual del modelo + +El panel de enraizamiento dibuja la división impuesta: el terminal elegido a un lado y un grupo colapsado con todos los demás al otro. No estima longitudes de ramas, relaciones internas ni estados ancestrales. El recorrido inicial emplea la misma terminología. + +Abre **Clock sigma prior** para ver cómo cambia la densidad gamma con Alpha y Beta, en la parametrización forma/escala. La línea discontinua marca la esperanza del prior; también se muestra su desviación estándar. El rango dibujado no es un intervalo de credibilidad. Con forma menor que uno, la densidad diverge en cero y la curva comienza por encima de cero. Las escalas numéricas extremas pueden no tener vista gráfica; esto no altera el prior del motor. + +La duración estimada corresponde al límite solicitado de pasos y usa el tiempo activo reciente del motor. No predice cuándo se establecerá la convergencia. Los controles de selección de caracteres y datación explican sus supuestos junto a la validación; estas explicaciones no demuestran adecuación para un estudio concreto. diff --git a/docs/guide/macos-preview.md b/docs/guide/macos-preview.md index 4bf2830..29ccb71 100644 --- a/docs/guide/macos-preview.md +++ b/docs/guide/macos-preview.md @@ -462,3 +462,11 @@ The exploration plan offers 1, 10, 20, 30, 50 and 100 million steps, paired with During a run, **Estimated time to step limit** and **Time per million steps** use recent step and engine active-time differences. Rove first collects at least three intervals spanning ten seconds, then uses up to eight recent intervals. Each chain is measured separately; the group estimate is the longest remaining time. Pausing and resuming starts a fresh measurement without counting paused time. Estimates disappear when stopping or finished. CPU load can change the pace. This predicts the requested step limit, not convergence; automatic stopping may finish earlier. **What are these files?** in Results and History opens an offline explanation. See the [run-folder guide](./run-files) for the file map and a worked path from trace to annotated tree. + +### Visual model guidance + +The rooting panel draws the actual constrained split: the selected terminal on one side and a collapsed group containing every other terminal on the other. It does not estimate branch lengths, internal relationships or ancestral states. Onboarding uses the same rooting terminology. + +Expand **Clock sigma prior** to see the Gamma shape/scale density update as Alpha and Beta change. A dashed line marks the prior expectation; the panel also shows its standard deviation. The plotted range is a display window, not a credible interval. For shape below one, the density diverges at zero and the plotted curve starts above zero. Extreme numerical scales may have no graphical preview; this does not change the engine's prior. + +The run-time estimate predicts the requested step limit from recent active engine time. It does not predict when convergence will be established. Character-selection and fossil-dating controls explain their assumptions alongside their validation messages; these explanations do not establish that a model fits a particular study. diff --git a/docs/pt-BR/guide/macos-preview.md b/docs/pt-BR/guide/macos-preview.md index 00fa48b..780604a 100644 --- a/docs/pt-BR/guide/macos-preview.md +++ b/docs/pt-BR/guide/macos-preview.md @@ -478,3 +478,11 @@ O plano oferece 1, 10, 20, 30, 50 e 100 milhões de passos, com intervalos de 10 Durante a execução, **Tempo estimado até o limite de passos** e **Tempo por milhão de passos** usam diferenças recentes de passos e de tempo ativo do motor. O Rove primeiro coleta pelo menos três intervalos cobrindo dez segundos e depois usa até oito intervalos recentes. Cada cadeia é medida separadamente; a estimativa do grupo é o maior tempo restante. Retomar depois de uma pausa inicia uma nova medição, sem contar o tempo parado. As estimativas desaparecem ao interromper ou concluir. A carga do processador pode mudar o ritmo. A previsão é até o limite de passos, não até a convergência; a parada automática pode encerrar antes. **O que são estes arquivos?**, nos resultados e no Histórico, abre uma explicação offline. O [guia da pasta da execução](./run-files) mostra os arquivos e o caminho do traço até a árvore anotada. + +### Orientação visual sobre o modelo + +O painel de enraizamento desenha a divisão imposta: o terminal escolhido de um lado e um grupo recolhido com todos os demais do outro. Ele não estima comprimentos de ramos, relações internas ou estados ancestrais. O tour usa a mesma terminologia de enraizamento. + +Abra **Prior do sigma do relógio** para ver a densidade gamma mudar com Alpha e Beta, na parametrização forma/escala. Uma linha tracejada marca a esperança do prior; o painel também mostra o desvio padrão. O trecho desenhado não é um intervalo de credibilidade. Com forma menor que um, a densidade diverge em zero e a curva começa acima de zero. Escalas numéricas extremas podem não ter prévia gráfica; isso não muda o prior do motor. + +A previsão de duração estima o limite de passos solicitado usando o tempo ativo recente do motor. Ela não prevê quando a convergência será estabelecida. As opções de seleção de caracteres e datação explicam suas hipóteses junto das mensagens de validação; essas explicações não demonstram adequação a um estudo específico. diff --git a/docs/zh-CN/guide/macos-preview.md b/docs/zh-CN/guide/macos-preview.md index abb17dc..b0e1831 100644 --- a/docs/zh-CN/guide/macos-preview.md +++ b/docs/zh-CN/guide/macos-preview.md @@ -375,3 +375,11 @@ History 中已完成的运行包含 **Can the model reproduce the matrix?** 面 运行中,**Estimated time to step limit** 和 **Time per million steps** 根据近期步数及引擎有效运行时间的差值计算。先收集至少三个、跨度不少于十秒的间隔,之后最多使用最近八个间隔。各链分别估计,链组采用最长剩余时间。恢复运行时重新测量,不计暂停时间。停止或结束后不再显示估计。CPU 负载可能改变速度。估计的是达到请求步数上限的时间,不是收敛时间;自动停止可能提前结束。 结果和 History 中的 **What are these files?** 提供离线说明。[运行文件夹指南](./run-files)展示文件结构及从轨迹到注释树的操作示例。 + +### 模型的可视化说明 + +定根面板显示实际施加的分割:一侧是所选末端,另一侧是包含其余所有末端的折叠类群。示意图不估计枝长、内部关系或祖先状态。初始引导使用一致的定根术语。 + +展开 **Clock sigma prior**,可查看 Gamma 密度随 Alpha 和 Beta 的变化,参数化为形状/尺度。虚线标示先验期望值,同时显示标准差。绘图范围不是可信区间。形状参数小于 1 时,密度在零处发散,因此曲线从大于零的位置开始。极端数值尺度可能无法绘图,但不会改变引擎使用的先验。 + +运行时间预测根据近期引擎活动时间估计达到所请求步数上限的时间,不预测何时能够确认收敛。性状选择和化石定年控件在验证信息旁解释相应假设;这些解释本身不能证明模型适合某项研究。