Select: wants on goals, the planner gate (satisfied not offered, planned scored by length, unplanned tried direct), one think budget per Select, the plan on the Actor

A GoalSpec.Want and a PlanSteps consideration; Brain.PlanDepth, DirectDiscount, ThinkBudget, ReachMeters; a Deliberation per Actor owning the planner, the want-pair heap and the budget; Select with no pair lets go of the target (stale-target-without-pair); Actor.PlanLength and PlanStep derived each tick.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-26 03:49:12 +01:00
commit dedd232d7b
5 changed files with 1032 additions and 23 deletions

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
@ -61,12 +62,15 @@ namespace Lodur
private readonly OrientRig? _rig;
private readonly bool _layered;
private Side _arm = Side.Right;
// The want gate's thinking space (null when no goal has a want) and the plan length of the committed pair, derived each tick.
private readonly Deliberation? _deliberation;
private int _planLength;
public Actor(
double tickSeconds, int regionCount,
NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, Brain brain,
NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null, Physiology? physiology = null,
WithdrawalParameters? breath = null, BodyPlan? body = null)
WithdrawalParameters? breath = null, BodyPlan? body = null, IReadOnlyList<Verb>? verbs = null)
{
brain.Validate();
drive.Validate();
@ -141,6 +145,16 @@ namespace Lodur
}
_perception = new Perception(nerve, tickSeconds, regionCount, senses, senseRegion, percepts);
if (brain.HasWants)
{
if (_perception.PerceptCount == 0)
{
throw new ArgumentException("A Brain with a want needs percepts: the planner reads the percepts' facts.");
}
_deliberation = new Deliberation(brain, verbs ?? Array.Empty<Verb>(), _perception.PerceptCount);
}
_reflexes = new WithdrawalReflex[regionCount];
for (var r = 0; r < regionCount; r++)
{
@ -201,6 +215,23 @@ namespace Lodur
/// <summary>The id of the percept the committed goal targets; 0 for an untargeted goal. Only the Brain's choice, committed after the latency, writes it.</summary>
public ulong TargetId => _target;
/// <summary>
/// The length of the plan to the committed pair's want, derived each tick from the percepts (never kept across ticks): n steps, -1 when he goes at it direct (no plan within
/// <see cref="Brain.PlanDepth"/>), 0 when the goal has no want, the want holds, or its target is no longer in memory.
/// </summary>
public int PlanLength => _planLength;
/// <summary>Step <paramref name="i"/> of the committed pair's plan, for i below <see cref="PlanLength"/>: a verb of the Actor's list and the percept ids it is grounded on.</summary>
public PlanStep PlanStep(int i)
{
if ((uint)i >= (uint)Math.Max(_planLength, 0))
{
throw new ArgumentOutOfRangeException(nameof(i), "There is no such step in the plan.");
}
return _deliberation!.Step(i);
}
/// <summary>The slot whose Id equals <see cref="TargetId"/>; default (Id 0) when the target is 0 or forgotten.</summary>
public Percept Target
{
@ -227,12 +258,18 @@ namespace Lodur
/// and targets spans one entry per muscle, written for the body to follow. The emitters are the game's point
/// sources, sensed at the sense region's point. The airway is what the caller finds at the body's airway openings; nothing by default.
/// The parts are the body's part poses (one per plan part), read when the goal in force has orient layers and ignored otherwise.
/// <paramref name="selfFacts"/> are the actor's own facts for the planner (the game's; bit 63 is refused), read only by a Brain with wants.
/// </summary>
public TickEvents Tick(
ReadOnlySpan<float> regionX, ReadOnlySpan<float> regionY, ReadOnlySpan<float> regionZ,
ReadOnlySpan<BoxStimulus> sources, Span<float> strengths, Span<Quat> targets,
ReadOnlySpan<Emitter> emitters = default, in AirwaySample airway = default, ReadOnlySpan<PartPose> parts = default)
ReadOnlySpan<Emitter> emitters = default, in AirwaySample airway = default, ReadOnlySpan<PartPose> parts = default, ulong selfFacts = 0UL)
{
if ((selfFacts & Perception.InReachFact) != 0UL)
{
throw new ArgumentException("Bit 63 is Lodur's reach; the actor's own facts have none.", nameof(selfFacts));
}
// The goal that will write this tick: a decision due now commits before the behaviour runs, and one made now cannot (the latency is a tick at least).
if (_layered && _brain.Goals[_pending >= 0 && _tick == _switchTick ? _pending : _goal].Behaviour.HasLayers && parts.Length != Body!.Parts.Count)
{
@ -323,7 +360,13 @@ namespace Lodur
if (_pending < 0)
{
var sr = _perception.SenseRegion;
var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], new Choice(_goal, _target));
var now = new Choice(_goal, _target);
if (_deliberation != null)
{
_deliberation.SelfFacts = selfFacts;
}
var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], now, _deliberation);
if (wanted != new Choice(_goal, _target)
&& (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority))
{
@ -363,6 +406,15 @@ namespace Lodur
}
}
// The committed pair's plan, derived afresh from the percepts of this tick with the whole think budget.
_planLength = 0;
if (_deliberation != null && _brain.Goals[_goal].Want is { } committedWant)
{
var sr = _perception.SenseRegion;
_deliberation.SelfFacts = selfFacts;
_planLength = _deliberation.Derive(_perception, regionX[sr], regionY[sr], regionZ[sr], committedWant, _target);
}
// For EntrySeconds after a takeover the Actor, not the drive, takes the gain (and the arousal, if the goal declares one) from their values at
// takeover to the goal's targets, linearly; its last tick assigns the targets themselves (a lerp need not land on a nonzero target), and after it the drive
// owns arousal again. Sense reads the gain at the start of the next tick, so a change of gain reaches Load one tick after the Actor sets it.

View file

@ -38,13 +38,21 @@ namespace Lodur
};
}
/// <summary>What a consideration reads: a percept's distance from the observer, its salience, the seconds since it was sensed, or a drive quantity.</summary>
/// <summary>
/// What a consideration reads: a percept's distance from the observer, its salience, the seconds since it was sensed, a drive quantity, or the length of
/// the plan to a want goal's pair.
/// </summary>
public enum ConsiderationInput
{
Distance,
Salience,
SecondsSinceSensed,
Drive,
/// <summary>
/// Only on a goal with a <see cref="GoalSpec.Want"/>: x is the pair's plan length (1..<see cref="Brain.PlanDepth"/>) for a planned pair and
/// <see cref="Brain.PlanDepth"/> + 1 for a direct try. Read by the gate in Brain.Select, never by the raw score.
/// </summary>
PlanSteps,
}
/// <summary>
@ -188,6 +196,14 @@ namespace Lodur
/// <summary>The kind of thing this goal targets; null is an untargeted goal. Whether a target exists is decided in <see cref="Brain.Select"/>, not by Eligible.</summary>
public TargetFilter? Target { get; init; }
/// <summary>
/// A fact the goal wants to make true, about himself (<see cref="FactSubject.Self"/>, never bit 63) or about the goal's target (<see cref="FactSubject.This"/>, which needs a
/// <see cref="Target"/>); null is no want. A want pair whose want already holds is not offered; one that does not is planned to <see cref="Brain.PlanDepth"/> steps and scored
/// by the plan's length through <see cref="ConsiderationInput.PlanSteps"/>, or tried direct at <see cref="Brain.DirectDiscount"/> when no plan is found. A want goal's Priority
/// must not be negative. Only an Actor built with verbs selects a Brain that has wants.
/// </summary>
public Fact? Want { get; init; }
private Consideration[] _considerations = Array.Empty<Consideration>();
private IReadOnlyList<Consideration> _considerationsView = Array.AsReadOnly(Array.Empty<Consideration>());
@ -207,6 +223,7 @@ namespace Lodur
}
}
/// <summary>Priority times every consideration but <see cref="ConsiderationInput.PlanSteps"/>: the raw score, before the plan's length is known.</summary>
internal double Score(in DriveState drive, in Percept percept, float ox, float oy, float oz)
{
var score = Priority;
@ -216,6 +233,8 @@ namespace Lodur
double x;
switch (k.Input)
{
case ConsiderationInput.PlanSteps:
continue;
case ConsiderationInput.Drive:
x = DriveReads.Read(drive, k.Quantity);
break;
@ -239,6 +258,21 @@ namespace Lodur
return score;
}
/// <summary>The product of the <see cref="ConsiderationInput.PlanSteps"/> responses at plan length <paramref name="x"/>; 1 with none.</summary>
internal double PlanFactor(int x)
{
var factor = 1.0;
for (var c = 0; c < _considerations.Length; c++)
{
if (_considerations[c].Input == ConsiderationInput.PlanSteps)
{
factor *= _considerations[c].Response(x);
}
}
return factor;
}
internal bool Eligible(in DriveState drive)
{
for (var c = 0; c < _when.Length; c++)
@ -288,19 +322,64 @@ namespace Lodur
/// <summary>How much the current (goal, target) pair's score is multiplied by, finite and at least 1; 1 is no commitment.</summary>
public double TargetCommitment { get; init; } = 1.0;
/// <summary>The planner's depth, the intelligence stat's base: the most steps a want goal's plan may have, 0..8, default 0 (no plans; every want pair is tried direct).</summary>
public int PlanDepth { get; init; }
/// <summary>The factor on a pair's score when its goal's want has no plan within <see cref="PlanDepth"/> (or the think budget ran out): he goes at the target directly, in [0, 1], default 0.5 (a placeholder).</summary>
public double DirectDiscount { get; init; } = 0.5;
/// <summary>The most groundings one Select may regress across all its plans, at least 1, default 4096: one budget per decision, spent on the best raw pairs first (lodur:question:bds-think-budget-per-decision).</summary>
public int ThinkBudget { get; init; } = Planner.NodeBudget;
/// <summary>How close a thing must be to be in reach, in meters, finite and above 0, default 0.6 (an arm's length, 0.575 m, as a placeholder).</summary>
public double ReachMeters { get; init; } = 0.6;
/// <summary>True when any goal has a want: such a Brain is selected through an Actor's Deliberation, not the public Select.</summary>
internal bool HasWants
{
get
{
for (var i = 0; i < Goals.Count; i++)
{
if (Goals[i].Want is not null)
{
return true;
}
}
return false;
}
}
/// <summary>
/// The pair wanted now. Each eligible untargeted goal is one pair (goal, 0) scored Priority times its Drive considerations; each eligible
/// targeted goal is one pair per percept slot with a non-zero Id and a Kind it accepts, scored Priority times every consideration. The pair
/// equal to <paramref name="current"/> is multiplied by <see cref="TargetCommitment"/>. The highest score wins; ties go to the current pair,
/// then the lowest goal index, then the lowest slot; with no pair at all the current choice stays. A percept Id is only compared, never decoded.
/// then the lowest goal index, then the lowest slot. With no pair at all the goal in force stays and lets go of its target: (current.Goal, 0),
/// so a forgotten target is not held (the Actor commits it a latency later and the orient layers rest). A percept Id is only compared, never decoded.
/// Throws for a Brain with a want: the planner's gate needs an Actor's verbs, so the Actor selects it.
/// </summary>
public Choice Select(in DriveState drive, Perception perception, float observerX, float observerY, float observerZ, Choice current)
{
var best = current;
var bestScore = 0.0;
var bestIsCurrent = false;
var found = false;
if (HasWants)
{
throw new InvalidOperationException("A Brain with a want is selected by its Actor, which holds the verbs the planner needs.");
}
return Select(drive, perception, observerX, observerY, observerZ, current, null);
}
/// <summary>
/// <see cref="Select(in DriveState, Perception, float, float, float, Choice)"/> with the want gate. Pass 1 scores every pair raw (commitment applied) and offers
/// the untargeted-by-want pairs; a want pair whose want holds is not offered, the rest wait in the Deliberation. Pass 2 takes them by raw, best first, plans each with what is
/// left of <see cref="ThinkBudget"/>, and offers raw times the plan-length factor, or raw times the factor at PlanDepth + 1 times <see cref="DirectDiscount"/> when no plan was found
/// or the budget is gone; it stops once no remaining raw can beat or tie-win the best (every factor is at most 1).
/// </summary>
internal Choice Select(in DriveState drive, Perception perception, float ox, float oy, float oz, Choice current, Deliberation? d)
{
var best = default(Pick);
var slots = perception.PerceptCount;
d?.Begin(perception, ox, oy, oz);
for (var i = 0; i < Goals.Count; i++)
{
var goal = Goals[i];
@ -311,7 +390,7 @@ namespace Lodur
if (goal.Target is null)
{
Offer(i, 0UL, goal.Score(drive, default, observerX, observerY, observerZ), current, ref best, ref bestScore, ref bestIsCurrent, ref found);
Consider(i, goal, -1, 0UL, goal.Score(drive, default, ox, oy, oz), current, d, ref best);
continue;
}
@ -323,28 +402,65 @@ namespace Lodur
continue;
}
Offer(i, percept.Id, goal.Score(drive, percept, observerX, observerY, observerZ), current, ref best, ref bestScore, ref bestIsCurrent, ref found);
Consider(i, goal, s, percept.Id, goal.Score(drive, percept, ox, oy, oz), current, d, ref best);
}
}
return found ? best : current;
while (d is not null && d.TryPop(out var pair))
{
if (best.Found && pair.Raw < best.Score)
{
break;
}
var goal = Goals[pair.Goal];
var length = d.Plan(pair.Goal, goal.Want!.Value, pair.Slot);
var factor = length > 0 ? goal.PlanFactor(length) : goal.PlanFactor(PlanDepth + 1) * DirectDiscount;
Offer(pair.Goal, pair.Slot, pair.Target, pair.Raw * factor, pair.Current, ref best);
}
return best.Found ? Pair(best.Goal, best.Target) : Pair(current.Goal, 0UL);
}
private void Offer(int goal, ulong target, double score, Choice current, ref Choice best, ref double bestScore, ref bool bestIsCurrent, ref bool found)
private static Choice Pair(int goal, ulong target) => new Choice(goal, target);
// One scored pair: offered now, or (a want pair) held back for the planner's gate. The commitment multiplies the raw score here, so pass 2 orders by the committed raw.
private void Consider(int goal, GoalSpec spec, int slot, ulong target, double raw, Choice current, Deliberation? d, ref Pick best)
{
var isCurrent = goal == current.Goal && target == current.Target;
if (isCurrent)
{
score *= TargetCommitment;
raw *= TargetCommitment;
}
if (!found || score > bestScore || (score == bestScore && isCurrent && !bestIsCurrent))
if (spec.Want is not { } want)
{
best = new Choice(goal, target);
bestScore = score;
bestIsCurrent = isCurrent;
found = true;
Offer(goal, slot, target, raw, isCurrent, ref best);
}
else if (!d!.Holds(goal, want, slot))
{
d.Add(goal, slot, target, raw, isCurrent);
}
}
// Ties resolve by key (current, then lowest goal, then lowest slot), not by call order: pass 2 offers out of index order.
private static void Offer(int goal, int slot, ulong target, double score, bool isCurrent, ref Pick best)
{
if (!best.Found || score > best.Score
|| (score == best.Score && (isCurrent != best.IsCurrent ? isCurrent : goal < best.Goal || (goal == best.Goal && slot < best.Slot))))
{
best = new Pick { Goal = goal, Slot = slot, Target = target, Score = score, IsCurrent = isCurrent, Found = true };
}
}
private struct Pick
{
public int Goal;
public int Slot;
public ulong Target;
public double Score;
public bool IsCurrent;
public bool Found;
}
internal void Validate()
@ -369,6 +485,26 @@ namespace Lodur
throw new ArgumentException("TargetCommitment must be finite and at least 1.");
}
if (PlanDepth < 0 || PlanDepth > 8)
{
throw new ArgumentException("PlanDepth must be in 0..8.");
}
if (!(DirectDiscount >= 0.0 && DirectDiscount <= 1.0))
{
throw new ArgumentException("DirectDiscount must be in [0, 1].");
}
if (ThinkBudget < 1)
{
throw new ArgumentException("ThinkBudget must be at least 1.");
}
if (!(double.IsFinite(ReachMeters) && ReachMeters > 0.0))
{
throw new ArgumentException("ReachMeters must be finite and above 0.");
}
var muscles = -1;
foreach (var goal in Goals)
{
@ -382,6 +518,29 @@ namespace Lodur
throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Target or considerations.");
}
if (goal.Want is { } want)
{
if (want.Subject != FactSubject.Self && want.Subject != FactSubject.This)
{
throw new ArgumentException($"Goal {goal.Id}: a Want is about himself or the target.");
}
if ((uint)want.Bit > 63u || (want.Subject == FactSubject.Self && want.Bit == 63))
{
throw new ArgumentException($"Goal {goal.Id}: a Want is on a bit in 0..63, and bit 63 is Lodur's reach, which the actor has none of.");
}
if (want.Subject == FactSubject.This && goal.Target is null)
{
throw new ArgumentException($"Goal {goal.Id}: a Want about the target needs a Target.");
}
if (!(goal.Priority >= 0.0))
{
throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Want.");
}
}
foreach (var k in goal.Considerations)
{
if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
@ -391,7 +550,14 @@ namespace Lodur
throw new ArgumentException($"Goal {goal.Id}: a consideration needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
}
if (k.Input != ConsiderationInput.Drive && goal.Target is null)
if (k.Input == ConsiderationInput.PlanSteps)
{
if (goal.Want is null)
{
throw new ArgumentException($"Goal {goal.Id}: a PlanSteps consideration needs a goal with a Want.");
}
}
else if (k.Input != ConsiderationInput.Drive && goal.Target is null)
{
throw new ArgumentException($"Goal {goal.Id}: Distance, Salience and SecondsSinceSensed considerations need a targeted goal.");
}

View file

@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>A want pair held back for the planner's gate: its goal, percept slot (-1 for an untargeted goal), the percept's id, its raw score (commitment applied) and whether it is the current pair.</summary>
internal struct WantPair
{
public int Goal;
public int Slot;
public ulong Target;
public double Raw;
public bool Current;
}
/// <summary>
/// What one Actor thinks with while its Brain selects: the planner, the want pairs waiting for the gate (a max-heap by raw score, ties current, lowest goal, lowest slot),
/// the think budget spent so far in this Select, and the plan of the last call. Owned by one Actor; allocates only in its constructor. Not thread-safe.
/// </summary>
internal sealed class Deliberation
{
private const int Unplanned = int.MinValue;
private readonly Planner _planner;
private readonly Brain _brain;
private readonly PlanStep[] _plan;
private readonly WantPair[] _heap;
private readonly sbyte[] _selfHeld; // per goal this Select: -1 not asked, 0 the Self want does not hold, 1 it holds
private readonly int[] _selfLength; // per goal this Select: the Self want's plan length, -1 direct, Unplanned not asked
private Perception _perception;
private float _ox;
private float _oy;
private float _oz;
private int _count;
private int _spent;
internal Deliberation(Brain brain, IReadOnlyList<Verb> verbs, int capacity)
{
_brain = brain;
_planner = new Planner(verbs, capacity, brain.PlanDepth, brain.ReachMeters);
_plan = new PlanStep[Math.Max(1, brain.PlanDepth)];
_heap = new WantPair[brain.Goals.Count * capacity];
_selfHeld = new sbyte[brain.Goals.Count];
_selfLength = new int[brain.Goals.Count];
_perception = null!;
}
/// <summary>The actor's own facts this tick, supplied by the game (bit 63 never set).</summary>
internal ulong SelfFacts { get; set; }
/// <summary>The groundings the current Select has paid out of <see cref="Brain.ThinkBudget"/>.</summary>
internal int Spent => _spent;
/// <summary>The plan of the last derivation, in execution order: step i for i below the length <see cref="Derive"/> returned.</summary>
internal PlanStep Step(int i) => _plan[i];
/// <summary>Starts a Select: nothing waits, nothing is spent, nothing is known of the Self wants.</summary>
internal void Begin(Perception perception, float ox, float oy, float oz)
{
_perception = perception;
_ox = ox;
_oy = oy;
_oz = oz;
_count = 0;
_spent = 0;
for (var g = 0; g < _selfHeld.Length; g++)
{
_selfHeld[g] = -1;
_selfLength[g] = Unplanned;
}
}
/// <summary>Whether the want already holds for the pair on <paramref name="slot"/> (-1 for an untargeted goal): a depth-0 plan, which spends no budget. A Self want is asked once per goal.</summary>
internal bool Holds(int goal, Fact want, int slot)
{
if (want.Subject != FactSubject.Self)
{
return AskHolds(want, slot);
}
if (_selfHeld[goal] < 0)
{
_selfHeld[goal] = (sbyte)(AskHolds(want, 0) ? 1 : 0);
}
return _selfHeld[goal] == 1;
}
private bool AskHolds(Fact want, int slot) =>
_planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, slot, want, 0, _plan, 1) == 0;
/// <summary>
/// The plan length of a want pair that does not hold: n steps, or -1 to go at it direct (no plan within the depth, the call spent the rest of the budget, or none was left).
/// A Self want is planned once per goal and shared by its pairs. Spends from the Select's one budget.
/// </summary>
internal int Plan(int goal, Fact want, int slot)
{
var self = want.Subject == FactSubject.Self;
if (self && _selfLength[goal] != Unplanned)
{
return _selfLength[goal];
}
var length = -1;
var left = _brain.ThinkBudget - _spent;
if (_brain.PlanDepth > 0 && left >= 1)
{
var n = _planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, self ? 0 : slot, want, _brain.PlanDepth, _plan, left);
_spent = Math.Min(_brain.ThinkBudget, _spent + _planner.LastNodes);
length = n > 0 ? n : -1;
}
if (self)
{
_selfLength[goal] = length;
}
return length;
}
/// <summary>
/// The committed pair's plan, derived with the full budget: 0 when the want holds or its target is not in memory; n for an n-step plan, readable through
/// <see cref="Step"/>; -1 for a direct try.
/// </summary>
internal int Derive(Perception perception, float ox, float oy, float oz, Fact want, ulong target)
{
var slot = 0;
if (want.Subject == FactSubject.This)
{
slot = -1;
var ids = perception.PerceptIds;
for (var s = 0; s < ids.Length; s++)
{
if (target != 0UL && ids[s] == target)
{
slot = s;
break;
}
}
if (slot < 0)
{
return 0;
}
}
return _planner.Plan(perception, SelfFacts, ox, oy, oz, slot, want, _brain.PlanDepth, _plan, _brain.ThinkBudget);
}
internal void Add(int goal, int slot, ulong target, double raw, bool current)
{
var i = _count++;
_heap[i] = new WantPair { Goal = goal, Slot = slot, Target = target, Raw = raw, Current = current };
while (i > 0)
{
var parent = (i - 1) >> 1;
if (!Before(_heap[i], _heap[parent]))
{
break;
}
(_heap[i], _heap[parent]) = (_heap[parent], _heap[i]);
i = parent;
}
}
/// <summary>The waiting want pair with the highest raw score (ties current, lowest goal, lowest slot).</summary>
internal bool TryPop(out WantPair pair)
{
if (_count == 0)
{
pair = default;
return false;
}
pair = _heap[0];
_heap[0] = _heap[--_count];
var i = 0;
while (true)
{
var l = 2 * i + 1;
if (l >= _count)
{
break;
}
var c = l + 1 < _count && Before(_heap[l + 1], _heap[l]) ? l + 1 : l;
if (!Before(_heap[c], _heap[i]))
{
break;
}
(_heap[i], _heap[c]) = (_heap[c], _heap[i]);
i = c;
}
return true;
}
private static bool Before(in WantPair a, in WantPair b) =>
a.Raw != b.Raw ? a.Raw > b.Raw
: a.Current != b.Current ? a.Current
: a.Goal != b.Goal ? a.Goal < b.Goal
: a.Slot < b.Slot;
}
}

View file

@ -66,7 +66,8 @@ public sealed class GoalTargetTests
Assert.Equal(new Choice(2, 0), Pick(brain, hears, new Choice(2, 0), calm));
Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(3, 0), calm));
var none = new Brain { Goals = new[] { Goal("x", 1.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)) } };
Assert.Equal(new Choice(0, 77), Pick(none, hears, new Choice(0, 77), calm));
// Nothing eligible: the goal in force stays and lets go of its target.
Assert.Equal(new Choice(0, 0), Pick(none, hears, new Choice(0, 77), calm));
}
[Fact]
@ -81,10 +82,10 @@ public sealed class GoalTargetTests
var rightKind = Hearing(At(1, 1f, Thing), At(2, 3f, Other));
Assert.Equal(new Choice(1, 2), Pick(brain, rightKind, new Choice(0, 0)));
// Only targeted goals, none with a percept: the current choice stays.
// Only targeted goals, none with a percept: the goal in force stays and lets go of its target (finding stale-target-without-pair).
var only = new Brain { Goals = new[] { Goal("chase", 5.0, Kinds(Other)) } };
Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 0)));
Assert.Equal(new Choice(0, 55), Pick(only, wrongKind, new Choice(0, 55)));
Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 55)));
}
[Fact]
@ -429,4 +430,46 @@ public sealed class GoalTargetTests
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
Assert.NotEqual(0UL, a.TargetId);
}
[Fact]
public void Ticking_with_a_want_goal_allocates_nothing()
{
const int Open = 0, Locked = 1;
var fact = new Fact(FactSubject.This, Open, true);
var brain = new Brain
{
PlanDepth = 4, TargetCommitment = 1.2,
Goals = new[]
{
Goal("idle", 0.5),
Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) with { Want = fact },
Goal("other", 1.0, Kinds(Other), new[] { new Consideration(ConsiderationInput.PlanSteps, 1.0, 9.0, 1.0, 0.0) }) with { Want = fact },
},
};
var verbs = new[]
{
new Verb { Id = "Approach", Gives = new[] { new Fact(FactSubject.This, 63, true) } },
new Verb { Id = "Unlock", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, true) }, Gives = new[] { new Fact(FactSubject.This, Locked, false) } },
new Verb { Id = "Open", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, false) }, Gives = new[] { fact } },
};
var a = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, verbs: verbs);
var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
emitters[0].Facts = 1UL << Locked;
for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
var strengths = new float[2];
var targets = new Quat[2];
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++)
{
emitters[1] = At(2, 9f - (i % 8));
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters, selfFacts: (ulong)(i & 3));
}
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
Assert.NotEqual(0UL, a.TargetId);
Assert.NotEqual(0, a.PlanLength);
}
}

View file

@ -0,0 +1,542 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The want gate of Brain.Select and the plan on the Actor: a satisfied want is not offered, a planned pair is scored by its length, an unplanned one is tried direct
/// at a discount, one think budget serves a whole Select, and a Select with no pair lets go of the target.
/// </summary>
public sealed class PlannerSelectTests
{
private const uint Door = 1, Key = 2, Knife = 3, Junk = 4;
private const int Open = 0, Locked = 1, Latched = 2, Held = 3, Fed = 4;
private const int Reach = 63;
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static Fact Self(int bit, bool v = true) => new(FactSubject.Self, bit, v);
private static Fact This(int bit, bool v = true) => new(FactSubject.This, bit, v);
private static Fact Tool(int bit, bool v = true) => new(FactSubject.Tool, bit, v);
private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
// Approach (anything, no needs: a move), Unlock and Unlatch (a door, in reach), Open (a door in reach, neither locked nor latched), Grab (a knife or key in reach), Calm (a knife in reach: fed).
private static Verb[] Catalogue() => new[]
{
new Verb { Id = "Approach", Gives = new[] { This(Reach) } },
new Verb { Id = "Unlock", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Unlatch", This = Kinds(Door), Needs = new[] { This(Reach), This(Latched) }, Gives = new[] { This(Latched, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false), This(Latched, false) }, Gives = new[] { This(Open) } },
new Verb { Id = "Grab", This = Kinds(Knife, Key), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "Calm", This = Kinds(Knife), Needs = new[] { This(Reach) }, Gives = new[] { Self(Fed) } },
};
private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Fact? want = null, params Consideration[] considerations) => new()
{
Id = id, Priority = priority, Target = target, Want = want, Considerations = considerations,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
// 1 at plan length 1 falling to 0 at length 9: a longer plan is worth less, in exact eighths.
private static Consideration Shorter() => new(ConsiderationInput.PlanSteps, 1.0, 9.0, 1.0, 0.0);
private static Emitter Thing(ulong id, uint kind, float x, ulong facts = 0UL, float y = 0f, float z = 0f) =>
new(Channel.Visual, x, y, z, 100f, 1.0, id, kind, facts);
private static Perception Ears(int capacity)
{
return new Perception(new NerveParameters(), Dt, 1,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = 5.0 });
}
private static Perception See(int capacity, params Emitter[] emitters)
{
var p = Ears(capacity);
p.Sense(Zero, Zero, Zero, NoBoxes, emitters);
return p;
}
private static Actor Build(Brain brain, int capacity = 8, double memory = 5.0, IReadOnlyList<Verb>? verbs = null) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = memory }, verbs: verbs ?? Catalogue());
private static void Run(Actor a, int ticks, Emitter[] emitters, ulong selfFacts = 0UL)
{
var strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < ticks; i++)
{
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters, selfFacts: selfFacts);
}
}
private const int Settle = 40; // well past the deliberate latency (10 ticks)
// The doors: a plain one two steps away (approach, open), a locked and latched one four (approach, unlock, unlatch, open).
private static Emitter PlainDoor(ulong id, float x = 6f) => Thing(id, Door, x);
private static Emitter BoltedDoor(ulong id, float x = 6f) => Thing(id, Door, x, (1UL << Locked) | (1UL << Latched));
[Fact]
public void A_satisfied_want_is_not_offered()
{
var brain = new Brain { PlanDepth = 6, Goals = new[] { Goal("idle", 1.0), Goal("open", 5.0, Kinds(Door), This(Open)) } };
var done = Build(brain);
Run(done, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, done.GoalIndex);
Assert.Equal(0UL, done.TargetId);
Assert.Equal(0, done.PlanLength);
// Flip the door's facts: the pair is offered, planned in two steps, and wins.
var todo = Build(brain);
Run(todo, Settle, new[] { PlainDoor(1) });
Assert.Equal(1, todo.GoalIndex);
Assert.Equal(1UL, todo.TargetId);
Assert.Equal(2, todo.PlanLength);
// The same Actor, the door opened on the way: the pair is withdrawn and the goal lets go.
Run(todo, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, todo.GoalIndex);
Assert.Equal(0, todo.PlanLength);
}
[Fact]
public void A_satisfied_self_want_drops_every_pair_of_its_goal()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("calm", 5.0, Kinds(Knife), Self(Fed)) } };
var hungry = Build(brain);
Run(hungry, Settle, new[] { Thing(1, Knife, 5f), Thing(2, Knife, 3f) });
Assert.Equal(1, hungry.GoalIndex);
Assert.Equal(2, hungry.PlanLength);
var fed = Build(brain);
Run(fed, Settle, new[] { Thing(1, Knife, 5f), Thing(2, Knife, 3f) }, 1UL << Fed);
Assert.Equal(0, fed.GoalIndex);
Assert.Equal(0UL, fed.TargetId);
}
[Fact]
public void A_planned_pair_scores_by_its_length()
{
// The bolted door is first in the slots, so only its longer plan can lose it the tie.
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 4.0, Kinds(Door), This(Open), Shorter()) } };
var a = Build(brain);
Run(a, Settle, new[] { BoltedDoor(1), PlainDoor(2, 9f) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(2UL, a.TargetId);
Assert.Equal(2, a.PlanLength);
Assert.Equal(new PlanStep(0, 2, 0), a.PlanStep(0));
Assert.Equal(new PlanStep(3, 2, 0), a.PlanStep(1));
Assert.Throws<ArgumentOutOfRangeException>(() => a.PlanStep(2));
// Without the length consideration the tie goes to the lowest slot: the longer plan is not worse.
var flat = Build(new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 4.0, Kinds(Door), This(Open)) } });
Run(flat, Settle, new[] { BoltedDoor(1), PlainDoor(2, 9f) });
Assert.Equal(1UL, flat.TargetId);
Assert.Equal(4, flat.PlanLength);
Assert.Equal(new PlanStep(2, 1, 0), flat.PlanStep(1));
Assert.Equal(new PlanStep(1, 1, 0), flat.PlanStep(2));
}
[Fact]
public void Too_dim_to_plan_tries_direct_at_the_discount()
{
// The bolted door needs four steps. Direct is raw x DirectDiscount (the length factor at depth + 1 is 1 with no consideration).
Brain Make(int depth, double priority) => new()
{
PlanDepth = depth, DirectDiscount = 0.5,
Goals = new[] { Goal("idle", 1.0), Goal("open", priority, Kinds(Door), This(Open)) },
};
var tries = Build(Make(3, 3.0)); // 3 x 0.5 = 1.5 beats idle's 1
Run(tries, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, tries.GoalIndex);
Assert.Equal(1UL, tries.TargetId);
Assert.Equal(-1, tries.PlanLength);
Assert.Throws<ArgumentOutOfRangeException>(() => tries.PlanStep(0));
var gives = Build(Make(3, 1.5)); // 1.5 x 0.5 = 0.75 loses to idle
Run(gives, Settle, new[] { BoltedDoor(1) });
Assert.Equal(0, gives.GoalIndex);
Assert.Equal(0, gives.PlanLength);
var plans = Build(Make(4, 1.5)); // depth 4 finds the plan: 1.5 beats idle
Run(plans, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, plans.GoalIndex);
Assert.Equal(4, plans.PlanLength);
// The factor at depth + 1 reads the length consideration: direct at depth 3 is x(4) = 0.625 of raw, then the discount.
var curve = Build(new Brain { PlanDepth = 3, DirectDiscount = 0.5, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) } });
Run(curve, Settle, new[] { BoltedDoor(1) }); // 3 x 0.625 x 0.5 = 0.9375 < 1
Assert.Equal(0, curve.GoalIndex);
var curveWins = Build(new Brain { PlanDepth = 3, DirectDiscount = 0.5, Goals = new[] { Goal("idle", 0.9), Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) } });
Run(curveWins, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, curveWins.GoalIndex);
Assert.Equal(-1, curveWins.PlanLength);
}
[Fact]
public void Depth_zero_tries_every_unsatisfied_want_direct()
{
var brain = new Brain { PlanDepth = 0, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain);
Run(a, Settle, new[] { PlainDoor(1) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(-1, a.PlanLength);
// A satisfied want is still not offered at depth 0.
var done = Build(brain);
Run(done, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, done.GoalIndex);
// A Brain with no want selects as the public Select does at any depth, and never plans.
var free = new Brain { PlanDepth = 5, Goals = new[] { Goal("idle", 1.0), Goal("chase", 3.0, Kinds(Door)) } };
var p = See(4, PlainDoor(1));
var viaActor = Build(free);
Run(viaActor, Settle, new[] { PlainDoor(1) });
Assert.Equal(free.Select(default, p, 0f, 0f, 0f, new Choice(0, 0)), new Choice(viaActor.GoalIndex, viaActor.TargetId));
Assert.Equal(0, viaActor.PlanLength);
}
[Fact]
public void The_public_select_refuses_a_brain_with_wants()
{
var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
Assert.Throws<InvalidOperationException>(() => brain.Select(default, See(4, PlainDoor(1)), 0f, 0f, 0f, new Choice(0, 0)));
}
[Fact]
public void One_budget_serves_the_whole_select_and_is_spent_best_raw_first()
{
// One want goal on two doors at equal raw: the bolted door (slot 0, four steps) is planned first, then the plain one (two steps).
var percepts = See(4, BoltedDoor(1), PlainDoor(2, 9f));
var probe = new Planner(Catalogue(), 4, 4, 0.6);
var steps = new PlanStep[4];
Assert.Equal(4, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 0, This(Open), 4, steps));
var boltedNodes = probe.LastNodes;
Assert.Equal(2, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 1, This(Open), 4, steps));
var plainNodes = probe.LastNodes;
(Choice Pick, int Spent) Select(int budget)
{
var brain = new Brain
{
PlanDepth = 4, ThinkBudget = budget, DirectDiscount = 0.5,
Goals = new[] { Goal("idle", 1.5), Goal("open", 4.0, Kinds(Door), This(Open), Shorter()) },
};
var d = new Deliberation(brain, Catalogue(), 4);
return (brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d), d.Spent);
}
// Both plans fit: bolted 4 x 0.625 = 2.5, plain 4 x 0.875 = 3.5 wins.
Assert.Equal((new Choice(1, 2), boltedNodes + plainNodes), Select(boltedNodes + plainNodes));
// The plain plan runs one short: it goes direct (4 x 0.5 x 0.5 = 1 < idle), the planned bolted pair wins.
Assert.Equal((new Choice(1, 1), boltedNodes + plainNodes - 1), Select(boltedNodes + plainNodes - 1));
// Exactly the bolted plan: the plain pair finds the budget gone, and goes direct.
Assert.Equal((new Choice(1, 1), boltedNodes), Select(boltedNodes));
// One short of it: both go direct at 1, which loses to idle.
Assert.Equal((new Choice(0, 0), boltedNodes - 1), Select(boltedNodes - 1));
}
[Fact]
public void A_self_want_is_planned_once_for_all_its_pairs()
{
// Three knives, one budget just over one plan: every pair of the goal shares the plan found for the first.
var percepts = See(4, Thing(1, Knife, 5f), Thing(2, Knife, 3f), Thing(3, Knife, 4f));
var probe = new Planner(Catalogue(), 4, 4, 0.6);
var steps = new PlanStep[4];
Assert.Equal(2, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 0, Self(Fed), 4, steps));
var brain = new Brain { PlanDepth = 4, ThinkBudget = probe.LastNodes, Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, Kinds(Knife), Self(Fed), Shorter()) } };
var d = new Deliberation(brain, Catalogue(), 4);
// 3 x 0.875 = 2.625 for every pair, the lowest slot wins, and the budget paid for one plan, not three.
Assert.Equal(new Choice(1, 1), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d));
Assert.Equal(probe.LastNodes, d.Spent);
// The commitment breaks the tie toward the current pair.
var committed = brain with { TargetCommitment = 1.1 };
var d2 = new Deliberation(committed, Catalogue(), 4);
Assert.Equal(new Choice(1, 3), committed.Select(default, percepts, 0f, 0f, 0f, new Choice(1, 3), d2));
}
[Fact]
public void Ties_resolve_by_key_not_by_the_order_pairs_are_offered()
{
// An untargeted goal at index 2 and a want pair at index 1 tie at 2: the want pair is offered later (pass 2) and wins on the lowest goal index.
var percepts = See(4, PlainDoor(1));
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 0.5), Goal("open", 2.0, Kinds(Door), This(Open)), Goal("also", 2.0) } };
var d = new Deliberation(brain, Catalogue(), 4);
Assert.Equal(new Choice(1, 1), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d));
// The same tie with the untargeted pair current: current wins.
Assert.Equal(new Choice(2, 0), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(2, 0), d));
}
[Fact]
public void No_pair_lets_go_of_the_target()
{
// A want goal whose door stands open, and then a plain one whose door is forgotten.
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain, memory: 0.5);
Run(a, Settle, new[] { PlainDoor(1) });
Assert.Equal(1UL, a.TargetId);
Run(a, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, a.GoalIndex);
Assert.Equal(0UL, a.TargetId);
var forgetful = Build(brain, memory: 0.5);
Run(forgetful, Settle, new[] { PlainDoor(1) });
Assert.Equal(1UL, forgetful.TargetId);
Run(forgetful, 120, Array.Empty<Emitter>()); // the memory runs out, the door is gone
Assert.Equal(0, forgetful.GoalIndex);
Assert.Equal(0UL, forgetful.TargetId);
Assert.Equal(0, forgetful.PlanLength);
// The Brain-level rule: nothing offered keeps the goal in force and drops the target.
var none = See(4);
var d = new Deliberation(brain, Catalogue(), 4);
Assert.Equal(new Choice(0, 0), brain.Select(default, none, 0f, 0f, 0f, new Choice(0, 55), d));
}
[Fact]
public void The_plan_is_derived_each_tick_from_the_percepts()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain);
Run(a, Settle, new[] { BoltedDoor(1) });
Assert.Equal(4, a.PlanLength);
// The door is sensed unlocked next tick: the plan shortens at once, without a new decision.
Run(a, 1, new[] { PlainDoor(1) });
Assert.Equal(2, a.PlanLength);
Run(a, 1, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, a.PlanLength);
}
[Fact]
public void Self_facts_reach_the_planner_and_bit_63_is_refused()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, Kinds(Knife), Self(Fed)) } };
var a = Build(brain);
var strengths = new float[2];
var targets = new Quat[2];
Assert.Throws<ArgumentException>(() => a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, selfFacts: 1UL << 63));
Assert.Equal(0L, a.TickCount);
Run(a, Settle, new[] { Thing(1, Knife, 5f) }, 1UL << Fed);
Assert.Equal(0, a.GoalIndex);
}
[Fact]
public void Validation_refuses_bad_wants_and_fields()
{
static Actor Make(Brain b) => Build(b);
void Refuses(Brain b) => Assert.Throws<ArgumentException>(() => Make(b));
Brain With(params GoalSpec[] goals) => new() { PlanDepth = 2, Goals = goals };
Make(With(Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)))); // the baseline is fine
Refuses(With(Goal("a", 1.0, Kinds(Door), Tool(Open)))); // Tool refused
Refuses(With(Goal("a", 1.0, null, This(Open)))); // This needs a Target
Refuses(With(Goal("a", 1.0, null, Self(Reach)))); // a Self want is not on bit 63
Refuses(With(Goal("a", 1.0, Kinds(Door), new Fact(FactSubject.This, 64, true)))); // bit out of range
Refuses(With(Goal("a", -1.0, Kinds(Door), This(Open)))); // a want goal's Priority >= 0
Refuses(With(Goal("a", 1.0, Kinds(Door), null, Shorter()))); // PlanSteps only on want goals
Make(With(Goal("a", 1.0, null, Self(Fed), Shorter()))); // ... and a Self want needs no target
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { PlanDepth = 9 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { PlanDepth = -1 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { DirectDiscount = 1.5 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { DirectDiscount = double.NaN });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ThinkBudget = 0 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ReachMeters = 0.0 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ReachMeters = double.PositiveInfinity });
// A want needs percepts to plan over.
Assert.Throws<ArgumentException>(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), With(Goal("a", 1.0, null, Self(Fed)))));
}
// ----- reference: every pair planned on its own, the original index-order tournament
private static Choice Reference(Brain brain, Perception p, Planner planner, ulong selfFacts, Choice current)
{
var buf = new PlanStep[Math.Max(1, brain.PlanDepth)];
var best = default(Choice);
var bestScore = 0.0;
var bestIsCurrent = false;
var found = false;
for (var g = 0; g < brain.Goals.Count; g++)
{
var goal = brain.Goals[g];
if (goal.Target is null)
{
Consider(g, goal, -1, 0UL, goal.Score(default, default, 0f, 0f, 0f));
continue;
}
for (var s = 0; s < p.PerceptCount; s++)
{
var pc = p.Percept(s);
if (pc.Id != 0UL && goal.Target.Accepts(pc.Kind))
{
Consider(g, goal, s, pc.Id, goal.Score(default, pc, 0f, 0f, 0f));
}
}
}
return found ? best : new Choice(current.Goal, 0UL);
void Consider(int g, GoalSpec goal, int slot, ulong target, double raw)
{
var isCurrent = g == current.Goal && target == current.Target;
if (isCurrent)
{
raw *= brain.TargetCommitment;
}
if (goal.Want is { } want)
{
var n = planner.Plan(p, selfFacts, 0f, 0f, 0f, want.Subject == FactSubject.Self ? 0 : slot, want, brain.PlanDepth, buf);
if (n == 0)
{
return;
}
raw *= n > 0 ? goal.PlanFactor(n) : goal.PlanFactor(brain.PlanDepth + 1) * brain.DirectDiscount;
}
if (!found || raw > bestScore || (raw == bestScore && isCurrent && !bestIsCurrent))
{
best = new Choice(g, target);
bestScore = raw;
bestIsCurrent = isCurrent;
found = true;
}
}
}
[Fact]
public void Ordered_selection_equals_the_exhaustive_reference()
{
var rng = new Random(20261126);
var wantChosen = 0;
var depthsSeen = new HashSet<int>();
for (var w = 0; w < 300; w++)
{
const int Slots = 16;
var emitters = new List<Emitter>();
var things = 5 + rng.Next(12);
for (var i = 0; i < things; i++)
{
var kind = (uint)(1 + rng.Next(4));
var facts = (ulong)rng.Next(8) << 1; // bits 1..3: locked, latched, held, never Open
var x = new[] { 0.3f, 0.5f, 1.0f, 2.0f, 5.0f }[rng.Next(5)];
emitters.Add(Thing((ulong)(10 + i), kind, x, facts, y: new[] { 0f, 0.4f, 3f }[rng.Next(3)]));
}
var percepts = See(Slots, emitters.ToArray());
var priorities = new[] { 1.0, 2.0, 3.0, 4.0 };
var goals = new List<GoalSpec>
{
Goal("idle", priorities[rng.Next(4)]),
Goal("open", priorities[rng.Next(4)], Kinds(Door), This(Open), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("grab", priorities[rng.Next(4)], Kinds(Knife, Key), This(Held), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("calm", priorities[rng.Next(4)], Kinds(Knife), Self(Fed), Shorter()),
Goal("rest", priorities[rng.Next(4)], null, Self(Fed), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("junk", priorities[rng.Next(4)], Kinds(Junk)),
};
var depth = rng.Next(6);
depthsSeen.Add(depth);
var brain = new Brain
{
Goals = goals, PlanDepth = depth, ThinkBudget = int.MaxValue, DirectDiscount = new[] { 0.25, 0.5, 0.75 }[rng.Next(3)],
TargetCommitment = new[] { 1.0, 1.25 }[rng.Next(2)], ReachMeters = 1.0,
};
var selfFacts = rng.Next(4) == 0 ? 1UL << Fed : 0UL;
var cur = new Choice(rng.Next(goals.Count), rng.Next(3) == 0 ? (ulong)(10 + rng.Next(things)) : 0UL);
var d = new Deliberation(brain, Catalogue(), Slots) { SelfFacts = selfFacts };
var planner = new Planner(Catalogue(), Slots, depth, 1.0);
var expected = Reference(brain, percepts, planner, selfFacts, cur);
var actual = brain.Select(default, percepts, 0f, 0f, 0f, cur, d);
Assert.True(expected == actual, $"world {w} depth {depth}: reference {expected}, select {actual}");
if (brain.Goals[actual.Goal].Want is not null)
{
wantChosen++;
}
}
Assert.True(wantChosen > 100 && depthsSeen.Count == 6, $"the worlds are too one-sided: {wantChosen} want pairs chosen, depths {depthsSeen.Count}");
}
// ----- the crowded room: how often a bounded budget changes the decision
private static (Perception Percepts, Verb[] Verbs) Crowd(Random rng, int things)
{
const uint Strap = 5, Switch = 6;
var emitters = new List<Emitter> { Thing(1, Strap, 0.3f), Thing(2, Knife, 0.5f) };
for (var i = 2; i < things; i++)
{
// Knives, keys, doors (70% locked), switches and four junk kinds, all within 12 m.
var pick = rng.Next(100);
var kind = pick switch { < 6 => Knife, < 12 => Key, < 20 => Door, < 26 => Switch, _ => (uint)(10 + rng.Next(4)) };
var facts = kind == Door && rng.Next(10) < 7 ? 1UL << Locked : 0UL;
emitters.Add(Thing((ulong)(1 + i), kind, (float)(rng.NextDouble() * 12.0), facts, (float)(rng.NextDouble() * 6.0 - 3.0)));
}
var verbs = new[]
{
new Verb { Id = "Approach", Needs = new[] { Self(Fed) }, Gives = new[] { This(Reach) } },
new Verb { Id = "Grab", This = Kinds(Knife, Key), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "Cut", This = Kinds(Strap), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { Self(Fed), This(Open) } },
new Verb { Id = "Pry", This = Kinds(Strap), Tool = Kinds(Door), Needs = new[] { Tool(Reach), This(Reach) }, Gives = new[] { Self(Fed), This(Open) } },
new Verb { Id = "Switch", This = Kinds(Switch), Needs = new[] { This(Reach) }, Gives = new[] { This(Open) } },
new Verb { Id = "Unlock", This = Kinds(Door), Tool = Kinds(Key), Needs = new[] { Tool(Held), This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false) }, Gives = new[] { This(Open) } },
new Verb { Id = "Fiddle", This = Kinds(10, 11), Needs = new[] { This(Reach) }, Gives = new[] { This(Latched) } },
new Verb { Id = "Stack", This = Kinds(12, 13), Tool = Kinds(10, 11), Needs = new[] { Tool(Latched), This(Reach) }, Gives = new[] { This(Latched) } },
};
var p = See(things, emitters.ToArray());
return (p, verbs);
}
private static Brain Crowded(int depth, int budget) => new()
{
PlanDepth = depth, ThinkBudget = budget, DirectDiscount = 0.5, ReachMeters = 1.0, TargetCommitment = 1.1,
Goals = new[]
{
Goal("idle", 0.5),
Goal("free", 2.0, Kinds(5), This(Open), Shorter()),
Goal("door", 3.0, Kinds(Door), This(Open), Shorter()),
Goal("switch", 2.5, Kinds(6), This(Open), Shorter()),
Goal("knife", 1.5, Kinds(Knife), This(Held), Shorter()),
},
};
private static int Differing(int things, int depth, int seeds)
{
var differ = 0;
for (var seed = 0; seed < seeds; seed++)
{
var rng = new Random(seed);
var (p, verbs) = Crowd(rng, things);
var bounded = Crowded(depth, Planner.NodeBudget);
var unbounded = Crowded(depth, int.MaxValue);
var cur = new Choice(0, 0);
var db = new Deliberation(bounded, verbs, things);
var du = new Deliberation(unbounded, verbs, things);
var a = bounded.Select(default, p, 0f, 0f, 0f, cur, db);
var b = unbounded.Select(default, p, 0f, 0f, 0f, cur, du);
if (a != b)
{
differ++;
}
}
return differ;
}
[Fact]
public void A_crowded_room_changes_few_decisions()
{
Assert.Equal(0, Differing(48, 4, 100));
Assert.Equal(CrowdedDepth6Differing, Differing(48, 6, 100));
}
private const int CrowdedDepth6Differing = 59;
}