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
3 changes: 3 additions & 0 deletions apps/macos/Sources/RoveApp/HistoryView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,9 @@ private struct HistoryDetail: View {
openWindow(id: "trace-diagnostics")
}.buttonStyle(LabButtonStyle(compact: true))
}
if entry.draft != nil && entry.status != .modelSetup {
RunAssessmentView(workspace: workspace, entry: entry)
}
if let draft = entry.draft, draft.settings.chains > 1, entry.status != .modelSetup {
ChainResultsView(
workspace: workspace, directory: entry.directory,
Expand Down
1 change: 1 addition & 0 deletions apps/macos/Sources/RoveApp/PredictiveCheckView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ struct PredictiveReportView: View {
}
Button(strings("Open folder")) { NSWorkspace.shared.open(prediction.directory) }
}.buttonStyle(LabButtonStyle(compact: true))
PredictiveDistributionView(prediction: prediction, strings: strings)
}
}

Expand Down
136 changes: 136 additions & 0 deletions apps/macos/Sources/RoveApp/PredictiveDistribution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import Charts
import SwiftUI

struct PredictiveDistribution: Sendable {
struct Bin: Identifiable, Sendable {
let id: Int
let lower: Double
let upper: Double
let count: Int
}
let name: String
let differences: [Double]
let undefined: Int

var bins: [Bin] {
guard let low = differences.min(), let high = differences.max() else { return [] }
let width = high == low ? max(abs(low) * 0.05, 0.1) : (high - low) / 20
guard width.isFinite && width > 0 else { return [] }
let start = high == low ? low - width / 2 : low
let count = high == low ? 1 : 20
var totals = [Int](repeating: 0, count: count)
for value in differences { totals[min(count - 1, max(0, Int((value - start) / width)))] += 1 }
return totals.indices.map {
Bin(
id: $0, lower: start + Double($0) * width,
upper: start + Double($0 + 1) * width, count: totals[$0])
}
}

static func read(_ prediction: SavedPrediction) throws -> [Self] {
struct Pair: Decodable {
let replicate: Int
let observed: [String: Double?]
let simulated: [String: Double?]
}
let file = prediction.directory.appendingPathComponent("replicates.jsonl")
let info = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
guard info.isRegularFile == true, (info.fileSize ?? 0) <= 64 * 1024 * 1024 else {
throw RunFailure.invalidCompletion
}
let data = try Data(contentsOf: file)
let pairs = try data.split(separator: 10).map {
try JSONDecoder().decode(Pair.self, from: Data($0))
}
guard pairs.count == prediction.report.replicates,
Set(pairs.map(\.replicate)) == Set(1...prediction.report.replicates)
else { throw RunFailure.invalidCompletion }
return try PredictiveReport.statistics.map { name in
let differences = try pairs.compactMap { pair -> Double? in
guard pair.observed.keys.contains(name), pair.simulated.keys.contains(name) else {
throw RunFailure.invalidCompletion
}
guard let a = pair.observed[name] ?? nil, let b = pair.simulated[name] ?? nil else {
return nil
}
let difference = b - a
guard a.isFinite, b.isFinite, difference.isFinite else {
throw RunFailure.invalidCompletion
}
return difference
}
guard let tail = prediction.report.global[name], tail.validPairs == differences.count,
tail.undefinedPairs == pairs.count - differences.count,
tail.lowerCount == differences.filter({ $0 <= 0 }).count,
tail.upperCount == differences.filter({ $0 >= 0 }).count,
tail.ties == differences.filter({ $0 == 0 }).count
else { throw RunFailure.invalidCompletion }
return Self(name: name, differences: differences, undefined: pairs.count - differences.count)
}
}
}

struct PredictiveDistributionView: View {
let prediction: SavedPrediction
let strings: AppStrings
@State private var distributions: [PredictiveDistribution] = []
@State private var selected = "parsimony_length"
@State private var failed = false

var body: some View {
VStack(alignment: .leading, spacing: 10) {
Picker(strings("Statistic"), selection: $selected) {
ForEach(PredictiveReport.statistics, id: \.self) { name in
Text(strings(PredictiveReportView.label(name))).tag(name)
}
}.frame(maxWidth: 360)
if let distribution = distributions.first(where: { $0.name == selected }) {
if !distribution.differences.isEmpty {
Chart {
ForEach(distribution.bins) { bin in
RectangleMark(
xStart: .value("Difference", bin.lower), xEnd: .value("Difference", bin.upper),
yStart: .value("Pairs", 0), yEnd: .value("Pairs", bin.count)
)
.foregroundStyle(Lab.lilac.opacity(0.7))
}
RuleMark(x: .value("Zero", 0)).lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3]))
.foregroundStyle(Lab.secondary)
}.frame(height: 180)
.chartXAxisLabel(strings("Simulated − observed"))
.chartYAxisLabel(strings("Valid pairs"))
.accessibilityLabel(
strings(
"Distribution of simulated minus observed paired statistics. Zero is equality."))
}
Text(
strings(
"%@ valid pairs · %@ undefined", String(distribution.differences.count),
String(distribution.undefined))
)
.font(.system(size: 10)).foregroundStyle(Lab.secondary)
} else if failed {
Text(
strings(
"Replicate details are missing or disagree with the check record. The distribution is unavailable."
)
)
.font(.system(size: 11)).foregroundStyle(Lab.secondary)
} else {
ProgressView().controlSize(.small)
}
Text(
strings(
"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test."
)
)
.font(.system(size: 10)).foregroundStyle(Lab.muted).fixedSize(
horizontal: false, vertical: true)
}.task(id: prediction.id) {
let prediction = prediction
distributions =
(try? await Task.detached { try PredictiveDistribution.read(prediction) }.value) ?? []
failed = distributions.isEmpty
}
}
}
38 changes: 38 additions & 0 deletions apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -1116,3 +1116,41 @@
"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "This is a prior preview, before seeing the data. The displayed range is not a credible interval.";
"Other %@ terminals" = "Other %@ terminals";
"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here.";

/* Evidence review and reproducibility exports. */
"Evidence review" = "Evidence review";
"What does this run establish?" = "What does this run establish?";
"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy.";
"Refresh evidence review" = "Refresh evidence review";
"Matching tree reports: %@ · Predictive reports: %@" = "Matching tree reports: %@ · Predictive reports: %@";
"Review record" = "Review record";
"Include the original matrix in the export" = "Include the original matrix in the export";
"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint.";
"Export reproducibility package…" = "Export reproducibility package…";
"Choose export folder" = "Choose export folder";
"Open exported package" = "Open exported package";
"Run completion" = "Run completion";
"Scalar sampling" = "Scalar sampling";
"Independent-chain agreement" = "Independent-chain agreement";
"Tree evidence" = "Tree evidence";
"Predictive evidence" = "Predictive evidence";
"Criteria met" = "Criteria met";
"Needs attention" = "Needs attention";
"Interpretation required" = "Interpretation required";
"Evidence unavailable" = "Evidence unavailable";
"The original matrix matches the recorded fingerprint." = "The original matrix matches the recorded fingerprint.";
"The original matrix has changed. Matrix inclusion will be refused." = "The original matrix has changed. Matrix inclusion will be refused.";
"The original matrix is unavailable. Records can still be exported without it." = "The original matrix is unavailable. Records can still be exported without it.";
"The review or export was cancelled." = "The review or export was cancelled.";
"The review or export could not be completed." = "The review or export could not be completed.";
"Recorded steps and sample files agree. Completion is not convergence." = "Recorded steps and sample files agree. Completion is not convergence.";
"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "The run is unfinished, incomplete or inconsistent. Review the source records and errors.";
"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not.";
"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence.";
"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space.";
"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy.";
"Simulated − observed" = "Simulated − observed";
"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribution of simulated minus observed paired statistics. Zero is equality.";
"%@ valid pairs · %@ undefined" = "%@ valid pairs · %@ undefined";
"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Replicate details are missing or disagree with the check record. The distribution is unavailable.";
"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test.";
Original file line number Diff line number Diff line change
Expand Up @@ -1116,3 +1116,41 @@
"This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "Esta é uma prévia do prior, antes de observar os dados. O intervalo exibido não é um intervalo de credibilidade.";
"Other %@ terminals" = "Outros %@ terminais";
"Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Diagrama da restrição. Os comprimentos dos ramos e as relações dentro do grupo recolhido não são estimados aqui.";

/* Evidence review and reproducibility exports. */
"Evidence review" = "Revisão das evidências";
"What does this run establish?" = "O que esta execução permite concluir?";
"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Revise separadamente a conclusão, a amostragem e os relatórios disponíveis. Este registro não certifica convergência nem adequação do modelo.";
"Refresh evidence review" = "Atualizar revisão das evidências";
"Matching tree reports: %@ · Predictive reports: %@" = "Relatórios de árvores correspondentes: %@ · Relatórios preditivos: %@";
"Review record" = "Registro da revisão";
"Include the original matrix in the export" = "Incluir a matriz original na exportação";
"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "O pacote local inclui configurações, sementes, identificação das compilações, amostras, diagnósticos e relatórios derivados com identificadores SHA-256. Os caminhos registrados e os nomes dos táxons são preservados. A retomada exata ainda exige o executável original e um checkpoint válido.";
"Export reproducibility package…" = "Exportar pacote de reprodução…";
"Choose export folder" = "Escolher pasta de exportação";
"Open exported package" = "Abrir pacote exportado";
"Run completion" = "Conclusão da execução";
"Scalar sampling" = "Amostragem dos parâmetros";
"Independent-chain agreement" = "Concordância entre cadeias independentes";
"Tree evidence" = "Evidências das árvores";
"Predictive evidence" = "Evidências preditivas";
"Criteria met" = "Critérios atendidos";
"Needs attention" = "Precisa de atenção";
"Interpretation required" = "Requer interpretação";
"Evidence unavailable" = "Evidência indisponível";
"The original matrix matches the recorded fingerprint." = "A matriz original corresponde ao identificador registrado.";
"The original matrix has changed. Matrix inclusion will be refused." = "A matriz original foi alterada. Sua inclusão será recusada.";
"The original matrix is unavailable. Records can still be exported without it." = "A matriz original está indisponível. Os registros ainda podem ser exportados sem ela.";
"The review or export was cancelled." = "A revisão ou exportação foi cancelada.";
"The review or export could not be completed." = "Não foi possível concluir a revisão ou exportação.";
"Recorded steps and sample files agree. Completion is not convergence." = "Os passos registrados e os arquivos de amostras correspondem. Concluir a execução não significa convergir.";
"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "A execução não terminou, está incompleta ou contém inconsistências. Revise os registros de origem e os erros.";
"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Revise todos os parâmetros amostrados: pelo menos 1.000 amostras retidas e ESS de 200 por cadeia, sem truncamento das defasagens. Valores comprovadamente fixos pelo modelo são excluídos; parâmetros amostrados que ficaram constantes não são.";
"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "A avaliação entre cadeias exige sementes independentes, entrada e modelo correspondentes, ESS de 200 por cadeia, pelo menos 1.000 amostras retidas e R-hat dividido e normalizado por postos de no máximo 1,01. Esses diagnósticos não comprovam convergência.";
"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Revise os resumos de árvores e as frequências dos clados sem restrição. Suporte alto ou concordância em clados constantes não demonstra exploração do espaço de árvores.";
"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Revise as discrepâncias preditivas pareadas, os pares indefinidos e a incerteza da simulação. Uma verificação salva, por si só, não demonstra adequação do modelo.";
"Simulated − observed" = "Simulado − observado";
"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribuição das diferenças pareadas entre estatísticas simuladas e observadas. Zero indica igualdade.";
"%@ valid pairs · %@ undefined" = "%@ pares válidos · %@ indefinidos";
"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Os detalhes das réplicas estão ausentes ou não correspondem ao registro da verificação. A distribuição está indisponível.";
"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Cada diferença usa a matriz simulada e a observada na mesma árvore posterior. A estatística observada pode variar conforme a árvore. Zero indica igualdade; este é um gráfico de discrepâncias, não um teste de convergência.";
Loading
Loading