phragmen_balancing/
phragmen_balancing.rs1mod common;
21
22use common::*;
23use honggfuzz::fuzz;
24use rand::{self, SeedableRng};
25use sp_npos_elections::{
26 assignment_ratio_to_staked_normalized, seq_phragmen, to_supports, BalancingConfig,
27 ElectionResult, EvaluateSupport, VoteWeight,
28};
29use sp_runtime::Perbill;
30
31fn main() {
32 loop {
33 fuzz!(|data: (usize, usize, usize, usize, u64)| {
34 let (mut target_count, mut voter_count, mut iterations, mut to_elect, seed) = data;
35 let rng = rand::rngs::SmallRng::seed_from_u64(seed);
36 target_count = to_range(target_count, 100, 200);
37 voter_count = to_range(voter_count, 100, 200);
38 iterations = to_range(iterations, 0, 30);
39 to_elect = to_range(to_elect, 25, target_count);
40
41 println!(
42 "++ [voter_count: {} / target_count:{} / to_elect:{} / iterations:{}]",
43 voter_count, target_count, to_elect, iterations,
44 );
45 let (unbalanced, candidates, voters, stake_of_tree) = generate_random_npos_result(
46 voter_count as u64,
47 target_count as u64,
48 to_elect,
49 rng,
50 ElectionType::Phragmen(None),
51 );
52
53 let stake_of = |who: &AccountId| -> VoteWeight { *stake_of_tree.get(who).unwrap() };
54
55 let unbalanced_score = {
56 let staked =
57 assignment_ratio_to_staked_normalized(unbalanced.assignments, &stake_of)
58 .unwrap();
59 let score = to_supports(staked.as_ref()).evaluate();
60
61 if score.minimal_stake == 0 {
62 return
64 }
65 score
66 };
67
68 if iterations > 0 {
69 let config = BalancingConfig { iterations, tolerance: 0 };
70 let balanced: ElectionResult<AccountId, sp_runtime::Perbill> =
71 seq_phragmen(to_elect, candidates, voters, Some(config)).unwrap();
72
73 let balanced_score = {
74 let staked =
75 assignment_ratio_to_staked_normalized(balanced.assignments, &stake_of)
76 .unwrap();
77 to_supports(staked.as_ref()).evaluate()
78 };
79
80 let enhance =
81 balanced_score.strict_threshold_better(unbalanced_score, Perbill::zero());
82
83 println!(
84 "iter = {} // {:?} -> {:?} [{}]",
85 iterations, unbalanced_score, balanced_score, enhance,
86 );
87
88 assert!(
91 balanced_score.minimal_stake >= unbalanced_score.minimal_stake &&
92 balanced_score.sum_stake == unbalanced_score.sum_stake &&
93 balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared
94 );
95 }
96 });
97 }
98}