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
use {
    crate::{
        *, 
        spacial::*, 
        er_c::draw_two_from_range
    },
    rand::Rng,
    std::{
        io::Write,
        f64::consts::PI
    }
};

#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};


/// # Implements a special Ensemble
///
/// * You can generate a dot file which includes special information.
/// * **NOTE** You should use **neato** for that to work 
/// * see [module](crate::spacial) for literature
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct SpacialEnsemble<T, R> 
{
    graph: SpacialGraph<T>,
    rng: R,
    f: f64,
    alpha: f64,
    sqrt_n_pi: f64,
}


impl<T, R> SpacialEnsemble<T, R> 
    where 
        T: Node, 
        R: Rng,
{
    /// Generate a new Spacial ensemble with 
    /// * `n` nodes
    /// * `rng` as random number generator
    /// * `f` - see paper
    /// * `alpha` - see paper
    /// 
    /// # The specific model I implemented is described in
    /// > Timo Dewenter and Alexander K. Hartmann,
    /// > "Large-deviation properties of resilience of power grids"
    /// > *New&nbsp;J.&nbsp;Phys.*&nbsp;**17**&nbsp;(2015),
    /// > DOI: [10.1088/1367-2630/17/1/015005](https://doi.org/10.1088/1367-2630/17/1/015005)
    pub fn new(n: usize, mut rng: R, f: f64, alpha: f64) -> Self
    {
        let mut graph = SpacialGraph::new(n);

        graph.vertices
            .iter_mut()
            .for_each(|v|
                {
                    v.x = rng.gen();
                    v.y = rng.gen();
                }
            );

        let mut res = Self{
            graph,
            rng,
            alpha,
            f,
            sqrt_n_pi: (n as f64 * PI).sqrt()
        };
        res.randomize();
        res
    }

    /// # Euclidean distance between two vertices
    /// * Calculates the distance between the vertices 
    /// corresponding to the indices `i` and `j`
    /// * `None` if any of the indices is out of bounds
    pub fn distance(&self, i: usize, j: usize) -> Option<f64>
    {
        self.as_ref()
            .distance(i, j)
    }

    /// # Calculates probability
    /// * calculates the probability for an edge between the 
    /// vertices corresponding to the indices `i` and `j`
    /// 
    /// Of cause you can check if there is currently an edge, but this probability is 
    /// the probability used when determining, if there should be an edge 
    pub fn edge_probability(&self, i: usize, j: usize) -> Option<f64>
    {
        let distance = self.distance(i, j)?;
        let prob = self.f * 
            (1.0 + self.sqrt_n_pi * distance / self.alpha)
            .powf(-self.alpha);
        Some(prob.clamp(0.0, 1.0))
    }

    #[inline]
    fn prob_unchecked(&self, i: usize, j: usize) -> f64
    {
        let distance = unsafe{
            self.graph
                .vertices
                .get_unchecked(i)
                .distance(self.graph.vertices.get_unchecked(j))
        };
        self.f * 
            (1.0 + self.sqrt_n_pi * distance / self.alpha)
            .powf(-self.alpha)
    }
}

impl<T, R> AsRef<SpacialGraph<T>> for SpacialEnsemble<T, R>
{
    fn as_ref(&self) -> &SpacialGraph<T>
    {
        &self.graph
    }
}


impl<T, R> SimpleSample for SpacialEnsemble<T, R>
where   T: Node + SerdeStateConform,
        R: rand::Rng,
{
    /// # Randomizes the edges according to Er probabilities
    /// * this is used by `ErEnsembleC::new` to create the initial topology
    /// * you can use this for sampling the ensemble
    /// * runs in `O(vertices * vertices)`
    fn randomize(&mut self) {
        self.graph.clear_edges();
        // iterate over all possible edges once
        for i in 0..self.graph.vertex_count() {
            for j in i+1..self.graph.vertex_count() {
                let prob = self.prob_unchecked(i, j);
                if self.rng.gen::<f64>() <= prob {
                    // in these circumstances equivalent to 
                    // self.graph.add_edge(i, j).unwrap();
                    // but without checking for existing edges and other errors -> a bit more efficient
                    unsafe{
                        self.graph
                            .vertices
                            .get_unchecked_mut(i)
                            .adj
                            .push(j);
                        self.graph
                            .vertices
                            .get_unchecked_mut(j)
                            .adj
                            .push(i);
                    }
                    
                    self.graph.edge_count += 1;
                }
            }
        }
    }
}

/// # Returned by markov steps
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum SpacialStep {
    /// nothing was changed
    Nothing,
    /// an edge was added
    AddedEdge((usize, usize)),
    /// an edge was removed
    RemovedEdge((usize, usize)),

    /// an error occured. Did you try to remove steps in the wrong order?
    Error,
}

impl<T, R> MarkovChain<SpacialStep, SpacialStep> for 
    SpacialEnsemble<T, R>
where 
    T: Node,
    R: Rng,
{
    fn m_step(&mut self) -> SpacialStep {
        let edge = draw_two_from_range(&mut self.rng, self.graph.vertex_count());
        let prob = self.prob_unchecked(edge.0, edge.1);
        if self.rng.gen::<f64>() <= prob {
            let success = self.graph.add_edge(edge.0, edge.1);
            match success{
                Ok(_) => SpacialStep::AddedEdge(edge),
                Err(_) => SpacialStep::Nothing,
            }
        } else {
            let success =  self.graph.remove_edge(edge.0, edge.1);
            match success {
                Ok(_)  => SpacialStep::RemovedEdge(edge),
                Err(_) => SpacialStep::Nothing,
            }
        }
    }

    fn m_steps_quiet(&mut self, count: usize) {
        for _ in 0..count {
            let (i, j) = draw_two_from_range(&mut self.rng, self.graph.vertex_count());
            let prob = self.prob_unchecked(i, j);
            if self.rng.gen::<f64>() <= prob {
                let _ = self.graph.add_edge(i, j);
            } else {
                let _ =  self.graph.remove_edge(i, j);
            }
        }
    }

    fn undo_step(&mut self, step: &SpacialStep) -> SpacialStep {
        match step {
            SpacialStep::AddedEdge(edge) => {
                let res = self.graph
                    .remove_edge(edge.0, edge.1);
                match res {
                    Ok(_) => SpacialStep::RemovedEdge(*edge),
                    _ => SpacialStep::Error,
                }
            },
            SpacialStep::RemovedEdge(edge) => {
                let res = self.graph
                    .add_edge(edge.0, edge.1);
                match res {
                    Ok(_) => SpacialStep::AddedEdge(*edge),
                    _ => SpacialStep::Error,
                }
            },
            SpacialStep::Nothing | SpacialStep::Error => *step,
            
        }
    }

    /// * panics if `step` is error, or cannot be undone
    /// The latter means, you are undoing the steps in the wrong order
    fn undo_step_quiet(&mut self, step: &SpacialStep) {
        match step {
            SpacialStep::AddedEdge(edge) =>
            {
                self.graph.remove_edge(edge.0, edge.1)
                    .expect("tried to remove non existing edge!");
            },
            SpacialStep::RemovedEdge(edge) => {
                self.graph
                    .add_edge(edge.0, edge.1)
                    .expect("Tried to add existing edge!");
            },
            SpacialStep::Nothing => (),
            SpacialStep::Error => unreachable!("You tried to undo an error! MarcovChain undo_step_quiet")
        }
    }
}

/// You should use **neato** if you want the correct spacial placement of nodes
impl<T, R> Dot for SpacialEnsemble<T, R>
where T: Node
{
    fn dot_from_indices<F, W, S1, S2>(&self, writer: W, dot_options: S1, mut f: F) -> Result<(), std::io::Error>
    where
        S1: AsRef<str>,
        S2: AsRef<str>,
        W: Write,
        F: FnMut(usize) -> S2 
    {
        self.graph.dot_from_indices(
            writer,
            dot_options,
            |index| {
                format!(
                    "{}\" pos=\"{:.2},{:.2}!",
                    f(index).as_ref(),
                    self.graph.container(index).x * 100.0,
                    100.0 * self.graph.container(index).y
                )
            }
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand_pcg::Pcg64;
    use rand::SeedableRng;
    use std::fs::*;
    #[test]
    fn spacial_print() {
        let rng = Pcg64::seed_from_u64(12232);
        let mut e = SpacialEnsemble::<EmptyNode, _>::new(50, rng, 0.95, 3.0);
        
        e.m_steps_quiet(2000);
        let f = File::create("Spacial.dot")
            .unwrap();
        e.dot(f, "").unwrap();
    }
}