Finishes coverge and changes the args as a single entity not a repeated struct #30

Merged
Dandaedre merged 4 commits from dan-cov into develop 2023-03-09 04:29:12 +01:00
12 changed files with 619 additions and 335 deletions

View File

@ -30,8 +30,9 @@ ignore_errors = true
script = [
"mkdir -p coverage",
"mkdir -p coverage/html",
"mkdir -p coverage/",
"CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off' LLVM_PROFILE_FILE='llvm/cargo-test-%p-%m.profraw' cargo test",
"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' -o coverage/html/"
"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*xiv_csolver.rs' --ignore '*python*.rs' -o coverage/html/",
]
[tasks.clean]

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 77%">
<title>coverage: 77%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%">
<title>coverage: 99%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@ -10,14 +10,14 @@
</clipPath>
<g clip-path="url(#r)">
<rect width="61" height="20" fill="#555"/>
<rect x="61" width="35" height="20" fill="#dfb317"/>
<rect x="61" width="35" height="20" fill="#97ca00"/>
<rect width="96" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
<text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">77%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">77%</text>
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">99%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1,13 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 77%">
<title>coverage: 77%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%">
<title>coverage: 99%</title>
<g shape-rendering="crispEdges">
<rect width="61" height="20" fill="#555"/>
<rect x="61" width="35" height="20" fill="#dfb317"/>
<rect x="61" width="35" height="20" fill="#97ca00"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">77%</text>
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 712 B

After

Width:  |  Height:  |  Size: 712 B

View File

@ -1,13 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="142.5" height="28" role="img" aria-label="COVERAGE: 77%">
<title>COVERAGE: 77%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="142.5" height="28" role="img" aria-label="COVERAGE: 99%">
<title>COVERAGE: 99%</title>
<g shape-rendering="crispEdges">
<rect width="91" height="28" fill="#555"/>
<rect x="91" width="51.5" height="28" fill="#dfb317"/>
<rect x="91" width="51.5" height="28" fill="#97ca00"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="100">
<text fill="#fff" x="455" y="175" transform="scale(.1)" textLength="670">COVERAGE</text>
<text fill="#fff" x="1167.5" y="175" font-weight="bold" transform="scale(.1)" textLength="275">77%</text>
<text fill="#fff" x="1167.5" y="175" font-weight="bold" transform="scale(.1)" textLength="275">99%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 739 B

After

Width:  |  Height:  |  Size: 739 B

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="18" role="img" aria-label="coverage: 77%">
<title>coverage: 77%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="18" role="img" aria-label="coverage: 99%">
<title>coverage: 99%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
@ -12,14 +12,14 @@
</clipPath>
<g clip-path="url(#r)">
<rect width="61" height="18" fill="#555"/>
<rect x="61" width="35" height="18" fill="#dfb317"/>
<rect x="61" width="35" height="18" fill="#97ca00"/>
<rect width="96" height="18" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
<text aria-hidden="true" x="315" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
<text x="315" y="130" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
<text aria-hidden="true" x="775" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">77%</text>
<text x="775" y="130" transform="scale(.1)" fill="#fff" textLength="250">77%</text>
<text aria-hidden="true" x="775" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">99%</text>
<text x="775" y="130" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="20" role="img" aria-label="Coverage: 77%">
<title>Coverage: 77%</title>
xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="20" role="img" aria-label="Coverage: 99%">
<title>Coverage: 99%</title>
<style>a:hover #llink{fill:url(#b);stroke:#ccc}a:hover #rlink{fill:#4183c4}</style>
<linearGradient id="a" x2="0" y2="100%">
<stop offset="0" stop-color="#fcfcfc" stop-opacity="0"/>
@ -20,8 +20,8 @@
<rect id="llink" stroke="#d5d5d5" fill="url(#a)" x=".5" y=".5" width="61" height="19" rx="2"/>
<text aria-hidden="true" x="305" y="150" fill="#fff" transform="scale(.1)" textLength="510">Coverage</text>
<text x="305" y="140" transform="scale(.1)" textLength="510">Coverage</text>
<text aria-hidden="true" x="825" y="150" fill="#fff" transform="scale(.1)" textLength="230">77%</text>
<text id="rlink" x="825" y="140" transform="scale(.1)" textLength="230">77%</text>
<text aria-hidden="true" x="825" y="150" fill="#fff" transform="scale(.1)" textLength="230">99%</text>
<text id="rlink" x="825" y="140" transform="scale(.1)" textLength="230">99%</text>
</g>
<script xmlns=""/>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -2,9 +2,9 @@ import xiv_csolver_lib
import rich
rich.inspect(xiv_csolver_lib)
rich.inspect(xiv_csolver_lib.test_result)
rich.inspect(xiv_csolver_lib.test_result())
rich.inspect(xiv_csolver_lib.test_result())
rich.inspect(xiv_csolver_lib.test_info())
rich.inspect(xiv_csolver_lib.test_final_results())
class FeedMeDaddy:

View File

@ -116,6 +116,7 @@ class Solver:
self.loggers = loggers
self.solutions = []
self.info = None
self.best_quality = None
self.least_steps = None
self.safe_50 = None
@ -124,7 +125,7 @@ class Solver:
self.compute_all()
def solve(self) -> str:
self.solutions = xcs.solve_from_python(self)
self.solutions,self.info = xcs.solve_from_python(self)
return self.solutions
def compute_all(self) -> True:

View File

@ -131,26 +131,26 @@ fn main() {
Some(ref res) => {
// Show best results
if args.verbose > 0 {
println!("[Final] {} results were found:", res.len());
println!("[Final] {} results were found:", res.0.len());
#[cfg(feature = "verbose")]
if args.verbose > 1 {
xiv_csolver_lib::print_routes(&results);
}
}
println!("\n > SOLUTION [Least steps] <");
xiv_csolver_lib::find_fast_route(&res)
.unwrap()
.pretty_print();
println!("\n > SOLUTION [Most durability] <");
xiv_csolver_lib::find_safe_route(&res)
.unwrap()
.pretty_print();
println!("\n > SOLUTION [Most quality] < ");
xiv_csolver_lib::find_quality_route(&res)
.unwrap()
.pretty_print();
}
}
println!("\n > SOLUTION [Least steps] <");
xiv_csolver_lib::find_fast_route(&results)
.unwrap()
.pretty_print();
println!("\n > SOLUTION [Most durability] <");
xiv_csolver_lib::find_safe_route(&results)
.unwrap()
.pretty_print();
println!("\n > SOLUTION [Most quality] < ");
xiv_csolver_lib::find_quality_route(&results)
.unwrap()
.pretty_print();
// #[cfg(feature = "verbose")]
// if params.verbose>2{

302
src/io.rs
View File

@ -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<String>,
/// 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::<Vec<String>>();
// 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<Option<Vec<SolverResult>>> {
// 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};
@ -372,7 +116,8 @@ mod tests {
#[test]
pub fn test_debug() {
let def = SolverResult::default();
assert_eq!(format!("{:?}", def),"SolverResult { steps: 0, quality: 0, progression: 0, durability: 0, cp: 0, total_cp: 0, total_progression: 0, total_quality: 0, total_durability: 0, actions: [\"Act1\", \"Act2\"], step1_solutions: 0, step2_solutions: 0, found_100_percent: false }");
assert_eq!(format!("{:?}", def),"SolverResult { steps: 0, quality: 0, progression: 0, durability: 0, cp: 0, total_cp: 0, total_progression: 0, total_quality: 0, total_durability: 0, actions: [\"Act1\", \"Act2\"] }");
//, step1_solutions: 0, step2_solutions: 0, found_100_percent: false }
}
#[test]
@ -391,7 +136,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 +176,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);
}
}

View File

@ -97,7 +97,8 @@
#![warn(missing_docs)]
use crate::craft::Craft;
use crate::io::{Parameters, SolverResult};
use crate::io::Parameters;
use crate::python_bindings::{Info, 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;
@ -113,7 +115,7 @@ pub fn solve_craft<'a>(
recipe: Recipe,
stats: Stats,
params: Parameters,
) -> Option<Vec<SolverResult>> {
) -> Option<(Vec<SolverResult>, Info)> {
// Load the craft with given arguments
let craft = Craft::new(recipe, stats, params);
@ -148,7 +150,7 @@ pub fn solve_craft<'a>(
}
}
// Core algorithm, fill all found routes with the best route (doesn't branch, just replace)
// Core algorithm, fill all found routes with the best route
let arc_phase2_routes = Arc::new(Mutex::new(Vec::<Craft>::new()));
for route in phase1_routes {
@ -194,17 +196,17 @@ pub fn solve_craft<'a>(
for route in phase2_routes.iter() {
if route.quality >= route.recipe.quality {
// valid_routes.push(route.clone());
valid_solutions.push(SolverResult::from_craft(route, nb_p1, nb_p2, true));
valid_solutions.push(SolverResult::from_craft(route)); //nb_p1, nb_p2, true
}
}
// If no craft can make it to 100% HQ, fallback to base results
if valid_solutions.len() == 0 {
for route in phase2_routes.iter() {
valid_solutions.push(SolverResult::from_craft(route, nb_p1, nb_p2, false));
valid_solutions.push(SolverResult::from_craft(route));
}
}
Some(valid_solutions)
Some((valid_solutions, Info::new(nb_p1, nb_p2, true)))
}
/// Load the config from args and make a craft from it
@ -321,9 +323,9 @@ pub fn load_from_config<'a>(
}
/// Print all routes in the vect, verbose
pub fn print_routes<'a>(routes: &Option<Vec<SolverResult>>) {
pub fn print_routes<'a>(routes: &Option<(Vec<SolverResult>, Info)>) {
match routes {
Some(r) => {
Some((r, _)) => {
println!("Showing {} routes", r.len());
for c in r.iter() {
println!(
@ -337,37 +339,206 @@ pub fn print_routes<'a>(routes: &Option<Vec<SolverResult>>) {
}
/// Find the route with the least amount of steps
pub fn find_fast_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
match routes {
Some(_routes) => {
if _routes.len() > 0 {
_routes.iter().min_by_key(|key| key.steps)
} else {
None
}
}
None => None,
pub fn find_fast_route<'a>(routes: &'a (Vec<SolverResult>, Info)) -> Option<&'a SolverResult> {
let (_routes, _info) = routes;
if _routes.len() > 0 {
_routes.iter().min_by_key(|key| key.steps)
} else {
None
}
}
/// Find the route with the maximum amount of quality
pub fn find_quality_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
match routes {
Some(_routes) => _routes.iter().max_by_key(|key| key.quality),
None => None,
}
pub fn find_quality_route<'a>(routes: &'a (Vec<SolverResult>, Info)) -> Option<&'a SolverResult> {
let (_routes, _info) = routes;
_routes.iter().max_by_key(|key| key.quality)
}
/// Find the route with the maximum of durability left
pub fn find_safe_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
match routes {
Some(_routes) => {
if _routes.len() > 0 {
_routes.iter().max_by_key(|key| key.durability)
} else {
None
}
}
None => None,
pub fn find_safe_route(routes: &(Vec<SolverResult>, Info)) -> Option<&SolverResult> {
let (_routes, _info) = routes;
if _routes.len() > 0 {
_routes.iter().max_by_key(|key| key.durability)
} else {
None
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn test_lib_find_route() {
// Supposed to find a route for the base craft
let mut craft = crate::craft::Craft::two_star();
let res = solve_craft(craft.recipe, craft.stats, craft.args);
assert!(res.unwrap().0.len() > 2000);
craft.recipe.progress = 0;
let res = solve_craft(craft.recipe, craft.stats, craft.args);
println!("{:?}", res);
assert!(res.is_none());
craft.recipe.progress = 100;
craft.stats.max_cp = 0;
craft.cp = 0;
let mut res = solve_craft(craft.recipe, craft.stats, craft.args).unwrap();
println!("{:?}", res);
assert_eq!(res.0.len(), 1);
assert_eq!(res.0.pop().unwrap().actions, vec!("basicSynth2"));
}
#[test]
pub fn test_lib_print_route() {
let craft = crate::craft::Craft::two_star();
print_routes(&solve_craft(craft.recipe, craft.stats, craft.args));
print_routes(&None);
}
#[test]
pub fn test_lib_best_solutions() {
let craft = crate::craft::Craft::two_star();
let routes = solve_craft(craft.recipe, craft.stats, craft.args).unwrap();
// assert!(find_fast_route(&(None)).is_none());
// assert!(find_quality_route(&None).is_none());
// assert!(find_safe_route(&None).is_none());
assert!(find_fast_route(&((vec![], Info::default()))).is_none());
assert!(find_quality_route(&((vec![], Info::default()))).is_none());
assert!(find_safe_route(&((vec![], Info::default()))).is_none());
let sol = find_fast_route(&routes).unwrap();
assert_eq!(sol.steps, 17);
assert_eq!(sol.quality, 11129);
assert_eq!(sol.progression, 3750);
assert_eq!(sol.durability, 0);
assert_eq!(sol.cp, 7);
assert_eq!(routes.1.step1_solutions, 9);
assert_eq!(routes.1.step2_solutions, 21193);
assert_eq!(routes.1.found_100_percent, true);
assert_eq!(
sol.actions,
vec!(
"muscleMemory",
"manipulation",
"veneration",
"wasteNot2",
"groundwork",
"delicateSynthesis",
"delicateSynthesis",
"innovation",
"preparatoryTouch",
"preparatoryTouch",
"preparatoryTouch",
"preparatoryTouch",
"innovation",
"basicTouch",
"standardTouch",
"greatStrides",
"byregotsBlessing",
"basicSynth2"
)
);
let sol = find_quality_route(&routes).unwrap();
assert_eq!(sol.steps, 23);
assert_eq!(sol.quality, 12032);
assert_eq!(sol.progression, 3675);
assert_eq!(sol.durability, -5);
assert_eq!(sol.cp, 3);
assert_eq!(routes.1.step1_solutions, 9);
assert_eq!(routes.1.step2_solutions, 21193);
assert_eq!(routes.1.found_100_percent, true);
assert_eq!(
sol.actions,
vec!(
"muscleMemory",
"manipulation",
"veneration",
"groundwork",
"prudentSynthesis",
"innovation",
"prudentTouch",
"basicTouch",
"standardTouch",
"advancedTouch",
"manipulation",
"innovation",
"prudentTouch",
"basicTouch",
"standardTouch",
"advancedTouch",
"innovation",
"basicTouch",
"standardTouch",
"advancedTouch",
"greatStrides",
"innovation",
"byregotsBlessing",
"basicSynth2"
)
);
let sol = find_safe_route(&routes).unwrap();
assert_eq!(sol.steps, 22);
assert_eq!(sol.quality, 11161);
assert_eq!(sol.progression, 3675);
assert_eq!(sol.durability, 10);
assert_eq!(sol.cp, 4);
assert_eq!(routes.1.step1_solutions, 9);
assert_eq!(routes.1.step2_solutions, 21193);
assert_eq!(routes.1.found_100_percent, true);
assert_eq!(
sol.actions,
vec!(
"muscleMemory",
"manipulation",
"veneration",
"groundwork",
"carefulSynthesis",
"prudentTouch",
"innovation",
"prudentTouch",
"prudentTouch",
"prudentTouch",
"prudentTouch",
"manipulation",
"innovation",
"prudentTouch",
"basicTouch",
"standardTouch",
"advancedTouch",
"innovation",
"basicTouch",
"standardTouch",
"greatStrides",
"byregotsBlessing",
"basicSynth2"
)
);
}
#[test]
pub fn test_load_from_config() {
load_from_config("default_recipe", "craft.toml", "default_character");
}
#[should_panic]
#[test]
pub fn test_bad_config_filename() {
load_from_config("default_recipe", "nocrafto.toml", "default_character");
}
#[should_panic]
#[test]
pub fn test_bad_config_recipename() {
load_from_config("bad_recipe", "craft.toml", "default_character");
}
#[should_panic]
#[test]
pub fn test_bad_config_charname() {
load_from_config("default_recipe", "craft.toml", "bad_character");
}
}

View File

@ -1,4 +1,337 @@
#[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
#[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<String>,
// /// 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,
}
/// Global info on the execution
#[derive(Debug)]
#[pyclass]
pub struct Info {
/// 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,
}
/// Solution information, contains information about the execution
impl Info {
/// Make a new information struct
pub fn new(
step1_solutions: usize,
step2_solutions: usize,
found_100_percent: bool,
// params: &'Parameters
) -> Self {
Self {
step1_solutions,
step2_solutions,
found_100_percent,
}
}
/// Default value of the info, only used for debug purposes
pub fn default() -> Self {
Self {
step1_solutions: 0,
step2_solutions: 0,
found_100_percent: false,
}
}
}
/// 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) -> SolverResult {
let mut actions = craft
.actions
.iter()
.map(|action| format!("{}", action.short_name))
.collect::<Vec<String>>();
// 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,
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()],
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!(test_final_results, m)?)?;
m.add_function(wrap_pyfunction!(test_info, 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::python_bindings::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()],
/// cp: 0,
/// total_cp: 0,
/// };
/// ```
#[cfg(not(feature = "no_python"))]
#[pyfunction]
pub fn test_result() -> SolverResult {
SolverResult::default()
}
/// A test info, useful for debugging, all values are set to zero as per the
/// [`default`](crate::python_bindings::Info::default())
/// ```
/// # use xiv_csolver_lib::python_bindings::Info;
/// Info {
/// step1_solutions: 0,
/// step2_solutions: 0,
/// found_100_percent: false,
/// };
/// ```
#[cfg(not(feature = "no_python"))]
#[pyfunction]
pub fn test_info() -> Info {
Info::default()
}
/// A test result array, useful for debugging, all values are set to zero as per the
/// [`default`](crate::python_bindings::Info::default())
/// ```
/// # use xiv_csolver_lib::python_bindings::{Info};
/// # use xiv_csolver_lib::python_bindings::SolverResult;
/// (
/// vec![SolverResult::default(), SolverResult::default()],
/// Info::default(),
/// );
/// ```
#[cfg(not(feature = "no_python"))]
#[pyfunction]
pub fn test_final_results() -> (Vec<SolverResult>, Info) {
(
vec![SolverResult::default(), SolverResult::default()],
Info::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<Option<(Vec<SolverResult>, Info)>> {
// 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 test {
use crate::python_bindings::{test_final_results, test_info, test_result};
#[test]
pub fn test_function_call() {
test_final_results();
test_info();
test_result();
}
}