Struct net_ensembles::sw::SwEnsemble
source · [−]pub struct SwEnsemble<T: Node, R> { /* private fields */ }
Expand description
Implements small-world graph ensemble
- for more details look at documentation of module
sw
Sampling
- for markov steps look at
MarkovChain
trait - for simple sampling look at
SimpleSample
trait
Other
- for topology functions look at
GenericGraph
- to access underlying topology or manipulate additional data look at
WithGraph
trait - to use or swap the random number generator, look at
HasRng
trait
Minimal example
use net_ensembles::{SwEnsemble, EmptyNode};
use net_ensembles::traits::*; // I recommend always using this
use rand_pcg::Pcg64; //or whatever you want to use as rng
use net_ensembles::rand::SeedableRng; // I use this to seed my rng, but you can use whatever
let rng = Pcg64::seed_from_u64(12);
// now create small-world ensemble with 200 nodes
// and a rewiring probability of 0.3 for each edge
let sw_ensemble = SwEnsemble::<EmptyNode, Pcg64>::new(200, 0.3, rng);
Simple sampling example
use net_ensembles::{SwEnsemble, EmptyNode};
use net_ensembles::traits::*; // I recommend always using this
use rand_pcg::Pcg64; //or whatever you want to use as rng
use net_ensembles::rand::SeedableRng; // I use this to seed my rng, but you can use whatever
use std::fs::File;
use std::io::{BufWriter, Write};
let rng = Pcg64::seed_from_u64(122);
// now create small-world ensemble with 100 nodes
// and a rewiring probability of 0.3 for each edge
let mut sw_ensemble = SwEnsemble::<EmptyNode, Pcg64>::new(100, 0.3, rng);
// setup file for writing
let f = File::create("simple_sample_sw_example.dat")
.expect("Unable to create file");
let mut f = BufWriter::new(f);
f.write_all(b"#diameter bi_connect_max average_degree\n")
.unwrap();
// simple sample for 10 steps
sw_ensemble.simple_sample(10,
|ensemble|
{
let diameter = ensemble.graph()
.diameter()
.unwrap();
let bi_connect_max = ensemble.graph()
.clone()
.vertex_biconnected_components(false)[0];
let average_degree = ensemble.graph()
.average_degree();
write!(f, "{} {} {}\n", diameter, bi_connect_max, average_degree)
.unwrap();
}
);
// or just collect this into a vector to print or do whatever
let vec = sw_ensemble.simple_sample_vec(10,
|ensemble|
{
let diameter = ensemble.graph()
.diameter()
.unwrap();
let transitivity = ensemble.graph()
.transitivity();
(diameter, transitivity)
}
);
println!("{:?}", vec);
Save and load example
- only works if feature
"serde_support"
is enabled - Note:
"serde_support"
is enabled by default - I need the
#[cfg(feature = "serde_support")]
to ensure the example does compile if you opt out of the default feature - you can do not have to use
serde_json
, look here for more info
use net_ensembles::traits::*; // I recommend always using this
use serde_json;
use rand_pcg::Pcg64;
use net_ensembles::{SwEnsemble, EmptyNode, rand::SeedableRng};
use std::fs::File;
let rng = Pcg64::seed_from_u64(95);
// create small-world ensemble
let sw_ensemble = SwEnsemble::<EmptyNode, Pcg64>::new(200, 0.3, rng);
#[cfg(feature = "serde_support")]
{
// storing the ensemble in a file:
let sw_file = File::create("store_SW.dat")
.expect("Unable to create file");
// or serde_json::to_writer(sw_file, &sw_ensemble);
serde_json::to_writer_pretty(sw_file, &sw_ensemble);
// loading ensemble from file:
let mut read = File::open("store_SW.dat")
.expect("Unable to open file");
let sw: SwEnsemble::<EmptyNode, Pcg64> = serde_json::from_reader(read).unwrap();
}
Implementations
sourceimpl<T, R> SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcepub fn new(n: usize, r_prob: f64, rng: R) -> Self
pub fn new(n: usize, r_prob: f64, rng: R) -> Self
Initialize
- create new SwEnsemble graph with
n
vertices r_prob
is probability of rewiring for each edgerng
is consumed and used as random number generator in the following- internally uses
SwGraph<T>::new(n)
sourcepub fn new_with_distance(
n: usize,
distance: NonZeroUsize,
r_prob: f64,
rng: R
) -> Result<Self, GraphErrors>
pub fn new_with_distance(
n: usize,
distance: NonZeroUsize,
r_prob: f64,
rng: R
) -> Result<Self, GraphErrors>
Initialize
- create new SwEnsemble graph with
n
vertices r_prob
is probability of rewiring for each edgerng
is consumed and used as random number generator in the following- internally uses
SwGraph<T>::new(n)
distance
: Initial ring will be created by connecting every node to the neighbors which are not more than distance away in the ring
sourcepub fn make_connected(&mut self)
pub fn make_connected(&mut self)
Experimental! Connect the connected components
- resets edges, to connect the connected components
- 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
sourcepub fn draw_edge(&mut self) -> (usize, usize)
pub fn draw_edge(&mut self) -> (usize, usize)
- draws random edge
(i0, i1)
- edge rooted at
i0
- uniform probability
- result dependent on order of adjecency lists
mut
because it uses therng
sourcepub fn set_r_prob(&mut self, r_prob: f64)
pub fn set_r_prob(&mut self, r_prob: f64)
- set new value for rewiring probability
Note
- will only set the value, which will be used from now on
- if you also want to create a new sample, call
randomize
afterwards
sourcepub fn contained_iter_neighbors_mut(
&mut self,
index: usize
) -> NContainedIterMut<'_, T, SwContainer<T>, IterWrapper<'_>>ⓘNotable traits for NContainedIterMut<'a, T, A, I>impl<'a, T, A, I> Iterator for NContainedIterMut<'a, T, A, I>where
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
pub fn contained_iter_neighbors_mut(
&mut self,
index: usize
) -> NContainedIterMut<'_, T, SwContainer<T>, IterWrapper<'_>>ⓘNotable traits for NContainedIterMut<'a, T, A, I>impl<'a, T, A, I> Iterator for NContainedIterMut<'a, T, A, I>where
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
- retuns
GenericGraph::contained_iter_neighbors_mut
- otherwise you would not have access to this function, since no mut access to the graph is allowed
Trait Implementations
sourceimpl<T, R> AsRef<GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node,
R: Rng,
impl<T, R> AsRef<GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node,
R: Rng,
sourceimpl<T, R> Borrow<GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node,
R: Rng,
impl<T, R> Borrow<GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node,
R: Rng,
sourceimpl<T: Clone + Node, R: Clone> Clone for SwEnsemble<T, R>
impl<T: Clone + Node, R: Clone> Clone for SwEnsemble<T, R>
sourcefn clone(&self) -> SwEnsemble<T, R>
fn clone(&self) -> SwEnsemble<T, R>
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresourceimpl<T, R> Contained<T> for SwEnsemble<T, R>where
T: Node,
impl<T, R> Contained<T> for SwEnsemble<T, R>where
T: Node,
sourcefn get_contained(&self, index: usize) -> Option<&T>
fn get_contained(&self, index: usize) -> Option<&T>
Returns a reference to the element stored in the specified node or
None
if out of Boundssourcefn get_contained_mut(&mut self, index: usize) -> Option<&mut T>
fn get_contained_mut(&mut self, index: usize) -> Option<&mut T>
Returns a mutable reference to the element stored in the specified node or
None
if out of Boundssourceunsafe fn get_contained_unchecked(&self, index: usize) -> &T
unsafe fn get_contained_unchecked(&self, index: usize) -> &T
For a save alternative see get_contained Read more
sourceunsafe fn get_contained_unchecked_mut(&mut self, index: usize) -> &mut T
unsafe fn get_contained_unchecked_mut(&mut self, index: usize) -> &mut T
Returns a mutable reference to the element stored in the specified node Read more
sourceimpl<'de, T: Node, R> Deserialize<'de> for SwEnsemble<T, R>where
T: Deserialize<'de>,
R: Deserialize<'de>,
impl<'de, T: Node, R> Deserialize<'de> for SwEnsemble<T, R>where
T: Deserialize<'de>,
R: Deserialize<'de>,
sourcefn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl<T, R> Dot for SwEnsemble<T, R>where
T: Node,
impl<T, R> Dot for SwEnsemble<T, R>where
T: Node,
sourcefn dot_from_indices<F, W, S1, S2>(
&self,
writer: W,
dot_options: S1,
f: F
) -> Result<(), Error>where
S1: AsRef<str>,
S2: AsRef<str>,
W: Write,
F: FnMut(usize) -> S2,
fn dot_from_indices<F, W, S1, S2>(
&self,
writer: W,
dot_options: S1,
f: F
) -> Result<(), Error>where
S1: AsRef<str>,
S2: AsRef<str>,
W: Write,
F: FnMut(usize) -> S2,
f
to create labels depending on the indexdot_options
use dot_options!
macro and take a look at module dot_constants
sourcefn dot<S, W>(&self, writer: W, dot_options: S) -> Result<(), Error>where
S: AsRef<str>,
W: Write,
fn dot<S, W>(&self, writer: W, dot_options: S) -> Result<(), Error>where
S: AsRef<str>,
W: Write,
sourcefn dot_string<S>(&self, dot_options: S) -> Stringwhere
S: AsRef<str>,
fn dot_string<S>(&self, dot_options: S) -> Stringwhere
S: AsRef<str>,
self.dot()
, but returns a String insteadsourcefn dot_string_from_indices<F, S1, S2>(&self, dot_options: S1, f: F) -> Stringwhere
S1: AsRef<str>,
S2: AsRef<str>,
F: FnMut(usize) -> S2,
fn dot_string_from_indices<F, S1, S2>(&self, dot_options: S1, f: F) -> Stringwhere
S1: AsRef<str>,
S2: AsRef<str>,
F: FnMut(usize) -> S2,
self.dot_from_indices
but returns String insteadsourcefn dot_string_with_indices<S>(&self, dot_options: S) -> Stringwhere
S: AsRef<str>,
fn dot_string_with_indices<S>(&self, dot_options: S) -> Stringwhere
S: AsRef<str>,
self.dot_with_indices
but returns String insteadsourceimpl<T, R> GraphIteratorsMut<T, GenericGraph<T, SwContainer<T>>, SwContainer<T>> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> GraphIteratorsMut<T, GenericGraph<T, SwContainer<T>>, SwContainer<T>> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcefn contained_iter_neighbors_mut(
&mut self,
index: usize
) -> NContainedIterMut<'_, T, SwContainer<T>, IterWrapper<'_>>ⓘNotable traits for NContainedIterMut<'a, T, A, I>impl<'a, T, A, I> Iterator for NContainedIterMut<'a, T, A, I>where
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
fn contained_iter_neighbors_mut(
&mut self,
index: usize
) -> NContainedIterMut<'_, T, SwContainer<T>, IterWrapper<'_>>ⓘNotable traits for NContainedIterMut<'a, T, A, I>impl<'a, T, A, I> Iterator for NContainedIterMut<'a, T, A, I>where
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
T: 'a,
A: AdjContainer<T>,
I: Iterator<Item = &'a usize> + 'a, type Item = &'a mut T;
index
&mut T
sort_adj
will affect the ordersourcefn contained_iter_neighbors_mut_with_index(
&mut self,
index: usize
) -> INContainedIterMut<'_, T, SwContainer<T>>ⓘNotable traits for INContainedIterMut<'a, T, A>impl<'a, T, A> Iterator for INContainedIterMut<'a, T, A>where
T: 'a + Node,
A: AdjContainer<T>, type Item = (usize, &'a mut T);
fn contained_iter_neighbors_mut_with_index(
&mut self,
index: usize
) -> INContainedIterMut<'_, T, SwContainer<T>>ⓘNotable traits for INContainedIterMut<'a, T, A>impl<'a, T, A> Iterator for INContainedIterMut<'a, T, A>where
T: 'a + Node,
A: AdjContainer<T>, type Item = (usize, &'a mut T);
T: 'a + Node,
A: AdjContainer<T>, type Item = (usize, &'a mut T);
index
(index_neighbor: usize, neighbor: &mut T)
sort_adj
will affect the ordersourcefn contained_iter_mut(&mut self) -> ContainedIterMut<'_, T, SwContainer<T>>ⓘNotable traits for ContainedIterMut<'a, T, A>impl<'a, T, A> Iterator for ContainedIterMut<'a, T, A>where
T: 'a + Node,
A: AdjContainer<T>, type Item = &'a mut T;
fn contained_iter_mut(&mut self) -> ContainedIterMut<'_, T, SwContainer<T>>ⓘNotable traits for ContainedIterMut<'a, T, A>impl<'a, T, A> Iterator for ContainedIterMut<'a, T, A>where
T: 'a + Node,
A: AdjContainer<T>, type Item = &'a mut T;
T: 'a + Node,
A: AdjContainer<T>, type Item = &'a mut T;
Node
(for example EmptyNode
or whatever you used)sourceimpl<T, R> HasRng<R> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> HasRng<R> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcefn rng(&mut self) -> &mut R
fn rng(&mut self) -> &mut R
Access RNG
If, for some reason, you want access to the internal random number generator: Here you go
sourcefn swap_rng(&mut self, rng: &mut R)
fn swap_rng(&mut self, rng: &mut R)
Swap random number generator
- returns old internal rng
sourceimpl<T, R> MarkovChain<SwChangeState, SwChangeState> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> MarkovChain<SwChangeState, SwChangeState> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcefn m_step(&mut self) -> SwChangeState
fn m_step(&mut self) -> SwChangeState
Markov step
- use this to perform a markov step
- keep in mind, that it is not unlikely for a step to do
Nothing
as it works by drawing an edge and then reseting it withr_prob
, else the edge is rewired - result
SwChangeState
can be used to undo the step withself.undo_step(result)
- result should never be
InvalidAdjecency
orGError
if used on a valid graph
sourcefn undo_step(&mut self, step: &SwChangeState) -> SwChangeState
fn undo_step(&mut self, step: &SwChangeState) -> SwChangeState
Undo a markov step
- rewires edge to old state
- Note: cannot undo
InvalidAdjecency
orGError
, will just returnInvalidAdjecency
orGError
respectively - returns result of rewire
Important:
Restored graph is the same as before the random step except the order of nodes in the adjacency list might be shuffled!
sourcefn undo_step_quiet(&mut self, step: &SwChangeState)
fn undo_step_quiet(&mut self, step: &SwChangeState)
Undo a Monte Carlo step
- rewires edge to old state
- panics if you try to undo
InvalidAdjecency
orGError
- panics if rewire result (
SwChangeState
) is invalid (i.e.!result.is_valid()
)
Important:
Restored graph is the same as before the random step except the order of nodes in the adjacency list might be shuffled!
sourcefn m_steps_quiet(&mut self, count: usize)
fn m_steps_quiet(&mut self, count: usize)
Markov steps without return Read more
sourcefn m_step_acc<Acc, AccFn>(&mut self, acc: &mut Acc, acc_fn: AccFn) -> Swhere
AccFn: FnMut(&Self, &S, &mut Acc),
fn m_step_acc<Acc, AccFn>(&mut self, acc: &mut Acc, acc_fn: AccFn) -> Swhere
AccFn: FnMut(&Self, &S, &mut Acc),
Accumulating markov step Read more
sourcefn m_steps_acc<Acc, AccFn>(
&mut self,
count: usize,
steps: &mut Vec<S, Global>,
acc: &mut Acc,
acc_fn: AccFn
)where
AccFn: FnMut(&Self, &S, &mut Acc),
fn m_steps_acc<Acc, AccFn>(
&mut self,
count: usize,
steps: &mut Vec<S, Global>,
acc: &mut Acc,
acc_fn: AccFn
)where
AccFn: FnMut(&Self, &S, &mut Acc),
Accumulating markov steps Read more
sourcefn m_steps_acc_quiet<Acc, AccFn>(
&mut self,
count: usize,
acc: &mut Acc,
acc_fn: AccFn
)where
AccFn: FnMut(&Self, &S, &mut Acc),
fn m_steps_acc_quiet<Acc, AccFn>(
&mut self,
count: usize,
acc: &mut Acc,
acc_fn: AccFn
)where
AccFn: FnMut(&Self, &S, &mut Acc),
Accumulating markov steps Read more
sourcefn undo_steps_quiet(&mut self, steps: &[S])
fn undo_steps_quiet(&mut self, steps: &[S])
Undo markov steps Read more
sourcefn steps_accepted(&mut self, _steps: &[S])
fn steps_accepted(&mut self, _steps: &[S])
Function called whenever the steps are accepted. Read more
sourcefn steps_rejected(&mut self, _steps: &[S])
fn steps_rejected(&mut self, _steps: &[S])
Function called whenever the steps are rejected. Read more
sourceimpl<T, R> SimpleSample for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> SimpleSample for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcefn randomize(&mut self)
fn randomize(&mut self)
Randomizes the edges according to small-world model
- this is used by
SwEnsemble::new
to create the initial topology - you can use this for sampling the ensemble
- runs in
O(vertices)
sourceimpl<T, R> WithGraph<T, GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
impl<T, R> WithGraph<T, GenericGraph<T, SwContainer<T>>> for SwEnsemble<T, R>where
T: Node + SerdeStateConform,
R: Rng,
sourcefn sort_adj(&mut self)
fn sort_adj(&mut self)
Sort adjecency lists
If you depend on the order of the adjecency lists, you can sort them
Performance
- internally uses pattern-defeating quicksort 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
Auto Trait Implementations
impl<T, R> RefUnwindSafe for SwEnsemble<T, R>where
R: RefUnwindSafe,
T: RefUnwindSafe,
impl<T, R> Send for SwEnsemble<T, R>where
R: Send,
T: Send,
impl<T, R> Sync for SwEnsemble<T, R>where
R: Sync,
T: Sync,
impl<T, R> Unpin for SwEnsemble<T, R>where
R: Unpin,
T: Unpin,
impl<T, R> UnwindSafe for SwEnsemble<T, R>where
R: UnwindSafe,
T: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<S, T> CastFloat<T> for Swhere
T: ConvFloat<S>,
impl<S, T> CastFloat<T> for Swhere
T: ConvFloat<S>,
fn cast_trunc(self) -> T
fn cast_trunc(self) -> T
Cast to integer, truncating Read more
fn cast_nearest(self) -> T
fn cast_nearest(self) -> T
Cast to the nearest integer Read more
fn cast_floor(self) -> T
fn cast_floor(self) -> T
Cast the floor to an integer Read more
fn try_cast_trunc(self) -> Result<T, Error>
fn try_cast_trunc(self) -> Result<T, Error>
Try converting to integer with truncation Read more
fn try_cast_nearest(self) -> Result<T, Error>
fn try_cast_nearest(self) -> Result<T, Error>
Try converting to the nearest integer Read more
fn try_cast_floor(self) -> Result<T, Error>
fn try_cast_floor(self) -> Result<T, Error>
Try converting the floor to an integer Read more
fn try_cast_ceil(self) -> Result<T, Error>
fn try_cast_ceil(self) -> Result<T, Error>
Try convert the ceiling to an integer Read more