From 2aa56b70e4bc5339998873c1e8a5df5da16b8e67 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 9 Mar 2023 02:02:02 +0100 Subject: [PATCH] Split Python bindings and finishes coverage --- coverage/html/badges/flat.svg | 8 +- coverage/html/badges/flat_square.svg | 6 +- coverage/html/badges/for_the_badge.svg | 6 +- coverage/html/badges/plastic.svg | 8 +- coverage/html/badges/social.svg | 8 +- src/io.rs | 299 ++++--------------------- src/lib.rs | 4 +- src/python_bindings.rs | 258 ++++++++++++++++++++- 8 files changed, 316 insertions(+), 281 deletions(-) diff --git a/coverage/html/badges/flat.svg b/coverage/html/badges/flat.svg index b7c0854..a43354b 100644 --- a/coverage/html/badges/flat.svg +++ b/coverage/html/badges/flat.svg @@ -1,6 +1,6 @@ - coverage: 96% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%"> + coverage: 99% @@ -16,8 +16,8 @@ coverage - - 96% + + 99% \ No newline at end of file diff --git a/coverage/html/badges/flat_square.svg b/coverage/html/badges/flat_square.svg index a18f634..7816a7a 100644 --- a/coverage/html/badges/flat_square.svg +++ b/coverage/html/badges/flat_square.svg @@ -1,13 +1,13 @@ - coverage: 96% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%"> + coverage: 99% coverage - 96% + 99% \ No newline at end of file diff --git a/coverage/html/badges/for_the_badge.svg b/coverage/html/badges/for_the_badge.svg index 12a1eb8..a58c41d 100644 --- a/coverage/html/badges/for_the_badge.svg +++ b/coverage/html/badges/for_the_badge.svg @@ -1,13 +1,13 @@ - COVERAGE: 96% + xmlns:xlink="http://www.w3.org/1999/xlink" width="142.5" height="28" role="img" aria-label="COVERAGE: 99%"> + COVERAGE: 99% COVERAGE - 96% + 99% \ No newline at end of file diff --git a/coverage/html/badges/plastic.svg b/coverage/html/badges/plastic.svg index 2245a14..a3720ca 100644 --- a/coverage/html/badges/plastic.svg +++ b/coverage/html/badges/plastic.svg @@ -1,6 +1,6 @@ - coverage: 96% + xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="18" role="img" aria-label="coverage: 99%"> + coverage: 99% @@ -18,8 +18,8 @@ coverage - - 96% + + 99% \ No newline at end of file diff --git a/coverage/html/badges/social.svg b/coverage/html/badges/social.svg index f26a8cf..e26d0fc 100644 --- a/coverage/html/badges/social.svg +++ b/coverage/html/badges/social.svg @@ -1,6 +1,6 @@ - Coverage: 96% + xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="20" role="img" aria-label="Coverage: 99%"> + Coverage: 99% @@ -20,8 +20,8 @@ Coverage - - 96% + + 99% \ No newline at end of file diff --git a/src/io.rs b/src/io.rs index e4214b7..75817ff 100644 --- a/src/io.rs +++ b/src/io.rs @@ -1,15 +1,8 @@ //! The main IO module -//! For now it contains the python bindings, the Args bindings (for clap) and the struct +//! For now it contains the Args bindings (for clap) and the struct //! needed to hold all parameters needed at runtime -//! -//! Moving the bindings and making them non mandatory is a WIP -use crate::Craft; use clap::Parser; -use core::fmt::Display; - -// #[cfg(not(feature = "no_python"))] -use pyo3::prelude::*; /// The parameters needed at runtime, used since Args cannot easily be passed to python #[derive(Debug, Clone, Copy)] @@ -68,149 +61,6 @@ pub struct Args { pub long: bool, } -/// A final stripped down version of a craft -/// used for final print and talking with python -/// TODO: Half of these parameter are unique and SHOULD NOT be replicated on every solution -#[derive(Debug)] -#[pyclass] -pub struct SolverResult { - /// The number of steps this particular craft takes - #[pyo3(get)] - pub steps: u32, - /// The quality obtained at the end of the craft (absolute value) - #[pyo3(get)] - pub quality: u32, - /// The amount of progression obtained at the end of the craft (absolute value) - #[pyo3(get)] - pub progression: u32, - /// The remaining durability at the end of this craft - #[pyo3(get)] - pub durability: i32, - /// The remaining crafting points at the end of this craft - #[pyo3(get)] - pub cp: i32, - /// The total amount of crafting points the crafter had available (Deprecated) - #[pyo3(get)] - pub total_cp: u32, - /// The total amount of progression needed to finish the craft (Deprecated) - #[pyo3(get)] - pub total_progression: u32, - /// The total quality needed to make this craft 100% HQ (Deprecated) - #[pyo3(get)] - pub total_quality: u32, - /// The total durability for this craft (Deprecated) - #[pyo3(get)] - pub total_durability: u32, - /// The list of actions, as a string - #[pyo3(get)] - pub actions: Vec, - /// The amount of solutions found during the first step of the solving (Used for debug) (Deprecated) - #[pyo3(get)] - pub step1_solutions: usize, - /// The amount of solutions found at the end of the second step of solving (Used for debug) (Deprecated) - #[pyo3(get)] - pub step2_solutions: usize, - #[pyo3(get)] - /// Wether a 100% HQ solution was found (Deprecated) - pub found_100_percent: bool, -} - -/// Pretty display for SolverResult -impl Display for SolverResult { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - write!(f, "{:?}", self.actions) - } -} - -impl SolverResult { - /// Create a SolverResult from a solution - /// Using this returns a solution, usable by Python - pub fn from_craft( - craft: &Craft, - step1_solutions: usize, - step2_solutions: usize, - found_100_percent: bool, - ) -> SolverResult { - let mut actions = craft - .actions - .iter() - .map(|action| format!("{}", action.short_name)) - .collect::>(); - // Todo: Stop adding these by hand - let arg = (craft.recipe.progress as f32 - craft.progression as f32) - / craft.get_base_progression() as f32; - if 0.0 < arg && arg < 1.2 { - actions.push("basicSynth2".to_string()); - } - if 1.2 <= arg && arg < 1.8 { - actions.push("carefulSynthesis".to_string()); - } - if 1.8 <= arg && arg < 2.0 { - actions.push("observe".to_string()); - actions.push("focusedSynthesis".to_string()); - } - SolverResult { - steps: craft.step_count, - progression: craft.progression, - quality: craft.quality, - durability: craft.durability, - actions: actions, - step1_solutions, - step2_solutions, - found_100_percent, - total_progression: craft.recipe.progress, - total_quality: craft.recipe.quality, - total_durability: craft.recipe.durability, - cp: craft.cp, - total_cp: craft.stats.max_cp, - } - } -} - -#[pymethods] -impl SolverResult { - /// Default method to create an empty solution, only used for debug purposes - /// to test wether the import worked - /// ```py - /// import xiv_csolver_lib - /// print(xiv_csolver_lib.default()) - /// ``` - #[staticmethod] - pub fn default() -> Self { - Self { - steps: 0, - progression: 0, - quality: 0, - durability: 0, - total_progression: 0, - total_quality: 0, - total_durability: 0, - actions: vec!["Act1".to_string(), "Act2".to_string()], - step1_solutions: 0, - step2_solutions: 0, - found_100_percent: false, - cp: 0, - total_cp: 0, - } - } - - /// Implement a pretty_print method - /// Mainly used for debug purposes - pub fn pretty_print(&self) { - println!( - "Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}", - self.quality, - self.total_quality, - self.durability, - self.total_durability, - self.cp, - self.total_cp, - self.steps - ); - println!("{:?}", self.actions); - } -} - impl Parameters { /// Create parameters from the arguments parsed by clap pub fn from_args(args: &Args) -> Self { @@ -224,116 +74,10 @@ impl Parameters { } } -////// Python Bindings ////// - -/// A Python module implemented in Rust. -#[cfg(not(feature = "no_python"))] -#[pymodule] -fn xiv_csolver_lib(_py: Python, m: &PyModule) -> PyResult<()> { - m.add_function(wrap_pyfunction!(test_result, m)?)?; - m.add_function(wrap_pyfunction!(solve_from_python, m)?)?; - Ok(()) -} - -/// A test result, useful for debugging, all values are set to zero as per the -/// [`default`](crate::io::SolverResult::default) -/// ``` -/// # use xiv_csolver_lib::io::SolverResult; -/// SolverResult { -/// steps: 0, -/// progression: 0, -/// quality: 0, -/// durability: 0, -/// total_progression: 0, -/// total_quality: 0, -/// total_durability: 0, -/// actions: vec!["Act1".to_string(), "Act2".to_string()], -/// step1_solutions: 0, -/// step2_solutions: 0, -/// found_100_percent: false, -/// cp: 0, -/// total_cp: 0, -/// }; -/// ``` -#[cfg(not(feature = "no_python"))] -#[pyfunction] -pub fn test_result() -> SolverResult { - SolverResult::default() -} - -/// Create a stat struct stats with the base values -#[cfg(not(feature = "no_python"))] -use crate::{solve_craft, Recipe, Stats}; - -/// Solve a craft from parameters given by python -/// The values are all obtained by a `&PyAny`, wich must guaranty that several attributes are -/// accesible by `__getattr__` -/// -/// ```python -/// import xiv_craft_solver, rich -/// -/// class FeedingClass: -/// durability = 70 -/// progress = 3900 -/// quality = 10920 -/// progress_divider = 130 -/// quality_divider = 115 -/// progress_modifier = 80 -/// quality_modifier = 70 -/// craftsmanship = 4041 -/// control = 3959 -/// max_cp = 602 -/// # Config -/// depth = 10 -/// byregot_step = 10 -/// desperate = False -/// threads = 8 -/// verbose = 0 -/// crafting_feeder = FeedingClass() -/// rich.inspect(xiv_csolver_lib.solve_from_python(crafting_feeder)) -/// ``` - -#[cfg(not(feature = "no_python"))] -#[pyfunction] -pub fn solve_from_python(py: Python<'_>, values: &PyAny) -> PyResult>> { - // Create Recipe - let recipe = Recipe { - durability: values.getattr("durability")?.extract()?, - progress: values.getattr("progress")?.extract()?, - progress_divider: values.getattr("progress_divider")?.extract()?, - progress_modifier: values.getattr("progress_modifier")?.extract()?, - quality: values.getattr("quality")?.extract()?, - quality_divider: values.getattr("quality_divider")?.extract()?, - quality_modifier: values.getattr("quality_modifier")?.extract()?, - }; - - // Create Stats - let stats = Stats { - craftsmanship: values.getattr("craftsmanship")?.extract()?, - control: values.getattr("control")?.extract()?, - max_cp: values.getattr("max_cp")?.extract()?, - }; - - // Create parameters - let param = Parameters { - depth: values.getattr("depth")?.extract()?, - byregot_step: values.getattr("byregot_step")?.extract()?, - desperate: values.getattr("desperate")?.extract()?, - threads: values.getattr("threads")?.extract()?, - verbose: values.getattr("verbose")?.extract()?, - }; - - // println!("{:?} len: {:?} ",values,values.getattr("len()")); - py.allow_threads(move || { - let res = solve_craft(recipe, stats, param); - Ok(res) - }) -} - #[cfg(test)] mod tests { - use crate::io::Args; - use crate::{Parameters, SolverResult}; + use crate::io::{Args, Parameters}; + use crate::python_bindings::SolverResult; use clap::Parser; use pretty_assertions::{assert_eq, assert_ne}; @@ -391,7 +135,7 @@ mod tests { let a2 = a.clone(); println!("{:?}", a2); // Test Custom recipe - let a3 = Args::parse_from([ + let a3 = crate::io::Args::parse_from([ "ultraman", "-r", "recipe", @@ -431,5 +175,38 @@ mod tests { } #[test] - pub fn test_parameters() {} + pub fn test_parameters() { + // Test a random config + let ar = Args::parse_from([ + "ultraman", + "-r", + "recipe", + "-c", + "dan", + "-f", + "bigfile.toml", + "-d", + "45", + "-t", + "4", + "-D", + "-l", + "-vvv", + ]); + let p = Parameters::from_args(&ar); + assert_eq!(p.depth, 11); + assert_eq!(p.verbose, 3); + assert_eq!(p.threads, 4); + assert_eq!(p.desperate, true); + assert_eq!(p.byregot_step, 6); + + // Test defaults + let ar = Args::parse_from(&["a"]); + let p = Parameters::from_args(&ar); + assert_eq!(p.depth, 8); + assert_eq!(p.verbose, 0); + assert_eq!(p.threads, 4); + assert_eq!(p.desperate, false); + assert_eq!(p.byregot_step, 8); + } } diff --git a/src/lib.rs b/src/lib.rs index ec165d2..57b51b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,7 +97,8 @@ #![warn(missing_docs)] use crate::craft::Craft; -use crate::io::{Parameters, SolverResult}; +use crate::io::Parameters; +use crate::python_bindings::SolverResult; use crate::specs::{Recipe, Stats}; use std::sync::{Arc, Mutex}; use threadpool::ThreadPool; @@ -105,6 +106,7 @@ use threadpool::ThreadPool; pub mod action; pub mod craft; pub mod io; +pub mod python_bindings; mod solver; pub mod specs; diff --git a/src/python_bindings.rs b/src/python_bindings.rs index 44e2247..d8bc847 100644 --- a/src/python_bindings.rs +++ b/src/python_bindings.rs @@ -1,4 +1,260 @@ -#[cfg(not(feature="no_python"))] +//! The binding module +//! It contains the python bindings, and the structs +//! needed to hold all parameters needed at runtime +//! +//! Making the bindings a build feature is a WIP + +use crate::Craft; +#[cfg(not(feature = "no_python"))] +use crate::Parameters; +use core::fmt::Display; use pyo3::prelude::*; +/// A final stripped down version of a craft +/// used for final print and talking with python +/// TODO: Half of these parameter are unique and SHOULD NOT be replicated on every solution +#[derive(Debug)] +#[pyclass] +pub struct SolverResult { + /// The number of steps this particular craft takes + #[pyo3(get)] + pub steps: u32, + /// The quality obtained at the end of the craft (absolute value) + #[pyo3(get)] + pub quality: u32, + /// The amount of progression obtained at the end of the craft (absolute value) + #[pyo3(get)] + pub progression: u32, + /// The remaining durability at the end of this craft + #[pyo3(get)] + pub durability: i32, + /// The remaining crafting points at the end of this craft + #[pyo3(get)] + pub cp: i32, + /// The total amount of crafting points the crafter had available (Deprecated) + #[pyo3(get)] + pub total_cp: u32, + /// The total amount of progression needed to finish the craft (Deprecated) + #[pyo3(get)] + pub total_progression: u32, + /// The total quality needed to make this craft 100% HQ (Deprecated) + #[pyo3(get)] + pub total_quality: u32, + /// The total durability for this craft (Deprecated) + #[pyo3(get)] + pub total_durability: u32, + /// The list of actions, as a string + #[pyo3(get)] + pub actions: Vec, + /// The amount of solutions found during the first step of the solving (Used for debug) (Deprecated) + #[pyo3(get)] + pub step1_solutions: usize, + /// The amount of solutions found at the end of the second step of solving (Used for debug) (Deprecated) + #[pyo3(get)] + pub step2_solutions: usize, + #[pyo3(get)] + /// Wether a 100% HQ solution was found (Deprecated) + pub found_100_percent: bool, +} +/// Pretty display for SolverResult +impl Display for SolverResult { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + write!(f, "{:?}", self.actions) + } +} + +impl SolverResult { + /// Create a SolverResult from a solution + /// Using this returns a solution, usable by Python + pub fn from_craft( + craft: &Craft, + step1_solutions: usize, + step2_solutions: usize, + found_100_percent: bool, + ) -> SolverResult { + let mut actions = craft + .actions + .iter() + .map(|action| format!("{}", action.short_name)) + .collect::>(); + // Todo: Stop adding these by hand + let arg = (craft.recipe.progress as f32 - craft.progression as f32) + / craft.get_base_progression() as f32; + if 0.0 < arg && arg < 1.2 { + actions.push("basicSynth2".to_string()); + } + if 1.2 <= arg && arg < 1.8 { + actions.push("carefulSynthesis".to_string()); + } + if 1.8 <= arg && arg < 2.0 { + actions.push("observe".to_string()); + actions.push("focusedSynthesis".to_string()); + } + SolverResult { + steps: craft.step_count, + progression: craft.progression, + quality: craft.quality, + durability: craft.durability, + actions: actions, + step1_solutions, + step2_solutions, + found_100_percent, + total_progression: craft.recipe.progress, + total_quality: craft.recipe.quality, + total_durability: craft.recipe.durability, + cp: craft.cp, + total_cp: craft.stats.max_cp, + } + } +} + +#[pymethods] +impl SolverResult { + /// Default method to create an empty solution, only used for debug purposes + /// to test wether the import worked + /// ```py + /// import xiv_csolver_lib + /// print(xiv_csolver_lib.default()) + /// ``` + #[staticmethod] + pub fn default() -> Self { + Self { + steps: 0, + progression: 0, + quality: 0, + durability: 0, + total_progression: 0, + total_quality: 0, + total_durability: 0, + actions: vec!["Act1".to_string(), "Act2".to_string()], + step1_solutions: 0, + step2_solutions: 0, + found_100_percent: false, + cp: 0, + total_cp: 0, + } + } + + /// Implement a pretty_print method + /// Mainly used for debug purposes + pub fn pretty_print(&self) { + println!( + "Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}", + self.quality, + self.total_quality, + self.durability, + self.total_durability, + self.cp, + self.total_cp, + self.steps + ); + println!("{:?}", self.actions); + } +} + +////// Python Bindings ////// + +/// A Python module implemented in Rust. +#[cfg(not(feature = "no_python"))] +#[pymodule] +fn xiv_csolver_lib(_py: Python, m: &PyModule) -> PyResult<()> { + m.add_function(wrap_pyfunction!(test_result, m)?)?; + m.add_function(wrap_pyfunction!(solve_from_python, m)?)?; + Ok(()) +} + +/// A test result, useful for debugging, all values are set to zero as per the +/// [`default`](crate::io::SolverResult::default) +/// ``` +/// # use xiv_csolver_lib::python_bindings::SolverResult; +/// SolverResult { +/// steps: 0, +/// progression: 0, +/// quality: 0, +/// durability: 0, +/// total_progression: 0, +/// total_quality: 0, +/// total_durability: 0, +/// actions: vec!["Act1".to_string(), "Act2".to_string()], +/// step1_solutions: 0, +/// step2_solutions: 0, +/// found_100_percent: false, +/// cp: 0, +/// total_cp: 0, +/// }; +/// ``` +#[cfg(not(feature = "no_python"))] +#[pyfunction] +pub fn test_result() -> SolverResult { + SolverResult::default() +} + +/// Create a stat struct stats with the base values +#[cfg(not(feature = "no_python"))] +use crate::{solve_craft, Recipe, Stats}; + +/// Solve a craft from parameters given by python +/// The values are all obtained by a `&PyAny`, wich must guaranty that several attributes are +/// accesible by `__getattr__` +/// +/// ```python +/// import xiv_craft_solver, rich +/// +/// class FeedingClass: +/// durability = 70 +/// progress = 3900 +/// quality = 10920 +/// progress_divider = 130 +/// quality_divider = 115 +/// progress_modifier = 80 +/// quality_modifier = 70 +/// craftsmanship = 4041 +/// control = 3959 +/// max_cp = 602 +/// # Config +/// depth = 10 +/// byregot_step = 10 +/// desperate = False +/// threads = 8 +/// verbose = 0 +/// crafting_feeder = FeedingClass() +/// rich.inspect(xiv_csolver_lib.solve_from_python(crafting_feeder)) +/// ``` + +#[cfg(not(feature = "no_python"))] +#[pyfunction] +pub fn solve_from_python(py: Python<'_>, values: &PyAny) -> PyResult>> { + // Create Recipe + let recipe = Recipe { + durability: values.getattr("durability")?.extract()?, + progress: values.getattr("progress")?.extract()?, + progress_divider: values.getattr("progress_divider")?.extract()?, + progress_modifier: values.getattr("progress_modifier")?.extract()?, + quality: values.getattr("quality")?.extract()?, + quality_divider: values.getattr("quality_divider")?.extract()?, + quality_modifier: values.getattr("quality_modifier")?.extract()?, + }; + + // Create Stats + let stats = Stats { + craftsmanship: values.getattr("craftsmanship")?.extract()?, + control: values.getattr("control")?.extract()?, + max_cp: values.getattr("max_cp")?.extract()?, + }; + + // Create parameters + let param = Parameters { + depth: values.getattr("depth")?.extract()?, + byregot_step: values.getattr("byregot_step")?.extract()?, + desperate: values.getattr("desperate")?.extract()?, + threads: values.getattr("threads")?.extract()?, + verbose: values.getattr("verbose")?.extract()?, + }; + + // println!("{:?} len: {:?} ",values,values.getattr("len()")); + py.allow_threads(move || { + let res = solve_craft(recipe, stats, param); + Ok(res) + }) +}