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
use core::marker::PhantomData;

use necsim_core::{
    cogs::{
        coalescence_sampler::CoalescenceRngSample, Backup, EmigrationExit, Habitat, MathsCore,
        RngCore,
    },
    landscape::{IndexedLocation, Location},
    lineage::{GlobalLineageReference, MigratingLineage, TieBreaker},
    simulation::partial::emigration_exit::PartialSimulation,
};
use necsim_core_bond::{NonNegativeF64, PositiveF64};

use crate::{
    cogs::lineage_store::independent::IndependentLineageStore, decomposition::Decomposition,
};

pub mod choice;
use choice::EmigrationChoice;

#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct IndependentEmigrationExit<
    M: MathsCore,
    H: Habitat<M>,
    C: Decomposition<M, H>,
    E: EmigrationChoice<M, H>,
> {
    decomposition: C,
    choice: E,
    emigrant: Option<(u32, MigratingLineage)>,
    _marker: PhantomData<(M, H)>,
}

#[contract_trait]
impl<M: MathsCore, H: Habitat<M>, C: Decomposition<M, H>, E: EmigrationChoice<M, H>> Backup
    for IndependentEmigrationExit<M, H, C, E>
{
    unsafe fn backup_unchecked(&self) -> Self {
        Self {
            decomposition: self.decomposition.backup_unchecked(),
            choice: self.choice.backup_unchecked(),
            emigrant: self
                .emigrant
                .as_ref()
                .map(|(partition, migrating_lineage)| {
                    (*partition, migrating_lineage.backup_unchecked())
                }),
            _marker: PhantomData::<(M, H)>,
        }
    }
}

#[contract_trait]
impl<
        M: MathsCore,
        H: Habitat<M>,
        C: Decomposition<M, H>,
        E: EmigrationChoice<M, H>,
        G: RngCore<M>,
    > EmigrationExit<M, H, G, IndependentLineageStore<M, H>>
    for IndependentEmigrationExit<M, H, C, E>
{
    #[must_use]
    #[inline]
    #[debug_requires(self.emigrant.is_none(), "can only hold one emigrant")]
    #[debug_ensures(ret.is_some() == (
        (
            old(self.decomposition.map_location_to_subdomain_rank(
                &dispersal_target, &simulation.habitat
            )) == self.decomposition.get_subdomain().rank()
        ) || !old(self.choice.should_lineage_emigrate(
            &dispersal_origin,
            event_time,
            &simulation.habitat,
        ))
    ), "lineage only emigrates to other subdomains")]
    fn optionally_emigrate(
        &mut self,
        lineage_reference: GlobalLineageReference,
        dispersal_origin: IndexedLocation,
        dispersal_target: Location,
        prior_time: NonNegativeF64,
        event_time: PositiveF64,
        simulation: &mut PartialSimulation<M, H, G, IndependentLineageStore<M, H>>,
        rng: &mut G,
    ) -> Option<(
        GlobalLineageReference,
        IndexedLocation,
        Location,
        NonNegativeF64,
        PositiveF64,
    )> {
        let target_subdomain = self
            .decomposition
            .map_location_to_subdomain_rank(&dispersal_target, &simulation.habitat);

        if (target_subdomain == self.decomposition.get_subdomain().rank())
            || !self.choice.should_lineage_emigrate(
                &dispersal_origin,
                event_time,
                &simulation.habitat,
            )
        {
            return Some((
                lineage_reference,
                dispersal_origin,
                dispersal_target,
                prior_time,
                event_time,
            ));
        }

        self.emigrant = Some((
            target_subdomain,
            MigratingLineage {
                global_reference: lineage_reference,
                dispersal_origin,
                dispersal_target,
                prior_time,
                event_time,
                coalescence_rng_sample: CoalescenceRngSample::new(rng),
                tie_breaker: if self.decomposition.get_subdomain().rank() < target_subdomain {
                    TieBreaker::PreferImmigrant
                } else {
                    TieBreaker::PreferLocal
                },
            },
        ));

        None
    }
}

impl<M: MathsCore, H: Habitat<M>, C: Decomposition<M, H>, E: EmigrationChoice<M, H>>
    IndependentEmigrationExit<M, H, C, E>
{
    #[must_use]
    pub fn new(decomposition: C, choice: E) -> Self {
        Self {
            decomposition,
            choice,
            emigrant: None,
            _marker: PhantomData::<(M, H)>,
        }
    }

    pub fn len(&self) -> usize {
        usize::from(self.emigrant.is_some())
    }

    pub fn is_empty(&self) -> bool {
        self.emigrant.is_none()
    }

    pub fn take(&mut self) -> Option<(u32, MigratingLineage)> {
        self.emigrant.take()
    }
}