From 589047baef6d091a68176abfafdb8ebff6b02d35 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 8 May 2024 19:02:11 +0200 Subject: [PATCH 1/8] Draft of the functions --- src/main.rs | 6 ++++ src/stat_io.rs | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/stats.rs | 67 ++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 src/stat_io.rs create mode 100644 src/stats.rs diff --git a/src/main.rs b/src/main.rs index 06d2a9a..2384a27 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,8 @@ // #![allow(dead_code)] #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] +mod stat_io; +mod stats; mod table_structs; mod table_types; mod tablegen; @@ -18,6 +20,7 @@ use std::{ use anyhow::{Context, Result}; use clap::{Args, Parser, Subcommand}; use serde::Deserialize; +use stats::{stat_solver, StatConfig}; use table_structs::Craft; use tablegen::table_gen; @@ -38,6 +41,8 @@ enum Commands { Tablegen(TableArgs), /// Show/Export config Config(ConfigArgs), + /// Handle stat repartition + Stats(StatConfig), } #[derive(Debug, Args)] @@ -82,6 +87,7 @@ fn main() -> Result<()> { match args.command { Commands::Tablegen(args) => table_gen(&args, &config), Commands::Config(args) => write_config(&args, &config, config_str), + Commands::Stats(args) => stat_solver(&args, &config), } } diff --git a/src/stat_io.rs b/src/stat_io.rs new file mode 100644 index 0000000..efc7b14 --- /dev/null +++ b/src/stat_io.rs @@ -0,0 +1,93 @@ +//! All the struct needed for IO purposes +#![allow(dead_code)] +#![allow(clippy::missing_docs_in_private_items)] +use std::{collections::HashMap, fs::File, path::Path}; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +/// How to represent mathematically the affinity for a stat +type Affinity = f64; + +#[derive(Serialize, Deserialize)] +/// A row representing the creature affinity for a stat +struct CreatureCharacteristicsAffinity { + /// Strength + f: Affinity, + /// Agility + ag: Affinity, + /// Perception + per: Affinity, + /// Psychic power + psy: Affinity, + /// Intellect + int: Affinity, + /// Willpower + vol: Affinity, + /// Luck + chn: Affinity, + /// Charisma + chr: Affinity, +} + +#[repr(u8)] +/// The names of all affinities (essentialy a list of characteristics) +enum AffName { + F, + Ag, + Per, + Psy, + Int, + Vol, + Chn, + Chr, +} + +impl CreatureCharacteristicsAffinity { + // Create an affinity from a record +} + +/// The list of all creature and their associated affinities +struct CreaturesAffinity { + list_creatures: HashMap, + matrix: CharacCharMatrix, +} + +/// A matrix representing: List of characteristics and associated list of creatures +/// All math is done at this level to avoid cost +/// Right now the index of every creature is used in the matrix, but a references could be used instead +struct CharacCharMatrix { + inner: Vec>, +} +struct Creature { + affinities: CreatureCharacteristicsAffinity, + actives_affinities: Vec, + selected_affinities: Vec, +} + +impl Creature { + // Get most desired affinity + // Get list of selected affinities +} + +/// Load all the records in the csv +pub fn load_stat_records(filename: T) -> Result<()> +where + T: AsRef, +{ + let file = File::open(filename)?; + let mut rdr = csv::ReaderBuilder::new() + .has_headers(true) + .delimiter(b',') + .double_quote(false) + .escape(Some(b'\\')) + .flexible(true) + .comment(Some(b'#')) + .from_reader(file); + println!("{:?}", rdr); + println!("{:?}", rdr.headers().cloned()); + for rec in rdr.into_records() { + println!("{:?}", rec); + } + Ok(()) +} diff --git a/src/stats.rs b/src/stats.rs new file mode 100644 index 0000000..fff5506 --- /dev/null +++ b/src/stats.rs @@ -0,0 +1,67 @@ +//! A module to handle stats disparity between all origins +#![allow(dead_code)] +#![allow(clippy::missing_docs_in_private_items)] + +use anyhow::Result; +use clap::Args; + +use crate::{stat_io::load_stat_records, Config, ParserCLIArgs}; + +#[derive(Args, Debug)] +pub(crate) struct StatConfig { + // #[arg(default_value_t: "data/Book1.csv")] + config_path: String, +} + +/// Main solver function, in charge of selecting algorithms and handling all program flow +pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { + load_stat_records(&"data/Book1.csv"); + Ok(()) +} + +// struct DesiredStats {} + +// struct Creature { +// stats: DesiredStats, +// name: String, +// } + +// enum CharacEnum { +// F, +// Ag, +// } + +// struct CharacWeight { +// charac: CharacEnum, +// list_weights: Vec<(f64, Creature)>, +// } + +// // impl Creature{ +// // fn get_ +// // } + +// // The first Algorithm, creating all creatures from scratch + +// fn get_next_stat_to_grow() {} + +// fn get_greatest_consumer_of(c: CharacEnum) {} + +// fn assign_stat_to_creature(c: CharacEnum) {} + +// fn get_greatest_despiser_of(c: CharacEnum) {} + +// // The second algorithm, appending to an existing solution + +// // Serialize and Deserialize Solutions + +// fn try_getting_desired_stat() {} + +// fn find_swap_creature() {} + +// // Integrity check and disparity check + +// fn check_stats_integrity() {} + +// fn show_stats() {} + +// fn show_outliers() {} -- 2.45.1 From 621e82e8b632177e58aaf90a17d7cb6f5a0fd008 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 8 May 2024 23:58:53 +0200 Subject: [PATCH 2/8] Working base import --- src/stat_io.rs | 142 ++++++++++++++++++++++++++++++++++++++----------- src/stats.rs | 6 ++- 2 files changed, 116 insertions(+), 32 deletions(-) diff --git a/src/stat_io.rs b/src/stat_io.rs index efc7b14..29baeb6 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -3,35 +3,72 @@ #![allow(clippy::missing_docs_in_private_items)] use std::{collections::HashMap, fs::File, path::Path}; -use anyhow::Result; +use anyhow::{Context, Result}; +use csv::StringRecord; use serde::{Deserialize, Serialize}; /// How to represent mathematically the affinity for a stat type Affinity = f64; -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug)] /// A row representing the creature affinity for a stat struct CreatureCharacteristicsAffinity { - /// Strength - f: Affinity, - /// Agility - ag: Affinity, - /// Perception - per: Affinity, - /// Psychic power - psy: Affinity, - /// Intellect - int: Affinity, - /// Willpower - vol: Affinity, - /// Luck - chn: Affinity, - /// Charisma - chr: Affinity, + affinity: Vec, +} + +impl CreatureCharacteristicsAffinity { + fn get_affinity(&self, affinity: AffName) -> Affinity { + self.affinity[affinity as usize] + } +} + +#[derive(Debug)] +struct Creature { + name: String, + // id : usize, + affinities: CreatureCharacteristicsAffinity, + actives_affinities: Vec, + selected_affinities: Vec, +} + +impl TryFrom for Creature { + type Error = anyhow::Error; + + fn try_from(value: StringRecord) -> std::prelude::v1::Result { + let mut iterable = value.into_iter(); + let creature = iterable.next().context("Getting name")?; + let aff = iterable + .map(|m| m.parse::().context("Parsing string").unwrap()) + .collect(); + Ok(Self { + name: creature.to_owned(), + affinities: CreatureCharacteristicsAffinity { affinity: aff }, + actives_affinities: Vec::new(), + selected_affinities: Vec::new(), + }) + } +} + +impl Creature { + // Get most desired affinity + // Get list of selected affinities +} + +impl TryFrom for CreatureCharacteristicsAffinity { + type Error = anyhow::Error; + + fn try_from(value: StringRecord) -> Result { + let aff = value + .into_iter() + .skip(1) + .map(|m| m.parse::().context("Parsing string").unwrap()) + .collect(); + Ok(Self { affinity: aff }) + } } -#[repr(u8)] /// The names of all affinities (essentialy a list of characteristics) +#[derive(Deserialize, Serialize, Debug)] enum AffName { F, Ag, @@ -43,6 +80,18 @@ enum AffName { Chr, } +#[inline] +fn get_aff_index(affinity: AffName) -> usize { + affinity as usize +} + +#[derive(Deserialize, Serialize)] +struct Solution { + creature: String, + affinities: CreatureCharacteristicsAffinity, + picks: Vec, +} + impl CreatureCharacteristicsAffinity { // Create an affinity from a record } @@ -53,21 +102,40 @@ struct CreaturesAffinity { matrix: CharacCharMatrix, } +#[derive(Debug)] /// A matrix representing: List of characteristics and associated list of creatures /// All math is done at this level to avoid cost /// Right now the index of every creature is used in the matrix, but a references could be used instead struct CharacCharMatrix { + /// The inner vector structure, used to access rapidly the underlying affinities inner: Vec>, -} -struct Creature { - affinities: CreatureCharacteristicsAffinity, - actives_affinities: Vec, - selected_affinities: Vec, + /// A translation vector to remember what is what + creatures: Vec, } -impl Creature { - // Get most desired affinity - // Get list of selected affinities +impl From> for CharacCharMatrix { + fn from(creatures: Vec) -> Self { + let size = creatures.len() + 1; + let mut inner = vec![ + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(usize, Affinity)>::with_capacity(size), + ]; + + println!("I: {:?}", creatures); + for (creature_id, creature) in creatures.iter().enumerate() { + for (index, value) in creature.affinities.affinity.iter().enumerate() { + inner[index].push((creature_id, *value)); + } + } + + Self { inner, creatures } + } } /// Load all the records in the csv @@ -86,8 +154,22 @@ where .from_reader(file); println!("{:?}", rdr); println!("{:?}", rdr.headers().cloned()); - for rec in rdr.into_records() { - println!("{:?}", rec); - } + // for rec in rdr.into_records() { + // println!("{:?}", rec); + // println!("{:?}", CreatureCharacteristicsAffinity::try_from(rec?)); + // } + // let creatures_aff: Vec = rdr + // .into_records() + // .flat_map(|c| CreatureCharacteristicsAffinity::try_from(c.unwrap())) + // .collect(); + + // println!("{:#?}", creatures_aff); + + let creatures: Vec = rdr + .into_records() + .flat_map(|c| Creature::try_from(c.unwrap())) + .collect(); + let creature_matrix = CharacCharMatrix::from(creatures); + println!("{:#?}", creature_matrix); Ok(()) } diff --git a/src/stats.rs b/src/stats.rs index fff5506..8b14c68 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -5,7 +5,7 @@ use anyhow::Result; use clap::Args; -use crate::{stat_io::load_stat_records, Config, ParserCLIArgs}; +use crate::{stat_io::load_stat_records, Config}; #[derive(Args, Debug)] pub(crate) struct StatConfig { @@ -15,7 +15,9 @@ pub(crate) struct StatConfig { /// Main solver function, in charge of selecting algorithms and handling all program flow pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { - load_stat_records(&"data/Book1.csv"); + let _ = config; + let _ = args; + let _ = load_stat_records("data/statw.csv"); Ok(()) } -- 2.45.1 From abf04e4fef1baa3e466b1c83b435f4f2f80e3a98 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 9 May 2024 04:55:34 +0200 Subject: [PATCH 3/8] Adds a cyclic operator and some process --- src/stat_io.rs | 79 +++++++++++++++++++++++++++++--------------------- src/stats.rs | 66 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 110 insertions(+), 35 deletions(-) diff --git a/src/stat_io.rs b/src/stat_io.rs index 29baeb6..364d0b7 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,7 +1,7 @@ //! All the struct needed for IO purposes #![allow(dead_code)] -#![allow(clippy::missing_docs_in_private_items)] -use std::{collections::HashMap, fs::File, path::Path}; +// #![allow(clippy::missing_docs_in_private_items)] +use std::{fs::File, path::Path}; use anyhow::{Context, Result}; use csv::StringRecord; @@ -13,21 +13,28 @@ type Affinity = f64; #[derive(Serialize, Deserialize, Debug)] /// A row representing the creature affinity for a stat struct CreatureCharacteristicsAffinity { + /// A list of witch stats are desired and at witch level affinity: Vec, } impl CreatureCharacteristicsAffinity { + /// Get the affinity level on the given stat fn get_affinity(&self, affinity: AffName) -> Affinity { self.affinity[affinity as usize] } } #[derive(Debug)] +/// A single creature with the needed fields to handle affinity selection struct Creature { + /// The name of the creature name: String, // id : usize, + /// The list of affinity desired affinities: CreatureCharacteristicsAffinity, + /// The actives affinities ? actives_affinities: Vec, + /// The currently selected affinities selected_affinities: Vec, } @@ -68,8 +75,9 @@ impl TryFrom for CreatureCharacteristicsAffinity { } /// The names of all affinities (essentialy a list of characteristics) -#[derive(Deserialize, Serialize, Debug)] -enum AffName { +#[allow(clippy::missing_docs_in_private_items)] +#[derive(Deserialize, Serialize, Debug, Clone, Copy)] +pub(crate) enum AffName { F, Ag, Per, @@ -81,37 +89,55 @@ enum AffName { } #[inline] +/// Shortcut to get the affinity fn get_aff_index(affinity: AffName) -> usize { affinity as usize } -#[derive(Deserialize, Serialize)] -struct Solution { - creature: String, - affinities: CreatureCharacteristicsAffinity, - picks: Vec, -} +// #[derive(Deserialize, Serialize)] +// /// A solution for the creature +// struct Solution { +// creature: String, +// affinities: CreatureCharacteristicsAffinity, +// picks: Vec, +// } impl CreatureCharacteristicsAffinity { // Create an affinity from a record } -/// The list of all creature and their associated affinities -struct CreaturesAffinity { - list_creatures: HashMap, - matrix: CharacCharMatrix, -} +// /// The list of all creature and their associated affinities +// struct CreaturesAffinity { +// list_creatures: HashMap, +// matrix: CharacCharMatrix, +// } #[derive(Debug)] /// A matrix representing: List of characteristics and associated list of creatures /// All math is done at this level to avoid cost /// Right now the index of every creature is used in the matrix, but a references could be used instead -struct CharacCharMatrix { +pub(crate) struct CharacCharMatrix { /// The inner vector structure, used to access rapidly the underlying affinities inner: Vec>, /// A translation vector to remember what is what creatures: Vec, } +impl CharacCharMatrix { + /// Check if the matrix is filled + pub(crate) fn not_filled(&self) -> bool { + for elt in &self.creatures { + if elt.selected_affinities.len() < 2 { + return false; + } + } + true + } + + /// Gives the size of the loop needed to fill all element + pub(crate) fn size_loop(&self) -> usize { + self.creatures.len() * 2 + } +} impl From> for CharacCharMatrix { fn from(creatures: Vec) -> Self { @@ -127,7 +153,6 @@ impl From> for CharacCharMatrix { Vec::<(usize, Affinity)>::with_capacity(size), ]; - println!("I: {:?}", creatures); for (creature_id, creature) in creatures.iter().enumerate() { for (index, value) in creature.affinities.affinity.iter().enumerate() { inner[index].push((creature_id, *value)); @@ -139,12 +164,12 @@ impl From> for CharacCharMatrix { } /// Load all the records in the csv -pub fn load_stat_records(filename: T) -> Result<()> +pub fn load_stat_records(filename: T) -> Result where T: AsRef, { let file = File::open(filename)?; - let mut rdr = csv::ReaderBuilder::new() + let rdr = csv::ReaderBuilder::new() .has_headers(true) .delimiter(b',') .double_quote(false) @@ -152,24 +177,12 @@ where .flexible(true) .comment(Some(b'#')) .from_reader(file); - println!("{:?}", rdr); - println!("{:?}", rdr.headers().cloned()); - // for rec in rdr.into_records() { - // println!("{:?}", rec); - // println!("{:?}", CreatureCharacteristicsAffinity::try_from(rec?)); - // } - // let creatures_aff: Vec = rdr - // .into_records() - // .flat_map(|c| CreatureCharacteristicsAffinity::try_from(c.unwrap())) - // .collect(); - - // println!("{:#?}", creatures_aff); let creatures: Vec = rdr .into_records() .flat_map(|c| Creature::try_from(c.unwrap())) .collect(); let creature_matrix = CharacCharMatrix::from(creatures); - println!("{:#?}", creature_matrix); - Ok(()) + // println!("{:#?}", creature_matrix); + Ok(creature_matrix) } diff --git a/src/stats.rs b/src/stats.rs index 8b14c68..e4832ae 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -2,10 +2,15 @@ #![allow(dead_code)] #![allow(clippy::missing_docs_in_private_items)] +use std::{iter::Cycle, vec::IntoIter}; + use anyhow::Result; use clap::Args; -use crate::{stat_io::load_stat_records, Config}; +use crate::{ + stat_io::{load_stat_records, AffName, CharacCharMatrix}, + Config, +}; #[derive(Args, Debug)] pub(crate) struct StatConfig { @@ -17,10 +22,67 @@ pub(crate) struct StatConfig { pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; let _ = args; - let _ = load_stat_records("data/statw.csv"); + let statmatrix = load_stat_records("data/statw.csv").unwrap(); + let sol = solution_from_empty(statmatrix); + println!("{:?}", sol); Ok(()) } +fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> { + // while statmatrix.not_filled() {} + let stats = vec![ + (AffName::F, 4), + (AffName::Ag, 3), + (AffName::Per, 3), + (AffName::Psy, 3), + (AffName::Int, 1), + (AffName::Vol, 1), + ]; + + println!("{:#?}", stats); + let mut sw = StatWeightList::from(stats).iter_cycle(); + println!("{:#?}", sw); + for i in 0..statmatrix.size_loop() { + println!("{:#?}", sw.next()); + } + Ok(()) +} + +type StatWeightsTuple = Vec<(AffName, usize)>; + +/// The statweights, holding looping methods +#[derive(Debug)] +struct StatWeightList { + weights: Vec, +} +impl StatWeightList { + fn iter_cycle(self) -> Cycle> { + self.weights.into_iter().cycle() + } +} + +// impl StatWeight { + +// } + +impl From for StatWeightList { + fn from(mut value: StatWeightsTuple) -> Self { + let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); + let mut weights = Vec::with_capacity(ln); + let mut i = 0; + while i < ln { + for (w, nb) in value.iter_mut() { + if nb != &0 { + *nb -= 1; + weights.push(*w); + i += 1; + } + } + } + Self { weights } + } +} + // struct DesiredStats {} // struct Creature { -- 2.45.1 From d4d137b8cf9aba0c1e3d76e26375b2a175f675cf Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 14 May 2024 01:44:54 +0200 Subject: [PATCH 4/8] Iterates and performs ... correctly --- src/main.rs | 2 ++ src/stat_algo.rs | 29 +++++++++++++++++++ src/stat_io.rs | 68 +++++++++++++++++++++++++++++++++++++++++---- src/stat_structs.rs | 1 + src/stats.rs | 58 ++++++++++++++++++++++++++++++-------- 5 files changed, 142 insertions(+), 16 deletions(-) create mode 100644 src/stat_algo.rs create mode 100644 src/stat_structs.rs diff --git a/src/main.rs b/src/main.rs index 2384a27..1b5deb9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,9 @@ // #![allow(dead_code)] #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] +mod stat_algo; mod stat_io; +mod stat_structs; mod stats; mod table_structs; mod table_types; diff --git a/src/stat_algo.rs b/src/stat_algo.rs new file mode 100644 index 0000000..cb6f3d6 --- /dev/null +++ b/src/stat_algo.rs @@ -0,0 +1,29 @@ +//! The stat repartition algorithm +#[allow(dead_code)] + +/// How much a solution fits the algorithm, or how much a solution fits a creature +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] +pub enum Fit { + /// Weakest fit, can't be used + VeryWeak, + /// Weak fit, shouldn't be used + Weak, + /// Average fit, can be used + Medium, + /// Strong fit, will always be used + Strong, + /// Best fit, must use + VeryStrong, +} +impl Fit { + /// Lower the fitness by one + pub(crate) fn lower(&self) -> Option { + match self { + Fit::VeryWeak => None, + Fit::Weak => Some(Fit::VeryWeak), + Fit::Medium => Some(Fit::Weak), + Fit::Strong => Some(Fit::Medium), + Fit::VeryStrong => Some(Fit::Strong), + } + } +} diff --git a/src/stat_io.rs b/src/stat_io.rs index 364d0b7..4dacbb3 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,12 +1,15 @@ //! All the struct needed for IO purposes #![allow(dead_code)] // #![allow(clippy::missing_docs_in_private_items)] +use anyhow::anyhow; use std::{fs::File, path::Path}; use anyhow::{Context, Result}; use csv::StringRecord; use serde::{Deserialize, Serialize}; +use crate::stat_algo::Fit; + /// How to represent mathematically the affinity for a stat type Affinity = f64; @@ -22,11 +25,15 @@ impl CreatureCharacteristicsAffinity { fn get_affinity(&self, affinity: AffName) -> Affinity { self.affinity[affinity as usize] } + + // fn fit(&self, stat: AffName) -> _ { + // fit(stat, self.affinity) + // } } #[derive(Debug)] /// A single creature with the needed fields to handle affinity selection -struct Creature { +pub(crate) struct Creature { /// The name of the creature name: String, // id : usize, @@ -56,9 +63,33 @@ impl TryFrom for Creature { } } +/// How much a stat fit into a vec of affinities +fn fit(value: Affinity, _vaff: &[Affinity]) -> Fit { + // For now ignore the other affinities + if value >= 5. { + Fit::VeryStrong + } else if value >= 4. { + Fit::Strong + } else if value >= 3. { + Fit::Medium + } else if value >= 1. { + Fit::Weak + } else { + Fit::VeryWeak + } +} + impl Creature { - // Get most desired affinity - // Get list of selected affinities + /// Return the fit of a stat + pub(crate) fn fit(&self, stat: AffName) -> Fit { + let stat = self.get_stat(stat); + fit(stat, &self.affinities.affinity) + } + + /// Get the stat associated to the given affinity + fn get_stat(&self, stat: AffName) -> Affinity { + self.affinities.get_affinity(stat) + } } impl TryFrom for CreatureCharacteristicsAffinity { @@ -137,6 +168,32 @@ impl CharacCharMatrix { pub(crate) fn size_loop(&self) -> usize { self.creatures.len() * 2 } + + /// Initialize the charac matrix by sorting it + fn init(&mut self) { + for v in self.inner.iter_mut() { + v.sort_unstable_by(|(_, v1), (_, v2)| v1.total_cmp(v2)) + } + } + + /// Find a creature having an affinity for the given stat + pub(crate) fn find_creature_for_stat_with_fit( + &self, + stat: AffName, + strong: &Fit, + ) -> Result { + for (creature, _affinity) in self.inner[stat as usize].iter() { + if self.creatures[*creature].fit(stat) >= *strong { + return Ok(*creature); + } + } + Err(anyhow!("Couldn't reach the specified Fit")) + } + + /// Get a creature by Id + pub(crate) fn get_creature(&self, id: usize) -> &Creature { + &self.creatures[id] + } } impl From> for CharacCharMatrix { @@ -158,8 +215,9 @@ impl From> for CharacCharMatrix { inner[index].push((creature_id, *value)); } } - - Self { inner, creatures } + let mut r = Self { inner, creatures }; + r.init(); + r } } diff --git a/src/stat_structs.rs b/src/stat_structs.rs new file mode 100644 index 0000000..43f2c3b --- /dev/null +++ b/src/stat_structs.rs @@ -0,0 +1 @@ +//! Stats repartition structs diff --git a/src/stats.rs b/src/stats.rs index e4832ae..fd55c31 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -8,11 +8,13 @@ use anyhow::Result; use clap::Args; use crate::{ + stat_algo::Fit, stat_io::{load_stat_records, AffName, CharacCharMatrix}, Config, }; #[derive(Args, Debug)] +/// The configuration struct for the StatSolver pub(crate) struct StatConfig { // #[arg(default_value_t: "data/Book1.csv")] config_path: String, @@ -23,12 +25,14 @@ pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; let _ = args; let statmatrix = load_stat_records("data/statw.csv").unwrap(); - let sol = solution_from_empty(statmatrix); + // println!("{:#?}", &statmatrix); + let sol = solution_from_empty(&statmatrix); println!("{:?}", sol); + // println!("{:#?}", &statmatrix); Ok(()) } -fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> { +fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { // while statmatrix.not_filled() {} let stats = vec![ (AffName::F, 4), @@ -39,15 +43,51 @@ fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> { (AffName::Vol, 1), ]; - println!("{:#?}", stats); - let mut sw = StatWeightList::from(stats).iter_cycle(); - println!("{:#?}", sw); - for i in 0..statmatrix.size_loop() { - println!("{:#?}", sw.next()); + // println!("{:#?}", statmatrix); + let sw = StatWeightList::from(stats).iter_cycle(); + let fits = find_all_fit(statmatrix, sw); + + Ok(()) +} + +fn find_all_fit(statmatrix: &CharacCharMatrix, mut sw: Cycle>) -> Result<()> { + let mut fits = statmatrix.size_loop(); + let mut desired_fit_level = Some(Fit::Strong); + while fits > 0 { + if let Some(fit_level) = desired_fit_level { + fits = find_for_fit(statmatrix, &mut sw, &fit_level, fits); + desired_fit_level = fit_level.lower(); + } else { + return Ok(()); + } } Ok(()) } +fn find_for_fit( + statmatrix: &CharacCharMatrix, + stat: &mut Cycle>, + fit: &Fit, + iterations: usize, +) -> usize { + let mut unfit = 0; + for _ in 0..iterations { + // println!("{:#?}",); + let stat = stat.next().unwrap(); + let found = statmatrix.find_creature_for_stat_with_fit(stat, fit); + if let Ok(creature) = found { + println!( + "Found creature {} to be a fit for stat {:?} with fitness {:?}", + creature, stat, fit + ); + } else { + unfit += 1; + } + } + println!("[{}] stats couldn't be fit at level {:?}", unfit, fit); + unfit +} + type StatWeightsTuple = Vec<(AffName, usize)>; /// The statweights, holding looping methods @@ -61,10 +101,6 @@ impl StatWeightList { } } -// impl StatWeight { - -// } - impl From for StatWeightList { fn from(mut value: StatWeightsTuple) -> Self { let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); -- 2.45.1 From 51f5e6753e94c0b35c5271dee4b71fbea2e897ba Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 14 May 2024 22:09:22 +0200 Subject: [PATCH 5/8] Huge leap in cleaning --- src/stat_algo.rs | 150 ++++++++++++++++++---- src/stat_io.rs | 302 ++++++++++++++++++++++++++++++++++---------- src/stat_structs.rs | 82 ++++++++++++ src/stats.rs | 157 ++++------------------- 4 files changed, 473 insertions(+), 218 deletions(-) diff --git a/src/stat_algo.rs b/src/stat_algo.rs index cb6f3d6..5e3d184 100644 --- a/src/stat_algo.rs +++ b/src/stat_algo.rs @@ -1,29 +1,133 @@ //! The stat repartition algorithm -#[allow(dead_code)] -/// How much a solution fits the algorithm, or how much a solution fits a creature -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] -pub enum Fit { - /// Weakest fit, can't be used - VeryWeak, - /// Weak fit, shouldn't be used - Weak, - /// Average fit, can be used - Medium, - /// Strong fit, will always be used - Strong, - /// Best fit, must use - VeryStrong, +use std::{iter::Cycle, vec::IntoIter}; + +use crate::stat_io::{AffName, CharacCharMatrix}; +use crate::stat_structs::Fit; +use anyhow::anyhow; +use anyhow::Result; + +/// Fitness mode +#[derive(Debug, Clone, Copy)] +pub(crate) enum Mode { + /// A positive fitness, looking for stats the creature has affinity with + Positive, + /// A negative fitness, looking for stats the creature has no affinity with + Negative, } -impl Fit { - /// Lower the fitness by one - pub(crate) fn lower(&self) -> Option { - match self { - Fit::VeryWeak => None, - Fit::Weak => Some(Fit::VeryWeak), - Fit::Medium => Some(Fit::Weak), - Fit::Strong => Some(Fit::Medium), - Fit::VeryStrong => Some(Fit::Strong), + +/// Find all the fits for the solution (algo1) +pub(crate) fn find_all_fits( + statmatrix: &mut CharacCharMatrix, + mut sw: Cycle>, + mode: Mode, +) -> Result<()> { + let (mut fits, mut desired_fit_level) = match mode { + Mode::Positive => (statmatrix.size_loop(), Some(Fit::Strong)), + Mode::Negative => (statmatrix.size_unfited_loop(), Some(Fit::VeryWeak)), + }; + while fits > 0 { + if let Some(fit_level) = desired_fit_level { + (fits, desired_fit_level) = match mode { + Mode::Positive => ( + find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode), + fit_level.lower(None), + ), + Mode::Negative => ( + find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode), + fit_level.upper(None), + ), + } + } else { + return Err(anyhow!( + "Can't find any ({:?}) fit at any level, please examine the remaining unfitted characters" + ,mode)); } } + Ok(()) +} + +// /// Find all the fits for the solution (algo1) +// pub(crate) fn find_all_negative_fits( +// statmatrix: &mut CharacCharMatrix, +// mut sw: Cycle>, +// ) -> Result<()> { +// let mut fits = statmatrix.size_unfited_loop(); +// let mut desired_fit_level = Some(Fit::VeryWeak); +// while fits > 0 { +// if let Some(fit_level) = desired_fit_level { +// fits = find_stat_unfit(statmatrix, &mut sw, &fit_level, fits); +// desired_fit_level = fit_level.upper(); +// } else { +// return Err(anyhow!( +// "Can't find any fit at any level, please examine the remaining unfitted characters" +// )); +// } +// } +// Ok(()) +// } + +/// Number of value that couldn't have a fit +type NbUnfit = usize; + +/// Find a stat that fits the given affinity +fn find_stat_fit( + statmatrix: &mut CharacCharMatrix, + stat: &mut Cycle>, + fit_level: &Fit, + iterations: usize, + mode: Mode, +) -> NbUnfit { + let mut unfit = 0; + // All iteration to do + for _ in 0..iterations { + let stat = stat.next().unwrap(); + // Iterate every creature this part of the algorithm is unneeded for our fitness function + // as the fitness doesn't depend on the creature + if test_fit_for_all_creatures(statmatrix, stat, fit_level, mode).is_err() { + unfit += 1; + } + } + println!( + "[{}] stats couldn't be [{:?}] fitted at level {:?}", + unfit, mode, fit_level + ); + unfit +} + +/// Iterate the fitness on every creature +/// Useless for our fitness algorithm +fn test_fit_for_all_creatures( + statmatrix: &mut CharacCharMatrix, + stat: AffName, + fit_level: &Fit, + mode: Mode, +) -> Result<()> { + for _ in 0..statmatrix.get_len_affinity(stat) { + let found = match mode { + Mode::Negative => statmatrix.find_creature_for_stat_with_negative_fit(stat, fit_level), + Mode::Positive => statmatrix.find_creature_for_stat_with_fit(stat, fit_level), + }; + + if let Ok(creature_id) = found { + statmatrix + .add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat) + .unwrap(); + + println!( + "Found creature {:?} to be a [{:?}] fit for stat {:?} with fitness {:?}", + // statmatrix.creature_name(creature_id), + creature_id, + mode, + stat, + fit_level + ); + return Ok(()); + } + } + Err(anyhow!( + "No creature can fit the charac {:?} at fitness {:?}", + stat, + fit_level + )) } diff --git a/src/stat_io.rs b/src/stat_io.rs index 4dacbb3..562567f 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,15 +1,12 @@ //! All the struct needed for IO purposes -#![allow(dead_code)] -// #![allow(clippy::missing_docs_in_private_items)] +use crate::stat_structs::Fit; use anyhow::anyhow; -use std::{fs::File, path::Path}; +use std::{fmt::Display, fs::File, iter::zip, path::Path}; use anyhow::{Context, Result}; use csv::StringRecord; use serde::{Deserialize, Serialize}; -use crate::stat_algo::Fit; - /// How to represent mathematically the affinity for a stat type Affinity = f64; @@ -20,6 +17,19 @@ struct CreatureCharacteristicsAffinity { affinity: Vec, } +impl Display for CreatureCharacteristicsAffinity { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + zip(&self.affinity, AffName::as_iter()) + .map(|(val, aname)| format!("[{:?}]: {}", aname, val)) + .collect::>() + .join(","), + ) + } +} + impl CreatureCharacteristicsAffinity { /// Get the affinity level on the given stat fn get_affinity(&self, affinity: AffName) -> Affinity { @@ -36,11 +46,10 @@ impl CreatureCharacteristicsAffinity { pub(crate) struct Creature { /// The name of the creature name: String, - // id : usize, /// The list of affinity desired affinities: CreatureCharacteristicsAffinity, - /// The actives affinities ? - actives_affinities: Vec, + // /// The actives affinities ? + // actives_affinities: Vec, /// The currently selected affinities selected_affinities: Vec, } @@ -57,7 +66,7 @@ impl TryFrom for Creature { Ok(Self { name: creature.to_owned(), affinities: CreatureCharacteristicsAffinity { affinity: aff }, - actives_affinities: Vec::new(), + // actives_affinities: Vec::new(), selected_affinities: Vec::new(), }) } @@ -78,18 +87,52 @@ fn fit(value: Affinity, _vaff: &[Affinity]) -> Fit { Fit::VeryWeak } } +// fn negative_fit(value: Affinity, _vaff: &[Affinity]) -> Fit { +// // For now ignore the other affinities +// if value >= 5. { +// Fit::VeryStrong +// } else if value >= 4. { +// Fit::Strong +// } else if value >= 3. { +// Fit::Medium +// } else if value >= 1. { +// Fit::Weak +// } else { +// Fit::VeryWeak +// } +// } impl Creature { /// Return the fit of a stat pub(crate) fn fit(&self, stat: AffName) -> Fit { - let stat = self.get_stat(stat); - fit(stat, &self.affinities.affinity) + fit(self.get_stat(stat), &self.affinities.affinity) } + /// Return the negative fitness of a stat + pub(crate) fn negative_fit(&self, stat: AffName) -> Fit { + fit(self.get_stat(stat), &self.affinities.affinity) + } /// Get the stat associated to the given affinity fn get_stat(&self, stat: AffName) -> Affinity { self.affinities.get_affinity(stat) } + + /// Add the given affinity to the list of affinities (Unckecked) + fn add_affinity(&mut self, stat: AffName) { + self.selected_affinities.push(stat); + } + + /// Can the stat be picked positively (aka, test the length and wether the stat was already selected) + #[deprecated] + fn can_pick(&self, stat: AffName) -> bool { + self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat) + } + + /// Can the stat be picked negatively (aka, is the length ok and does the vector already contains the value) + #[deprecated] + fn can_pick_negatively(&self, stat: AffName) -> bool { + self.selected_affinities.len() < 3 && !self.selected_affinities.contains(&stat) + } } impl TryFrom for CreatureCharacteristicsAffinity { @@ -107,7 +150,7 @@ impl TryFrom for CreatureCharacteristicsAffinity { /// The names of all affinities (essentialy a list of characteristics) #[allow(clippy::missing_docs_in_private_items)] -#[derive(Deserialize, Serialize, Debug, Clone, Copy)] +#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum AffName { F, Ag, @@ -119,29 +162,54 @@ pub(crate) enum AffName { Chr, } -#[inline] -/// Shortcut to get the affinity -fn get_aff_index(affinity: AffName) -> usize { - affinity as usize +impl AffName { + /// Return the list of stats as iterable + pub(crate) fn as_iter() -> impl Iterator { + [ + AffName::F, + AffName::Ag, + AffName::Per, + AffName::Psy, + AffName::Int, + AffName::Vol, + AffName::Chn, + AffName::Chr, + ] + .iter() + .copied() + } } -// #[derive(Deserialize, Serialize)] -// /// A solution for the creature -// struct Solution { -// creature: String, -// affinities: CreatureCharacteristicsAffinity, -// picks: Vec, -// } +/// A creature id in the vector of creatures +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct CreatureVecId(usize); -impl CreatureCharacteristicsAffinity { - // Create an affinity from a record +/// A creature id in the inner vector +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct CreatureInnerId(usize); + +impl CreatureInnerId { + fn id(self) -> usize { + self.0 + } } -// /// The list of all creature and their associated affinities -// struct CreaturesAffinity { -// list_creatures: HashMap, -// matrix: CharacCharMatrix, -// } +impl CreatureVecId { + fn id(self) -> usize { + self.0 + } +} + +impl Into for usize { + fn into(self) -> CreatureInnerId { + CreatureInnerId(self) + } +} +impl Into for usize { + fn into(self) -> CreatureVecId { + CreatureVecId(self) + } +} #[derive(Debug)] /// A matrix representing: List of characteristics and associated list of creatures @@ -149,26 +217,11 @@ impl CreatureCharacteristicsAffinity { /// Right now the index of every creature is used in the matrix, but a references could be used instead pub(crate) struct CharacCharMatrix { /// The inner vector structure, used to access rapidly the underlying affinities - inner: Vec>, - /// A translation vector to remember what is what + inner: Vec>, + /// The list of creatures refered to by the inner structure creatures: Vec, } impl CharacCharMatrix { - /// Check if the matrix is filled - pub(crate) fn not_filled(&self) -> bool { - for elt in &self.creatures { - if elt.selected_affinities.len() < 2 { - return false; - } - } - true - } - - /// Gives the size of the loop needed to fill all element - pub(crate) fn size_loop(&self) -> usize { - self.creatures.len() * 2 - } - /// Initialize the charac matrix by sorting it fn init(&mut self) { for v in self.inner.iter_mut() { @@ -177,22 +230,144 @@ impl CharacCharMatrix { } /// Find a creature having an affinity for the given stat + /// Returns the id in the inner struct pub(crate) fn find_creature_for_stat_with_fit( &self, stat: AffName, - strong: &Fit, - ) -> Result { - for (creature, _affinity) in self.inner[stat as usize].iter() { - if self.creatures[*creature].fit(stat) >= *strong { - return Ok(*creature); + fit_level: &Fit, + ) -> Result { + for (i, (creature, _affinity)) in self.inner[stat as usize].iter().enumerate() { + if self.available(*creature, stat, *fit_level).is_ok() { + return Ok(i.into()); } } Err(anyhow!("Couldn't reach the specified Fit")) } + /// Find a create with a negative fit for a stat + /// Returns the id in the inner struct + pub(crate) fn find_creature_for_stat_with_negative_fit( + &self, + stat: AffName, + fit_level: &Fit, + ) -> Result { + for (i, (creature, _)) in self.inner[stat as usize].iter().rev().enumerate() { + if self.available_negative(*creature, stat, *fit_level).is_ok() { + return Ok(i.into()); + } + } + Err(anyhow!("Coudln't find a match at the given negative fit")) + } /// Get a creature by Id - pub(crate) fn get_creature(&self, id: usize) -> &Creature { - &self.creatures[id] + pub(crate) fn get_creature(&self, id: CreatureVecId) -> &Creature { + &self.creatures[id.id()] + } + /// Get a mutable reference to the creature by Id + pub(crate) fn get_mut_creature(&mut self, id: CreatureVecId) -> &mut Creature { + &mut self.creatures[id.id()] + } + + /// Get the creature name + #[allow(dead_code)] + pub(crate) fn creature_name(&self, id: CreatureVecId) -> &String { + &self.get_creature(id).name + } + + /// Adds the affinity given to a creature + pub(crate) fn add_affinity_to_creature( + &mut self, + id: CreatureVecId, + stat: AffName, + ) -> Result<()> { + self.get_mut_creature(id).add_affinity(stat); + Ok(()) + } + + /// Returns Ok() if the creature can fit the stat at the fit level Err otherwise + fn available(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> { + let creature = self.get_creature(id); + if creature.fit(stat) >= fit && creature.can_pick(stat) { + Ok(()) + } else { + Err(anyhow!( + "Creature {:?} can't find a fit for {:?} with affinity {:?}", + creature, + stat, + fit + )) + } + } + /// Returns Ok() if the creature can fit the negative stat at the fit level Err otherwise + fn available_negative(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> { + let creature = self.get_creature(id); + if creature.negative_fit(stat) <= fit && creature.can_pick_negatively(stat) { + Ok(()) + } else { + Err(anyhow!( + "Creature {:?} can't find a negative fit for {:?} with affinity {:?}", + creature, + stat, + fit + )) + } + } + + /// Show the list of solutions chosen for each creature + pub(crate) fn print_solutions(&self) { + for creature in self.creatures.iter() { + println!( + "[{}] Les Caractéristiques maximum à la création : {:?} (7), {:?} (7), {:?} (5)", + creature.name, + creature.selected_affinities[0], + creature.selected_affinities[1], + creature.selected_affinities[2] + ) + } + } + + /// Print all stat weights + pub(crate) fn print_weights(&self) { + for creature in self.creatures.iter() { + println!("[{}] {}", creature.name, creature.affinities); + } + } + + /// Gives the size of the loop needed to fill all negative characteristics + pub(crate) fn size_unfited_loop(&self) -> usize { + self.creatures.len() + } + + /// Gives the size of the loop needed to fill all characteristics + pub(crate) fn size_loop(&self) -> usize { + self.creatures.len() * 2 + } + + /// Get the length of the affinity vector related to the given stat + pub(crate) fn get_len_affinity(&self, stat: AffName) -> usize { + self.get_affinity(stat).len() + } + + /// Get a reference to an affinity vector + fn get_affinity(&self, stat: AffName) -> &Vec<(CreatureVecId, f64)> { + &self.inner[stat as usize] + } + + /// Find the id in the vector associated to the inner id + pub(crate) fn to_vec_id(&self, creature_id: CreatureInnerId, stat: AffName) -> CreatureVecId { + self.inner[stat as usize][creature_id.id()].0 + } + + #[deprecated] + /// Find the inner id associated to the creature_id give + pub(crate) fn to_inner_id(&self, creature_id: CreatureVecId, stat: AffName) -> CreatureInnerId { + let a = &self.creatures[creature_id.id()]; + // self.inner[stat as usize] + // .iter() + // .find(|(id, _)| &creature_id == id) + // .and_then(|(id, _)| Some(*id)) + // .unwrap() + + todo!() } } @@ -200,19 +375,19 @@ impl From> for CharacCharMatrix { fn from(creatures: Vec) -> Self { let size = creatures.len() + 1; let mut inner = vec![ - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), ]; for (creature_id, creature) in creatures.iter().enumerate() { for (index, value) in creature.affinities.affinity.iter().enumerate() { - inner[index].push((creature_id, *value)); + inner[index].push((creature_id.into(), *value)); } } let mut r = Self { inner, creatures }; @@ -241,6 +416,5 @@ where .flat_map(|c| Creature::try_from(c.unwrap())) .collect(); let creature_matrix = CharacCharMatrix::from(creatures); - // println!("{:#?}", creature_matrix); Ok(creature_matrix) } diff --git a/src/stat_structs.rs b/src/stat_structs.rs index 43f2c3b..7a74f61 100644 --- a/src/stat_structs.rs +++ b/src/stat_structs.rs @@ -1 +1,83 @@ //! Stats repartition structs + +use std::{iter::Cycle, vec::IntoIter}; + +use crate::stat_io::AffName; +/// How much a solution fits the algorithm, or how much a solution fits a creature +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] +pub(crate) enum Fit { + /// Weakest fit, can't be used + VeryWeak, + /// Weak fit, shouldn't be used + Weak, + /// Average fit, can be used + Medium, + /// Strong fit, will always be used + Strong, + /// Best fit, must use + VeryStrong, +} +impl Fit { + /// Lower the fitness by one, with an optionnal maximum + pub(crate) fn lower(&self, min: Option) -> Option { + let f = match self { + Fit::VeryWeak => None, + Fit::Weak => Some(Fit::VeryWeak), + Fit::Medium => Some(Fit::Weak), + Fit::Strong => Some(Fit::Medium), + Fit::VeryStrong => Some(Fit::Strong), + }; + if f <= min { + return None; + } + f + } + + /// Raise the fitness level by one, with an optionnal maximum + pub(crate) fn upper(&self, min: Option) -> Option { + let f = match self { + Fit::VeryWeak => Some(Fit::Weak), + Fit::Weak => Some(Fit::Medium), + Fit::Medium => Some(Fit::Strong), + Fit::Strong => Some(Fit::VeryStrong), + Fit::VeryStrong => None, + }; + if f <= min { + return None; + } + f + } +} +/// A stat weight level (Affinity name and weight) +type StatWeightsTuple = Vec<(AffName, usize)>; + +/// The statweights, holding looping methods +#[derive(Debug)] +pub(crate) struct StatWeightList { + /// The list of all affinities + weights: Vec, +} +impl StatWeightList { + /// Iterate over all affinites to fill, endlessly + pub(crate) fn iter_cycle(self) -> Cycle> { + self.weights.into_iter().cycle() + } +} + +impl From for StatWeightList { + fn from(mut value: StatWeightsTuple) -> Self { + let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); + let mut weights = Vec::with_capacity(ln); + let mut i = 0; + while i < ln { + for (w, nb) in value.iter_mut() { + if nb != &0 { + *nb -= 1; + weights.push(*w); + i += 1; + } + } + } + Self { weights } + } +} diff --git a/src/stats.rs b/src/stats.rs index fd55c31..ae5358b 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -1,14 +1,13 @@ //! A module to handle stats disparity between all origins -#![allow(dead_code)] -#![allow(clippy::missing_docs_in_private_items)] -use std::{iter::Cycle, vec::IntoIter}; +use crate::stat_algo::find_all_fits; +use crate::stat_algo::Mode; +use crate::stat_structs::StatWeightList; use anyhow::Result; use clap::Args; use crate::{ - stat_algo::Fit, stat_io::{load_stat_records, AffName, CharacCharMatrix}, Config, }; @@ -17,24 +16,24 @@ use crate::{ /// The configuration struct for the StatSolver pub(crate) struct StatConfig { // #[arg(default_value_t: "data/Book1.csv")] + /// The path where the data to analyse is config_path: String, } /// Main solver function, in charge of selecting algorithms and handling all program flow pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; - let _ = args; - let statmatrix = load_stat_records("data/statw.csv").unwrap(); - // println!("{:#?}", &statmatrix); - let sol = solution_from_empty(&statmatrix); - println!("{:?}", sol); - // println!("{:#?}", &statmatrix); + let mut statmatrix = load_stat_records(&args.config_path).unwrap(); + solution_from_empty(&mut statmatrix).unwrap(); + println!("{:?}", statmatrix.print_weights()); + println!("{:?}", statmatrix.print_solutions()); Ok(()) } -fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { +/// Find a solution from an empty solution (algo1) +fn solution_from_empty(statmatrix: &mut CharacCharMatrix) -> Result<()> { // while statmatrix.not_filled() {} - let stats = vec![ + let stats_desired = vec![ (AffName::F, 4), (AffName::Ag, 3), (AffName::Per, 3), @@ -42,126 +41,22 @@ fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { (AffName::Int, 1), (AffName::Vol, 1), ]; + let stats_undesirable = vec![ + (AffName::Int, 3), + (AffName::Vol, 3), + (AffName::Chr, 2), + (AffName::Chn, 2), + (AffName::F, 1), + (AffName::Ag, 1), + (AffName::Per, 1), + (AffName::Psy, 1), + ]; - // println!("{:#?}", statmatrix); - let sw = StatWeightList::from(stats).iter_cycle(); - let fits = find_all_fit(statmatrix, sw); + let sw = StatWeightList::from(stats_desired).iter_cycle(); + let nsw = StatWeightList::from(stats_undesirable).iter_cycle(); + find_all_fits(statmatrix, sw, Mode::Positive).unwrap(); + find_all_fits(statmatrix, nsw, Mode::Negative).unwrap(); + // find_all_negative_fits(statmatrix, nsw).unwrap(); Ok(()) } - -fn find_all_fit(statmatrix: &CharacCharMatrix, mut sw: Cycle>) -> Result<()> { - let mut fits = statmatrix.size_loop(); - let mut desired_fit_level = Some(Fit::Strong); - while fits > 0 { - if let Some(fit_level) = desired_fit_level { - fits = find_for_fit(statmatrix, &mut sw, &fit_level, fits); - desired_fit_level = fit_level.lower(); - } else { - return Ok(()); - } - } - Ok(()) -} - -fn find_for_fit( - statmatrix: &CharacCharMatrix, - stat: &mut Cycle>, - fit: &Fit, - iterations: usize, -) -> usize { - let mut unfit = 0; - for _ in 0..iterations { - // println!("{:#?}",); - let stat = stat.next().unwrap(); - let found = statmatrix.find_creature_for_stat_with_fit(stat, fit); - if let Ok(creature) = found { - println!( - "Found creature {} to be a fit for stat {:?} with fitness {:?}", - creature, stat, fit - ); - } else { - unfit += 1; - } - } - println!("[{}] stats couldn't be fit at level {:?}", unfit, fit); - unfit -} - -type StatWeightsTuple = Vec<(AffName, usize)>; - -/// The statweights, holding looping methods -#[derive(Debug)] -struct StatWeightList { - weights: Vec, -} -impl StatWeightList { - fn iter_cycle(self) -> Cycle> { - self.weights.into_iter().cycle() - } -} - -impl From for StatWeightList { - fn from(mut value: StatWeightsTuple) -> Self { - let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); - let mut weights = Vec::with_capacity(ln); - let mut i = 0; - while i < ln { - for (w, nb) in value.iter_mut() { - if nb != &0 { - *nb -= 1; - weights.push(*w); - i += 1; - } - } - } - Self { weights } - } -} - -// struct DesiredStats {} - -// struct Creature { -// stats: DesiredStats, -// name: String, -// } - -// enum CharacEnum { -// F, -// Ag, -// } - -// struct CharacWeight { -// charac: CharacEnum, -// list_weights: Vec<(f64, Creature)>, -// } - -// // impl Creature{ -// // fn get_ -// // } - -// // The first Algorithm, creating all creatures from scratch - -// fn get_next_stat_to_grow() {} - -// fn get_greatest_consumer_of(c: CharacEnum) {} - -// fn assign_stat_to_creature(c: CharacEnum) {} - -// fn get_greatest_despiser_of(c: CharacEnum) {} - -// // The second algorithm, appending to an existing solution - -// // Serialize and Deserialize Solutions - -// fn try_getting_desired_stat() {} - -// fn find_swap_creature() {} - -// // Integrity check and disparity check - -// fn check_stats_integrity() {} - -// fn show_stats() {} - -// fn show_outliers() {} -- 2.45.1 From fa4cf4be292f9ddb0b0d46ee0104194116bdd442 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 May 2024 02:23:14 +0200 Subject: [PATCH 6/8] Cleanup and bug hunting --- src/stat_algo.rs | 48 +++++++++++------- src/stat_io.rs | 127 ++++++++++++++++++++++++++++++++++++++--------- src/stats.rs | 22 +++++--- src/tablegen.rs | 2 +- 4 files changed, 150 insertions(+), 49 deletions(-) diff --git a/src/stat_algo.rs b/src/stat_algo.rs index 5e3d184..314b8d8 100644 --- a/src/stat_algo.rs +++ b/src/stat_algo.rs @@ -2,10 +2,11 @@ use std::{iter::Cycle, vec::IntoIter}; -use crate::stat_io::{AffName, CharacCharMatrix}; -use crate::stat_structs::Fit; -use anyhow::anyhow; -use anyhow::Result; +use crate::{ + stat_io::{AffName, CharacCharMatrix}, + stat_structs::Fit, +}; +use anyhow::{anyhow, Result}; /// Fitness mode #[derive(Debug, Clone, Copy)] @@ -88,10 +89,16 @@ fn find_stat_fit( unfit += 1; } } - println!( - "[{}] stats couldn't be [{:?}] fitted at level {:?}", - unfit, mode, fit_level - ); + if statmatrix.verbose() { + if unfit > 0 { + println!( + "[{}] stats couldn't be [{:?}] fitted at level {:?}", + unfit, mode, fit_level + ); + } else { + println!("All stats [{:?}] fitted at level [{:?}]", mode, fit_level); + } + } unfit } @@ -111,17 +118,24 @@ fn test_fit_for_all_creatures( if let Ok(creature_id) = found { statmatrix - .add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat) + .add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat, mode) .unwrap(); - println!( - "Found creature {:?} to be a [{:?}] fit for stat {:?} with fitness {:?}", - // statmatrix.creature_name(creature_id), - creature_id, - mode, - stat, - fit_level - ); + if statmatrix.verbose() { + let creature = statmatrix.inner_creature(creature_id, stat); + println!( + "[{:?}] [{:?}] is a fit for stat {:?} [{:?}]", + mode, + creature.get_name(), + stat, + fit_level + ); + println!( + " --> [{:?}] {:?}", + creature.get_name(), + creature.get_all_selected() + ) + } return Ok(()); } } diff --git a/src/stat_io.rs b/src/stat_io.rs index 562567f..1d73ba7 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,5 +1,5 @@ //! All the struct needed for IO purposes -use crate::stat_structs::Fit; +use crate::{stat_algo::Mode, stat_structs::Fit, stats::StatConfig}; use anyhow::anyhow; use std::{fmt::Display, fs::File, iter::zip, path::Path}; @@ -12,7 +12,7 @@ type Affinity = f64; #[derive(Serialize, Deserialize, Debug)] /// A row representing the creature affinity for a stat -struct CreatureCharacteristicsAffinity { +pub(crate) struct CreatureCharacteristicsAffinity { /// A list of witch stats are desired and at witch level affinity: Vec, } @@ -52,6 +52,41 @@ pub(crate) struct Creature { // actives_affinities: Vec, /// The currently selected affinities selected_affinities: Vec, + /// The currently selected negative affinities + selected_negative_affinities: Vec, +} + +impl Creature { + /// Get the underlying name + pub(crate) fn get_name(&self) -> &str { + &self.name + } + + /// The list of affinities + #[allow(dead_code)] + pub(crate) fn get_affinities(&self) -> &CreatureCharacteristicsAffinity { + &self.affinities + } + + /// The list of selected characs + #[allow(dead_code)] + pub(crate) fn get_selected(&self) -> &Vec { + &self.selected_affinities + } + + /// The list of selected negative characs + #[allow(dead_code)] + pub(crate) fn get_negative_selected(&self) -> &Vec { + &self.selected_negative_affinities + } + + /// The list of all selected characs + #[allow(dead_code)] + pub(crate) fn get_all_selected(&self) -> Vec { + let mut v = self.selected_affinities.clone(); + v.extend(&self.selected_negative_affinities); + v + } } impl TryFrom for Creature { @@ -68,6 +103,7 @@ impl TryFrom for Creature { affinities: CreatureCharacteristicsAffinity { affinity: aff }, // actives_affinities: Vec::new(), selected_affinities: Vec::new(), + selected_negative_affinities: Vec::new(), }) } } @@ -121,17 +157,23 @@ impl Creature { fn add_affinity(&mut self, stat: AffName) { self.selected_affinities.push(stat); } + /// Add the given affinity to the list of affinities (Unckecked) + fn add_negative_affinity(&mut self, stat: AffName) { + self.selected_negative_affinities.push(stat); + } /// Can the stat be picked positively (aka, test the length and wether the stat was already selected) + /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick(&self, stat: AffName) -> bool { self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat) } /// Can the stat be picked negatively (aka, is the length ok and does the vector already contains the value) + /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick_negatively(&self, stat: AffName) -> bool { - self.selected_affinities.len() < 3 && !self.selected_affinities.contains(&stat) + self.selected_affinities.is_empty() && !self.selected_affinities.contains(&stat) } } @@ -189,25 +231,29 @@ pub(crate) struct CreatureVecId(usize); pub(crate) struct CreatureInnerId(usize); impl CreatureInnerId { + /// Get the underlying Inner Id fn id(self) -> usize { self.0 } } impl CreatureVecId { + /// Gets the underlying creature Id fn id(self) -> usize { self.0 } } -impl Into for usize { - fn into(self) -> CreatureInnerId { - CreatureInnerId(self) +/// Create a creature inner id from an id +impl From for CreatureInnerId { + fn from(val: usize) -> Self { + CreatureInnerId(val) } } -impl Into for usize { - fn into(self) -> CreatureVecId { - CreatureVecId(self) +/// Create a creature vector id from an id +impl From for CreatureVecId { + fn from(val: usize) -> Self { + CreatureVecId(val) } } @@ -220,6 +266,8 @@ pub(crate) struct CharacCharMatrix { inner: Vec>, /// The list of creatures refered to by the inner structure creatures: Vec, + /// The module config, handy to have + config: StatConfig, } impl CharacCharMatrix { /// Initialize the charac matrix by sorting it @@ -273,13 +321,23 @@ impl CharacCharMatrix { &self.get_creature(id).name } + /// Get the creature name from it's inner value + #[allow(dead_code)] + pub(crate) fn inner_creature(&self, id: CreatureInnerId, stat: AffName) -> &Creature { + &self.creatures[self.to_vec_id(id, stat).id()] + } + /// Adds the affinity given to a creature pub(crate) fn add_affinity_to_creature( &mut self, id: CreatureVecId, stat: AffName, + mode: Mode, ) -> Result<()> { - self.get_mut_creature(id).add_affinity(stat); + match mode { + Mode::Positive => self.get_mut_creature(id).add_affinity(stat), + Mode::Negative => self.get_mut_creature(id).add_negative_affinity(stat), + } Ok(()) } @@ -320,7 +378,7 @@ impl CharacCharMatrix { creature.name, creature.selected_affinities[0], creature.selected_affinities[1], - creature.selected_affinities[2] + creature.selected_negative_affinities[0] ) } } @@ -358,21 +416,40 @@ impl CharacCharMatrix { } #[deprecated] + #[allow(dead_code)] /// Find the inner id associated to the creature_id give pub(crate) fn to_inner_id(&self, creature_id: CreatureVecId, stat: AffName) -> CreatureInnerId { - let a = &self.creatures[creature_id.id()]; - // self.inner[stat as usize] - // .iter() - // .find(|(id, _)| &creature_id == id) - // .and_then(|(id, _)| Some(*id)) - // .unwrap() + // let a = &self.[creature_id.id()]; + self.inner[stat as usize] + .iter() + .enumerate() + .find(|(_index, (id, _))| &creature_id == id) + .map(|(id, _)| id.into()) + .unwrap() + } - todo!() + // /// Consume the config object to add it to the CharacStatMatrix + // #[deprecated] + // pub(crate) fn add_config(&mut self, config: StatConfig) { + // self.config = config; + // } + + /// Get the level of verbosity + pub(crate) fn verbose(&self) -> bool { + self.config.verbosity + } + + /// Get a reference to the active config + #[allow(dead_code)] + pub(crate) fn get_config(&self) -> &StatConfig { + &self.config } } -impl From> for CharacCharMatrix { - fn from(creatures: Vec) -> Self { +// impl From> for CharacCharMatrix { +impl CharacCharMatrix { + /// Create a CharacCharMatrix from a vec of creature and a config + fn from_vec(creatures: Vec, config: StatConfig) -> Self { let size = creatures.len() + 1; let mut inner = vec![ Vec::<(CreatureVecId, Affinity)>::with_capacity(size), @@ -390,14 +467,18 @@ impl From> for CharacCharMatrix { inner[index].push((creature_id.into(), *value)); } } - let mut r = Self { inner, creatures }; + let mut r = Self { + inner, + creatures, + config, + }; r.init(); r } } /// Load all the records in the csv -pub fn load_stat_records(filename: T) -> Result +pub fn load_stat_records(filename: T, config: StatConfig) -> Result where T: AsRef, { @@ -415,6 +496,6 @@ where .into_records() .flat_map(|c| Creature::try_from(c.unwrap())) .collect(); - let creature_matrix = CharacCharMatrix::from(creatures); + let creature_matrix = CharacCharMatrix::from_vec(creatures, config); Ok(creature_matrix) } diff --git a/src/stats.rs b/src/stats.rs index ae5358b..dba68ba 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -1,8 +1,9 @@ //! A module to handle stats disparity between all origins -use crate::stat_algo::find_all_fits; -use crate::stat_algo::Mode; -use crate::stat_structs::StatWeightList; +use crate::{ + stat_algo::{find_all_fits, Mode}, + stat_structs::StatWeightList, +}; use anyhow::Result; use clap::Args; @@ -12,21 +13,26 @@ use crate::{ Config, }; -#[derive(Args, Debug)] +#[derive(Args, Debug, Clone)] /// The configuration struct for the StatSolver pub(crate) struct StatConfig { // #[arg(default_value_t: "data/Book1.csv")] /// The path where the data to analyse is - config_path: String, + pub(crate) config_path: String, + /// The verbosity level + #[arg(short, long, default_value_t = false)] + pub(crate) verbosity: bool, } /// Main solver function, in charge of selecting algorithms and handling all program flow pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; - let mut statmatrix = load_stat_records(&args.config_path).unwrap(); + let mut statmatrix = load_stat_records(&args.config_path, args.clone()).unwrap(); solution_from_empty(&mut statmatrix).unwrap(); - println!("{:?}", statmatrix.print_weights()); - println!("{:?}", statmatrix.print_solutions()); + if args.verbosity { + println!("{:?}", statmatrix.print_weights()); + println!("{:?}", statmatrix.print_solutions()); + } Ok(()) } diff --git a/src/tablegen.rs b/src/tablegen.rs index d5790d1..597dff4 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -9,9 +9,9 @@ use std::{ path::{Path, PathBuf}, }; -use crate::table_types::{ClassesArray, GenericArray, RecordClass, WriteTable}; use crate::{ table_structs::{TableArgs, TableGenerationTarget, TableTargets, RE, STR_TO_TARGET_FULL}, + table_types::{ClassesArray, GenericArray, RecordClass, WriteTable}, Config, }; -- 2.45.1 From 5158360fb57bc9f0bad4f7b765ac5ec25402f406 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 May 2024 02:42:04 +0200 Subject: [PATCH 7/8] Squashes last bugs --- src/stat_algo.rs | 9 +++++++++ src/stat_io.rs | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/stat_algo.rs b/src/stat_algo.rs index 314b8d8..fdb6f82 100644 --- a/src/stat_algo.rs +++ b/src/stat_algo.rs @@ -111,12 +111,21 @@ fn test_fit_for_all_creatures( mode: Mode, ) -> Result<()> { for _ in 0..statmatrix.get_len_affinity(stat) { + println!( + "[{:?}] Testing fit for stat {:?} at level {:?}", + mode, stat, fit_level + ); let found = match mode { Mode::Negative => statmatrix.find_creature_for_stat_with_negative_fit(stat, fit_level), Mode::Positive => statmatrix.find_creature_for_stat_with_fit(stat, fit_level), }; if let Ok(creature_id) = found { + println!( + " ==> Creature {} has affinity for stat {:?}", + statmatrix.inner_creature(creature_id, stat).get_name(), + stat + ); statmatrix .add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat, mode) .unwrap(); diff --git a/src/stat_io.rs b/src/stat_io.rs index 1d73ba7..e280fc7 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -166,6 +166,7 @@ impl Creature { /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick(&self, stat: AffName) -> bool { + println!(" ==> Testing if {} can fit {:?}", self.name, stat); self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat) } @@ -173,7 +174,8 @@ impl Creature { /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick_negatively(&self, stat: AffName) -> bool { - self.selected_affinities.is_empty() && !self.selected_affinities.contains(&stat) + println!(" ==> Testing if {} can fit {:?}", self.name, stat); + self.selected_negative_affinities.is_empty() && !self.selected_affinities.contains(&stat) } } @@ -299,7 +301,7 @@ impl CharacCharMatrix { stat: AffName, fit_level: &Fit, ) -> Result { - for (i, (creature, _)) in self.inner[stat as usize].iter().rev().enumerate() { + for (i, (creature, _)) in self.inner[stat as usize].iter().enumerate().rev() { if self.available_negative(*creature, stat, *fit_level).is_ok() { return Ok(i.into()); } -- 2.45.1 From 0f81bb4d424efda744bf5d820c711083eddc0299 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 16 May 2024 02:51:59 +0200 Subject: [PATCH 8/8] Corrects a bad algo and adds todo "Working" stat generator --- Cargo.toml | 1 + Todo.md | 7 +++++++ src/stat_algo.rs | 23 ++++++++++++++++------- src/stat_io.rs | 42 ++++++++++++++++++++++++++++++++++-------- src/stats.rs | 2 +- 5 files changed, 59 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3e58724..2e83686 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ edition = "2021" anyhow = "1.0.82" clap = { version = "4.5.4", features = ["derive"] } csv = "1.3.0" +debug_print = "1.0.0" dynfmt = { version = "0.1.5", features = ["curly"] } enum_dispatch = "0.3.13" glob = "0.3.1" diff --git a/Todo.md b/Todo.md index 5d46061..c9808a5 100644 --- a/Todo.md +++ b/Todo.md @@ -11,6 +11,13 @@ * Have interactive mode ? * Dissociate Model from generation +## StatGen +* Get rid of cycle and have a struct that gives stats according to % and keeps tracks of % +* Test VecDeque +* Add testing +* Add the swap algo (swap a bad fit creature with another) +* Save/load states + ## Test Units diff --git a/src/stat_algo.rs b/src/stat_algo.rs index fdb6f82..84c7367 100644 --- a/src/stat_algo.rs +++ b/src/stat_algo.rs @@ -1,12 +1,12 @@ //! The stat repartition algorithm -use std::{iter::Cycle, vec::IntoIter}; - use crate::{ stat_io::{AffName, CharacCharMatrix}, stat_structs::Fit, }; use anyhow::{anyhow, Result}; +use debug_print::debug_println; +use std::{iter::Cycle, vec::IntoIter}; /// Fitness mode #[derive(Debug, Clone, Copy)] @@ -24,8 +24,14 @@ pub(crate) fn find_all_fits( mode: Mode, ) -> Result<()> { let (mut fits, mut desired_fit_level) = match mode { - Mode::Positive => (statmatrix.size_loop(), Some(Fit::Strong)), - Mode::Negative => (statmatrix.size_unfited_loop(), Some(Fit::VeryWeak)), + Mode::Positive => { + statmatrix.sort(); + (statmatrix.size_loop(), Some(Fit::Strong)) + } + Mode::Negative => { + statmatrix.reverse_sort(); + (statmatrix.size_unfited_loop(), Some(Fit::VeryWeak)) + } }; while fits > 0 { if let Some(fit_level) = desired_fit_level { @@ -111,9 +117,11 @@ fn test_fit_for_all_creatures( mode: Mode, ) -> Result<()> { for _ in 0..statmatrix.get_len_affinity(stat) { - println!( + debug_println!( "[{:?}] Testing fit for stat {:?} at level {:?}", - mode, stat, fit_level + mode, + stat, + fit_level ); let found = match mode { Mode::Negative => statmatrix.find_creature_for_stat_with_negative_fit(stat, fit_level), @@ -121,7 +129,7 @@ fn test_fit_for_all_creatures( }; if let Ok(creature_id) = found { - println!( + debug_println!( " ==> Creature {} has affinity for stat {:?}", statmatrix.inner_creature(creature_id, stat).get_name(), stat @@ -145,6 +153,7 @@ fn test_fit_for_all_creatures( creature.get_all_selected() ) } + statmatrix.remove_creature_from_stat(creature_id, stat); return Ok(()); } } diff --git a/src/stat_io.rs b/src/stat_io.rs index e280fc7..77b9212 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,11 +1,11 @@ //! All the struct needed for IO purposes use crate::{stat_algo::Mode, stat_structs::Fit, stats::StatConfig}; use anyhow::anyhow; -use std::{fmt::Display, fs::File, iter::zip, path::Path}; - use anyhow::{Context, Result}; use csv::StringRecord; +use debug_print::debug_println; use serde::{Deserialize, Serialize}; +use std::{fmt::Display, fs::File, iter::zip, path::Path}; /// How to represent mathematically the affinity for a stat type Affinity = f64; @@ -166,7 +166,7 @@ impl Creature { /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick(&self, stat: AffName) -> bool { - println!(" ==> Testing if {} can fit {:?}", self.name, stat); + debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat); self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat) } @@ -174,7 +174,7 @@ impl Creature { /// This test only works if the algo is done in the correct order #[deprecated] fn can_pick_negatively(&self, stat: AffName) -> bool { - println!(" ==> Testing if {} can fit {:?}", self.name, stat); + debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat); self.selected_negative_affinities.is_empty() && !self.selected_affinities.contains(&stat) } } @@ -274,9 +274,7 @@ pub(crate) struct CharacCharMatrix { impl CharacCharMatrix { /// Initialize the charac matrix by sorting it fn init(&mut self) { - for v in self.inner.iter_mut() { - v.sort_unstable_by(|(_, v1), (_, v2)| v1.total_cmp(v2)) - } + // self.sort() } /// Find a creature having an affinity for the given stat @@ -301,7 +299,7 @@ impl CharacCharMatrix { stat: AffName, fit_level: &Fit, ) -> Result { - for (i, (creature, _)) in self.inner[stat as usize].iter().enumerate().rev() { + for (i, (creature, _)) in self.inner[stat as usize].iter().enumerate() { if self.available_negative(*creature, stat, *fit_level).is_ok() { return Ok(i.into()); } @@ -446,6 +444,34 @@ impl CharacCharMatrix { pub(crate) fn get_config(&self) -> &StatConfig { &self.config } + + /// Sort the underlying data + pub(crate) fn sort(&mut self) { + for v in self.inner.iter_mut() { + v.sort_unstable_by(|(_, v1), (_, v2)| v1.total_cmp(v2)) + } + } + /// Sort the underlying data in the reverse order + pub(crate) fn reverse_sort(&mut self) { + for v in self.inner.iter_mut() { + v.sort_unstable_by(|(_, v1), (_, v2)| v2.total_cmp(v1)) + } + } + + /// Remove the creature to avoid doing incessant lookups + pub(crate) fn remove_creature_from_stat( + &mut self, + creature_id: CreatureInnerId, + stat: AffName, + ) { + let _rem = self.inner[stat as usize].remove(creature_id.id()); + // println!( + // " ==> Removing stat {:?} on creature {} (was: {:?})", + // stat, + // self.creature_name(_rem.0), + // _rem.1 + // ); + } } // impl From> for CharacCharMatrix { diff --git a/src/stats.rs b/src/stats.rs index dba68ba..50e2dd7 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -31,8 +31,8 @@ pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { solution_from_empty(&mut statmatrix).unwrap(); if args.verbosity { println!("{:?}", statmatrix.print_weights()); - println!("{:?}", statmatrix.print_solutions()); } + statmatrix.print_solutions(); Ok(()) } -- 2.45.1