21. 核心构建块与自定义算法
core 与 utils 暴露求解器内部使用的基础设施:校验回调调用、严格预算、最佳点记录、观察者、箱体投影与随机数生成器。外部算法可以只依赖这些公开构件实现新的求解器。理论背景见第 12 章与第 8 章。
21.1 EvaluationContext
pub struct EvaluationContext<'a, P: Evaluator + ?Sized> { /* ... */ }
impl<'a, P: Evaluator + ?Sized> EvaluationContext<'a, P> {
pub fn new(problem: &'a P, dimension: usize, budget: &BudgetOptions)
-> Result<Self, Error>;
pub fn with_observer(self, observer: &'a mut Observer<'a>) -> Self;
pub fn counts(&self) -> EvaluationCounts;
pub fn best(&self) -> Option<&EvaluatedPoint>;
pub fn stop_reason(&self) -> Option<SearchTermination>;
pub fn evaluate(&mut self, x: &[f64]) -> Result<f64, Error>;
pub fn evaluate_into(&mut self, x: &[f64], gradient: Option<&mut [f64]>)
-> Result<f64, Error>;
pub fn failure(&self, source: Error) -> Error;
}
docs.rs API:EvaluationContext、BudgetOptions、EvaluationCounts、EvaluatedPoint、SearchTermination。
调用语义:
- 形状不合法或梯度缓冲长度错误的输入直接拒绝,不计数;
- 预算/目标/取消判据已满足时返回
Error::SearchStopped(SearchTermination),不调用回调; - 合法调用先计入
objective(请求梯度时另计gradient),再调用应用回调; - 输出非有限或梯度缓冲遗漏写入时报错;本次尝试已计数;
- 全部输出有效后更新最佳点(平局保留较早的点);
- 观察者最后调用,返回
Control::Stop或错误时终止后续调用。
EvaluatedPoint 字段:
| 字段 | 类型 | 含义 |
|---|---|---|
x | Vector | 成功评估的点 |
value | f64 | 该点的有限目标值 |
best() 返回当前记录的最小有效点;目标值相同时保留较早的点。
示例:
#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};
let problem = value_only(|x: &[f64]| Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0]));
let budget = BudgetOptions { max_evaluations: 2, target_value: None };
let mut context = EvaluationContext::new(&problem, 1, &budget)?;
context.evaluate(&[2.0])?;
context.evaluate(&[1.0])?;
assert_eq!(context.best().unwrap().value, 1.0);
assert_eq!(context.counts().objective, 2);
assert!(context.evaluate(&[0.5]).is_err()); // 预算已耗尽
Ok::<(), nlopt4r::Error>(())
}
21.2 观察者与失败包装
pub enum Control { Continue, Stop }
pub struct EvaluationEvent<'a> {
pub x: &'a [f64],
pub value: f64,
pub best_value: f64,
pub evaluations: EvaluationCounts,
}
pub type Observer<'a> =
dyn for<'b> FnMut(&EvaluationEvent<'b>) -> Result<Control, EvaluationError> + 'a;
docs.rs API:Control、EvaluationEvent、Observer。
failure(source) 在已有最佳点时把错误包装为 Error::SearchFailure { source, last_point, evaluations },保留检查点。
#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};
let problem = value_only(|x: &[f64]| {
if x[0] < 0.0 {
return Err("simulation failed".into());
}
Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0])
});
let mut context = EvaluationContext::new(&problem, 1, &BudgetOptions::default())?;
context.evaluate(&[2.0])?;
let source = context.evaluate(&[-1.0]).unwrap_err();
let error = context.failure(source);
assert_eq!(error.last_point().unwrap().value, 4.0);
assert_eq!(context.counts().objective, 2);
Ok::<(), nlopt4r::Error>(())
}
21.3 Bounds
impl Bounds {
pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Result<Self, Error>;
pub fn uniform(n: usize, lower: f64, upper: f64) -> Result<Self, Error>;
pub fn dimension(&self) -> usize;
pub fn lower(&self) -> &[f64];
pub fn upper(&self) -> &[f64];
pub fn width(&self, i: usize) -> f64;
pub fn validate_point(&self, x: &[f64]) -> Result<(), Error>;
pub fn contains(&self, x: &[f64]) -> bool;
pub fn project(&self, x: &mut [f64]) -> Result<(), Error>;
pub fn midpoint(&self) -> Vector;
pub fn from_unit(&self, unit: &[f64]) -> Result<Vector, Error>;
pub fn to_unit(&self, x: &[f64]) -> Result<Vector, Error>;
pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R, x: &mut [f64])
-> Result<(), Error>;
}
docs.rs API:Bounds。
约定:
- 构造时要求下界与上界有限、逐坐标满足 \(l_i\le u_i\)、维度为正;
width(i) = u_i - l_i,零宽坐标视为固定变量;from_unit/to_unit在单位盒与物理盒之间映射,零宽坐标映射到固定值;project把越界坐标截断到区间端点。
21.4 utils
| 函数 | 作用 |
|---|---|
validate_slice(x, n, context) | 检查切片长度与有限性 |
solve_dense(a, b) | 校验后求解方阵线性系统 |
directional_difference(context, x, direction, step) | 中心差分 \((f(x+sd)-f(x-sd))/(2s)\),两次调用都计入上下文预算 |
RNG 重导出:utils::ChaCha8Rng、utils::Rng、utils::SeedableRng。全局算法用 ChaCha8Rng::seed_from_u64(seed) 创建可复现流。
docs.rs API:validate_slice、solve_dense、directional_difference、ChaCha8Rng、Rng、SeedableRng。
21.5 自定义有界模式搜索
以下算法只使用公开构件,约 30 行完成“中点起步、逐坐标试探、失败减半”的完整搜索:
use nlopt4r::{Bounds, Error, value_only};
use nlopt4r::core::{BudgetOptions, EvaluationContext};
fn main() -> Result<(), Error> {
let problem = value_only(|x: &[f64]| {
Ok::<_, nlopt4r::EvaluationError>((x[0] - 0.3).powi(2) + (x[1] + 0.4).powi(2))
});
let bounds = Bounds::uniform(2, -1.0, 1.0)?;
let budget = BudgetOptions {
max_evaluations: 400,
target_value: Some(1e-10),
};
let mut context = EvaluationContext::new(&problem, bounds.dimension(), &budget)?;
let mut x = bounds.midpoint();
context.evaluate(x.as_slice())?;
let mut step = 0.5;
while step > 1e-7 && context.stop_reason().is_none() {
let before = context.best().expect("initial evaluation").value;
for i in 0..x.len() {
if bounds.width(i) == 0.0 {
continue;
}
for sign in [-1.0, 1.0] {
if context.stop_reason().is_some() {
break;
}
let mut trial = x.clone();
trial[i] += sign * step * bounds.width(i);
bounds.project(trial.as_mut_slice())?;
context.evaluate(trial.as_slice())?;
}
}
let best = context.best().expect("evaluated point");
x.copy_from(&best.x);
if best.value >= before {
step *= 0.5;
}
}
println!("best f = {}", context.best().unwrap().value);
Ok(())
}
要点:
stop_reason()覆盖目标命中、预算、迭代与观察者取消;- 每次
evaluate前检查停止状态,预算耗尽后的请求在回调之前返回停止错误; Bounds::project保证试探点可行;- 结束状态由
stop_reason()给出,None对应步长阈值(此示例以step <= 1e-7退出)。
仓库中的完整外部求解器示例位于 tools/extension,由基准工具的 external-pattern 算法直接调用:
cargo test -p nlopt4r-extension-example
cargo run --release --locked -p nlopt4r-bench -- \
--suite smoke --algorithms external-pattern --seeds 0..3 \
--dimension 2 --budget-per-dimension 1000 --output target/extension.jsonl
21.6 组合建议
| 需求 | 构件 |
|---|---|
| 严格预算与最佳点 | EvaluationContext |
| 取消与外部记录 | with_observer + Control |
| 失败时保留检查点 | context.failure(error) |
| 有限箱体 | Bounds + project/sample |
| 可复现随机流 | ChaCha8Rng::seed_from_u64 |
| 差分梯度(诊断用) | utils::directional_difference |
| 稠密线性求解 | utils::solve_dense |