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
10 changes: 10 additions & 0 deletions .changeset/raw-trace-files-view.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@platforma-open/milaboratories.clone-annotation.block": patch
"@platforma-open/milaboratories.clone-annotation.model": patch
"@platforma-open/milaboratories.clone-annotation.ui": patch
"@platforma-open/milaboratories.clone-annotation.workflow": patch
---

Add a raw trace view on the Files tab. Open any uploaded Sanger file (.ab1/.scf) to
see its full-length chromatogram and read quality, with the Mott-trimmed ends marked —
the read as the instrument wrote it, before trimming and the consensus merge.
24 changes: 24 additions & 0 deletions model/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ export type TraceRead = {
/** Mean Phred over that stretch. Absent where the form carried no quality. */
meanQuality?: number;
kept: boolean;
/** Bases Mott trimming cut from the start and the end. Absent for a form that
* carries no quality, which is not trimmed. */
trimmed?: [number, number];
};

/** A trace that produced nothing usable, and why. */
Expand Down Expand Up @@ -260,6 +263,11 @@ export type TraceReport = {
sequences: Sequence[];
};

/**
* Every raw read behind each sequence and clone, for the raw-trace view. Paths are
* the ones the Files table shows; the UI maps each to its uploaded file. Keyed as
* the tables are, so a table selection resolves straight to its reads.
*/
/**
* How a sheet's columns are read. Stated by the scientist rather than guessed
* from the headers, on the same terms as the name pattern.
Expand Down Expand Up @@ -642,6 +650,22 @@ export const platforma = BlockModelV3.create({ dataModel, kind })
{ isActive: true },
)

// Each uploaded read as a downloadable blob handle, keyed by its import handle, so
// the UI can fetch the raw .ab1 bytes and draw the untrimmed chromatogram. These are
// the exported blobs (`traceBlobs`), not `fileImports`, which holds the import index.
// Reads upload in the main run, so a handle appears here only once the block has run.
// A project last run before this field existed has no `traceBlobs`, so its absence
// is normal, not an error.
.output("traceContent", (ctx) =>
Object.fromEntries(
ctx.outputs
?.resolve({ field: "traceBlobs", assertFieldType: "Input", allowPermanentAbsence: true })
?.mapFields((handle, acc) => [handle as ImportFileHandle, acc.getFileHandle()], {
skipUnresolved: true,
}) ?? [],
),
)

// Drives the sheet's upload and lets the UI read its bytes to offer the columns.
// The field exists only once a sheet has been picked, so its absence is normal.
.output(
Expand Down
72 changes: 70 additions & 2 deletions ui/src/FilesTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
} from "@platforma-open/milaboratories.clone-annotation.model";
import {
basename,
DEFAULT_QUALITY_THRESHOLD,
getFilePathFromHandle,
} from "@platforma-open/milaboratories.clone-annotation.model";
import type { PlAgHeaderComponentParams } from "@platforma-sdk/ui-vue";
Expand All @@ -14,12 +15,14 @@ import {
PlAgCellFile,
PlAgCellStatusTag,
PlAgColumnHeader,
PlAgTextAndButtonCell,
} from "@platforma-sdk/ui-vue";
import type { ColDef, GridApi, GridOptions, GridReadyEvent, IRowNode } from "ag-grid-enterprise";
import { AgGridVue } from "ag-grid-vue3";
import { computed, shallowRef } from "vue";
import { computed, ref, shallowRef } from "vue";
import { useApp } from "./app";
import { cloneKey } from "./properties";
import RawTraceViewer, { type RawTraceRead } from "./RawTraceViewer.vue";
import type { SelectedFile } from "./trace_set";
import { ALL_EXTENSIONS, compilePattern } from "./trace_set";

Expand Down Expand Up @@ -162,7 +165,26 @@ const wellLabel = computed(() => (identityIsName.value ? "Sequence ID" : "Well")

const columnDefs = computed<ColDef<FileRow>[]>(() => [
makeRowNumberColDef(),
{ headerName: "Path", field: "path", flex: 2, minWidth: 160 },
{
headerName: "Path",
field: "path",
flex: 2,
minWidth: 160,
// On an uploaded trace file, a hover button opens its raw Sanger trace. Other
// rows keep the plain path cell.
cellRendererSelector: (cell) =>
canViewRaw(cell.data)
? {
component: PlAgTextAndButtonCell,
params: {
icon: "maximize",
btnLabel: "Trace",
invokeRowsOnDoubleClick: false,
onClick: (p: { data?: FileRow }) => p.data && openRawRow(p.data),
},
}
: undefined,
},
...(hasValue("plate") && !identityIsName.value
? [{ headerName: "Plate", field: "plate", flex: 1, minWidth: 100 } satisfies ColDef<FileRow>]
: []),
Expand Down Expand Up @@ -262,6 +284,51 @@ const columnDefs = computed<ColDef<FileRow>[]>(() => [
},
]);

// Downloadable handle per uploaded read, keyed by its import handle. Present only
// after the block has run (reads upload in the main run), so the raw-trace action
// is offered only for files that are already there.
const traceContent = computed(() => app.model.outputs.traceContent ?? {});
const isTraceForm = computed(() => (app.model.data.form ?? "trace") === "trace");
const qualityThreshold = computed(
() => app.model.data.qualityThreshold ?? DEFAULT_QUALITY_THRESHOLD,
);

const rawOpen = ref(false);
const rawReads = ref<RawTraceRead[]>([]);

function rawLabel(row: FileRow): string {
return [row.plate, row.well, row.chain, row.direction].filter(Boolean).join(" / ") || row.path;
}

function rawReadsOf(rows: FileRow[]): RawTraceRead[] {
return rows.flatMap((row) => {
const handle = traceContent.value[row.file];
return handle
? [
{
key: row.key,
label: rawLabel(row),
chainLabel: "",
handle: handle.handle,
trimmed: row.read?.trimmed,
},
]
: [];
});
}

/** True once a file's read is uploaded, so its raw trace can be opened. */
function canViewRaw(row: FileRow | undefined): boolean {
return isTraceForm.value && row !== undefined && traceContent.value[row.file] !== undefined;
}

function openRawRow(row: FileRow) {
const reads = rawReadsOf([row]);
if (reads.length === 0) return;
rawReads.value = reads;
rawOpen.value = true;
}

const gridApi = shallowRef<GridApi<FileRow>>();

function onGridReady(params: GridReadyEvent) {
Expand Down Expand Up @@ -318,6 +385,7 @@ const gridOptions: GridOptions<FileRow> = {
:gridOptions="gridOptions"
@grid-ready="onGridReady"
/>
<RawTraceViewer v-model="rawOpen" :reads="rawReads" :quality-threshold="qualityThreshold" />
</template>

<style>
Expand Down
164 changes: 164 additions & 0 deletions ui/src/RawTraceViewer.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<script setup lang="ts">
/**
* Shows raw Sanger reads: each `.ab1` as its own row, drawn against its own base
* calls, at full length, before trimming or the consensus merge. It uses the
* sequence viewer's bare renderer, not the plugin: the plugin lays one consensus
* trace per chain, which is the opposite of what this view is for.
*/
import {
parseAb1,
SequenceViewerView,
traceFromRead,
type ChainData,
type ChainTrace,
type SequenceEntry,
type SequenceViewerData,
type SequenceViewerSettings,
} from "@milaboratories/sequence-viewer";
import { PlAlert, PlSlideModal, ReactiveFileContent } from "@platforma-sdk/ui-vue";
import { computed, ref } from "vue";

const reactiveFileContent = ReactiveFileContent.useGlobal();

/** The blob handle `ReactiveFileContent` reads bytes from; `traceContent` carries one
* per uploaded read (via each handle's `.handle`). */
type TraceHandle = NonNullable<Parameters<typeof reactiveFileContent.getContentBytes>[0]>;

/** One raw read to draw. */
export type RawTraceRead = {
/** Stable, unique row key. */
key: string;
/** Row label: plate, well, chain and direction. */
label: string;
/** Short chain tag beside the label (`VH`, `VL`), or empty. */
chainLabel: string;
/** Downloadable handle from the model's `traceContent` output. */
handle: TraceHandle;
/** Bases Mott trimming cut from the start and the end, to mark on the read. */
trimmed?: [number, number];
};

const props = defineProps<{
reads: RawTraceRead[];
/** Phred below which read quality is drawn red; Q20 when not given. */
qualityThreshold?: number;
title?: string;
}>();

const open = defineModel<boolean>({ required: true });

// View state only (decision D4): nothing is written back to the block.
const settings = ref<SequenceViewerSettings>({});

/** Most reads drawn at once; mirrors the viewer's own row limit. */
const ROW_LIMIT = 200;

// Self-placement needs no consensus, so a read placed once serves every clone it
// backs. The cost is the Smith-Waterman in `traceFromRead`; the cache pays it once
// per file for the page's life.
const cache = new Map<string, { nt?: string; trace: ChainData["trace"] }>();

function miss(reason: string): { status: "missing"; reason: string } {
return { status: "missing", reason };
}

// The trimmed ends as regions on the read, so the kept middle stands out. Each
// trim is counted from its own end, so it stays right even where the ab1's base
// count differs a little from Tracy's.
function trimRegions(ntLen: number, trimmed?: [number, number]): ChainData["regions"] {
if (trimmed === undefined || ntLen === 0) return miss("raw read, not annotated");
const [left, right] = trimmed;
const spans: { name: string; start: number; end: number }[] = [];
if (left > 0) spans.push({ name: "Trimmed", start: 0, end: Math.min(left, ntLen) });
if (right > 0) spans.push({ name: "Trimmed", start: Math.max(0, ntLen - right), end: ntLen });
return spans.length > 0 ? { status: "ok", value: spans } : miss("nothing trimmed");
}

function placeOf(handle: string, bytes: Uint8Array) {
let hit = cache.get(handle);
if (hit === undefined) {
try {
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
) as ArrayBuffer;
const read = parseAb1(buffer);
const trace: ChainTrace | undefined = traceFromRead(read, read.bases);
hit = {
nt: read.bases,
trace: trace ? { status: "ok", value: trace } : miss("read too short to place"),
};
} catch {
hit = { trace: miss("could not read the file") };
}
cache.set(handle, hit);
}
return hit;
}

const data = computed<SequenceViewerData>(() => {
const entries: SequenceEntry[] = [];
for (const read of props.reads.slice(0, ROW_LIMIT)) {
const bytes = reactiveFileContent.getContentBytes(read.handle)?.value;
if (bytes === undefined) continue;
const { nt, trace } = placeOf(read.handle, bytes);
const chain: ChainData = {
label: read.chainLabel,
nt,
aaOffset: 0,
regions: trimRegions(nt?.length ?? 0, read.trimmed),
segments: miss("raw read, not annotated"),
germline: miss("raw read, not annotated"),
liabilities: miss("raw read, not annotated"),
trace,
};
entries.push({ key: read.key, name: read.label, chains: [chain], properties: {} });
}
return { entries, properties: [] };
});

const loading = computed(() =>
props.reads
.slice(0, ROW_LIMIT)
.some((read) => reactiveFileContent.getContentBytes(read.handle)?.value === undefined),
);

const exceedsLimit = computed(() => props.reads.length > ROW_LIMIT);
</script>

<template>
<PlSlideModal v-model="open" width="100%" :close-on-outside-click="false">
<template #title>{{ title ?? "Raw traces" }}</template>
<div v-if="open" :class="$style.root">
<PlAlert v-if="reads.length === 0" type="warn" icon>No raw reads to show.</PlAlert>
<template v-else>
<PlAlert v-if="exceedsLimit" type="warn" icon label="Not every read is shown">
At most {{ ROW_LIMIT }} reads are shown at once. Select fewer to choose which.
</PlAlert>
<SequenceViewerView
v-model="settings"
:data="data"
:loading="loading"
:quality-threshold="qualityThreshold"
export-name="raw-traces"
:class="$style.view"
/>
</template>
</div>
</PlSlideModal>
</template>

<style module>
.root {
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
min-height: 0;
}

.view {
flex: 1;
min-height: 0;
}
</style>
5 changes: 5 additions & 0 deletions workflow/src/main.tpl.tengo
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ wf.setPreRun(assets.importTemplate(":prerun"))

wf.body(func(args) {
fileImports := {}
// The imported read blobs, keyed by import handle, so the UI can download the raw
// .ab1 bytes. fileImports holds the import index (for progress), not a blob.
traceBlobs := {}

traces := args.traces
if is_undefined(traces) {
Expand Down Expand Up @@ -91,6 +94,7 @@ wf.body(func(args) {
nextFile = nextFile + 1
fileIds[t.handle] = fileId
blobs[fileId] = imp.file
traceBlobs[t.handle] = file.exportFile(imp.file)

plate := "Unplaced"
if !is_undefined(t.fields) {
Expand All @@ -109,6 +113,7 @@ wf.body(func(args) {
blockId := wf.blockId().getDataAsJson()
outputs := {
fileImports: fileImports,
traceBlobs: traceBlobs,
clones: joined.clones,
unmatched: clones.unmatched(traces),
wellsWithoutProperties: joined.clonesWithout,
Expand Down
Loading