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/main.rs b/src/main.rs index 06d2a9a..1b5deb9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,10 @@ // #![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; mod tablegen; @@ -18,6 +22,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 +43,8 @@ enum Commands { Tablegen(TableArgs), /// Show/Export config Config(ConfigArgs), + /// Handle stat repartition + Stats(StatConfig), } #[derive(Debug, Args)] @@ -82,6 +89,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_algo.rs b/src/stat_algo.rs new file mode 100644 index 0000000..84c7367 --- /dev/null +++ b/src/stat_algo.rs @@ -0,0 +1,165 @@ +//! The stat repartition algorithm + +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)] +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, +} + +/// 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.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 { + (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; + } + } + 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 +} + +/// 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) { + debug_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 { + debug_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(); + + 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() + ) + } + statmatrix.remove_creature_from_stat(creature_id, stat); + 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 new file mode 100644 index 0000000..77b9212 --- /dev/null +++ b/src/stat_io.rs @@ -0,0 +1,529 @@ +//! All the struct needed for IO purposes +use crate::{stat_algo::Mode, stat_structs::Fit, stats::StatConfig}; +use anyhow::anyhow; +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; + +#[derive(Serialize, Deserialize, Debug)] +/// A row representing the creature affinity for a stat +pub(crate) struct CreatureCharacteristicsAffinity { + /// A list of witch stats are desired and at witch level + 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 { + 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 +pub(crate) struct Creature { + /// The name of the creature + name: String, + /// The list of affinity desired + affinities: CreatureCharacteristicsAffinity, + // /// The actives affinities ? + // 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 { + 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(), + selected_negative_affinities: Vec::new(), + }) + } +} + +/// 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 + } +} +// 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 { + 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); + } + /// 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 { + debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat); + 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 { + debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat); + self.selected_negative_affinities.is_empty() && !self.selected_affinities.contains(&stat) + } +} + +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 }) + } +} + +/// The names of all affinities (essentialy a list of characteristics) +#[allow(clippy::missing_docs_in_private_items)] +#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum AffName { + F, + Ag, + Per, + Psy, + Int, + Vol, + Chn, + Chr, +} + +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() + } +} + +/// A creature id in the vector of creatures +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct CreatureVecId(usize); + +/// A creature id in the inner vector +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +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 + } +} + +/// Create a creature inner id from an id +impl From for CreatureInnerId { + fn from(val: usize) -> Self { + CreatureInnerId(val) + } +} +/// Create a creature vector id from an id +impl From for CreatureVecId { + fn from(val: usize) -> Self { + CreatureVecId(val) + } +} + +#[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 +pub(crate) struct CharacCharMatrix { + /// The inner vector structure, used to access rapidly the underlying affinities + 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 + fn init(&mut self) { + // self.sort() + } + + /// 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, + 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().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: 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 + } + + /// 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<()> { + match mode { + Mode::Positive => self.get_mut_creature(id).add_affinity(stat), + Mode::Negative => self.get_mut_creature(id).add_negative_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_negative_affinities[0] + ) + } + } + + /// 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] + #[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.[creature_id.id()]; + self.inner[stat as usize] + .iter() + .enumerate() + .find(|(_index, (id, _))| &creature_id == id) + .map(|(id, _)| id.into()) + .unwrap() + } + + // /// 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 + } + + /// 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 { +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), + 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.into(), *value)); + } + } + let mut r = Self { + inner, + creatures, + config, + }; + r.init(); + r + } +} + +/// Load all the records in the csv +pub fn load_stat_records(filename: T, config: StatConfig) -> Result +where + T: AsRef, +{ + let file = File::open(filename)?; + let rdr = csv::ReaderBuilder::new() + .has_headers(true) + .delimiter(b',') + .double_quote(false) + .escape(Some(b'\\')) + .flexible(true) + .comment(Some(b'#')) + .from_reader(file); + + let creatures: Vec = rdr + .into_records() + .flat_map(|c| Creature::try_from(c.unwrap())) + .collect(); + let creature_matrix = CharacCharMatrix::from_vec(creatures, config); + Ok(creature_matrix) +} diff --git a/src/stat_structs.rs b/src/stat_structs.rs new file mode 100644 index 0000000..7a74f61 --- /dev/null +++ b/src/stat_structs.rs @@ -0,0 +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 new file mode 100644 index 0000000..50e2dd7 --- /dev/null +++ b/src/stats.rs @@ -0,0 +1,68 @@ +//! A module to handle stats disparity between all origins + +use crate::{ + stat_algo::{find_all_fits, Mode}, + stat_structs::StatWeightList, +}; + +use anyhow::Result; +use clap::Args; + +use crate::{ + stat_io::{load_stat_records, AffName, CharacCharMatrix}, + Config, +}; + +#[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 + 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, args.clone()).unwrap(); + solution_from_empty(&mut statmatrix).unwrap(); + if args.verbosity { + println!("{:?}", statmatrix.print_weights()); + } + statmatrix.print_solutions(); + Ok(()) +} + +/// Find a solution from an empty solution (algo1) +fn solution_from_empty(statmatrix: &mut CharacCharMatrix) -> Result<()> { + // while statmatrix.not_filled() {} + let stats_desired = vec![ + (AffName::F, 4), + (AffName::Ag, 3), + (AffName::Per, 3), + (AffName::Psy, 3), + (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), + ]; + + 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(()) +} 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, };