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
use std::fmt;

use necsim_core::{event::SpeciationEvent, impl_finalise, impl_report, reporter::Reporter};

#[allow(clippy::module_name_repetitions)]
pub struct BiodiversityReporter {
    last_event: Option<SpeciationEvent>,

    biodiversity: usize,
}

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

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

impl<'de> serde::Deserialize<'de> for BiodiversityReporter {
    fn deserialize<D: serde::Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
        Ok(Self::default())
    }
}

impl Reporter for BiodiversityReporter {
    impl_report!(speciation(&mut self, speciation: Used) {
        if Some(speciation) == self.last_event.as_ref() {
            return;
        }

        self.last_event = Some(speciation.clone());

        self.biodiversity += 1;
    });

    impl_report!(dispersal(&mut self, _dispersal: Ignored) {});

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

    impl_finalise!((self) {
        if self.biodiversity > 0 {
            info!(
                "The simulation resulted in a biodiversity of {} unique species.",
                self.biodiversity
            );
        }
    });
}

impl Default for BiodiversityReporter {
    #[debug_ensures(ret.biodiversity == 0, "biodiversity initialised to 0")]
    fn default() -> Self {
        Self {
            last_event: None,
            biodiversity: 0,
        }
    }
}