Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Cancel button #92

Merged
merged 4 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions assets/locales/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ stats_window:
label:
none:
en: None
cancel:
en: Cancel
clear:
en: Clear
select:
Expand Down
3 changes: 2 additions & 1 deletion raphael-cli/src/commands/solve.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::Args;
use game_data::{get_game_settings, CrafterStats, MEALS, POTIONS, RECIPES};
use simulator::SimulationState;
use solvers::MacroSolver;
use solvers::{AtomicFlag, MacroSolver};

#[derive(Args, Debug)]
pub struct SolveArgs {
Expand Down Expand Up @@ -258,6 +258,7 @@ pub fn execute(args: &SolveArgs) {
args.unsound,
Box::new(|_| {}),
Box::new(|_| {}),
AtomicFlag::new(),
);
let actions = solver.solve(state).expect("Failed to solve");

Expand Down
15 changes: 11 additions & 4 deletions solvers/examples/macro_solver_example.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use simulator::{Action, ActionMask, Settings, SimulationState};
use solvers::MacroSolver;
use solvers::{AtomicFlag, MacroSolver};

fn main() {
#[cfg(feature = "env_logger")]
Expand Down Expand Up @@ -32,9 +32,16 @@ fn main() {
};

let state = SimulationState::new(&settings);
let actions = MacroSolver::new(settings, false, false, Box::new(|_| {}), Box::new(|_| {}))
.solve(state)
.unwrap();
let actions = MacroSolver::new(
settings,
false,
false,
Box::new(|_| {}),
Box::new(|_| {}),
AtomicFlag::new(),
)
.solve(state)
.unwrap();

let quality = SimulationState::from_macro(&settings, &actions)
.unwrap()
Expand Down
7 changes: 5 additions & 2 deletions solvers/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod actions;
mod branch_pruning;
mod utils;

mod finish_solver;
use finish_solver::FinishSolver;
Expand All @@ -14,8 +13,11 @@ use step_lower_bound_solver::StepLowerBoundSolver;
mod macro_solver;
pub use macro_solver::MacroSolver;

mod utils;
pub use utils::AtomicFlag;

pub mod test_utils {
use crate::MacroSolver;
use crate::{utils::AtomicFlag, MacroSolver};
use simulator::*;

pub fn solve(
Expand All @@ -29,6 +31,7 @@ pub mod test_utils {
unsound_branch_pruning,
Box::new(|_| {}),
Box::new(|_| {}),
AtomicFlag::new(),
)
.solve(SimulationState::new(settings))
}
Expand Down
8 changes: 4 additions & 4 deletions solvers/src/macro_solver/fast_lower_bound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn fast_lower_bound(
settings: &Settings,
finish_solver: &mut FinishSolver,
upper_bound_solver: &mut QualityUpperBoundSolver,
) -> u16 {
) -> Option<u16> {
let _timer = NamedTimer::new("Fast lower bound");
let allowed_actions = settings.allowed_actions.intersection(SEARCH_ACTIONS);

Expand All @@ -29,7 +29,7 @@ pub fn fast_lower_bound(

let mut quality_lower_bound = 0;

search_queue.push(upper_bound_solver.quality_upper_bound(state), state);
search_queue.push(upper_bound_solver.quality_upper_bound(state)?, state);

while let Some((score, state)) = search_queue.pop() {
if score <= quality_lower_bound {
Expand All @@ -48,7 +48,7 @@ pub fn fast_lower_bound(
if action == Action::ByregotsBlessing {
continue;
}
let quality_upper_bound = upper_bound_solver.quality_upper_bound(state);
let quality_upper_bound = upper_bound_solver.quality_upper_bound(state)?;
if quality_upper_bound <= quality_lower_bound {
continue;
}
Expand All @@ -62,7 +62,7 @@ pub fn fast_lower_bound(
}

log::debug!("Fast quality lower bound: {}", quality_lower_bound);
std::cmp::min(settings.max_quality, quality_lower_bound)
Some(std::cmp::min(settings.max_quality, quality_lower_bound))
}

fn should_use_action(action: Action, state: &SimulationState, allowed_actions: ActionMask) -> bool {
Expand Down
28 changes: 22 additions & 6 deletions solvers/src/macro_solver/solver.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use simulator::{Action, ActionMask, Condition, Settings, SimulationState};

use super::search_queue::SearchScore;
use crate::actions::{DURABILITY_ACTIONS, PROGRESS_ACTIONS, QUALITY_ACTIONS};
use crate::branch_pruning::{is_progress_only_state, strip_quality_effects};
use crate::macro_solver::fast_lower_bound::fast_lower_bound;
use crate::macro_solver::search_queue::SearchQueue;
use crate::utils::NamedTimer;
use crate::{
actions::{DURABILITY_ACTIONS, PROGRESS_ACTIONS, QUALITY_ACTIONS},
utils::AtomicFlag,
};
use crate::{FinishSolver, QualityUpperBoundSolver, StepLowerBoundSolver};

use std::vec::Vec;
Expand Down Expand Up @@ -36,6 +39,7 @@ pub struct MacroSolver<'a> {
step_lower_bound_solver: StepLowerBoundSolver,
solution_callback: Box<SolutionCallback<'a>>,
progress_callback: Box<ProgressCallback<'a>>,
flag: AtomicFlag,
WorkingRobot marked this conversation as resolved.
Show resolved Hide resolved
}

impl<'a> MacroSolver<'a> {
Expand All @@ -45,6 +49,7 @@ impl<'a> MacroSolver<'a> {
unsound_branch_pruning: bool,
solution_callback: Box<SolutionCallback<'a>>,
progress_callback: Box<ProgressCallback<'a>>,
flag: AtomicFlag,
) -> MacroSolver<'a> {
MacroSolver {
settings,
Expand All @@ -55,14 +60,17 @@ impl<'a> MacroSolver<'a> {
settings,
backload_progress,
unsound_branch_pruning,
flag.clone(),
),
step_lower_bound_solver: StepLowerBoundSolver::new(
settings,
backload_progress,
unsound_branch_pruning,
flag.clone(),
),
solution_callback,
progress_callback,
flag,
}
}

Expand All @@ -80,11 +88,15 @@ impl<'a> MacroSolver<'a> {
}

fn do_solve(&mut self, state: SimulationState) -> Option<Vec<Action>> {
if self.flag.is_set() {
WorkingRobot marked this conversation as resolved.
Show resolved Hide resolved
return None;
}

let mut search_queue = {
let _timer = NamedTimer::new("Initial upper bound");
let quality_upper_bound = self.quality_upper_bound_solver.quality_upper_bound(state);
let quality_upper_bound = self.quality_upper_bound_solver.quality_upper_bound(state)?;
let step_lower_bound = if quality_upper_bound >= self.settings.max_quality {
self.step_lower_bound_solver.step_lower_bound(state)
self.step_lower_bound_solver.step_lower_bound(state)?
} else {
1 // quality dominates the search score, so no need to query the step solver
};
Expand All @@ -94,7 +106,7 @@ impl<'a> MacroSolver<'a> {
&self.settings,
&mut self.finish_solver,
&mut self.quality_upper_bound_solver,
);
)?;
let minimum_score = SearchScore::new(quality_lower_bound, u8::MAX, u8::MAX);
SearchQueue::new(state, initial_score, minimum_score)
};
Expand All @@ -103,6 +115,10 @@ impl<'a> MacroSolver<'a> {

let mut popped = 0;
while let Some((state, score, backtrack_id)) = search_queue.pop() {
if self.flag.is_set() {
return None;
}

popped += 1;
if popped % (1 << 14) == 0 {
(self.progress_callback)(popped);
Expand Down Expand Up @@ -136,14 +152,14 @@ impl<'a> MacroSolver<'a> {
} else {
std::cmp::min(
score.quality,
self.quality_upper_bound_solver.quality_upper_bound(state),
self.quality_upper_bound_solver.quality_upper_bound(state)?,
)
};

let step_lb_hint = score.steps.saturating_sub(current_steps + 1);
let step_lower_bound = if quality_upper_bound >= self.settings.max_quality {
self.step_lower_bound_solver
.step_lower_bound_with_hint(state, step_lb_hint)
.step_lower_bound_with_hint(state, step_lb_hint)?
.saturating_add(current_steps + 1)
} else {
current_steps + 1
Expand Down
43 changes: 32 additions & 11 deletions solvers/src/quality_upper_bound_solver/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::i16;

use crate::{
actions::{PROGRESS_ACTIONS, QUALITY_ACTIONS},
utils::{ParetoFrontBuilder, ParetoFrontId, ParetoValue},
utils::{AtomicFlag, ParetoFrontBuilder, ParetoFrontId, ParetoValue},
};
use simulator::*;

Expand Down Expand Up @@ -31,13 +31,19 @@ pub struct QualityUpperBoundSolver {
solver_settings: SolverSettings,
solved_states: HashMap<ReducedState, ParetoFrontId>,
pareto_front_builder: ParetoFrontBuilder<u16, u16>,
flag: AtomicFlag,
// pre-computed branch pruning values
waste_not_1_min_cp: i16,
waste_not_2_min_cp: i16,
}

impl QualityUpperBoundSolver {
pub fn new(settings: Settings, backload_progress: bool, unsound_branch_pruning: bool) -> Self {
pub fn new(
settings: Settings,
backload_progress: bool,
unsound_branch_pruning: bool,
flag: AtomicFlag,
) -> Self {
log::trace!(
"ReducedState (QualityUpperBoundSolver) - size: {}, align: {}",
std::mem::size_of::<ReducedState>(),
Expand Down Expand Up @@ -77,14 +83,19 @@ impl QualityUpperBoundSolver {
settings.max_progress,
settings.max_quality,
),
flag,
waste_not_1_min_cp: waste_not_min_cp(56, 4, durability_cost),
waste_not_2_min_cp: waste_not_min_cp(98, 8, durability_cost),
}
}

/// Returns an upper-bound on the maximum Quality achievable from this state while also maxing out Progress.
/// There is no guarantee on the tightness of the upper-bound.
pub fn quality_upper_bound(&mut self, state: SimulationState) -> u16 {
pub fn quality_upper_bound(&mut self, state: SimulationState) -> Option<u16> {
if self.flag.is_set() {
return None;
}

let current_quality = state.quality;
let missing_progress = self
.simulator_settings
Expand All @@ -108,10 +119,10 @@ impl QualityUpperBoundSolver {
match pareto_front.last() {
Some(element) => {
if element.first < missing_progress {
return 0;
return Some(0);
}
}
None => return 0,
None => return Some(0),
}

let index = match pareto_front.binary_search_by_key(&missing_progress, |value| value.first)
Expand All @@ -120,13 +131,17 @@ impl QualityUpperBoundSolver {
Err(i) => i,
};

std::cmp::min(
Some(std::cmp::min(
self.simulator_settings.max_quality,
pareto_front[index].second.saturating_add(current_quality),
)
))
}

fn solve_state(&mut self, state: ReducedState) {
if self.flag.is_set() {
return;
WorkingRobot marked this conversation as resolved.
Show resolved Hide resolved
}

if state.data.combo() == Combo::None {
self.solve_normal_state(state);
} else {
Expand Down Expand Up @@ -180,6 +195,10 @@ impl QualityUpperBoundSolver {
}

fn build_child_front(&mut self, state: ReducedState, action: Action) {
if self.flag.is_set() {
return;
}

if let Ok((new_state, action_progress, action_quality)) =
state.use_action(action, &self.simulator_settings, &self.solver_settings)
{
Expand Down Expand Up @@ -245,7 +264,9 @@ mod tests {

fn solve(settings: Settings, actions: &[Action]) -> u16 {
let state = SimulationState::from_macro(&settings, actions).unwrap();
QualityUpperBoundSolver::new(settings, false, false).quality_upper_bound(state)
QualityUpperBoundSolver::new(settings, false, false, AtomicFlag::new())
.quality_upper_bound(state)
.unwrap()
}

#[test]
Expand Down Expand Up @@ -721,15 +742,15 @@ mod tests {
/// Test that the upper-bound solver is monotonic,
/// i.e. the quality UB of a state is never less than the quality UB of any of its children.
fn monotonic_fuzz_check(settings: Settings) {
let mut solver = QualityUpperBoundSolver::new(settings, false, false);
let mut solver = QualityUpperBoundSolver::new(settings, false, false, AtomicFlag::new());
for _ in 0..10000 {
let state = random_state(&settings);
let state_upper_bound = solver.quality_upper_bound(state);
let state_upper_bound = solver.quality_upper_bound(state).unwrap();
for action in settings.allowed_actions.actions_iter() {
let child_upper_bound = match state.use_action(action, Condition::Normal, &settings)
{
Ok(child) => match child.is_final(&settings) {
false => solver.quality_upper_bound(child),
false => solver.quality_upper_bound(child).unwrap(),
true if child.progress >= settings.max_progress => {
std::cmp::min(settings.max_quality, child.quality)
}
Expand Down
Loading