ligase 0.4.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! The `EntitySet` kind: the first that holds no sequence.
#![allow(clippy::unwrap_used, clippy::expect_used)]

use ligase::check;
use ligase::dim::Dimension;
use ligase::types::DataKind;

#[test]
fn a_gene_list_has_no_coordinate_system() {
    // The category error `types.rs` warns about: a gene list has no
    // coordinates, no contigs, no pairing and no quality scores, and
    // demanding any of them would be a gap nobody can fill.
    for dimension in [
        Dimension::ContigNaming,
        Dimension::Coordinates,
        Dimension::Pairing,
        Dimension::QualityEncoding,
        Dimension::Reference,
        Dimension::SampleSet,
    ] {
        assert!(!DataKind::EntitySet.applies(dimension), "{dimension}");
    }
}

#[test]
fn a_gene_list_carries_organism_namespace_subject_and_release() {
    for dimension in [
        Dimension::Organism,
        Dimension::IdentifierNamespace,
        Dimension::Subject,
        Dimension::Release,
    ] {
        assert!(DataKind::EntitySet.applies(dimension), "{dimension}");
    }
}

#[test]
fn no_kind_that_holds_sequence_has_an_identifier_namespace() {
    // Three kinds, since M15: a gene list, the ranked list that is a gene
    // list which remembers its order, and a knowledge graph. No sequence
    // kind has a namespace, because no sequence kind names entities.
    //
    // This was `only_a_kind_that_names_entities_has_…` until M17, and that
    // name stopped being true: a molecule table names entities too, and
    // claims no namespace, because `representation.identity` already says
    // which space its names are in and two axes carrying one fact is D36's
    // objection in mirror image. Renaming it rather than widening the
    // matchlist quietly is the point -- a test whose name no longer
    // describes what it asserts is a test nobody reads. See
    // `molecules.rs::an_identifier_namespace_is_not_a_molecule_sets_business`.
    for kind in DataKind::ALL {
        assert_eq!(
            kind.applies(Dimension::IdentifierNamespace),
            matches!(
                kind,
                DataKind::EntitySet | DataKind::RankedList | DataKind::KnowledgeGraph
            ),
            "{kind:?}"
        );
    }
}

#[test]
fn only_a_kind_that_is_about_something_named_has_a_subject() {
    // Five kinds since M17, and the molecule tables joined without
    // argument: a compound set is about a target, an assay or a
    // therapeutic area as squarely as a gene list is about a disease. The
    // sequence kinds are not about one named thing -- a BAM is a
    // measurement of a sample, which is `sample_set`.
    for kind in DataKind::ALL {
        assert_eq!(
            kind.applies(Dimension::Subject),
            matches!(
                kind,
                DataKind::EntitySet
                    | DataKind::RankedList
                    | DataKind::KnowledgeGraph
                    | DataKind::MoleculeSet
                    | DataKind::MoleculeRanking
            ),
            "{kind:?}"
        );
    }
}

#[test]
fn a_gene_list_claims_no_source_set() {
    // It never did, and now that matters more rather than less. A gene list
    // is one file, not an assembly, so there is no list of contributing
    // sources to be a fact about it -- and since M15 the axis is no longer
    // unapplied, so claiming it here would mean comparing a gene list on a
    // dimension it has nothing to say about.
    //
    // This test was `source_set_still_has_no_kind` through M8, M10 and M12,
    // each of which declined the axis and recorded that D36's dedup question
    // travelled on. M15 answered it: `KnowledgeGraph` applies the axis and
    // `SourceSet` compares exactly. See
    // `knowledge_graph.rs::a_source_set_compares_exactly`.
    assert!(!DataKind::EntitySet.applies(Dimension::SourceSet));
}

#[test]
fn two_gene_lists_must_both_say_which_space_they_are_in() {
    // A demand a user can always meet: declare it, or let the loader infer
    // it. Unknown on both sides would be two gene lists agreeing by silence.
    assert!(
        check::required_pair(DataKind::EntitySet, DataKind::EntitySet)
            .contains(&Dimension::IdentifierNamespace)
    );
}

#[test]
fn a_gene_list_demands_nothing_of_a_sequence_kind() {
    // A ranked list is not a sequence kind, and nor is a knowledge graph:
    // all three name entities, and the namespace is demanded between any
    // two of them. See
    // `ranked_list.rs::two_named_lists_must_both_say_which_space_they_are_in`
    // and `knowledge_graph.rs::two_graphs_must_both_say_which_space_they_are_named_in`.
    for kind in DataKind::ALL {
        if !matches!(
            kind,
            DataKind::EntitySet | DataKind::RankedList | DataKind::KnowledgeGraph
        ) {
            assert!(
                check::required_pair(DataKind::EntitySet, kind).is_empty(),
                "{kind:?}"
            );
            assert!(
                check::required_pair(kind, DataKind::EntitySet).is_empty(),
                "{kind:?}"
            );
        }
    }
}

#[test]
fn a_gene_list_round_trips_through_its_name() {
    assert_eq!(DataKind::EntitySet.name(), "EntitySet");
    assert_eq!(DataKind::from_name("EntitySet"), Some(DataKind::EntitySet));
}

#[test]
fn a_gene_list_is_written_as_a_table() {
    // Tools read a format off the name, so the suffix is not cosmetic.
    assert_eq!(ligase::exec::output_suffix(DataKind::EntitySet), ".tsv");
}

#[test]
fn a_dataset_carries_what_loading_it_noticed() {
    use ligase::dim::Dimensions;
    use ligase::note::Note;
    use ligase::types::Dataset;

    let noticed = Dataset::new(DataKind::EntitySet, None, Dimensions::default()).with_notes(vec![
        Note::IdentifierIsADate {
            identifier: "2-Sep".to_owned(),
        },
    ]);
    assert_eq!(noticed.notes().len(), 1);

    // And an ordinary dataset says nothing, so this channel stays silent
    // for every kind that has nothing to report.
    let quiet = Dataset::new(DataKind::Reference, None, Dimensions::default());
    assert!(quiet.notes().is_empty());
}

// ------------------------------------------------------------- loading --

mod common;

use common::fixture;
use ligase::dim::Source;
use ligase::load::{self, Declared};

/// A declaration naming the organism and nothing else.
fn declared_human() -> Declared {
    Declared {
        organism: Some(vec!["Homo sapiens".to_owned()]),
        ..Declared::default()
    }
}

#[test]
fn a_namespace_is_inferred_from_the_identifiers_themselves() {
    // `entities_hgnc.tsv` was in this table until M19 and is now in
    // `a_list_of_bare_symbols_leaves_the_namespace_unknown` below: its
    // shape carries no marker, so the file does not state its own space
    // (D56). Every space here does carry one, and still infers.
    for (file, expected) in [
        ("entities_ensembl.tsv", "Ensembl gene"),
        ("entities_entrez.tsv", "Entrez gene"),
        ("entities_uniprot.tsv", "UniProt accession"),
    ] {
        let loaded = load::entity_set(&fixture(file), None, &declared_human()).unwrap();
        let dimensions = loaded.dimensions();
        assert_eq!(
            dimensions.render(Dimension::IdentifierNamespace).as_deref(),
            Some(expected),
            "{file}"
        );
        // And it says where it got that from, which is what makes the
        // inference checkable rather than magic.
        let source = dimensions
            .source(Dimension::IdentifierNamespace)
            .map(Source::describe)
            .unwrap_or_default();
        assert!(
            source.contains("the identifiers' own pattern"),
            "{file}: {source}"
        );
    }
}

#[test]
fn a_file_that_mixes_two_namespaces_declines_to_infer() {
    let loaded = load::entity_set(&fixture("entities_mixed.tsv"), None, &declared_human()).unwrap();
    assert!(!loaded.dimensions().identifier_namespace.is_known());
    assert!(
        loaded
            .dimensions()
            .reason(Dimension::IdentifierNamespace)
            .is_some()
    );
}

#[test]
fn a_header_with_no_rows_declines_to_infer() {
    // Every pattern fits all zero identifiers, so a vacuous answer here
    // would declare a space for a file that names nothing.
    let loaded = load::entity_set(
        &fixture("entities_header_only.tsv"),
        None,
        &declared_human(),
    )
    .unwrap();
    assert!(!loaded.dimensions().identifier_namespace.is_known());
}

#[test]
fn the_loader_notices_a_symbol_excel_turned_into_a_date() {
    let loaded = load::entity_set(
        &fixture("entities_excel_dates.tsv"),
        None,
        &declared_human(),
    )
    .unwrap();
    let said: Vec<String> = loaded.notes().iter().map(ToString::to_string).collect();
    assert_eq!(loaded.notes().len(), 2, "{said:?}");
    assert!(said.iter().any(|note| note.contains("2-Sep")), "{said:?}");
    assert!(said.iter().any(|note| note.contains("1-Mar")), "{said:?}");
}

#[test]
fn a_carriage_return_is_not_part_of_an_identifier() {
    // Excel writes CRLF, and `TP53\r` matches no namespace at all.
    //
    // Since M19 a bare-symbol list infers no namespace either (D56), so
    // what is asserted is the *reason* the axis is unknown, and it is the
    // stronger assertion: `TP53` reaches the symbol shape and declines for
    // want of a marker, where `TP53\r` would reach no shape and decline for
    // being unreadable. Two sentences, and only one of them is this file's.
    let loaded = load::entity_set(&fixture("entities_crlf.tsv"), None, &declared_human()).unwrap();
    let why = loaded
        .dimensions()
        .reason(Dimension::IdentifierNamespace)
        .unwrap_or_default();
    assert!(why.contains("bare gene-symbol shapes"), "{why}");
    assert!(loaded.notes().is_empty());
}

#[test]
fn a_list_of_bare_symbols_leaves_the_namespace_unknown() {
    // D56. `entities_hgnc.tsv` holds `TP53`, `BRCA1`, `SEPT7` and `NKX2-1`,
    // which are HGNC symbols — and are also the exact shape of ChEMBL's
    // component synonyms and of most in-house panels. Through 0.3.0 this
    // file reported `HGNC symbol` with no hedge, and two files reporting it
    // alike is how an undeclared join across two spaces passed `check`.
    let loaded = load::entity_set(&fixture("entities_hgnc.tsv"), None, &declared_human()).unwrap();
    let dimensions = loaded.dimensions();
    assert_eq!(dimensions.render(Dimension::IdentifierNamespace), None);

    // And the reason sends the user to the one-argument fix, which is what
    // separates this from the spreadsheet-date case below.
    let why = dimensions
        .reason(Dimension::IdentifierNamespace)
        .unwrap_or_default();
    assert!(why.contains("bare gene-symbol shapes"), "{why}");
    assert!(why.contains("declare identifier_namespace"), "{why}");
    assert!(!why.contains("re-export"), "{why}");
}

#[test]
fn a_declared_namespace_wins_over_what_the_identifiers_look_like() {
    // A declaration is recorded, not checked: a user who says their list is
    // an in-house spelling is telling the engine something it cannot read
    // off the file, and `map_identifiers` is how they find out otherwise.
    let declared = Declared {
        identifier_namespace: Some("my curated list".to_owned()),
        ..declared_human()
    };
    let loaded = load::entity_set(&fixture("entities_hgnc.tsv"), None, &declared).unwrap();
    assert_eq!(
        loaded
            .dimensions()
            .render(Dimension::IdentifierNamespace)
            .as_deref(),
        Some("my curated list")
    );
    assert_eq!(
        loaded.dimensions().source(Dimension::IdentifierNamespace),
        Some(&Source::Declared)
    );
}

#[test]
fn a_blank_declared_namespace_is_a_gap_not_a_blank_label() {
    // A blank that compares equal to another blank is a false agreement.
    for blank in ["", "   "] {
        let declared = Declared {
            identifier_namespace: Some(blank.to_owned()),
            ..declared_human()
        };
        let loaded = load::entity_set(&fixture("entities_hgnc.tsv"), None, &declared).unwrap();
        // A blank is not a label, so the loader falls back to the
        // identifiers — which since M19 do not settle a bare-symbol list's
        // space either. Either way the axis must be *unknown*: a blank
        // label would compare equal to another blank label, and that is the
        // false agreement this test is about.
        assert_eq!(
            loaded
                .dimensions()
                .render(Dimension::IdentifierNamespace)
                .as_deref(),
            None,
            "{blank:?}"
        );
        assert!(
            !loaded.dimensions().is_known(Dimension::IdentifierNamespace),
            "{blank:?}"
        );
    }
}

#[test]
fn a_declared_subject_and_release_are_carried() {
    let declared = Declared {
        subject: Some("breast carcinoma".to_owned()),
        release: Some("HGNC 2026-09".to_owned()),
        ..declared_human()
    };
    let loaded = load::entity_set(&fixture("entities_hgnc.tsv"), None, &declared).unwrap();
    assert_eq!(
        loaded.dimensions().render(Dimension::Subject).as_deref(),
        Some("breast carcinoma")
    );
    assert_eq!(
        loaded.dimensions().render(Dimension::Release).as_deref(),
        Some("HGNC 2026-09")
    );
}

#[test]
fn the_identifier_column_can_be_named() {
    // The mapping table's own identifiers live under `id`; a file that
    // spells it differently says so rather than being guessed at.
    let loaded = load::entity_set(
        &fixture("map_hgnc_to_ensembl.tsv"),
        Some("id"),
        &declared_human(),
    )
    .unwrap();
    // The named column holds this table's source identifiers, which are
    // bare symbols: read, and declining for want of a marker (D56) rather
    // than for being unreadable. Had the column not been found, the loader
    // would have errored instead of reaching a reason at all.
    let why = loaded
        .dimensions()
        .reason(Dimension::IdentifierNamespace)
        .unwrap_or_default();
    assert!(why.contains("bare gene-symbol shapes"), "{why}");
}

#[test]
fn a_file_with_no_such_column_says_which_columns_it_has() {
    let error = load::entity_set(
        &fixture("entities_hgnc.tsv"),
        Some("symbol"),
        &declared_human(),
    )
    .unwrap_err();
    let said = error.to_string();
    assert!(said.contains("symbol"), "{said}");
    assert!(said.contains("log2fc"), "{said}");
}

#[test]
fn a_file_with_carriage_return_line_endings_is_read_as_its_rows() {
    // Excel 2011 and classic Mac tools write CR alone. Read as one line,
    // a 400-gene list loads as an empty gene list and says nothing -- which
    // is data loss that every later check would be happy with.
    let loaded =
        load::entity_set(&fixture("entities_cr_only.tsv"), None, &declared_human()).unwrap();
    // Read as one line the file holds a single unreadable identifier, which
    // declines for being unreadable; read as its rows it holds bare symbols,
    // which decline for want of a marker (D56). The reason is what tells
    // the two apart, so it is what this asserts.
    let why = loaded
        .dimensions()
        .reason(Dimension::IdentifierNamespace)
        .unwrap_or_default();
    assert!(why.contains("bare gene-symbol shapes"), "{why}");
}

#[test]
fn a_file_whose_symbols_are_dates_says_so_where_the_user_is_looking() {
    // The reason an axis is unknown is what a user acts on. "declare
    // identifier_namespace" is the one piece of advice that buries this
    // file's problem: declare it and `SEPT7` is missing from every join
    // for good. So the reason names the cause and sends them to the notes.
    let loaded = load::entity_set(
        &fixture("entities_excel_dates.tsv"),
        None,
        &declared_human(),
    )
    .unwrap();
    let reason = loaded
        .dimensions()
        .reason(Dimension::IdentifierNamespace)
        .unwrap();
    assert!(reason.contains("date"), "{reason}");
    assert!(reason.contains("notes"), "{reason}");

    // A file that merely mixes two spaces still gets the other reason.
    let mixed = load::entity_set(&fixture("entities_mixed.tsv"), None, &declared_human()).unwrap();
    let other = mixed
        .dimensions()
        .reason(Dimension::IdentifierNamespace)
        .unwrap();
    assert!(!other.contains("date"), "{other}");
    assert!(other.contains("declare"), "{other}");
}