phragmms_balancing/
phragmms_balancing.rs1mod common;
21
22use common::*;
23use honggfuzz::fuzz;
24use rand::{self, SeedableRng};
25use sp_npos_elections::{
26 assignment_ratio_to_staked_normalized, phragmms, to_supports, BalancingConfig, ElectionResult,
27 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, 5, 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::Phragmms(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).evaluate();
60
61 if score.minimal_stake == 0 {
62 return
64 }
65 score
66 };
67
68 let config = BalancingConfig { iterations, tolerance: 0 };
69 let balanced: ElectionResult<AccountId, Perbill> =
70 phragmms(to_elect, candidates, voters, Some(config)).unwrap();
71
72 let balanced_score = {
73 let staked =
74 assignment_ratio_to_staked_normalized(balanced.assignments, &stake_of).unwrap();
75 to_supports(staked.as_ref()).evaluate()
76 };
77
78 let enhance = balanced_score.strict_threshold_better(unbalanced_score, Perbill::zero());
79
80 println!(
81 "iter = {} // {:?} -> {:?} [{}]",
82 iterations, unbalanced_score, balanced_score, enhance,
83 );
84
85 assert!(
88 balanced_score.minimal_stake >= unbalanced_score.minimal_stake &&
89 balanced_score.sum_stake == unbalanced_score.sum_stake &&
90 balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared
91 );
92 });
93 }
94}