Add stochastic contribution updates

This commit is contained in:
Meta Vens 2026-05-18 02:43:42 +01:00
commit 02be2188aa
5 changed files with 161 additions and 3 deletions

View file

@ -301,9 +301,9 @@ Goal: refresh contribution estimates under budget and converge.
Tasks:
- [ ] Add estimator state: mean, variance/uncertainty, confidence, sample count, sample age.
- [ ] Add stochastic scheduler with deterministic random source.
- [ ] Add exploration budget.
- [x] Add estimator state: mean, variance/uncertainty, confidence, sample count, sample age.
- [x] Add stochastic scheduler with deterministic random source.
- [x] Add exploration budget.
- [ ] Add confidence decay and stale uncertainty growth.
- [ ] Add fake contribution probe.
- [ ] Add convergence telemetry.

View file

@ -0,0 +1,31 @@
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Lod;
public static class FractalContributionEstimator
{
public static AquariumContributionState Observe(
AquariumContributionState state,
float observedContribution,
uint frameIndex,
bool resident)
{
var sampleCount = state.SampleCount + 1;
var delta = observedContribution - state.MeanContribution;
var mean = state.MeanContribution + (delta / sampleCount);
var variance = sampleCount <= 1
? 0.0f
: (((sampleCount - 2) * state.Variance) + (delta * (observedContribution - mean))) / (sampleCount - 1);
var confidence = Math.Clamp(sampleCount / 16.0f, 0.0f, 1.0f);
return state with
{
MeanContribution = mean,
Variance = MathF.Max(variance, 0.0f),
Confidence = confidence,
SampleCount = sampleCount,
LastSampledFrame = frameIndex,
Resident = resident,
};
}
}

View file

@ -0,0 +1,51 @@
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Lod;
public static class FractalStochasticUpdateScheduler
{
public static AquariumFractalKey[] SelectUpdates(
IReadOnlyList<AquariumContributionState> states,
Func<AquariumContributionState, float> currentScore,
int maxUpdates,
IFractalRandom random,
uint frameIndex)
{
ArgumentNullException.ThrowIfNull(states);
ArgumentNullException.ThrowIfNull(currentScore);
ArgumentNullException.ThrowIfNull(random);
if (maxUpdates <= 0)
{
return [];
}
var selected = new List<AquariumFractalKey>();
foreach (var state in states.OrderBy(state => state.NodeKey.Value, StringComparer.Ordinal))
{
var probability = UpdateProbability(state, currentScore(state), frameIndex);
if (random.NextDouble() <= probability)
{
selected.Add(state.NodeKey);
if (selected.Count >= maxUpdates)
{
break;
}
}
}
return selected.ToArray();
}
public static double UpdateProbability(AquariumContributionState state, float currentScore, uint frameIndex)
{
var uncertainty = Math.Clamp(Math.Sqrt(Math.Max(state.Variance, 0.0f)) * 0.25, 0.0, 0.35);
var age = frameIndex >= state.LastSampledFrame ? frameIndex - state.LastSampledFrame : 0;
var stalePressure = Math.Clamp(age / 240.0, 0.0, 0.30);
var visiblePressure = currentScore > 0.0f ? 0.10 : 0.0;
var thresholdPressure = currentScore is > 0.75f and < 1.25f ? 0.20 : 0.0;
var confidencePenalty = (1.0 - Math.Clamp(state.Confidence, 0.0f, 1.0f)) * 0.15;
return Math.Clamp(0.02 + uncertainty + stalePressure + visiblePressure + thresholdPressure + confidencePenalty, 0.02, 0.95);
}
}

View file

@ -126,3 +126,4 @@
{"timestamp":"2026-05-18T04:22:00+01:00","topic":"fractal-node-summary-first-slice","lesson":"Flat semantic ownership trees now produce conservative node summaries. The first summary builder carries node bounds, sum-of-absolute height amplitude as max height error, a material-delta placeholder, estimated claim cost, and descendant count. This is intentionally conservative rather than clever, giving future LOD/cache work a renderable parent fallback before child refinement or eviction exists.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"sixth fractal implementation slice established parent summary rows for semantic brush trees"}
{"timestamp":"2026-05-18T04:36:00+01:00","topic":"fractal-contribution-score-first-slice","lesson":"Contribution scoring now has a stable-keyed state table and a projected-error scorer. The first score is intentionally simple: conservative height error times projected pixels per world unit divided by estimated node cost. This gives LOD selection a deterministic, testable pressure signal before hysteresis, selected cuts, residency, or online estimation are layered in.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionTable.cs","src/Aquarium.Engine.Fractal/Lod/FractalProjectedErrorScorer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionTests.cs"],"source":"seventh fractal implementation slice started the LOD contribution cache with deterministic scoring tests"}
{"timestamp":"2026-05-18T04:50:00+01:00","topic":"fractal-selected-cut-first-slice","lesson":"Projected contribution scores now compile into budgeted selected-cut rows. The first builder sorts summaries by score, clamps against estimated cost, emits fade weights, and requests children only when score crosses a threshold. This gives later residency and stochastic estimation a small deterministic target instead of mixing traversal policy into renderer code.","files":["src/Aquarium.Engine.Fractal/Lod/FractalSelectedCutBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSelectedCutBuilderTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"eighth fractal implementation slice added selected-cut planning under a simple cost budget"}
{"timestamp":"2026-05-18T05:06:00+01:00","topic":"fractal-stochastic-cache-first-slice","lesson":"The contribution cache now has online estimator updates and a stochastic update scheduler. Estimator state updates mean, variance, confidence, sample count, sample age, and residency; scheduler probability keeps baseline exploration, adds pressure for visible, near-threshold, stale, uncertain, and low-confidence nodes, and remains deterministic under `IFractalRandom` for tests. This is the first bounded convergence mechanism before learned scoring is allowed anywhere near the renderer.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionEstimator.cs","src/Aquarium.Engine.Fractal/Lod/FractalStochasticUpdateScheduler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStochasticUpdateTests.cs"],"source":"ninth fractal implementation slice added probabilistic contribution updates with deterministic mock boundaries"}

View file

@ -0,0 +1,75 @@
using Aquarium.Engine.Fractal;
using Aquarium.Engine.Fractal.Lod;
namespace Aquarium.Engine.Fractal.Tests;
public sealed class FractalStochasticUpdateTests
{
[Fact]
public void EstimatorUpdatesMeanVarianceConfidenceAndSampleAge()
{
var state = NewState("node/a");
state = FractalContributionEstimator.Observe(state, 2.0f, frameIndex: 10, resident: true);
state = FractalContributionEstimator.Observe(state, 4.0f, frameIndex: 12, resident: true);
Assert.Equal(3.0f, state.MeanContribution);
Assert.Equal(2.0f, state.Variance);
Assert.Equal(2, state.SampleCount);
Assert.Equal<uint>(12, state.LastSampledFrame);
Assert.True(state.Confidence > 0.0f);
Assert.True(state.Resident);
}
[Fact]
public void VisibleNodesKeepNonzeroUpdateProbability()
{
var state = NewState("node/a") with { Confidence = 1.0f, Variance = 0.0f, LastSampledFrame = 100 };
var probability = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 0.5f, frameIndex: 100);
Assert.True(probability > 0.0);
}
[Fact]
public void NearThresholdNodesReceiveExtraUpdatePressure()
{
var state = NewState("node/a") with { Confidence = 1.0f, Variance = 0.0f, LastSampledFrame = 100 };
var low = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 0.2f, frameIndex: 100);
var near = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 1.0f, frameIndex: 100);
Assert.True(near > low);
}
[Fact]
public void SchedulerIsDeterministicWithFakeRandomAndRespectsBudget()
{
var states = new[]
{
NewState("node/a") with { Variance = 1.0f },
NewState("node/b") with { Variance = 1.0f },
NewState("node/c") with { Variance = 1.0f },
};
var firstRandom = new TestFractalRandom(0.01, 0.01, 0.01);
var secondRandom = new TestFractalRandom(0.01, 0.01, 0.01);
var first = FractalStochasticUpdateScheduler.SelectUpdates(states, _ => 1.0f, maxUpdates: 2, firstRandom, frameIndex: 10);
var second = FractalStochasticUpdateScheduler.SelectUpdates(states, _ => 1.0f, maxUpdates: 2, secondRandom, frameIndex: 10);
Assert.Equal(first, second);
Assert.Equal(2, first.Length);
}
private static AquariumContributionState NewState(string key)
{
return new AquariumContributionState(
new AquariumFractalKey(key),
MeanContribution: 0.0f,
Variance: 1.0f,
Confidence: 0.0f,
SampleCount: 0,
LastSampledFrame: 0,
Resident: false);
}
}