3 · The gradient
The "hello world" of aggregate computing: every device works out its distance from the nearest source, and nobody knows the whole network.
Shared state: share
share(initial, (n) => ...) combines rep and nbr: like rep it remembers a value across rounds, and it also shares it with the neighbours. The function gets n, the field of the neighbours' latest values, and returns the device's new value.
A gradient in hops is a local rule: "if I am a source I am 0, otherwise 1 more than my closest neighbour".
Press Reset and watch the information travel one hop per round. A node with no neighbours stays at ∞: the minimum of an empty field is Infinity.
Real distances
Adding the distance to each neighbour (nbrSense('range')) to its value gives a distance in metres instead of hops. Wrapped in a function, it becomes a reusable block.
Try adding a second source, moving nodes, then removing a source. When distances shrink the network adapts quickly; when they must grow, they climb slowly, a little per round. This is the known rising value problem: nodes bounce stale values off each other. More robust gradients exist (BIS, SVD, ULT), built from the same pieces.
share and not rep + nbr? The classic field calculus gradient uses rep and nbr, but then every value waits one extra round before reaching the neighbours. share, which comes with XC, shares the result at once: the gradient converges about twice as fast.Try it
1. Write the rep + nbr version and compare how fast it converges after a Reset.
2. A "zone": true for the nodes within 2 hops of a source.
Solutions
var program = () => rep(Infinity, (d) => {
var m = nbr(d).min() + 1; // outside the ternary: everyone runs it, the source too
return sense('source') ? 0 : m;
});
var hops = (src) => share(Infinity, (d) => src ? 0 : d.min() + 1);
var program = () => hops(sense('source')) <= 2;
In the first one, nbr has to stay outside the ternary. Inside it, only the non-source nodes would run it, and the source would never share its 0: chapter 5 explains why.