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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! # Erdős-Rényi ensemble with target connectivity
//! * Draw from an Erdős-Rényi graph ensemble with a target connectivity.
//! * In this model, all possible edges are equally likely
//! * The number of edges is variable
//!
//! # Citations
//! > P. Erdős and A. Rényi, "On the evolution of random graphs,"
//!   Publ. Math. Inst. Hungar. Acad. Sci. **5**, 17-61 (1960)

use{
    crate::{
        traits::*,
        iter::*,
        graph::*
    },
    std::{
        borrow::Borrow,
        convert::AsRef,
        io::Write
    }
};

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

/// # Returned by markov steps
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum ErStepC {
    /// nothing was changed
    Nothing,
    /// an edge was added
    AddedEdge((usize, usize)),
    /// an edge was removed
    RemovedEdge((usize, usize)),
    /// a GraphError occured and is wrapped here
    GError(GraphErrors),
}

impl ErStepC {
    /// `true` if `self` is not `GError` variant
    pub fn is_valid(&self) -> bool {
        !matches!(self, Self::GError(..))
    }

    /// `panic!` if `self` is `GError` variant
    pub fn valid_or_panic(&self) {
        if let Self::GError(error) = self {
            panic!("ErStepC - invalid - {}", error)
        }
    }

    /// `panic!(msg)` if `self` is `GError` variant
    pub fn valid_or_panic_msg(&self, msg: &str) {
        if let Self::GError(error) = self {
            panic!("ErStepC - invalid {}- {}", msg, error)
        }
    }
}

/// # Implements Erdős-Rényi graph ensemble
/// * variable number of edges
/// * targets a connectivity
/// ## Sampling
/// * for *simple sampling* look at [```SimpleSample``` trait](./sampling/traits/trait.SimpleSample.html)
/// * for *markov steps* look at [```MarkovChain``` trait](../sampling/traits/trait.MarkovChain.html)
/// ## Other
/// * for topology functions look at [`GenericGraph`](../generic_graph/struct.GenericGraph.html)
/// * to access underlying topology or manipulate additional data look at [```WithGraph``` trait](../traits/trait.WithGraph.html)
/// * to use or swap the random number generator, look at [```HasRng``` trait](../traits/trait.HasRng.html)
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ErEnsembleC<T, R>
where T: Node
{
    graph: Graph<T>,
    prob: f64,
    c_target: f64,
    rng: R,
}

impl<T, R> AsRef<Graph<T>> for ErEnsembleC<T, R>
where T: Node,
      R: rand::Rng
{
    #[inline]
    fn as_ref(&self) -> &Graph<T>{
        &self.graph
    }
}

impl<T, R> Borrow<Graph<T>> for ErEnsembleC<T, R>
where T: Node,
      R: rand::Rng
{
    #[inline]
    fn borrow(&self) -> &Graph<T> {
        &self.graph
    }
}


impl<T, R> HasRng<R> for ErEnsembleC<T, R>
    where   T: Node,
            R: rand::Rng,
{
    /// # Access RNG
    /// If, for some reason, you want access to the internal random number generator: Here you go
    fn rng(&mut self) -> &mut R {
        &mut self.rng
    }

    /// # Swap random number generator
    /// * returns old internal rng
    fn swap_rng(&mut self, rng: &mut R) {
        std::mem::swap(&mut self.rng, rng);
    }
}

impl<T, R> SimpleSample for ErEnsembleC<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() {
                if self.rng.gen::<f64>() <= self.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
                    self.graph.vertices[i].adj.push(j);
                    self.graph.vertices[j].adj.push(i);
                    self.graph.edge_count += 1;
                }
            }
        }
    }
}

impl<T, R> MarkovChain<ErStepC, ErStepC> for ErEnsembleC<T, R>
    where   T: Node + SerdeStateConform,
            R: rand::Rng,
{

    /// # Markov step
    /// * use this to perform a markov step, e.g., to create a markov chain
    /// * result `ErStepC` can be used to undo the step with `self.undo_step(result)`
    fn m_step(&mut self) -> ErStepC {
        let edge = draw_two_from_range(&mut self.rng, self.graph.vertex_count());

        // Try to add edge. else: remove edge
        if self.rng.gen::<f64>() <= self.prob {

            let success = self.graph.add_edge(edge.0, edge.1);
            match success {
                Ok(_)  => ErStepC::AddedEdge(edge),
                Err(_) => ErStepC::Nothing,
            }

        } else {

            let success =  self.graph.remove_edge(edge.0, edge.1);
            match success {
                Ok(_)  => ErStepC::RemovedEdge(edge),
                Err(_) => ErStepC::Nothing,
            }
        }
    }

    /// # Undo a markcov step
    /// * adds removed edge, or removes added edge, or does nothing
    /// * if it returns an Err value, you probably used the function wrong
    /// ## Important:
    /// Restored graph is the same as before the random step **except** the order of nodes
    /// in the adjacency list might be shuffled!
    fn undo_step(&mut self, step: &ErStepC) -> ErStepC {
        match step {
            ErStepC::AddedEdge(edge)     => {
                let res = self.graph.remove_edge(edge.0, edge.1);
                match res {
                    Err(err)        => ErStepC::GError(err),
                    Ok(_)           => ErStepC::RemovedEdge(*edge),
                }
            },
            ErStepC::RemovedEdge(edge)   => {
                let res = self.graph.add_edge(edge.0, edge.1);
                match res {
                    Err(err)     => ErStepC::GError(err),
                    Ok(_)        => ErStepC::AddedEdge(*edge),
                }
            },
            ErStepC::Nothing |
            ErStepC::GError(_)   => *step,
        }
    }

    /// # Undo a markov step
    /// * adds removed edge, or removes added edge, or does nothing
    /// * if it returns an Err value, you probably used the function wrong
    /// ## Important:
    /// Restored graph is the same as before the random step **except** the order of nodes
    /// in the adjacency list might be shuffled!
    fn undo_step_quiet(&mut self, step: &ErStepC) {
        match step {
            ErStepC::AddedEdge(edge)     => {
                let res = self.graph.remove_edge(edge.0, edge.1);
                if res.is_err() {
                    panic!("ErEnsembleC - undo_step - panic {:?}", res.unwrap_err());
                }
            },
            ErStepC::RemovedEdge(edge)   => {
                let res = self.graph.add_edge(edge.0, edge.1);
                if res.is_err() {
                    panic!("ErEnsembleC - undo_step - panic {:?}", res.unwrap_err());
                }
            },
            _       => step.valid_or_panic_msg("ErEnsembleC - quiet")
        }
    }
}

impl<T, R> ErEnsembleC<T, R>
where T: Node + SerdeStateConform,
      R: rand::Rng
{
    /// # Initialize
    /// create new `ErEnsembleC` with:
    /// * `n` vertices
    /// * target connectivity `c_target`
    /// * `rng` is consumed and used as random number generator in the following
    /// * internally uses `Graph<T>::new(n)`
    /// * generates random edges according to ER model
    pub fn new(n: usize, c_target: f64, rng: R) -> Self {
        let prob = c_target / (n - 1) as f64;
        let graph: Graph<T> = Graph::new(n);
        let mut e = ErEnsembleC {
            graph,
            c_target,
            prob,
            rng,
        };
        e.randomize();
        e
    }

    /// # **Experimental!** Connect the connected components
    /// * adds edges, to connect the connected components
    /// * panics if no vertices are in the graph
    /// * intended as starting point for a markov chain, if you require connected graphs
    /// * do **not** use this to independently (simple-) sample connected networks,
    ///   as this will skew the statistics
    /// * **This is still experimental, this member might change the internal functionallity
    ///   resulting in different connected networks, without prior notice**
    /// * **This member might be removed in braking releases**
    pub fn make_connected(&mut self){
        let mut suggestions = self.graph.suggest_connections();
        let mut last_suggestion = suggestions.pop().unwrap();
        while let Some(suggestion) = suggestions.pop(){
            self.graph.add_edge(last_suggestion, suggestion).unwrap();
            last_suggestion = suggestion;
        }
    }

    /// returns target connectivity
    /// # Explanation
    /// The target connectivity `c_target` is used to
    /// calculate the probability `p`, that any two vertices `i` and `j` (where `i != j`)
    /// are connected.
    ///
    /// `p = c_target / (N - 1)`
    /// where `N` is the number of vertices in the graph
    pub fn target_connectivity(&self) -> f64 {
        self.c_target
    }

    /// * set new value for target connectivity
    /// ## Note
    /// * will only set the value (and probability), which will be used from now on
    /// * if you also want to create a new sample, call `randomize` afterwards
    pub fn set_target_connectivity(&mut self, c_target: f64) {
        let prob = c_target / (self.graph().vertex_count() - 1) as f64;
        self.prob = prob;
        self.c_target = c_target;
    }

    fn graph_mut(&mut self) -> &mut Graph<T> {
        &mut self.graph
    }
}

impl<T, R> GraphIteratorsMut<T, Graph<T>, NodeContainer<T>> for ErEnsembleC<T, R>
where   T: Node + SerdeStateConform,
        R: rand::Rng
{
    fn contained_iter_neighbors_mut(&mut self, index: usize) ->
        NContainedIterMut<T, NodeContainer<T>, IterWrapper>
    {
        self.graph.contained_iter_neighbors_mut(index)
    }

    fn contained_iter_neighbors_mut_with_index(&mut self, index: usize)
        -> INContainedIterMut<'_, T, NodeContainer<T>>
    {
        self.graph.contained_iter_neighbors_mut_with_index(index)
    }

    fn contained_iter_mut(&mut self) ->  ContainedIterMut<T, NodeContainer<T>> {
        self.graph.contained_iter_mut()
    }
}


impl<T, R> WithGraph<T, Graph<T>> for ErEnsembleC<T, R>
where   T: Node + SerdeStateConform,
        R: rand::Rng
{
    fn at(&self, index: usize) -> &T{
        self.graph.at(index)
    }

    fn at_mut(&mut self, index: usize) -> &mut T{
        self.graph.at_mut(index)
    }

    fn graph(&self) -> &Graph<T> {
        self.borrow()
    }

    /// # Sort adjecency lists
    /// If you depend on the order of the adjecency lists, you can sort them
    /// # Performance
    /// * internally uses [pattern-defeating quicksort](https://github.com/orlp/pdqsort)
    /// as long as that is the standard
    /// * sorts an adjecency list with length `d` in worst-case: `O(d log(d))`
    /// * is called for each adjecency list, i.e., `self.vertex_count()` times
    fn sort_adj(&mut self) {
        self.graph_mut().sort_adj();
    }
}

/// high is exclusive
#[inline]
pub(crate) fn draw_two_from_range<T: rand::Rng>(rng: &mut T, high: usize) -> (usize, usize){
    let first = rng.gen_range(0..high);
    let second = rng.gen_range(0..high - 1);

    if second < first {
        (first, second)
    } else {
        (first, second + 1)
    }
}

#[cfg(test)]
mod testing {
    use super::*;
    use rand_pcg::Pcg64;
    use crate::EmptyNode;
    use rand::SeedableRng;

    #[test]
    fn test_edge_count() {
        // create empty graph
        let rng = Pcg64::seed_from_u64(12);
        let mut e = ErEnsembleC::<EmptyNode, Pcg64>::new(100, 0.0, rng);
        let ec = e.graph().edge_count();
        assert_eq!(0, ec);
        // empty graph should not be connected:
        assert!(
            !e.graph()
                .is_connected()
                .expect("test_edge_count error 1")
        );
        assert!(e.graph.dfs(100).next().is_none());

        // add edge
        e.graph_mut()
            .add_edge(0, 1)
            .unwrap();
        let ec_1 = e.graph().edge_count();
        assert_eq!(1, ec_1);

        let mut res = e.graph_mut()
            .add_edge(0, 1);
        assert!(res.is_err());

        // remove edge
        e.graph_mut()
            .remove_edge(0, 1)
            .unwrap();
        let ec_0 = e.graph().edge_count();
        assert_eq!(0, ec_0);

        res = e.graph_mut()
            .remove_edge(0, 1);
        assert!(res.is_err());
    }

    #[test]
    fn draw_2(){
        let mut rng = Pcg64::seed_from_u64(762132);
        for _i in 0..100 {
            let (first, second) = draw_two_from_range(&mut rng, 2);
            assert!(first != second);
        }
        for i in 2..100 {
            let (first, second) = draw_two_from_range(&mut rng, i);
            assert!(first != second);
        }
    }
}


impl<T, R> Dot for ErEnsembleC<T, R>
where T: Node
{
    fn dot_from_indices<F, W, S1, S2>(&self, writer: W, dot_options: S1, 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, f)
    }

    fn dot<S, W>(&self, writer: W, dot_options: S) -> Result<(), std::io::Error>
    where
        S: AsRef<str>,
        W: Write {
        self.graph
            .dot(writer, dot_options)
    }

    fn dot_string<S>(&self, dot_options: S) -> String
    where
        S: AsRef<str> {
        self.graph.dot_string(dot_options)
    }

    fn dot_string_from_indices<F, S1, S2>(&self, dot_options: S1, f: F) -> String
    where
        S1: AsRef<str>,
        S2: AsRef<str>,
        F: FnMut(usize) -> S2 {
        self.graph
            .dot_string_from_indices(dot_options, f)
    }

    fn dot_string_with_indices<S>(&self, dot_options: S) -> String
    where
        S: AsRef<str> {
        self.graph
            .dot_string_with_indices(dot_options)
    }

    fn dot_with_indices<S, W>(
            &self, writer: W,
            dot_options: S
        ) -> Result<(), std::io::Error>
    where
        S: AsRef<str>,
        W: Write {
        self.graph
            .dot_with_indices(writer, dot_options)
    }
}

impl<T, R> Contained<T> for ErEnsembleC<T, R>
where T: Node
{
    fn get_contained(&self, index: usize) -> Option<&T> {
        self.graph.get_contained(index)
    }

    fn get_contained_mut(&mut self, index: usize) -> Option<&mut T> {
        self.graph.get_contained_mut(index)
    }

    unsafe fn get_contained_unchecked(&self, index: usize) -> &T {
        self.graph.get_contained_unchecked(index)
    }

    unsafe fn get_contained_unchecked_mut(&mut self, index: usize) -> &mut T {
        self.graph.get_contained_unchecked_mut(index)
    }
}