载入中...
搜索中...
未找到
BalanceBindings.cpp
浏览该文件的文档.
3
4#include <cmath>
5
6namespace eve::agent::balance {
7namespace {
8struct StackScope {
10 SQInteger top;
11 explicit StackScope(HSQUIRRELVM v) : vm(v), top(sq_gettop(v)) {}
12 ~StackScope() { sq_settop(vm, top); }
13};
14
15class ScriptEvaluator final : public IEvaluator {
16public:
17 ScriptEvaluator(const ssq::Table& table, const Problem& problem) : table_(table), problem_(problem) {}
18 Result<std::vector<double>> evaluate(std::span<const double> parameters, std::uint64_t seed, double dt,
19 std::uint32_t steps) override {
20 const auto vm = table_.getHandle();
21 StackScope stack(vm);
22 sq_pushobject(vm, table_.getRaw());
23 sq_pushstring(vm, "evaluate", -1);
24 if (SQ_FAILED(sq_get(vm, -2))) return fail("Missing evaluate(parameters, seed, dt, steps) method");
25 HSQOBJECT function;
26 sq_getstackobj(vm, -1, &function);
28 for (std::size_t i = 0; i < parameters.size(); ++i)
29 values.emplace(problem_.parameters[i].name, Value(parameters[i]));
30 auto pushed = script::pushValue(vm, Value(std::move(values)));
31 if (!pushed) return Result<std::vector<double>>::failure(pushed.status());
32 const auto seedText = std::to_string(seed);
33 HSQOBJECT arguments;
34 sq_getstackobj(vm, -1, &arguments);
35 if (SQ_FAILED(
36 script::callFunctionResult(vm, function, table_, arguments, seedText, SQFloat(dt), SQInteger(steps)))) {
37 sq_getlasterror(vm);
38 const SQChar* error = nullptr;
39 const auto converted = sq_getstring(vm, -1, &error);
40 return fail(SQ_SUCCEEDED(converted) && error ? error : "Balance evaluator callback failed");
41 }
43 if (!result) return Result<std::vector<double>>::failure(result.status());
44 const auto* metrics = result.value().getIf<Value::Object>();
45 if (!metrics || metrics->size() != problem_.targets.size())
46 return fail("Return exactly the named target metrics");
47 std::vector<double> numbers;
48 for (const auto& target : problem_.targets) {
49 auto it = metrics->find(target.name);
50 if (it == metrics->end()) return fail("Missing metric: " + target.name);
51 if (const auto* d = it->second.getIf<double>())
52 numbers.push_back(*d);
53 else if (const auto* n = it->second.getIf<std::int64_t>())
54 numbers.push_back(double(*n));
55 else
56 return fail("Metric is not numeric: " + target.name);
57 }
58 return Result<std::vector<double>>::success(std::move(numbers));
59 }
60
61private:
62 Result<std::vector<double>> fail(std::string message) {
63 return Result<std::vector<double>>::failure(
64 Diagnostic::error(DiagnosticCode::CallbackFailure, std::move(message), {}, {}, "agent.balance.script"));
65 }
66 ssq::Table table_;
67 const Problem& problem_;
68};
69} // namespace
70
71void BalanceSearch::expose(ssq::Table& table) {
72 auto cls = table.addClass<BalanceSearch>("BalanceSearch",
73 std::function<BalanceSearch*()>([] { return new BalanceSearch(); }), true);
74 expose(cls);
75}
76
77void BalanceSearch::expose(ssq::Class& cls) {
78 const auto vm = cls.getHandle();
79 cls.addFunc("configure", [vm](BalanceSearch* self, ssq::Table input) {
82 auto problem = decodeProblem(value.value());
83 if (!problem) return script::projectResult(vm, Result<void>::failure(problem.status()));
84 return script::projectResult(vm, self->configure(problem.value()));
85 });
86 cls.addFunc("run", [vm](BalanceSearch* self, ssq::Table evaluator) {
88 if (!self->problem_)
90 Diagnostic::error(DiagnosticCode::InvalidArgument, "Configure the balance search before run"));
91 ScriptEvaluator adapter(evaluator, *self->problem_);
92 auto report = self->run(adapter);
93 if (!report) return Result<Value>::failure(report.status());
94 return Result<Value>::success(encodeBalanceReport(report.value()));
95 }();
96 if (result) {
97 StackScope stack(vm);
98 auto checked = script::pushValue(vm, result.value());
99 if (!checked)
100 return script::projectResult(vm, Result<Value>::failure(checked.status()), [](Value v) { return v; });
101 }
102 return script::projectResult(vm, std::move(result), [](Value v) { return v; });
103 });
104}
105} // namespace eve::agent::balance
LogicalId target
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< FieldTarget > targets
std::string message
glm::vec3 n
Definition Grass.cpp:63
float v
std::vector< NumericField > numbers
Poco::JSON::Object::Ptr result
double dt
std::string error
Definition Package.cpp:174
std::array< uint32_t, 9 > parameters
std::set< std::string > values
Object::Ptr value
float d
int steps
MigrationFunction function
The single Squirrel projection for common Result, Status and Value.
std::string_view adapter
uint32_t seed
Definition TreeMesh.cpp:276
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
Configure-then-run builder for bounded black-box numerical balancing. @ownership Owns configuration; ...
Definition Balance.h:108
static void expose(ssq::Table &table)
Register the VM-owned builder in the Agent script surface; composition thread only.
BalanceSearch()=default
Create an unconfigured search builder.
Result< void > configure(const Problem &problem)
Validate and copy a problem atomically; a failed configuration preserves the previous one.
Definition Balance.cpp:92
Result< Report > run(IEvaluator &evaluator)
Search on training seeds, then assess initial and best parameters on untouched holdout seeds.
Definition Balance.cpp:99
SQInteger top
Definition Snapshot.cpp:115
Result< Problem > decodeProblem(const Value &value)
Decode version-1 problem data; reject unknown schema/version/fields and invalid types.
Value encodeBalanceReport(const Report &r)
Project an owning version-1 evidence report, including the full reproduction specification....
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
SQRESULT callFunctionResult(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
callFunction() that keeps the return value on top for the caller to read.
Result< void > pushValue(HSQUIRRELVM vm, const Value &value, const SquirrelValueOptions &options)
Push a canonical Value into the active Squirrel VM.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
std::vector< OnnxNamedTensor > evaluate(const ModelData &, std::span< const OnnxNamedTensor >, const std::vector< std::string > &, OnnxCompute *, OnnxRunOptions options)
Evaluate.