1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use crate::problem::KurobakoProblemRecipe;
use crate::runner::{StudyRunner, StudyRunnerOptions};
use crate::solver::{KurobakoSolver, KurobakoSolverRecipe};
use crate::variable::{VarPath, Variable};
use kurobako_core::parameter::{ParamDomain, ParamValue};
use kurobako_core::problem::{
    BoxProblem, Evaluate, EvaluatorCapability, Problem, ProblemRecipe, ProblemSpec, Values,
};
use kurobako_core::solver::{Solver, SolverRecipe, SolverSpec};
use kurobako_core::{json, Error, Result};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::num::NonZeroU64;
use structopt::StructOpt;
use yamakan::budget::Budget;
use yamakan::observation::ObsId;

#[derive(Debug, Clone, StructOpt, Serialize, Deserialize)]
pub struct ExamRecipe {
    #[structopt(long, parse(try_from_str = "json::parse_json"))]
    pub solver: KurobakoSolverRecipe,

    #[structopt(long, parse(try_from_str = "json::parse_json"))]
    pub problem: KurobakoProblemRecipe,

    #[serde(flatten)]
    #[structopt(flatten)]
    pub runner: StudyRunnerOptions,
    // TODO: Metric (best or auc, ...)
}
impl ExamRecipe {
    fn bind(&self, vals: &Vals) -> Result<Self> {
        let mut recipe = track!(serde_json::to_value(self.clone()).map_err(Error::from))?;
        track!(Self::bind_recur(&mut recipe, vals, &mut VarPath::new()))?;
        track!(serde_json::from_value(recipe).map_err(Error::from))
    }

    fn bind_recur(recipe: &mut serde_json::Value, vals: &Vals, path: &mut VarPath) -> Result<()> {
        if let Some(val) = vals.get(path) {
            *recipe = track!(val.to_json_value())?;
        } else {
            match recipe {
                serde_json::Value::Array(a) => {
                    for (i, v) in a.iter_mut().enumerate() {
                        path.push(i.to_string());
                        track!(Self::bind_recur(v, vals, path))?;
                        path.pop();
                    }
                }
                serde_json::Value::Object(o) => {
                    for (k, v) in o {
                        path.push(k.to_owned());
                        track!(Self::bind_recur(v, vals, path))?;
                        path.pop();
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
}

type Vars = Vec<ParamDomain>;
type Vals = HashMap<VarPath, ParamValue>;

#[derive(Debug, Clone, StructOpt, Serialize, Deserialize)]
pub struct ExamProblemRecipe {
    #[structopt(long)]
    pub recipe: json::JsonValue,

    #[structopt(long, parse(try_from_str = "json::parse_json"))]
    pub vars: Vec<Variable>,
}
impl ProblemRecipe for ExamProblemRecipe {
    type Problem = ExamProblem;

    fn create_problem(&self) -> Result<Self::Problem> {
        let exam: ExamRecipe =
            track!(serde_json::from_value(self.recipe.get().clone()).map_err(Error::from))?;
        let problem = track!(exam.problem.create_problem())?.specification();
        let solver = track!(exam.solver.create_solver(problem.clone()))?.specification();

        Ok(ExamProblem {
            exam,
            vars: self
                .vars
                .iter()
                .map(|v| track!(v.to_param_domain()))
                .collect::<Result<_>>()?,
            problem,
            solver,
        })
    }
}

#[derive(Debug)]
pub struct ExamProblem {
    exam: ExamRecipe,
    vars: Vars,
    problem: ProblemSpec,
    solver: SolverSpec,
}
impl Problem for ExamProblem {
    type Evaluator = ExamEvaluator;

    fn specification(&self) -> ProblemSpec {
        let evaluation_expense =
            NonZeroU64::new(self.exam.runner.budget as u64 * self.problem.evaluation_expense.get())
                .unwrap_or_else(|| unimplemented!());
        ProblemSpec {
            name: format!("exam/{}/{}", self.solver.name, self.problem.name),
            version: None, // TODO
            params_domain: self.vars.clone(),
            values_domain: self.problem.values_domain.clone(), // TODO
            evaluation_expense,
            capabilities: vec![EvaluatorCapability::Concurrent].into_iter().collect(),
        }
    }

    fn create_evaluator(&mut self, _id: ObsId) -> Result<Self::Evaluator> {
        Ok(ExamEvaluator::NotStarted {
            exam: self.exam.clone(),
            vars: self.vars.clone(),
        })
    }
}

#[derive(Debug)]
pub enum ExamEvaluator {
    NotStarted {
        exam: ExamRecipe,
        vars: Vars,
    },
    Running {
        runner: StudyRunner<KurobakoSolver, BoxProblem>,
    },
}
impl Evaluate for ExamEvaluator {
    fn evaluate(&mut self, params: &[ParamValue], budget: &mut Budget) -> Result<Values> {
        loop {
            let next = match self {
                ExamEvaluator::NotStarted { exam, vars } => {
                    let vals = vars
                        .iter()
                        .zip(params.iter())
                        .map(|(var, param)| {
                            let path = track!(var.name().parse())
                                .unwrap_or_else(|e| unreachable!("{}", e));
                            (path, param.clone())
                        })
                        .collect();
                    debug!("Before bind: {:?}", exam);
                    let exam = track!(exam.bind(&vals))?;
                    debug!("After bind: {:?}", exam);

                    let runner =
                        track!(StudyRunner::new(&exam.solver, &exam.problem, &exam.runner))?;
                    ExamEvaluator::Running { runner }
                }
                ExamEvaluator::Running { runner } => {
                    track!(runner.run_once(budget))?;
                    loop {
                        trace!("Study: {:?}", runner.study());
                        if let Some(v) = runner.study().best_value() {
                            debug!(
                                "Evaluated: budget={:?}, params={:?}, value={:?}",
                                budget,
                                params,
                                v.get()
                            );
                            return Ok(vec![v]);
                        }

                        budget.amount = budget.consumption + 1;
                        track!(runner.run_once(budget))?;
                    }
                }
            };
            *self = next;
        }
    }
}