536 lines
17 KiB
Rust
536 lines
17 KiB
Rust
// Workspace: stats
|
|
// File: stats/src/stat_io.rs
|
|
//! The module `CharacStatMatrix` allows for manipulation of creatures and their associated affinities.
|
|
//! It provides a structured way to add, manage, and retrieve information about creatures based on
|
|
//! different affinity statistics.
|
|
//!
|
|
use crate::{stat_algo::Mode, stat_structs::Fit};
|
|
use anyhow::anyhow;
|
|
use anyhow::{Context, Result};
|
|
use config::statsolver::StatConfig;
|
|
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(super) struct CreatureCharacteristicsAffinity {
|
|
/// A list of witch stats are desired and at witch level
|
|
affinity: Vec<Affinity>,
|
|
}
|
|
|
|
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::<Vec<String>>()
|
|
.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(super) struct Creature {
|
|
/// The name of the creature
|
|
name: String,
|
|
/// The list of affinity desired
|
|
affinities: CreatureCharacteristicsAffinity,
|
|
// /// The actives affinities ?
|
|
// actives_affinities: Vec<Affinity>,
|
|
/// The currently selected affinities
|
|
selected_affinities: Vec<AffName>,
|
|
/// The currently selected negative affinities
|
|
selected_negative_affinities: Vec<AffName>,
|
|
}
|
|
|
|
impl Creature {
|
|
/// Get the underlying name
|
|
pub(super) fn get_name(&self) -> &str {
|
|
&self.name
|
|
}
|
|
|
|
/// The list of affinities
|
|
#[allow(dead_code)]
|
|
pub(super) fn get_affinities(&self) -> &CreatureCharacteristicsAffinity {
|
|
&self.affinities
|
|
}
|
|
|
|
/// The list of selected characs
|
|
#[allow(dead_code)]
|
|
pub(super) fn get_selected(&self) -> &Vec<AffName> {
|
|
&self.selected_affinities
|
|
}
|
|
|
|
/// The list of selected negative characs
|
|
#[allow(dead_code)]
|
|
pub(super) fn get_negative_selected(&self) -> &Vec<AffName> {
|
|
&self.selected_negative_affinities
|
|
}
|
|
|
|
/// The list of all selected characs
|
|
#[allow(dead_code)]
|
|
pub(super) fn get_all_selected(&self) -> Vec<AffName> {
|
|
let mut v = self.selected_affinities.clone();
|
|
v.extend(&self.selected_negative_affinities);
|
|
v
|
|
}
|
|
}
|
|
|
|
impl TryFrom<StringRecord> for Creature {
|
|
type Error = anyhow::Error;
|
|
|
|
fn try_from(value: StringRecord) -> std::prelude::v1::Result<Self, Self::Error> {
|
|
let mut iterable = value.into_iter();
|
|
let creature = iterable.next().context("Getting name")?;
|
|
let aff = iterable
|
|
.map(|m| m.parse::<f64>().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(super) fn fit(&self, stat: AffName) -> Fit {
|
|
fit(self.get_stat(stat), &self.affinities.affinity)
|
|
}
|
|
|
|
/// Return the negative fitness of a stat
|
|
pub(super) 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
|
|
// TODO: #[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
|
|
// TODO: #[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<StringRecord> for CreatureCharacteristicsAffinity {
|
|
type Error = anyhow::Error;
|
|
|
|
fn try_from(value: StringRecord) -> Result<Self> {
|
|
let aff = value
|
|
.into_iter()
|
|
.skip(1)
|
|
.map(|m| m.parse::<f64>().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(super) enum AffName {
|
|
F,
|
|
Ag,
|
|
Per,
|
|
Psy,
|
|
Int,
|
|
Vol,
|
|
Chn,
|
|
Chr,
|
|
}
|
|
|
|
impl AffName {
|
|
/// Return the list of stats as iterable
|
|
pub(super) fn as_iter() -> impl Iterator<Item = AffName> {
|
|
[
|
|
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(super) struct CreatureVecId(usize);
|
|
|
|
/// A creature id in the inner vector
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub(super) 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<usize> for CreatureInnerId {
|
|
fn from(val: usize) -> Self {
|
|
CreatureInnerId(val)
|
|
}
|
|
}
|
|
/// Create a creature vector id from an id
|
|
impl From<usize> 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(super) struct CharacCharMatrix {
|
|
/// The inner vector structure, used to access rapidly the underlying affinities
|
|
inner: Vec<Vec<(CreatureVecId, Affinity)>>,
|
|
/// The list of creatures refered to by the inner structure
|
|
creatures: Vec<Creature>,
|
|
/// 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(super) fn find_creature_for_stat_with_fit(
|
|
&self,
|
|
stat: AffName,
|
|
fit_level: &Fit,
|
|
) -> Result<CreatureInnerId> {
|
|
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(super) fn find_creature_for_stat_with_negative_fit(
|
|
&self,
|
|
stat: AffName,
|
|
fit_level: &Fit,
|
|
) -> Result<CreatureInnerId> {
|
|
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(super) fn get_creature(&self, id: CreatureVecId) -> &Creature {
|
|
&self.creatures[id.id()]
|
|
}
|
|
/// Get a mutable reference to the creature by Id
|
|
pub(super) fn get_mut_creature(&mut self, id: CreatureVecId) -> &mut Creature {
|
|
&mut self.creatures[id.id()]
|
|
}
|
|
|
|
/// Get the creature name
|
|
#[allow(dead_code)]
|
|
pub(super) 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(super) 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(super) 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(super) 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(super) 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(super) fn size_unfited_loop(&self) -> usize {
|
|
self.creatures.len()
|
|
}
|
|
|
|
/// Gives the size of the loop needed to fill all characteristics
|
|
pub(super) fn size_loop(&self) -> usize {
|
|
self.creatures.len() * 2
|
|
}
|
|
|
|
/// Get the length of the affinity vector related to the given stat
|
|
pub(super) 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(super) 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(super) 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(super) fn add_config(&mut self, config: StatConfig) {
|
|
// self.config = config;
|
|
// }
|
|
|
|
/// Get the level of verbosity
|
|
pub(super) fn verbose(&self) -> bool {
|
|
self.config.verbosity
|
|
}
|
|
|
|
/// Get a reference to the active config
|
|
#[allow(dead_code)]
|
|
pub(super) fn get_config(&self) -> &StatConfig {
|
|
&self.config
|
|
}
|
|
|
|
/// Sort the underlying data
|
|
pub(super) 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(super) 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(super) 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<Vec<Creature>> for CharacCharMatrix {
|
|
impl CharacCharMatrix {
|
|
/// Create a CharacCharMatrix from a vec of creature and a config
|
|
fn from_vec(creatures: Vec<Creature>, 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<T>(filename: T, config: StatConfig) -> Result<CharacCharMatrix>
|
|
where
|
|
T: AsRef<Path>,
|
|
{
|
|
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<Creature> = rdr
|
|
.into_records()
|
|
.flat_map(|c| Creature::try_from(c.unwrap()))
|
|
.collect();
|
|
let creature_matrix = CharacCharMatrix::from_vec(creatures, config);
|
|
Ok(creature_matrix)
|
|
}
|