Improvement(Bindings) - Adds more python binding and refactor code

This commit is contained in:
Dandaedre 2023-02-20 23:45:01 +01:00
parent 8fc83e2f2f
commit b564cd094c
5 changed files with 186 additions and 84 deletions

View File

@ -17,6 +17,9 @@ threadpool = "1.8.1"
# For python bindings TODO: make it optionnal
pyo3 = { version = "0.18.0", features = ["extension-module"] }
# [target.'cfg(not(no_python))'.dependencies]
# pyo3 = { version = "0.18.0", features = ["extension-module"] }
# [build]
# target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"]
@ -24,11 +27,11 @@ pyo3 = { version = "0.18.0", features = ["extension-module"] }
panic = 'abort'
opt-level = 3
lto = true
vere0 = false
[features]
default = []
verbose = []
no_python = []
[lib]
name = "xiv_craft_solver"

7
python3.py Normal file
View File

@ -0,0 +1,7 @@
import xiv_craft_solver
import rich
rich.inspect(xiv_craft_solver)
rich.inspect(xiv_craft_solver.pouet)
rich.inspect(xiv_craft_solver.pouet())
rich.inspect(xiv_craft_solver.pouet())

View File

@ -1,4 +1,6 @@
// #![warn(missing_docs,unsafe_code,unstable_features,)]
use xiv_craft_solver::print_routes;
use std::time::{Instant};
use clap::Parser;
use xiv_craft_solver;
@ -6,15 +8,26 @@ use xiv_craft_solver;
struct CustomError(String);
fn main() {
let args = xiv_craft_solver::Args::parse();
let params = xiv_craft_solver::Parameters{
let args = xiv_craft_solver::io::Args::parse();
let params = xiv_craft_solver::io::Parameters{
depth: args.depth,
threads: args.threads,
verbose: args.verbose,
};
// Start timer
let now = Instant::now();
// Solve from config
let (recipe,stats) = xiv_craft_solver::load_from_config(&args.recipe_name, &args.file_name, &args.character_name);
xiv_craft_solver::solve_craft(recipe,stats,params);
let results = xiv_craft_solver::solve_craft(recipe,stats,params);
// Show results
let t_final = now.elapsed().as_millis();
print_routes(results);
// Wait for user input
println!("\nProgram finished successfully in {}ms\nPress enter to exit...", t_final);
let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap();
()
}

120
src/io.rs Normal file
View File

@ -0,0 +1,120 @@
use crate::Craft;
use core::fmt::Display;
use clap::Parser;
#[cfg(not(feature="no_python"))]
use pyo3::prelude::*;
#[derive(Debug, Clone, Copy)]
pub struct Parameters {
pub threads: usize,
pub verbose: u8,
pub depth: u32,
}
#[derive(Parser, Debug, Clone)]
#[command(author, version, about, long_about = None)]
pub struct Args {
/// Name of the receipe
#[arg(short, long, default_value_t = String::from("default_recipe"))]
pub recipe_name: String,
/// Name of the character
#[arg(short, long, default_value_t = String::from("default_character"))]
pub character_name: String,
/// The ml file name
#[arg(short, long, default_value_t = String::from("craft.toml"))]
pub file_name: String,
/// The verbose flag
#[arg(short, long, action = clap::ArgAction::Count)]
pub verbose: u8,
/// The depth of the first pass
#[arg(short, long, default_value_t = 8)]
pub depth: u32,
/// Thread counts, default is 4 (can you even run ff with less ?)
#[arg(short, long, default_value_t = 4)]
pub threads: usize,
}
/// A final stripped down version of a craft
/// used for final print and talking with python
#[derive(Debug)]
#[pyclass]
pub struct SolverResult{
#[pyo3(get)]
pub steps: u32,
#[pyo3(get)]
pub quality: u32,
#[pyo3(get)]
pub progression: u32,
#[pyo3(get)]
pub durability: i32,
#[pyo3(get)]
pub actions: Vec<String>,
#[pyo3(get)]
pub step1_solutions: u32,
#[pyo3(get)]
pub step2_solutions: u32,
}
#[pyfunction]
pub fn pouet()-> SolverResult {
// return "pouet";
SolverResult{
steps:0,
progression: 0,
quality:0,
durability:0,
actions:vec!["BLLLL".to_string(),"WWWWW".to_string()],
step1_solutions:0,
step2_solutions:0,
}
}
/// Pretty display for SolverResult
impl Display for SolverResult{
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
println!("{:?}",self.actions);
Ok(())
}
}
impl SolverResult{
pub fn from_craft(&self,craft: & Craft)->SolverResult{
// Todo: recreate actions
// Where steps ?
SolverResult{
steps:craft.step_count,
progression: craft.progression,
quality:craft.quality,
durability:craft.durability,
actions:vec!["BLLLL".to_string(),"WWWWW".to_string()],
step1_solutions:0,
step2_solutions:0,
}
}
}
/// Python Bindings
/// A Python module implemented in Rust.
#[cfg(not(feature="no_python"))]
#[pymodule]
fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(pouet, m)?)?;
Ok(())
}
pub fn e(){
}

View File

@ -1,72 +1,34 @@
use crate::{
craft::Craft,
specs::{Recipe,Stats},
io::Parameters,
};
use std::time::{Instant};
use threadpool::ThreadPool;
use std::sync::{Arc,Mutex};
use clap::Parser;
use pyo3::prelude::*;
mod solver;
mod specs;
pub mod action;
pub mod craft;
pub mod io;
#[derive(Debug, Clone, Copy)]
pub struct Parameters {
pub threads: usize,
pub verbose: u8,
pub depth: u32,
}
#[derive(Parser, Debug, Clone)]
#[command(author, version, about, long_about = None)]
pub struct Args {
/// Name of the receipe
#[arg(short, long, default_value_t = String::from("default_recipe"))]
pub recipe_name: String,
/// Create stats
/// Name of the character
#[arg(short, long, default_value_t = String::from("default_character"))]
pub character_name: String,
/// Create recipe
/// The ml file name
#[arg(short, long, default_value_t = String::from("craft.toml"))]
pub file_name: String,
/// The verbose flag
#[arg(short, long, action = clap::ArgAction::Count)]
pub verbose: u8,
/// Create parameters
/// The depth of the first pass
#[arg(short, long, default_value_t = 8)]
pub depth: u32,
/// Thread counts, default is 4 (can you even run ff with less ?)
#[arg(short, long, default_value_t = 4)]
pub threads: usize,
}
/// Create from config
#[pyfunction]
pub fn pouet()-> &'static str {
return "pouet";
}
/// A Python module implemented in Rust.
#[pymodule]
fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(pouet, m)?)?;
Ok(())
}
/// Solve the craft with given arguments
/// Solve the craft with given arguments, this functions calls threads and must own it's values
pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option<Vec<Craft<'a>>>{
// Load the craft with given arguments
let craft = Craft::new(recipe,stats,params);
// Start timer
let now = Instant::now();
// Start a threadpool
let pool = ThreadPool::new(params.threads);
@ -76,23 +38,18 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
println!("Solving...\n");
println!("[P1] Starting phase 1...");
}
let phase1_routes = solver::generate_routes_phase1(craft);
let nb_p1 = phase1_routes.len();
#[cfg(feature = "verbose")]
if params.verbose>0{
println!("[P1] Found {} routes, testing them all...",phase1_routes.len());
if params.verbose>1{
for r in &phase1_routes{
println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",
r.actions,
r.progression * 100 / r.recipe.progress,
r.quality * 100 / r.recipe.quality,
r.cp,
r.durability,
);
};
}
if params.verbose>1{ for r in &phase1_routes{
println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",r.actions,r.quality * 100 / r.recipe.quality,r.cp,r.durability);
}}
}
// Core algorithm, fill all found routes with the best route (doesn't branch, just replace)
let arc_phase2_routes = Arc::new(Mutex::new(Vec::<Craft>::new()));
@ -109,36 +66,31 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
pool.join();
let phase2_routes = arc_phase2_routes.lock().unwrap();
let nb_p2 = phase2_routes.len();
// Print the results if verbose
#[cfg(feature = "verbose")]
if params.verbose>0{
println!("[P2] Found {} solutions, sorting",phase2_routes.len());
if params.verbose>1{
for r in phase2_routes.iter(){
println!("[P2] {:?} p:{}% q:{}% d:{}",
r.actions,
r.progression * 100 / r.recipe.progress,
r.quality * 100 / r.recipe.quality,
r.durability);
};
}
if params.verbose>1{ for r in phase2_routes.iter(){
println!("[P2] {:?} p:{}% q:{}% d:{}", r.actions, r.progression * 100 / r.recipe.progress, r.quality * 100 / r.recipe.quality, r.durability);
}}
}
// Copy the valid results for analysis, by default only the valid one are copied
// Prune the results for analysis
let mut valid_routes : Vec<Craft> = vec![];
for route in phase2_routes.iter(){
if route.quality>=route.recipe.quality{
valid_routes.push(route.clone());
}
}
// If no craft can make it to 100% HQ, fallback to base results
if valid_routes.len()==0{
for route in phase2_routes.iter(){valid_routes.push(route.clone())} // Deep copy through the mutex guard
}
//// Show best results
// Select best route TODO: Seperate function
let top_route = match valid_routes.iter().max_by_key(|route| route.quality) {
Some(top) => top,
@ -157,6 +109,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
})
.collect::<Vec<String>>();
// Setting something to print, adding the missing actions TODO: Change this behaviour and move to separate function
let arg = (top_route.recipe.progress as f32 - top_route.progression as f32) / top_route.get_base_progression() as f32;
if 0.0 < arg && arg < 1.2 { content.push("\"basicSynth2\"".to_string()); }
@ -176,15 +129,8 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
println!("\t[{}]", content.join(", "));
}
// Wait for enter TODO: Remove
println!();
println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]",
now.elapsed().as_millis(),
phase2_routes.len(),
top_route.recipe.progress);
println!("Press enter to exit...");
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
Some(valid_routes)
}
@ -256,4 +202,17 @@ pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name:
// fn make_craft_from_values(){
// }
// }
// /// Print results
// enum SHOW_TYPE{
// BEST,
// SAFEST,
// SHORTEST,
// }
pub fn print_routes<'a>(routes: Option<Vec<Craft<'a>>>){
match routes{
Some(r) => println!("{:?}",r),
None => println!("Noooooooooooooo")
}
}