ligase 0.3.0

Type-safe, reproducible computational biology pipelines (core engine)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Biological data types, and which dimensions each one can speak to.

use std::fmt;
use std::path::{Path, PathBuf};

use crate::dim::{Dimension, Dimensions};
use crate::hash::ContentHash;
use crate::note::Note;

/// What kind of biological data a dataset holds.
///
/// These are the types in the golden example, plus intervals: the reference
/// demo does not use them, but they are where the `coordinates` dimension
/// earns its keep.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataKind {
    /// Unaligned sequencing reads (FASTQ).
    Reads,
    /// A reference sequence (FASTA).
    Reference,
    /// Reads placed on a reference (SAM/BAM).
    Alignment,
    /// Variant calls (VCF).
    Variants,
    /// Genomic intervals (BED/GFF).
    Intervals,
    /// An interpreted drug-resistance report.
    ResistanceReport,
    /// A set of genes or proteins, named in one identifier space (TSV).
    EntitySet,
    /// The same, ranked: the row order is the result (TSV).
    ///
    /// Separate from [`Self::EntitySet`] for one reason, and it is the
    /// reason the kind exists: a ranking's canonical form keeps its order
    /// where a set's discards it (D41). Everything else about the two is
    /// the same, dimensions included, so a change to either that is not
    /// about order belongs to both.
    RankedList,
    /// Typed nodes and edges with per-edge provenance (JSON).
    ///
    /// The first kind here that is *assembled* rather than measured. What a
    /// graph holds is a function of which evidence sources were folded into
    /// it, no node or edge says what that list was, and two graphs that
    /// differ only in it join and score against each other in silence — so
    /// the sources are a dimension, which is what admits the kind under
    /// D35. See [`Dimension::SourceSet`], and
    /// [`load::knowledge_graph`](crate::load::knowledge_graph) for the
    /// failure in full.
    KnowledgeGraph,
    /// A set of molecules, named in one standardisation state (TSV).
    ///
    /// The kind `representation` admits. The same substance has different
    /// InChIKeys depending on what was done to it before the key was
    /// computed -- twelve of thirty ordinary drugs, measured -- and two
    /// columns of keys look identical whatever produced them. See
    /// [`Dimension::Representation`] and
    /// [`load::molecule_set`](crate::load::molecule_set).
    MoleculeSet,
    /// The same, ranked: the row order is the result (TSV).
    ///
    /// Separate from [`Self::MoleculeSet`] for the reason
    /// [`Self::RankedList`] is separate from [`Self::EntitySet`], and
    /// admitted on the same grounds: it brings no axis its unranked sibling
    /// does not bring, but a canonical form that sorted a ranking would
    /// declare two different answers identical and the cache would serve
    /// one for the other (D41, D48). For ten thousand docked compounds the
    /// order decides the length of the prefix anybody orders.
    MoleculeRanking,
}

impl DataKind {
    /// Every kind, so the Python layer can enumerate them.
    pub const ALL: [Self; 11] = [
        Self::Reads,
        Self::Reference,
        Self::Alignment,
        Self::Variants,
        Self::Intervals,
        Self::ResistanceReport,
        Self::EntitySet,
        Self::RankedList,
        Self::KnowledgeGraph,
        Self::MoleculeSet,
        Self::MoleculeRanking,
    ];

    /// The name used in messages and in the Python API.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Reads => "Reads",
            Self::Reference => "Reference",
            Self::Alignment => "Alignment",
            Self::Variants => "Variants",
            Self::Intervals => "Intervals",
            Self::ResistanceReport => "ResistanceReport",
            Self::EntitySet => "EntitySet",
            Self::RankedList => "RankedList",
            Self::KnowledgeGraph => "KnowledgeGraph",
            Self::MoleculeSet => "MoleculeSet",
            Self::MoleculeRanking => "MoleculeRanking",
        }
    }

    /// Look a kind up by the name [`Self::name`] gives it.
    ///
    /// Used by the Python layer to turn a step's type annotation into a
    /// kind, so the two surfaces cannot drift apart.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|kind| kind.name() == name)
    }

    /// Whether a dimension means anything for this kind.
    ///
    /// This encodes the `n/a` cells of the table in
    /// `web/content/reference/dimensions.mdx`. A dimension that does not
    /// apply is never compared and never demanded: asking a FASTA for its
    /// quality encoding is not a gap to be filled, it is a category error.
    #[must_use]
    pub const fn applies(self, dimension: Dimension) -> bool {
        match (self, dimension) {
            // Organism and sample set are meaningful everywhere they can be
            // stated; a report inherits both from what it was built from.
            (_, Dimension::Organism) => true,

            (Self::Reads, Dimension::SampleSet | Dimension::Pairing) => true,
            (Self::Reads, Dimension::QualityEncoding) => true,
            (Self::Reads, _) => false,

            (Self::Reference, Dimension::Reference | Dimension::ContigNaming) => true,
            // A reference has a release (GRCh38.p13 against GRCh38.p14), and
            // it is checked whenever both sides state it. It is deliberately
            // not in `check::required_pair`: a FASTA records no release, so
            // demanding one would make an ordinary file unloadable. A
            // demand the user cannot always meet is worse than a missed check.
            (Self::Reference, Dimension::Release) => true,
            (Self::Reference, _) => false,

            // Pairing applies to an alignment (the SAM flags record it), but
            // inferring it means reading records rather than headers, which
            // M1 does not do. It therefore stays unknown for now.
            (
                Self::Alignment,
                Dimension::Reference
                | Dimension::ContigNaming
                | Dimension::Coordinates
                | Dimension::SampleSet
                | Dimension::Pairing,
            ) => true,
            (Self::Alignment, _) => false,

            (
                Self::Variants,
                Dimension::Reference
                | Dimension::ContigNaming
                | Dimension::Coordinates
                | Dimension::SampleSet,
            ) => true,
            (Self::Variants, _) => false,

            // An interval file describes regions, not samples: no sample
            // set, no pairing, no quality scores.
            (
                Self::Intervals,
                Dimension::Reference | Dimension::ContigNaming | Dimension::Coordinates,
            ) => true,
            (Self::Intervals, _) => false,

            (Self::ResistanceReport, Dimension::SampleSet) => true,
            (Self::ResistanceReport, _) => false,

            // The kinds here that hold no sequence, and the place this
            // table earns the warning above it. A gene list has no
            // coordinate system, no contigs, no read pairing and no
            // quality scores -- not as gaps to be filled in, but because
            // a list of gene names has no such properties to have. What
            // it does have is the space its names live in, which is the
            // dimension it was admitted for (D35), the organism those
            // genes belong to, what the list is about, and the release of
            // whatever named them.
            // A ranked list is here beside the set rather than below it
            // because the two answer this question identically: they differ
            // in their canonical form and in nothing else (D41). Were one
            // given an axis the other lacked, the difference would have
            // spread past the one place it is meant to live.
            (
                Self::EntitySet | Self::RankedList,
                Dimension::IdentifierNamespace | Dimension::Subject | Dimension::Release,
            ) => true,
            (Self::EntitySet | Self::RankedList, _) => false,

            // A knowledge graph answers the three above the same way, for
            // the same reason: it names entities, it is about something,
            // and whatever named its entities had a release. It has its own
            // arm rather than joining the named lists' because of the
            // fourth axis, which is the one it was admitted for. A graph is
            // *assembled*, so which sources contributed is a fact about it
            // — and `source_set` applies to no other kind, because no other
            // kind is assembled from anything. Two named lists are each one
            // file; a BAM is a measurement.
            (
                Self::KnowledgeGraph,
                Dimension::IdentifierNamespace
                | Dimension::Subject
                | Dimension::Release
                | Dimension::SourceSet,
            ) => true,
            (Self::KnowledgeGraph, _) => false,

            // The molecule kinds, and the one axis they were admitted for.
            // A compound table names substances, it is about something --
            // a target, an assay, a therapeutic area -- and whatever named
            // its compounds had a release, so it answers those three as the
            // named lists do. What it brings is the fourth: what a name in
            // it *is*, and what standardisation produced it.
            //
            // `identifier_namespace` is deliberately absent even though an
            // InChIKey is an identifier space, because
            // `representation.identity` already says which space this file
            // is in. Two axes carrying one fact is D36's objection in
            // mirror image, and it would make `required_pair` demand two
            // things where one will do.
            //
            // `source_set` is absent too, and that one is a judgement
            // rather than a category error: a library merged from three
            // vendors *is* assembled. It is declined because nothing here
            // can read it -- which vendor a compound came from is a column,
            // an attribute, not a fact about the set -- and an axis the
            // loader cannot fill is the unexercised value type M7's
            // standing requirement exists to prevent.
            //
            // The ranking is here beside the set rather than below it for
            // the reason the ranked list is beside the gene list: the two
            // answer this question identically and differ only in their
            // canonical form (D41). Were one given an axis the other
            // lacked, the difference would have spread past the one place
            // it is meant to live.
            (
                Self::MoleculeSet | Self::MoleculeRanking,
                Dimension::Representation | Dimension::Subject | Dimension::Release,
            ) => true,
            (Self::MoleculeSet | Self::MoleculeRanking, _) => false,
        }
    }
}

/// What a remote input's reproducibility rests on.
///
/// Reported beside a step's own verdict rather than folded into it, because
/// the two are not on one scale: a replayed query is not a worse pinned
/// remote, and a pipeline's verdict should not degrade for using one.
///
/// Only `Pinned` exists yet. `Replayed` and `Live` arrive with
/// `RecordedQuery`, which is the other half of D39.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum RemoteVerdict {
    /// The same bytes forever, from the source, pinned by digest. Anyone,
    /// anywhere, at any time gets this input.
    Pinned,
    /// Served from a record of a past response, with no network touched.
    ///
    /// The same bytes forever *from the record*, which is a weaker promise
    /// than `Pinned` and a different one rather than a lesser one: the
    /// source promises nothing, so what makes this reproducible is that the
    /// body itself is in the store and travels in the bundle.
    Replayed,
    /// Fetched on this run, from a source that promises nothing.
    ///
    /// What the run that *writes* a record gets, and what a `--refresh`
    /// gets. Honest rather than reassuring: this run's answer came off the
    /// network, and it is the record written here that makes the next one
    /// repeatable.
    Live,
}

impl fmt::Display for RemoteVerdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Pinned => "pinned",
            Self::Replayed => "replayed",
            Self::Live => "live",
        })
    }
}

/// Where a dataset was fetched from.
///
/// The summary that travels with the dataset, as against the full record in
/// the cache: a locator and a kind are enough to find that record again, and
/// everything here is what a methods paragraph or an audit report prints.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origin {
    /// The locator as the pipeline wrote it, which is what a reader can go
    /// and look up. Not the URL that answered, which is a different fact.
    pub locator: String,
    /// The digest of what the fetched files mean, which is what the pin is
    /// over.
    pub digest: ContentHash,
    /// The digest of their bytes.
    pub bytes: ContentHash,
    /// When they were fetched, as seconds since the epoch.
    pub fetched_at: i64,
    /// What this input's reproducibility rests on.
    pub verdict: RemoteVerdict,
}

/// A piece of data, its kind, and the dimensions it carries.
#[derive(Clone, Debug)]
pub struct Dataset {
    kind: DataKind,
    /// Where this came from, when it did not come from a local file.
    ///
    /// `None` for the ordinary case — a path the user gave — and `Some` for
    /// a remote, which is what lets provenance, the methods paragraph and
    /// the audit report say that a result rests on something fetched rather
    /// than on something somebody already had.
    origin: Option<Origin>,
    path: Option<PathBuf>,
    /// The other files of the same dataset: the second mate of a pair.
    ///
    /// Kept beside `path` rather than replacing it because every other kind
    /// of data is one file, and a dataset's *primary* file is what a
    /// message names.
    mates: Vec<PathBuf>,
    dimensions: Dimensions,
    /// What loading this noticed, which its dimensions cannot say.
    ///
    /// Until now a [`Note`] could only come out of a step: either the
    /// canonical form of its output or the body's own account of its work.
    /// That leaves a file nobody computes with nothing to say, and a gene
    /// list is exactly such a file — its symbols can arrive corrupted by a
    /// spreadsheet, which is a fact about the input and not about any step.
    /// So a loader may attach notes to what it loaded, and they travel with
    /// the dataset to whoever is looking at it, `ligase inspect` included.
    notes: Vec<Note>,
}

impl Dataset {
    /// Build a dataset from its kind and dimensions.
    #[must_use]
    pub const fn new(kind: DataKind, path: Option<PathBuf>, dimensions: Dimensions) -> Self {
        Self {
            kind,
            origin: None,
            path,
            mates: Vec::new(),
            dimensions,
            notes: Vec::new(),
        }
    }

    /// The same dataset, with what loading it noticed.
    ///
    /// A builder rather than an argument to [`Self::new`], so that every
    /// loader that notices nothing — which is all of them but one — needs
    /// no change and says nothing by saying nothing.
    #[must_use]
    pub fn with_notes(mut self, notes: Vec<Note>) -> Self {
        self.notes = notes;
        self
    }

    /// The same dataset, with where it was fetched from.
    ///
    /// A builder for the reason [`Self::with_notes`] is one: a local file
    /// has no origin, which is nearly every dataset, and saying nothing
    /// should need no change at any call site.
    #[must_use]
    pub fn with_origin(mut self, origin: Origin) -> Self {
        self.origin = Some(origin);
        self
    }

    /// Where this was fetched from, if it was fetched.
    #[must_use]
    pub const fn origin(&self) -> Option<&Origin> {
        self.origin.as_ref()
    }

    /// The same dataset, with a second file belonging to it.
    #[must_use]
    pub fn with_mate(mut self, mate: PathBuf) -> Self {
        self.mates.push(mate);
        self
    }

    /// What kind of data this is.
    #[must_use]
    pub const fn kind(&self) -> DataKind {
        self.kind
    }

    /// The file it was loaded from, if it came from one.
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Every file this dataset is, in order.
    ///
    /// One file for everything except a paired sample, which is two — and
    /// their order is the pairing, so a step is handed `r1` and `r2` the way
    /// round they were read.
    #[must_use]
    pub fn files(&self) -> Vec<PathBuf> {
        self.path.iter().chain(self.mates.iter()).cloned().collect()
    }

    /// The dimensions it carries.
    #[must_use]
    pub const fn dimensions(&self) -> &Dimensions {
        &self.dimensions
    }

    /// What loading this noticed, which its dimensions cannot say.
    ///
    /// Empty for almost every file. A note is not an error and never stops
    /// a run; it is something true of the data that a user cannot act on
    /// without being told.
    #[must_use]
    pub fn notes(&self) -> &[Note] {
        &self.notes
    }
}