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
#![deny(clippy::pedantic)]

use std::{
    convert::TryFrom,
    fmt,
    fs::{File, OpenOptions},
    io::{self, BufWriter, Write},
    path::PathBuf,
};

use serde::{Deserialize, Serialize};

use necsim_core::{
    impl_finalise, impl_report, landscape::IndexedLocation, lineage::GlobalLineageReference,
    reporter::Reporter,
};

necsim_plugins_core::export_plugin!(Csv => CsvReporter);

#[allow(clippy::module_name_repetitions)]
#[derive(Deserialize)]
#[serde(try_from = "CsvReporterArgs")]
pub struct CsvReporter {
    output: PathBuf,
    writer: Option<BufWriter<File>>,
}

impl fmt::Debug for CsvReporter {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct(stringify!(CsvReporter))
            .field("output", &self.output)
            .finish_non_exhaustive()
    }
}

impl serde::Serialize for CsvReporter {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        CsvReporterArgs {
            output: self.output.clone(),
        }
        .serialize(serializer)
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CsvReporterArgs {
    output: PathBuf,
}

impl TryFrom<CsvReporterArgs> for CsvReporter {
    type Error = io::Error;

    fn try_from(args: CsvReporterArgs) -> Result<Self, Self::Error> {
        // Preliminary argument parsing check if the output is a writable file
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&args.output)?;
        std::mem::drop(file);

        Ok(Self {
            output: args.output,
            writer: None,
        })
    }
}

impl Reporter for CsvReporter {
    impl_report!(speciation(&mut self, speciation: Used) {
        self.write_event(
            &speciation.global_lineage_reference,
            speciation.event_time.get(), &speciation.origin, 's'
        );
    });

    impl_report!(dispersal(&mut self, dispersal: Used) {
        self.write_event(
            &dispersal.global_lineage_reference,
            dispersal.event_time.get(), &dispersal.origin, 'd'
        );
    });

    impl_report!(progress(&mut self, _progress: Ignored) {});

    impl_finalise!((mut self) {
        if let Some(writer) = &mut self.writer {
            std::mem::drop(writer.flush());
        }
    });

    fn initialise(&mut self) -> Result<(), String> {
        if self.writer.is_some() {
            return Ok(());
        }

        let result = (|| -> io::Result<BufWriter<File>> {
            let file = OpenOptions::new()
                .create(true)
                .truncate(true)
                .write(true)
                .open(&self.output)?;

            let mut writer = BufWriter::new(file);

            writeln!(writer, "reference,time,x,y,index,type")?;

            Ok(writer)
        })();

        match result {
            Ok(writer) => {
                self.writer = Some(writer);

                Ok(())
            },
            Err(err) => Err(err.to_string()),
        }
    }
}

impl CsvReporter {
    fn write_event(
        &mut self,
        reference: &GlobalLineageReference,
        time: f64,
        origin: &IndexedLocation,
        r#type: char,
    ) {
        if let Some(writer) = &mut self.writer {
            std::mem::drop(writeln!(
                writer,
                "{},{},{},{},{},{}",
                reference,
                time,
                origin.location().x(),
                origin.location().y(),
                origin.index(),
                r#type,
            ));
        }
    }
}