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
pub mod version0;
pub mod version1;
pub mod version2;
pub mod version3;
pub mod version4;

pub use crate::testcase::runner::common::version0::TestcaseVersion0;
pub use crate::testcase::runner::common::version1::TestcaseVersion1;
pub use crate::testcase::runner::common::version2::TestcaseVersion2;
pub use crate::testcase::runner::common::version3::TestcaseVersion3;
pub use crate::testcase::runner::common::version4::TestcaseVersion4;

use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str;

use anyhow::Result;
use bio::io::fasta;
use bio::stats::{PHREDProb, Prob};
use eval::Expr;
use itertools::Itertools;
use rust_htslib::bcf::Read as BCFRead;
use rust_htslib::{bam, bcf};
use serde_json;
use tempfile::{self, NamedTempFile};
use yaml_rust::{Yaml, YamlLoader};

use crate::cli::{run, CallKind, PreprocessKind, VariantCallMode, Varlociraptor};
use crate::testcase::builder::Mode;
use crate::utils;

pub fn load_testcase(path: impl AsRef<Path>) -> Result<Box<dyn Testcase>> {
    let mut reader = File::open(path.as_ref().join("testcase.yaml"))?;
    let mut content2 = String::new();
    reader.read_to_string(&mut content2)?;
    let yaml = YamlLoader::load_from_str(&content2)?;
    Ok(match &yaml[0]["version"] {
        Yaml::BadValue => Box::new(TestcaseVersion0 {
            inner: yaml,
            path: path.as_ref().to_owned(),
        }),
        Yaml::String(version) if version == "1" => Box::new(TestcaseVersion1 {
            inner: yaml,
            path: path.as_ref().to_owned(),
        }),
        Yaml::String(version) if version == "2" => Box::new(TestcaseVersion2 {
            inner: yaml,
            path: path.as_ref().to_owned(),
        }),
        Yaml::String(version) if version == "3" => Box::new(TestcaseVersion3 {
            inner: yaml,
            path: path.as_ref().to_owned(),
        }),
        Yaml::String(version) if version == "4" => Box::new(TestcaseVersion4 {
            inner: yaml,
            path: path.as_ref().to_owned(),
        }),
        _ => panic!("unsupported testcase version"),
    })
}

pub trait Testcase {
    fn inner(&self) -> &[Yaml];

    fn path(&self) -> &PathBuf;

    /// Index of record in the candidates.vcf to evaluate expressions for.
    fn test_record_index(&self) -> usize {
        self.yaml()
            .as_hash()
            .unwrap()
            .get(&Yaml::String("record-index".to_owned()))
            .map(|value| {
                value
                    .as_i64()
                    .expect("Invalid record index, expected integer") as usize
            })
            .unwrap_or(0)
    }

    fn preprocess_options(&self, sample_name: &str) -> String {
        self.yaml()["samples"][sample_name]["options"]
            .as_str()
            .unwrap()
            .to_owned()
    }

    fn mode(&self) -> Mode {
        match self.yaml()["mode"].as_str().unwrap() {
            "Generic" => Mode::Generic,
            "TumorNormal" => Mode::TumorNormal,
            _ => panic!("unsupported mode"),
        }
    }

    fn omit_strand_bias(&self) -> bool {
        if self.yaml()["omit_strand_bias"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_strand_bias"].as_bool().unwrap()
        }
    }

    fn omit_read_orientation_bias(&self) -> bool {
        if self.yaml()["omit_read_orientation_bias"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_read_orientation_bias"].as_bool().unwrap()
        }
    }

    fn omit_read_position_bias(&self) -> bool {
        if self.yaml()["omit_read_position_bias"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_read_position_bias"].as_bool().unwrap()
        }
    }

    fn omit_softclip_bias(&self) -> bool {
        if self.yaml()["omit_softclip_bias"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_softclip_bias"].as_bool().unwrap()
        }
    }

    fn omit_homopolymer_artifact_detection(&self) -> bool {
        if self.yaml()["omit_homopolymer_artifact_detection"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_homopolymer_artifact_detection"]
                .as_bool()
                .unwrap()
        }
    }

    fn omit_alt_locus_bias(&self) -> bool {
        if self.yaml()["omit_alt_locus_bias"].is_badvalue() {
            false
        } else {
            self.yaml()["omit_alt_locus_bias"].as_bool().unwrap()
        }
    }

    fn yaml(&self) -> &Yaml {
        &self.inner()[0]
    }

    fn output(&self) -> PathBuf {
        self.path().join("calls.bcf")
    }

    fn candidates(&self) -> PathBuf {
        self.path().join(self.yaml()["candidate"].as_str().unwrap())
    }

    fn samples(&self) -> Vec<String> {
        self.yaml()["samples"]
            .as_hash()
            .unwrap()
            .keys()
            .map(|name| name.as_str().unwrap().to_owned())
            .collect_vec()
    }

    fn sample_preprocessed_path(
        &self,
        sample_name: &str,
        temp_preprocess: &tempfile::TempDir,
    ) -> PathBuf {
        let mut path = temp_preprocess.as_ref().join(sample_name);
        path.set_extension("bcf");

        path
    }

    fn sample_observations_path(&self, sample_name: &str) -> PathBuf {
        let mut path = self.path().join("observations").join(sample_name);

        path
    }

    fn sample(&self, sample_name: &str) -> &Yaml {
        &self.yaml()["samples"][sample_name]
    }

    fn sample_bam(&self, sample_name: &str) -> PathBuf {
        self.path()
            .join(self.sample(sample_name)["path"].as_str().unwrap())
    }

    fn sample_alignment_properties(&self, sample_name: &str) -> String {
        self.sample(sample_name)["properties"]
            .as_str()
            .unwrap()
            .to_owned()
    }

    fn scenario(&self) -> Option<PathBuf> {
        self.yaml()["scenario"]
            .as_str()
            .map(|p| self.path().join(p))
    }

    fn purity(&self) -> Option<f64> {
        self.yaml()["purity"].as_f64()
    }

    fn run(&self, pairhmm_mode_override: &str) -> Result<()> {
        let temp_ref = self.reference()?;

        let temp_preprocess = tempfile::tempdir()?;

        // Step 1: preprocess all samples
        for sample_name in &self.samples() {
            let options = self.preprocess_options(sample_name);
            let mut options = serde_json::from_str(&options)?;
            match &mut options {
                Varlociraptor::Preprocess {
                    kind:
                        PreprocessKind::Variants {
                            ref mut reference,
                            ref mut candidates,
                            ref mut output,
                            ref mut bam,
                            ref mut alignment_properties,
                            ref mut output_raw_observations,
                            ref mut pairhmm_mode,
                            ..
                        },
                } => {
                    // prepare test bam
                    let test_bam = self.sample_bam(sample_name);
                    bam::index::build(&test_bam, None, bam::index::Type::Bai, 1).unwrap();

                    // prepare alignment properties
                    let props =
                        self.alignment_properties(&self.sample_alignment_properties(sample_name))?;

                    // replace options
                    *bam = test_bam;
                    *reference = PathBuf::from((*temp_ref).as_ref());
                    *candidates = self.candidates();
                    *output = Some(self.sample_preprocessed_path(sample_name, &temp_preprocess));
                    *alignment_properties = Some(props.path().to_owned());
                    *output_raw_observations = Some(self.sample_observations_path(sample_name));
                    *pairhmm_mode = pairhmm_mode_override.into();
                    run(options)?;
                }
                _ => panic!("bug: unsupported options"),
            }
        }

        // Step 2: run calling
        match self.mode() {
            Mode::Generic => {
                let options = Varlociraptor::Call {
                    kind: CallKind::Variants {
                        testcase_locus: None,
                        testcase_prefix: None,
                        testcase_anonymous: true,
                        omit_strand_bias: self.omit_strand_bias(),
                        omit_read_orientation_bias: self.omit_read_orientation_bias(),
                        omit_read_position_bias: self.omit_read_position_bias(),
                        omit_softclip_bias: self.omit_softclip_bias(),
                        omit_homopolymer_artifact_detection: self
                            .omit_homopolymer_artifact_detection(),
                        omit_alt_locus_bias: self.omit_alt_locus_bias(),
                        output: Some(self.output()),
                        propagate_info_fields: Vec::new(),
                        mode: VariantCallMode::Generic {
                            scenario: self.scenario().unwrap(),
                            sample_observations: self
                                .samples()
                                .iter()
                                .map(|sample_name| {
                                    format!(
                                        "{}={}",
                                        sample_name,
                                        self.sample_preprocessed_path(
                                            sample_name,
                                            &temp_preprocess
                                        )
                                        .to_str()
                                        .unwrap()
                                    )
                                })
                                .collect_vec(),
                        },
                        log_mode: "default".to_owned(),
                        full_prior: false,
                    },
                };

                Ok(run(options)?)
            }
            Mode::TumorNormal => {
                let options = Varlociraptor::Call {
                    kind: CallKind::Variants {
                        testcase_locus: None,
                        testcase_prefix: None,
                        testcase_anonymous: true,
                        omit_strand_bias: self.omit_strand_bias(),
                        omit_read_orientation_bias: self.omit_read_orientation_bias(),
                        omit_read_position_bias: self.omit_read_position_bias(),
                        omit_softclip_bias: self.omit_softclip_bias(),
                        omit_homopolymer_artifact_detection: self
                            .omit_homopolymer_artifact_detection(),
                        omit_alt_locus_bias: self.omit_alt_locus_bias(),
                        output: Some(self.output()),
                        propagate_info_fields: Vec::new(),
                        mode: VariantCallMode::TumorNormal {
                            tumor_observations: self
                                .sample_preprocessed_path("tumor", &temp_preprocess),
                            normal_observations: self
                                .sample_preprocessed_path("normal", &temp_preprocess),
                            purity: self.purity().unwrap(),
                        },
                        log_mode: "default".to_owned(),
                        full_prior: false,
                    },
                };

                Ok(run(options)?)
            }
        }
    }

    fn check(&self) {
        let mut reader = bcf::Reader::from_path(self.output()).unwrap();
        let mut calls = reader.records().map(|r| r.unwrap()).collect_vec();

        let calls: Box<dyn Iterator<Item = &mut bcf::Record>> =
            if utils::is_bnd(&mut calls[0]).expect("bug: failed to check for breakend") {
                Box::new(calls.iter_mut())
            } else {
                Box::new(calls.iter_mut().skip(self.test_record_index()).take(1))
            };

        for call in calls {
            let afs = call.format(b"AF").float().unwrap();
            if let Some(exprs) = self.yaml()["expected"]["allelefreqs"].as_vec() {
                for expr in exprs.iter() {
                    let mut expr = Expr::new(expr.as_str().unwrap());

                    for (sample, af) in reader.header().samples().into_iter().zip(afs.iter()) {
                        expr = expr.value(str::from_utf8(sample).unwrap(), af[0]);
                    }
                    assert!(
                        expr.exec()
                            .map(|v| v.as_bool().unwrap_or(false))
                            .unwrap_or(false),
                        "{:?} did not return true",
                        expr
                    );
                }
            }

            if let Some(exprs) = self.yaml()["expected"]["posteriors"].as_vec() {
                for expr in exprs.iter() {
                    let mut expr = Expr::new(expr.as_str().unwrap());

                    for rec in reader.header().header_records() {
                        match rec {
                            bcf::HeaderRecord::Info { values, .. } => {
                                let id = values.get("ID").unwrap().clone();
                                if id.starts_with("PROB_") {
                                    if let Ok(Some(values)) = call.info(id.as_bytes()).float() {
                                        expr = expr.value(id.clone(), values[0]);
                                        expr = expr.value(
                                            format!("PLAIN_{id}"),
                                            Prob::from(PHREDProb(values[0] as f64)),
                                        );
                                    }
                                }
                            }
                            _ => (), // ignore other tags
                        }
                    }
                    assert!(
                        expr.exec()
                            .map(|v| v.as_bool().unwrap_or(false))
                            .unwrap_or(false),
                        "{:?} did not return true",
                        expr
                    );
                }
            }
        }
    }

    fn reference(&self) -> Result<Box<dyn AsRef<Path>>> {
        let ref_name = self.yaml()["reference"]["name"].as_str().unwrap();
        let ref_seq = self.yaml()["reference"]["seq"].as_str().unwrap();

        let mut tmp_ref = tempfile::Builder::new().suffix(".fasta").tempfile()?;
        {
            let mut writer = fasta::Writer::new(&mut tmp_ref);
            writer.write(ref_name, None, ref_seq.as_bytes())?;
        }
        self.index_reference(&tmp_ref);

        Ok(Box::new(tmp_ref))
    }

    fn index_reference(&self, path: &dyn AsRef<Path>) {
        Command::new("samtools")
            .args(&["faidx", path.as_ref().to_str().unwrap()])
            .status()
            .expect("failed to create fasta index");
    }

    fn alignment_properties(&self, properties: &str) -> Result<NamedTempFile> {
        let mut tmp_props = tempfile::Builder::new().suffix(".json").tempfile()?;
        tmp_props.as_file_mut().write_all(properties.as_bytes())?;

        Ok(tmp_props)
    }
}