mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 19:51:05 +00:00
Rename all the election operations (#6245)
* Rename and move sp-phragmen * More renames for equalise * Update main module doc * Fix line width * Line width
This commit is contained in:
@@ -215,7 +215,7 @@ mod tests {
|
||||
assert_eq!(r(MAX128 - 10, MAX128).to_den(10), Ok(r(10, 10)));
|
||||
assert_eq!(r(MAX128 / 2, MAX128).to_den(10), Ok(r(5, 10)));
|
||||
|
||||
// large to perbill. This is very well needed for phragmen.
|
||||
// large to perbill. This is very well needed for npos-elections.
|
||||
assert_eq!(
|
||||
r(MAX128 / 2, MAX128).to_den(1000_000_000),
|
||||
Ok(r(500_000_000, 1000_000_000))
|
||||
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "sp-phragmen"
|
||||
name = "sp-npos-elections"
|
||||
version = "2.0.0-rc2"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://substrate.dev"
|
||||
repository = "https://github.com/paritytech/substrate/"
|
||||
description = "Phragmen primitives"
|
||||
description = "NPoS election algorithm primitives"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
@@ -15,13 +15,13 @@ targets = ["x86_64-unknown-linux-gnu"]
|
||||
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
sp-std = { version = "2.0.0-rc2", default-features = false, path = "../std" }
|
||||
sp-phragmen-compact = { version = "2.0.0-rc2", path = "./compact" }
|
||||
sp-npos-elections-compact = { version = "2.0.0-rc2", path = "./compact" }
|
||||
sp-arithmetic = { version = "2.0.0-rc2", default-features = false, path = "../arithmetic" }
|
||||
|
||||
[dev-dependencies]
|
||||
substrate-test-utils = { version = "2.0.0-rc2", path = "../../test-utils" }
|
||||
rand = "0.7.3"
|
||||
sp-phragmen = { version = "2.0.0-rc2", path = "." }
|
||||
sp-npos-elections = { version = "2.0.0-rc2", path = "." }
|
||||
sp-runtime = { version = "2.0.0-rc2", path = "../../primitives/runtime" }
|
||||
|
||||
[features]
|
||||
+11
-13
@@ -25,10 +25,15 @@ extern crate test;
|
||||
use test::Bencher;
|
||||
|
||||
use rand::{self, Rng};
|
||||
use sp_phragmen::{PhragmenResult, VoteWeight};
|
||||
use sp_npos_elections::{ElectionResult, VoteWeight};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use sp_runtime::{Perbill, traits::Zero};
|
||||
use sp_runtime::{Perbill, PerThing, traits::Zero};
|
||||
use sp_npos_elections::{
|
||||
balance_solution, assignment_ratio_to_staked, build_support_map, to_without_backing, VoteWeight,
|
||||
ExtendedBalance, Assignment, StakedAssignment, IdentifierT, assignment_ratio_to_staked,
|
||||
seq_phragmen,
|
||||
};
|
||||
|
||||
// default params. Each will be scaled by the benchmarks individually.
|
||||
const VALIDATORS: u64 = 100;
|
||||
@@ -42,13 +47,7 @@ const PREFIX: AccountId = 1000_000;
|
||||
type AccountId = u64;
|
||||
|
||||
mod bench_closure_and_slice {
|
||||
use sp_phragmen::{
|
||||
VoteWeight, ExtendedBalance, Assignment, StakedAssignment, IdentifierT,
|
||||
assignment_ratio_to_staked,
|
||||
};
|
||||
use sp_runtime::{Perbill, PerThing};
|
||||
use rand::{self, Rng, RngCore};
|
||||
use test::Bencher;
|
||||
use super::*;
|
||||
|
||||
fn random_assignment() -> Assignment<u32, Perbill> {
|
||||
let mut rng = rand::thread_rng();
|
||||
@@ -135,7 +134,7 @@ fn do_phragmen(
|
||||
});
|
||||
|
||||
b.iter(|| {
|
||||
let PhragmenResult { winners, assignments } = sp_phragmen::elect::<AccountId, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<AccountId, Perbill>(
|
||||
to_elect,
|
||||
Zero::zero(),
|
||||
candidates.clone(),
|
||||
@@ -146,14 +145,13 @@ fn do_phragmen(
|
||||
*stake_of_tree.get(who).unwrap()
|
||||
};
|
||||
|
||||
// Do the benchmarking with equalize.
|
||||
// Do the benchmarking with balancing.
|
||||
if eq_iters > 0 {
|
||||
use sp_phragmen::{equalize, assignment_ratio_to_staked, build_support_map, to_without_backing};
|
||||
let staked = assignment_ratio_to_staked(assignments, &stake_of);
|
||||
let winners = to_without_backing(winners);
|
||||
let mut support = build_support_map(winners.as_ref(), staked.as_ref()).0;
|
||||
|
||||
equalize(
|
||||
balance_solution(
|
||||
staked.into_iter().map(|a| (a.clone(), stake_of(&a.who))).collect(),
|
||||
&mut support,
|
||||
eq_tolerance,
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "sp-phragmen-compact"
|
||||
name = "sp-npos-elections-compact"
|
||||
version = "2.0.0-rc2"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://substrate.dev"
|
||||
repository = "https://github.com/paritytech/substrate/"
|
||||
description = "Phragmen Compact Solution"
|
||||
description = "NPoS Compact Solution Type"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
+7
-1
@@ -57,7 +57,13 @@ fn from_impl(count: usize) -> TokenStream2 {
|
||||
let last = quote!(index_of_target(&distribution[#last_index].0).ok_or(_phragmen::Error::CompactInvalidIndex)?);
|
||||
|
||||
quote!(
|
||||
#c => compact.#field_name.push((index_of_voter(&who).ok_or(_phragmen::Error::CompactInvalidIndex)?, [#inner], #last)),
|
||||
#c => compact.#field_name.push(
|
||||
(
|
||||
index_of_voter(&who).ok_or(_phragmen::Error::CompactInvalidIndex)?,
|
||||
[#inner],
|
||||
#last,
|
||||
)
|
||||
),
|
||||
)
|
||||
}).collect::<TokenStream2>();
|
||||
|
||||
+6
-6
@@ -15,7 +15,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Proc macro for phragmen compact assignment.
|
||||
//! Proc macro for a npos compact assignment.
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::{TokenStream as TokenStream2, Span, Ident};
|
||||
@@ -29,7 +29,7 @@ mod staked;
|
||||
// prefix used for struct fields in compact.
|
||||
const PREFIX: &'static str = "votes";
|
||||
|
||||
/// Generates a struct to store the phragmen assignments in a compact way. The struct can only store
|
||||
/// Generates a struct to store the election assignments in a compact way. The struct can only store
|
||||
/// distributions up to the given input count. The given count must be greater than 2.
|
||||
///
|
||||
/// ```ignore
|
||||
@@ -176,7 +176,7 @@ fn struct_def(
|
||||
}).collect::<TokenStream2>();
|
||||
|
||||
Ok(quote! (
|
||||
/// A struct to encode a Phragmen assignment in a compact way.
|
||||
/// A struct to encode a election assignment in a compact way.
|
||||
#[derive(
|
||||
Default,
|
||||
PartialEq,
|
||||
@@ -224,9 +224,9 @@ fn struct_def(
|
||||
}
|
||||
|
||||
fn imports() -> Result<TokenStream2> {
|
||||
let sp_phragmen_imports = match crate_name("sp-phragmen") {
|
||||
Ok(sp_phragmen) => {
|
||||
let ident = syn::Ident::new(&sp_phragmen, Span::call_site());
|
||||
let sp_phragmen_imports = match crate_name("sp-npos-elections") {
|
||||
Ok(sp_npos_elections) => {
|
||||
let ident = syn::Ident::new(&sp_npos_elections, Span::call_site());
|
||||
quote!( extern crate #ident as _phragmen; )
|
||||
}
|
||||
Err(e) => return Err(syn::Error::new(Span::call_site(), &e)),
|
||||
+3
-1
@@ -57,7 +57,9 @@ fn from_impl(count: usize) -> TokenStream2 {
|
||||
let last = quote!(index_of_target(&distribution[#last_index].0).ok_or(_phragmen::Error::CompactInvalidIndex)?);
|
||||
|
||||
quote!(
|
||||
#c => compact.#field_name.push((index_of_voter(&who).ok_or(_phragmen::Error::CompactInvalidIndex)?, [#inner], #last)),
|
||||
#c => compact.#field_name.push(
|
||||
(index_of_voter(&who).ok_or(_phragmen::Error::CompactInvalidIndex)?, [#inner], #last)
|
||||
),
|
||||
)
|
||||
}).collect::<TokenStream2>();
|
||||
|
||||
+5
-5
@@ -1234,19 +1234,19 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sp-phragmen"
|
||||
name = "sp-npos-elections"
|
||||
version = "2.0.0-alpha.3"
|
||||
dependencies = [
|
||||
"parity-scale-codec",
|
||||
"serde",
|
||||
"sp-core",
|
||||
"sp-phragmen-compact",
|
||||
"sp-npos-elections-compact",
|
||||
"sp-runtime",
|
||||
"sp-std",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sp-phragmen-compact"
|
||||
name = "sp-npos-elections-compact"
|
||||
version = "2.0.0-rc2"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
@@ -1256,12 +1256,12 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sp-phragmen-fuzzer"
|
||||
name = "sp-npos-elections-fuzzer"
|
||||
version = "2.0.0"
|
||||
dependencies = [
|
||||
"honggfuzz",
|
||||
"rand 0.7.3",
|
||||
"sp-phragmen",
|
||||
"sp-npos-elections",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "sp-phragmen-fuzzer"
|
||||
name = "sp-npos-elections-fuzzer"
|
||||
version = "2.0.0-alpha.5"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
@@ -7,14 +7,14 @@ license = "Apache-2.0"
|
||||
homepage = "https://substrate.dev"
|
||||
repository = "https://github.com/paritytech/substrate/"
|
||||
description = "Fuzzer for phragmén implementation."
|
||||
documentation = "https://docs.rs/sp-phragmen-fuzzer"
|
||||
documentation = "https://docs.rs/sp-npos-elections-fuzzer"
|
||||
publish = false
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
sp-phragmen = { version = "2.0.0-rc2", path = ".." }
|
||||
sp-npos-elections = { version = "2.0.0-rc2", path = ".." }
|
||||
sp-std = { version = "2.0.0-rc2", path = "../../std" }
|
||||
sp-runtime = { version = "2.0.0-rc2", path = "../../runtime" }
|
||||
honggfuzz = "0.5"
|
||||
@@ -25,5 +25,5 @@ name = "reduce"
|
||||
path = "src/reduce.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "equalize"
|
||||
path = "src/equalize.rs"
|
||||
name = "balance_solution"
|
||||
path = "src/balance_solution.rs"
|
||||
+16
-9
@@ -15,7 +15,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Fuzzing fro the equalize algorithm
|
||||
//! Fuzzing fro the balance_solution algorithm
|
||||
//!
|
||||
//! It ensures that any solution which gets equalized will lead into a better or equally scored
|
||||
//! one.
|
||||
@@ -23,9 +23,9 @@
|
||||
mod common;
|
||||
use common::to_range;
|
||||
use honggfuzz::fuzz;
|
||||
use sp_phragmen::{
|
||||
equalize, assignment_ratio_to_staked, build_support_map, to_without_backing, elect,
|
||||
PhragmenResult, VoteWeight, evaluate_support, is_score_better,
|
||||
use sp_npos_elections::{
|
||||
balance_solution, assignment_ratio_to_staked, build_support_map, to_without_backing, seq_phragmen,
|
||||
ElectionResult, VoteWeight, evaluate_support, is_score_better,
|
||||
};
|
||||
use sp_std::collections::btree_map::BTreeMap;
|
||||
use sp_runtime::Perbill;
|
||||
@@ -39,7 +39,7 @@ fn generate_random_phragmen_result(
|
||||
to_elect: usize,
|
||||
edge_per_voter: u64,
|
||||
mut rng: impl RngCore,
|
||||
) -> (PhragmenResult<AccountId, Perbill>, BTreeMap<AccountId, VoteWeight>) {
|
||||
) -> (ElectionResult<AccountId, Perbill>, BTreeMap<AccountId, VoteWeight>) {
|
||||
let prefix = 100_000;
|
||||
// Note, it is important that stakes are always bigger than ed and
|
||||
let base_stake: u64 = 1_000_000_000;
|
||||
@@ -73,7 +73,7 @@ fn generate_random_phragmen_result(
|
||||
});
|
||||
|
||||
(
|
||||
elect::<AccountId, sp_runtime::Perbill>(
|
||||
seq_phragmen::<AccountId, sp_runtime::Perbill>(
|
||||
to_elect,
|
||||
0,
|
||||
candidates,
|
||||
@@ -86,7 +86,14 @@ fn generate_random_phragmen_result(
|
||||
fn main() {
|
||||
loop {
|
||||
fuzz!(|data: (usize, usize, usize, usize, usize, u64)| {
|
||||
let (mut target_count, mut voter_count, mut iterations, mut edge_per_voter, mut to_elect, seed) = data;
|
||||
let (
|
||||
mut target_count,
|
||||
mut voter_count,
|
||||
mut iterations,
|
||||
mut edge_per_voter,
|
||||
mut to_elect,
|
||||
seed,
|
||||
) = data;
|
||||
let rng = rand::rngs::SmallRng::seed_from_u64(seed);
|
||||
target_count = to_range(target_count, 50, 2000);
|
||||
voter_count = to_range(voter_count, 50, 1000);
|
||||
@@ -95,7 +102,7 @@ fn main() {
|
||||
edge_per_voter = to_range(edge_per_voter, 1, target_count);
|
||||
|
||||
println!("++ [{} / {} / {} / {}]", voter_count, target_count, to_elect, iterations);
|
||||
let (PhragmenResult { winners, assignments }, stake_of_tree) = generate_random_phragmen_result(
|
||||
let (ElectionResult { winners, assignments }, stake_of_tree) = generate_random_phragmen_result(
|
||||
voter_count as u64,
|
||||
target_count as u64,
|
||||
to_elect,
|
||||
@@ -117,7 +124,7 @@ fn main() {
|
||||
return;
|
||||
}
|
||||
|
||||
let i = equalize(
|
||||
let i = balance_solution(
|
||||
&mut staked,
|
||||
&mut support,
|
||||
10,
|
||||
+1
-1
@@ -34,7 +34,7 @@ use honggfuzz::fuzz;
|
||||
|
||||
mod common;
|
||||
use common::to_range;
|
||||
use sp_phragmen::{StakedAssignment, ExtendedBalance, build_support_map, reduce};
|
||||
use sp_npos_elections::{StakedAssignment, ExtendedBalance, build_support_map, reduce};
|
||||
use rand::{self, Rng, SeedableRng, RngCore};
|
||||
|
||||
type Balance = u128;
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Helper methods for phragmen.
|
||||
//! Helper methods for npos-elections.
|
||||
|
||||
use crate::{Assignment, ExtendedBalance, VoteWeight, IdentifierT, StakedAssignment, WithApprovalOf};
|
||||
use sp_arithmetic::PerThing;
|
||||
+29
-36
@@ -15,22 +15,16 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Rust implementation of the Phragmén election algorithm. This is used in several pallets to
|
||||
//! optimally distribute the weight of a set of voters among an elected set of candidates. In the
|
||||
//! context of staking this is mapped to validators and nominators.
|
||||
//! A set of election algorithms to be used with a substrate runtime, typically within the staking
|
||||
//! sub-system. Notable implementation include
|
||||
//!
|
||||
//! The algorithm has two phases:
|
||||
//! - Sequential phragmen: performed in [`elect`] function which is first pass of the distribution
|
||||
//! The results are not optimal but the execution time is less.
|
||||
//! - Equalize post-processing: tries to further distribute the weight fairly among candidates.
|
||||
//! Incurs more execution time.
|
||||
//! - [`seq_phragmen`]: Implements the Phragmén Sequential Method. An un-ranked, relatively fast
|
||||
//! election method that ensures PJR, but does not provide a constant factor approximation of the
|
||||
//! maximin problem.
|
||||
//! - [`balance_solution`]: Implements the star balancing algorithm. This iterative process can
|
||||
//! increase a solutions score, as described in [`evaluate_support`].
|
||||
//!
|
||||
//! The main objective of the assignments done by phragmen is to maximize the minimum backed
|
||||
//! candidate in the elected set.
|
||||
//!
|
||||
//! Reference implementation: https://github.com/w3f/consensus
|
||||
//! Further details:
|
||||
//! https://research.web3.foundation/en/latest/polkadot/NPoS/4.%20Sequential%20Phragm%C3%A9n%E2%80%99s%20method/
|
||||
//! More information can be found at: https://arxiv.org/abs/2004.12990
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
@@ -67,7 +61,7 @@ pub use codec;
|
||||
pub use sp_arithmetic;
|
||||
|
||||
// re-export the compact solution type.
|
||||
pub use sp_phragmen_compact::generate_compact_solution_type;
|
||||
pub use sp_npos_elections_compact::generate_compact_solution_type;
|
||||
|
||||
/// A trait to limit the number of votes per voter. The generated compact type will implement this.
|
||||
pub trait VotingLimit {
|
||||
@@ -100,7 +94,7 @@ pub type VoteWeight = u64;
|
||||
pub type ExtendedBalance = u128;
|
||||
|
||||
/// The score of an assignment. This can be computed from the support map via [`evaluate_support`].
|
||||
pub type PhragmenScore = [ExtendedBalance; 3];
|
||||
pub type ElectionScore = [ExtendedBalance; 3];
|
||||
|
||||
/// A winner, with their respective approval stake.
|
||||
pub type WithApprovalOf<A> = (A, ExtendedBalance);
|
||||
@@ -110,7 +104,7 @@ pub type WithApprovalOf<A> = (A, ExtendedBalance);
|
||||
/// bigger than u64::max_value() is needed. For maximum accuracy we simply use u128;
|
||||
const DEN: u128 = u128::max_value();
|
||||
|
||||
/// A candidate entity for phragmen election.
|
||||
/// A candidate entity for the election.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
struct Candidate<AccountId> {
|
||||
/// Identifier.
|
||||
@@ -147,9 +141,9 @@ struct Edge<AccountId> {
|
||||
candidate_index: usize,
|
||||
}
|
||||
|
||||
/// Final result of the phragmen election.
|
||||
/// Final result of the election.
|
||||
#[derive(Debug)]
|
||||
pub struct PhragmenResult<AccountId, T: PerThing> {
|
||||
pub struct ElectionResult<AccountId, T: PerThing> {
|
||||
/// Just winners zipped with their approval stake. Note that the approval stake is merely the
|
||||
/// sub of their received stake and could be used for very basic sorting and approval voting.
|
||||
pub winners: Vec<WithApprovalOf<AccountId>>,
|
||||
@@ -298,10 +292,10 @@ impl<AccountId> StakedAssignment<AccountId> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure to demonstrate the phragmen result from the perspective of the candidate, i.e. how
|
||||
/// A structure to demonstrate the election result from the perspective of the candidate, i.e. how
|
||||
/// much support each candidate is receiving.
|
||||
///
|
||||
/// This complements the [`PhragmenResult`] and is needed to run the equalize post-processing.
|
||||
/// This complements the [`ElectionResult`] and is needed to run the balancing post-processing.
|
||||
///
|
||||
/// This, at the current version, resembles the `Exposure` defined in the Staking pallet, yet
|
||||
/// they do not necessarily have to be the same.
|
||||
@@ -332,12 +326,12 @@ pub type SupportMap<A> = BTreeMap<A, Support<A>>;
|
||||
/// responsibility of the caller to make sure only those candidates who have a sensible economic
|
||||
/// value are passed in. From the perspective of this function, a candidate can easily be among the
|
||||
/// winner with no backing stake.
|
||||
pub fn elect<AccountId, R>(
|
||||
pub fn seq_phragmen<AccountId, R>(
|
||||
candidate_count: usize,
|
||||
minimum_candidate_count: usize,
|
||||
initial_candidates: Vec<AccountId>,
|
||||
initial_voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
|
||||
) -> Option<PhragmenResult<AccountId, R>> where
|
||||
) -> Option<ElectionResult<AccountId, R>> where
|
||||
AccountId: Default + Ord + Clone,
|
||||
R: PerThing,
|
||||
{
|
||||
@@ -388,7 +382,6 @@ pub fn elect<AccountId, R>(
|
||||
|
||||
|
||||
// we have already checked that we have more candidates than minimum_candidate_count.
|
||||
// run phragmen.
|
||||
let to_elect = candidate_count.min(candidates.len());
|
||||
elected_candidates = Vec::with_capacity(candidate_count);
|
||||
assigned = Vec::with_capacity(candidate_count);
|
||||
@@ -524,13 +517,13 @@ pub fn elect<AccountId, R>(
|
||||
}
|
||||
}
|
||||
|
||||
Some(PhragmenResult {
|
||||
Some(ElectionResult {
|
||||
winners: elected_candidates,
|
||||
assignments: assigned,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the support map from the given phragmen result. It maps a flat structure like
|
||||
/// Build the support map from the given election result. It maps a flat structure like
|
||||
///
|
||||
/// ```nocompile
|
||||
/// assignments: vec![
|
||||
@@ -588,7 +581,7 @@ pub fn build_support_map<AccountId>(
|
||||
(supports, errors)
|
||||
}
|
||||
|
||||
/// Evaluate a phragmen result, given the support map. The returned tuple contains:
|
||||
/// Evaluate a support map. The returned tuple contains:
|
||||
///
|
||||
/// - Minimum support. This value must be **maximized**.
|
||||
/// - Sum of all supports. This value must be **maximized**.
|
||||
@@ -597,7 +590,7 @@ pub fn build_support_map<AccountId>(
|
||||
/// `O(E)` where `E` is the total number of edges.
|
||||
pub fn evaluate_support<AccountId>(
|
||||
support: &SupportMap<AccountId>,
|
||||
) -> PhragmenScore {
|
||||
) -> ElectionScore {
|
||||
let mut min_support = ExtendedBalance::max_value();
|
||||
let mut sum: ExtendedBalance = Zero::zero();
|
||||
// NOTE: The third element might saturate but fine for now since this will run on-chain and need
|
||||
@@ -614,14 +607,14 @@ pub fn evaluate_support<AccountId>(
|
||||
[min_support, sum, sum_squared]
|
||||
}
|
||||
|
||||
/// Compares two sets of phragmen scores based on desirability and returns true if `this` is
|
||||
/// Compares two sets of election scores based on desirability and returns true if `this` is
|
||||
/// better than `that`.
|
||||
///
|
||||
/// Evaluation is done in a lexicographic manner, and if each element of `this` is `that * epsilon`
|
||||
/// greater or less than `that`.
|
||||
///
|
||||
/// Note that the third component should be minimized.
|
||||
pub fn is_score_better<P: PerThing>(this: PhragmenScore, that: PhragmenScore, epsilon: P) -> bool
|
||||
pub fn is_score_better<P: PerThing>(this: ElectionScore, that: ElectionScore, epsilon: P) -> bool
|
||||
where ExtendedBalance: From<sp_arithmetic::InnerOf<P>>
|
||||
{
|
||||
match this
|
||||
@@ -648,17 +641,17 @@ pub fn is_score_better<P: PerThing>(this: PhragmenScore, that: PhragmenScore, ep
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs equalize post-processing to the output of the election algorithm. This happens in
|
||||
/// Performs balancing post-processing to the output of the election algorithm. This happens in
|
||||
/// rounds. The number of rounds and the maximum diff-per-round tolerance can be tuned through input
|
||||
/// parameters.
|
||||
///
|
||||
/// Returns the number of iterations that were preformed.
|
||||
///
|
||||
/// - `assignments`: exactly the same is the output of phragmen.
|
||||
/// - `assignments`: exactly the same as the output of [`seq_phragmen`].
|
||||
/// - `supports`: mutable reference to s `SupportMap`. This parameter is updated.
|
||||
/// - `tolerance`: maximum difference that can occur before an early quite happens.
|
||||
/// - `iterations`: maximum number of iterations that will be processed.
|
||||
pub fn equalize<AccountId>(
|
||||
pub fn balance_solution<AccountId>(
|
||||
assignments: &mut Vec<StakedAssignment<AccountId>>,
|
||||
supports: &mut SupportMap<AccountId>,
|
||||
tolerance: ExtendedBalance,
|
||||
@@ -672,7 +665,7 @@ pub fn equalize<AccountId>(
|
||||
for assignment in assignments.iter_mut() {
|
||||
let voter_budget = assignment.total();
|
||||
let StakedAssignment { who, distribution } = assignment;
|
||||
let diff = do_equalize(
|
||||
let diff = do_balancing(
|
||||
who,
|
||||
voter_budget,
|
||||
distribution,
|
||||
@@ -689,9 +682,9 @@ pub fn equalize<AccountId>(
|
||||
}
|
||||
}
|
||||
|
||||
/// actually perform equalize. same interface is `equalize`. Just called in loops with a check for
|
||||
/// actually perform balancing. same interface is `balance_solution`. Just called in loops with a check for
|
||||
/// maximum difference.
|
||||
fn do_equalize<AccountId>(
|
||||
fn do_balancing<AccountId>(
|
||||
voter: &AccountId,
|
||||
budget: ExtendedBalance,
|
||||
elected_edges: &mut Vec<(AccountId, ExtendedBalance)>,
|
||||
+3
-3
@@ -15,11 +15,11 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Mock file for phragmen.
|
||||
//! Mock file for npos-elections.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use crate::{elect, PhragmenResult, Assignment, VoteWeight, ExtendedBalance};
|
||||
use crate::{seq_phragmen, ElectionResult, Assignment, VoteWeight, ExtendedBalance};
|
||||
use sp_arithmetic::{PerThing, traits::{SaturatedConversion, Zero, One}};
|
||||
use sp_std::collections::btree_map::BTreeMap;
|
||||
use sp_runtime::assert_eq_error_rate;
|
||||
@@ -326,7 +326,7 @@ pub(crate) fn run_and_compare<Output: PerThing>(
|
||||
min_to_elect: usize,
|
||||
) {
|
||||
// run fixed point code.
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Output>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Output>(
|
||||
to_elect,
|
||||
min_to_elect,
|
||||
candidates.clone(),
|
||||
+21
-18
@@ -15,14 +15,14 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Tests for phragmen.
|
||||
//! Tests for npos-elections.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use crate::mock::*;
|
||||
use crate::{
|
||||
elect, equalize, build_support_map, is_score_better, helpers::*,
|
||||
Support, StakedAssignment, Assignment, PhragmenResult, ExtendedBalance,
|
||||
seq_phragmen, balance_solution, build_support_map, is_score_better, helpers::*,
|
||||
Support, StakedAssignment, Assignment, ElectionResult, ExtendedBalance,
|
||||
};
|
||||
use substrate_test_utils::assert_eq_uvec;
|
||||
use sp_arithmetic::{Perbill, Permill, Percent, PerU16};
|
||||
@@ -83,7 +83,7 @@ fn phragmen_poc_works() {
|
||||
];
|
||||
|
||||
let stake_of = create_stake_of(&[(10, 10), (20, 20), (30, 30)]);
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates,
|
||||
@@ -146,7 +146,7 @@ fn phragmen_poc_works() {
|
||||
Support::<AccountId> { total: 35, voters: vec![(20, 20), (30, 15)] },
|
||||
);
|
||||
|
||||
equalize(
|
||||
balance_solution(
|
||||
&mut staked,
|
||||
&mut support_map,
|
||||
0,
|
||||
@@ -240,11 +240,14 @@ fn phragmen_accuracy_on_large_scale_only_validators() {
|
||||
(5, (u64::max_value() - 2).into()),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates.clone(),
|
||||
auto_generate_self_voters(&candidates).iter().map(|(ref v, ref vs)| (v.clone(), stake_of(v), vs.clone())).collect::<Vec<_>>(),
|
||||
auto_generate_self_voters(&candidates)
|
||||
.iter()
|
||||
.map(|(ref v, ref vs)| (v.clone(), stake_of(v), vs.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
).unwrap();
|
||||
|
||||
assert_eq_uvec!(winners, vec![(1, 18446744073709551614u128), (5, 18446744073709551613u128)]);
|
||||
@@ -270,7 +273,7 @@ fn phragmen_accuracy_on_large_scale_validators_and_nominators() {
|
||||
(14, u64::max_value().into()),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates,
|
||||
@@ -313,7 +316,7 @@ fn phragmen_accuracy_on_small_scale_self_vote() {
|
||||
(30, 1),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments: _ } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments: _ } = seq_phragmen::<_, Perbill>(
|
||||
3,
|
||||
3,
|
||||
candidates,
|
||||
@@ -343,7 +346,7 @@ fn phragmen_accuracy_on_small_scale_no_self_vote() {
|
||||
(3, 1),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments: _ } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments: _ } = seq_phragmen::<_, Perbill>(
|
||||
3,
|
||||
3,
|
||||
candidates,
|
||||
@@ -376,7 +379,7 @@ fn phragmen_large_scale_test() {
|
||||
(50, 990000000000000000),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates,
|
||||
@@ -402,7 +405,7 @@ fn phragmen_large_scale_test_2() {
|
||||
(50, nom_budget.into()),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates,
|
||||
@@ -478,7 +481,7 @@ fn elect_has_no_entry_barrier() {
|
||||
(2, 10),
|
||||
]);
|
||||
|
||||
let PhragmenResult { winners, assignments: _ } = elect::<_, Perbill>(
|
||||
let ElectionResult { winners, assignments: _ } = seq_phragmen::<_, Perbill>(
|
||||
3,
|
||||
3,
|
||||
candidates,
|
||||
@@ -505,7 +508,7 @@ fn minimum_to_elect_is_respected() {
|
||||
(2, 10),
|
||||
]);
|
||||
|
||||
let maybe_result = elect::<_, Perbill>(
|
||||
let maybe_result = seq_phragmen::<_, Perbill>(
|
||||
10,
|
||||
10,
|
||||
candidates,
|
||||
@@ -531,7 +534,7 @@ fn self_votes_should_be_kept() {
|
||||
(1, 8),
|
||||
]);
|
||||
|
||||
let result = elect::<_, Perbill>(
|
||||
let result = seq_phragmen::<_, Perbill>(
|
||||
2,
|
||||
2,
|
||||
candidates,
|
||||
@@ -570,7 +573,7 @@ fn self_votes_should_be_kept() {
|
||||
&Support { total: 24u128, voters: vec![(20u64, 20u128), (1u64, 4u128)] },
|
||||
);
|
||||
|
||||
equalize(
|
||||
balance_solution(
|
||||
&mut staked_assignments,
|
||||
&mut supports,
|
||||
0,
|
||||
@@ -771,8 +774,8 @@ mod compact {
|
||||
use codec::{Decode, Encode};
|
||||
use crate::{generate_compact_solution_type, VoteWeight};
|
||||
use super::{AccountId};
|
||||
// these need to come from the same dev-dependency `sp-phragmen`, not from the crate.
|
||||
use sp_phragmen::{Assignment, StakedAssignment, Error as PhragmenError, ExtendedBalance};
|
||||
// these need to come from the same dev-dependency `sp-npos-elections`, not from the crate.
|
||||
use sp_npos_elections::{Assignment, StakedAssignment, Error as PhragmenError, ExtendedBalance};
|
||||
use sp_std::{convert::{TryInto, TryFrom}, fmt::Debug};
|
||||
use sp_arithmetic::Percent;
|
||||
|
||||
Reference in New Issue
Block a user