Im trying to make a game where the user places like 100 dots on a grid, and 4 apples try to move so that they are each closest to as many dots as possible. Im using gradient descent. Is there like a continuous loss function for each apple that can reference both like distance from dots and other apples so that each apple tries to cover the most ground possible. This should lead to them each getting 25 apples, but I want them to be competing
I was thinking of like the loss for each apple being the mean distance from every dot weighted by their distance from their nearest apple (not including the apple being measured), but this led them all to going to the center at larger numbers of dots. I don't want to have to balance different losses. I want them to converge automatically
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a fantastic problem that perfectly lends itself to gradient descent and has a beautiful analogue in statistical clustering (like soft K-means or Gaussian Mixture Models). The key is to define a "soft" version of ownership that is continuous and differentiable, and then have each apple try to maximize its share of that ownership.
Your previous attempt failed because the "repulsion" term (weighted by distance from nearest apple) was probably fighting against the attraction term in an unintended way. When apples went to the center, they became close, making the weight large, which increased the "mean distance" term for all apples, possibly making them try to escape, but then they'd be pulled back to the dot centroid.
Let's think about what "closest to as many dots as possible" means in a continuous sense. For any given dot, we can calculate how "likely" each apple is to be its "owner" based on proximity.
The Proposed Loss Function: Soft Ownership / Competitive Influence
For each dot Dk, we can define the "influence" or "attraction strength" of each apple Aj on that dot. A common way to do this in a differentiable manner is using an exponential function of the negative squared distance.
Let Aj=(xj,yj) be the position of apple , and be the position of dot .
The squared Euclidean distance is .
Influence Score: For each apple Aj and dot Dk, define an influence score S:
Where is a positive hyperparameter (e.g., 0.1 to 1.0). A larger makes the ownership assignment "sharper" (more like a true nearest neighbor). A smaller makes it "softer" (apples influence dots further away).
Implementation Steps:
Define Grid and Dots:
Set up your grid dimensions (e.g., 0 to 100 on x and y).
Generate 100 random dot positions on this grid. Store them as an array of (x,y) coordinates.
Initialize Apples:
Randomly initialize the positions of your 4 apples. This is crucial to break symmetry and prevent them all from converging to the exact same spot (e.g., the center of all dots).
Choose Hyperparameters:
N_dots = 100
N_apples = 4
beta: Start with something like 0.1 or 0.5. You might need to tune this. If apples clump, decrease it slightly. If they oscillate too much, increase it slightly or reduce the learning rate.
learning_rate: Standard for gradient descent (e.g., 0.01 to 0.1).
iterations: Number of gradient descent steps.
Gradient Descent Loop:
For each iteration:
a. Calculate Gradients: For each apple A:
* You'll need to compute the gradient of with respect to 's coordinates ().
* This requires calculus (chain rule). Libraries like TensorFlow or PyTorch can do this automatically via automatic differentiation if you implement the loss function using their tensor operations. If you're doing it from scratch in a language like Python/JS, you'd need to derive the partial derivatives.
Example (Conceptual Python/Numpy or PyTorch/TensorFlow)
python
Important Note on Gradient Calculation: The calculate_loss_and_ownership function I provided is for calculating the value of the loss. For gradient descent, you need the derivatives of this loss with respect to apples_pos. Manually deriving these can be complex. This is where automatic differentiation libraries (like PyTorch or TensorFlow) shine. You'd simply implement the loss function using their tensor operations, and then call loss.backward() to get the gradients automatically.
If you are building this in a web game (JavaScript/HTML5 Canvas):
You would manually implement the calculate_loss_and_ownership function and then need to derive the partial derivatives for dL_i/dx_i and dL_i/dy_i. This is feasible but requires careful calculus. Alternatively, look for JS libraries that offer automatic differentiation if performance is critical (e.g., tfjs for TensorFlow.js).
This approach provides a single, continuous loss function for each apple that naturally encourages them to spread out and claim distinct territories, leading to the desired competitive behavior.
User
Okay. Can you make a single html file with tf.js that demonstrates that with 100(adjustable) random dots and 4(adjustable) random apples
Assistant
Okay, this is a fantastic project for TF.js! It handles the automatic differentiation beautifully, making the complex gradient calculations (which would be a nightmare to do manually) trivial.
Here's a single HTML file that demonstrates this.
Key features:
HTML Structure: Simple setup with a canvas for drawing, and input fields for configuration.
TF.js Integration: Uses tf.variable for apple positions and tf.tensor2d for dots.
Loss Function Implementation: Directly translates the mathematical formula into TF.js tensor operations.
Automatic Differentiation: Uses optimizer.minimize() with a tf.tidy() block to automatically compute and apply gradients while managing memory.
Real-time Visualization: Draws dots and apples, coloring dots based on which apple has the highest "soft ownership" probability for that dot.
User Controls: Adjustable number of dots, apples, learning rate, and beta (sharpness) parameter.
html
j
Dk=(xk,yk)
k
dist(Aj,Dk)2=(xj−xk)2+(yj−yk)2
jk
Sjk=e−β⋅dist(Aj,Dk)2
β
β
β
Soft Ownership Probability: For each dot Dk, normalize the influence scores across all apples to get a "soft ownership probability" for apple Ai over dot Dk:
SoftOwnership
Notice that for each dot Dk, ∑j=1NapplesP. This Pik represents the "share" of dot k that apple Ai claims.
Loss Function for Apple Ai: Each apple wants to maximize its total soft ownership across all dots. So, the loss for apple Ai will be the negative sum of its soft ownership probabilities:
Li(Ai,Aothers)=−∑k
Why this works:
Attraction to dots: If apple Ai moves closer to a dot Dk, decreases, which increases , which in turn increases . This reduces . So, is incentivized to move closer to dots.
i
Li
Ai
xi,yi
code
*(Self-correction: Deriving the gradients manually can be tedious. Using a library with auto-diff is highly recommended for this type of problem.)*
Let's outline the conceptual gradient calculation for $A_i = (x_i, y_i)$:
$\frac{\partial L_i}{\partial x_i} = -\sum_{k=1}^{N_{dots}} \frac{\partial P_{ik}}{\partial x_i}$
And similarly for $\frac{\partial L_i}{\partial y_i}$.
The $\frac{\partial P_{ik}}{\partial x_i}$ term will involve the derivative of the numerator and the denominator, and will depend on $x_i$ and $x_k$, and implicitly on all other $x_j$ via the denominator.
b. Update Apple Positions:Ainew=Aiold−learning_rate⋅∇AiLi
(i.e., xinew=xio and similar for yi)
c. Optional: Constraint Positions: If your grid has boundaries, you might want to clip apple positions so they don't go outside the grid.
Visualization:
Plot the dots.
Plot the apples.
To visualize the "territories," you could iterate through the dots and color-code each dot based on which apple has the highest Pik for that dot. As the apples move, these regions will change.
import numpy as np
# For auto-differentiation, you'd use a framework like PyTorch or TensorFlow
# import torch
# from torch.autograd import grad
# --- Configuration ---
N_dots = 100
N_apples = 4
GRID_SIZE = 100 # e.g., 0 to 100 for x and y
BETA = 0.5 # Hyperparameter for sharpness of ownership
LEARNING_RATE = 0.05
ITERATIONS = 500
# --- 1. Define Grid and Dots ---
np.random.seed(42) # for reproducibility
dots = np.random.rand(N_dots, 2) * GRID_SIZE # (N_dots, 2) array
# --- 2. Initialize Apples ---
apples = np.random.rand(N_apples, 2) * GRID_SIZE # (N_apples, 2) array
# If using PyTorch:
# apples_tensor = torch.tensor(apples, requires_grad=True, dtype=torch.float32)
# dots_tensor = torch.tensor(dots, dtype=torch.float32)
# --- Loss Function (Conceptual, without auto-diff) ---
def calculate_loss_and_ownership(apples_pos, dots_pos, beta):
num_apples = apples_pos.shape[0]
num_dots = dots_pos.shape[0]
# Calculate squared distances for all (apple, dot) pairs
# distances_sq[i, k] = dist(apple_i, dot_k)^2
# Using broadcasting:
# (N_apples, 1, 2) - (1, N_dots, 2) -> (N_apples, N_dots, 2) -> sum over last dim
diffs = apples_pos[:, np.newaxis, :] - dots_pos[np.newaxis, :, :]
distances_sq = np.sum(diffs**2, axis=-1) # (N_apples, N_dots)
# Calculate influence scores S_jk
influence_scores = np.exp(-beta * distances_sq) # (N_apples, N_dots)
# Calculate SoftOwnership P_ik
# sum_j_S_jk is the sum of influence scores for each dot k, over all apples j
sum_j_S_jk = np.sum(influence_scores, axis=0) # (N_dots,)
# P_ik = S_ik / sum_j_S_jk
# We need to divide influence_scores (N_apples, N_dots) by sum_j_S_jk (N_dots,)
# np.newaxis makes sum_j_S_jk broadcastable to (1, N_dots) then to (N_apples, N_dots)
soft_ownership_probs = influence_scores / (sum_j_S_jk[np.newaxis, :] + 1e-8) # Add small epsilon to avoid division by zero
# Calculate individual loss for each apple
# Loss_i = - sum_k P_ik
losses = -np.sum(soft_ownership_probs, axis=1) # (N_apples,)
return losses, soft_ownership_probs
# --- Gradient Descent (Conceptual) ---
for iteration in range(ITERATIONS):
# In a real setup, apples would be torch.tensor with requires_grad=True
# and you'd use loss.backward() and optimizer.step()
# Here, we're just simulating the concept.
# Calculate losses and probabilities for current apple positions
current_losses, current_probs = calculate_loss_and_ownership(apples, dots, BETA)
# For auto-diff frameworks:
# If using PyTorch:
# total_loss = current_losses.sum() # Sum all apple losses for backward pass
# total_loss.backward() # This computes gradients for apples_tensor.grad
# with torch.no_grad():
# apples_tensor -= LEARNING_RATE * apples_tensor.grad
# apples_tensor.grad.zero_() # Reset gradients for next iteration
# apples = apples_tensor.numpy()
# For manual gradient (much more complex and error-prone for this formula):
# You'd need to derive dL_i/dx_i and dL_i/dy_i for each apple.
# This involves partial derivatives of exp(), sums, and divisions.
# It's highly recommended to use a library for this.
# Placeholder for gradient computation (REPLACE WITH REAL AUTO-DIFF)
# This is just a conceptual step to show where gradients would be used.
# Let's pretend we have a `compute_gradients` function
# that returns `gradients` (N_apples, 2)
# A simple, but often wrong, approximation for demonstration:
gradients = np.zeros_like(apples)
# In reality, this is where the magic of auto-diff happens.
# For example, to make a small change and observe the loss change:
# for i in range(N_apples):
# original_pos = apples[i].copy()
# # Perturb x
# apples[i, 0] += 0.001
# new_loss_x, _ = calculate_loss_and_ownership(apples, dots, BETA)
# gradients[i, 0] = (new_loss_x[i] - current_losses[i]) / 0.001
# apples[i, 0] = original_pos[0] # Reset
#
# # Perturb y
# apples[i, 1] += 0.001
# new_loss_y, _ = calculate_loss_and_ownership(apples, dots, BETA)
# gradients[i, 1] = (new_loss_y[i] - current_losses[i]) / 0.001
# apples[i, 1] = original_pos[1] # Reset
# UPDATE: A simplified, but still not perfectly accurate,
# way to think about the gradient for understanding without auto-diff:
# Each apple moves towards the weighted average of the dots,
# where the weights are its soft ownership probabilities.
# This is conceptually like K-means, but the "ownership" itself is dynamic.
# This is a simplification; the true gradient is more complex due to the denominator.
# However, it often leads to similar behavior for this specific loss.
# Simplified update rule (closer to Soft K-Means, not strictly dL/dA for L_i)
# Each apple moves towards the "center of mass" of the dots it mostly owns.
# This is actually the gradient for a different loss function: sum_k P_ik * dist(A_i, D_k)^2
# But it often provides good intuition and can serve as a starting point.
# For the *actual* loss defined, the gradient calculation is more involved.
# For this game, it might be that a slightly different loss is also good:
# L_i = sum_k P_ik * dist(A_i, D_k)^2 -- this *is* the soft k-means loss
# Let's stick to the originally proposed L_i = -sum(P_ik) for now and rely on auto-diff for implementation.
# If you're using Python for a real game, you must use a library like PyTorch or TensorFlow for auto-diff.
# Conceptual update step if you had gradients:
# apples -= LEARNING_RATE * gradients # Where `gradients` come from auto-diff
# For demonstration purposes, if you cannot use auto-diff,
# you might try a very crude approximation or simpler update:
# This is NOT gradient descent on the specified loss, but a heuristic:
for i in range(N_apples):
# Calculate the weighted average of dots for apple i
# This is a heuristic to move the apple towards its "assigned" dots
# This is what a soft K-Means objective minimizes for each centroid
weighted_dots_sum = np.sum(dots * current_probs[i][:, np.newaxis], axis=0)
sum_of_weights = np.sum(current_probs[i])
if sum_of_weights > 1e-8: # Avoid division by zero
target_pos = weighted_dots_sum / sum_of_weights
apples[i] = apples[i] - LEARNING_RATE * (apples[i] - target_pos) # Move towards target
# Clip positions to stay within grid
apples = np.clip(apples, 0, GRID_SIZE)
# --- Visualization (e.g., plot using matplotlib) ---
if iteration % 50 == 0 or iteration == ITERATIONS - 1:
print(f"Iteration {iteration}, Losses: {current_losses}")
# import matplotlib.pyplot as plt
# plt.figure(figsize=(8,8))
# plt.scatter(dots[:,0], dots[:,1], s=10, c='gray', label='Dots')
# plt.scatter(apples[:,0], apples[:,1], s=100, c=['red', 'green', 'blue', 'purple'], marker='o', edgecolors='black', label='Apples')
#
# # Visualize territories (optional)
# for k in range(N_dots):
# owning_apple_idx = np.argmax(current_probs[:, k])
# plt.scatter(dots[k,0], dots[k,1], s=10,
# color=['red', 'green', 'blue', 'purple'][owning_apple_idx])
#
# plt.title(f"Iteration {iteration}")
# plt.xlim(0, GRID_SIZE)
# plt.ylim(0, GRID_SIZE)
# plt.legend()
# plt.grid(True)
# plt.show()
print("\nFinal Apple Positions:")
print(apples)
final_losses, final_probs = calculate_loss_and_ownership(apples, dots, BETA)
print("Final Losses:", final_losses)
# Calculate final dot counts per apple (hard assignment)
final_dot_assignments = np.argmax(final_probs, axis=0) # For each dot, which apple has max P_ik
unique_assignments, counts = np.unique(final_dot_assignments, return_counts=True)
dot_counts_per_apple = dict(zip(unique_assignments, counts))
print("Final Dot Counts per Apple (hard assignment):")
for i in range(N_apples):
print(f"Apple {i}: {dot_counts_per_apple.get(i, 0)} dots")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apple Territories Game (TF.js Gradient Descent)</title>
<!-- Include TensorFlow.js library -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
margin: 20px;
}
h1 {
color: #333;
}
#controls {
margin-bottom: 20px;
padding: 15px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px 20px;
}
#controls label {
display: flex;
align-items: center;
gap: 8px;
font-weight: bold;
color: #555;
}
#controls input[type="number"] {
width: 80px;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
#controls button {
grid-column: 1 / span 2;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#controls button:hover {
background-color: #45a049;
}
#controls button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
canvas {
border: 2px solid #333;
background-color: #fff;
box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}
#status {
margin-top: 10px;
font-size: 1.1em;
color: #666;
}
.apple-info {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
}
.apple-color-box {
width: 20px;
height: 20px;
border: 1px solid #333;
}
.apple-colors-legend {
display: flex;
flex-wrap: wrap;
gap: 15px;
margin-top: 15px;
padding: 10px;
background-color: #eee;
border-radius: 5px;
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<h1>Apple Territories Game</h1>
<div id="controls">
<label>Number of Dots: <input type="number" id="numDots" value="100" min="10" max="500"></label>
<label>Number of Apples: <input type="number" id="numApples" value="4" min="2" max="10"></label>
<label>Learning Rate: <input type="number" id="learningRate" value="0.05" step="0.005" min="0.001" max="0.5"></label>
<label>Beta (Sharpness): <input type="number" id="beta" value="0.5" step="0.05" min="0.1" max="5.0"></label>
<button id="startButton">Start Simulation</button>
<button id="stopButton" disabled>Stop Simulation</button>
<button id="resetButton">Reset Simulation</button>
</div>
<canvas id="gameCanvas" width="600" height="600"></canvas>
<div id="status">Simulation ready. Click 'Start Simulation'.</div>
<div class="apple-colors-legend">
<div class="apple-info"><span class="apple-color-box" style="background-color: red;"></span> Apple 0</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: green;"></span> Apple 1</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: blue;"></span> Apple 2</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: purple;"></span> Apple 3</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: orange;"></span> Apple 4</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: teal;"></span> Apple 5</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: magenta;"></span> Apple 6</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: brown;"></span> Apple 7</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: limegreen;"></span> Apple 8</div>
<div class="apple-info"><span class="apple-color-box" style="background-color: darkgoldenrod;"></span> Apple 9</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const statusDiv = document.getElementById('status');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const resetButton = document.getElementById('resetButton');
const numDotsInput = document.getElementById('numDots');
const numApplesInput = document.getElementById('numApples');
const learningRateInput = document.getElementById('learningRate');
const betaInput = document.getElementById('beta');
const GRID_SIZE = canvas.width; // Assume square grid
let dots; // tf.tensor2d
let apples; // tf.Variable
let optimizer;
let animationFrameId;
// Configuration
let numDots = parseInt(numDotsInput.value);
let numApples = parseInt(numApplesInput.value);
let learningRate = parseFloat(learningRateInput.value);
let beta = parseFloat(betaInput.value); // Sharpness of soft ownership
// Predefined colors for apples (more than 4 for flexibility)
const appleColors = [
'red', 'green', 'blue', 'purple', 'orange',
'teal', 'magenta', 'brown', 'limegreen', 'darkgoldenrod'
];
// --- Core Simulation Logic ---
function generateRandomPoints(count, size) {
return tf.randomUniform([count, 2], 0, size);
}
function setupSimulation() {
// Dispose of previous tensors to prevent memory leaks
if (dots) dots.dispose();
if (apples) apples.dispose();
// 1. Generate random dots
dots = generateRandomPoints(numDots, GRID_SIZE);
// 2. Initialize apples (as tf.Variable for gradient descent)
apples = tf.variable(generateRandomPoints(numApples, GRID_SIZE));
// 3. Setup optimizer
optimizer = tf.train.adam(learningRate);
statusDiv.textContent = `Simulation ready with ${numDots} dots and ${numApples} apples.`;
}
// The Loss Function
// L_i(A_i, A_others) = -sum_k P_ik
// P_ik = exp(-beta * dist(A_i, D_k)^2) / sum_j exp(-beta * dist(A_j, D_k)^2)
function calculateLoss() {
return tf.tidy(() => {
// Calculate squared distances for all (apple, dot) pairs
// apples: (numApples, 2)
// dots: (numDots, 2)
// We need (numApples, numDots, 2) for broadcasting difference
const diffs = tf.sub(apples.expandDims(1), dots.expandDims(0)); // (numApples, numDots, 2)
const distancesSq = tf.sum(tf.square(diffs), -1); // (numApples, numDots)
// Calculate influence scores S_jk = exp(-beta * dist(A_j, D_k)^2)
const influenceScores = tf.exp(tf.mul(beta, tf.neg(distancesSq))); // (numApples, numDots)
// Calculate sum of influence scores for each dot (denominator for P_ik)
// sum_j_S_jk = sum_j S_jk over all apples for each dot k
const sumJ_S_jk = tf.sum(influenceScores, 0); // (numDots,)
// Calculate SoftOwnership P_ik = S_ik / sum_j_S_jk
// Add a small epsilon to denominator to prevent division by zero for isolated dots
const softOwnershipProbs = tf.div(influenceScores, sumJ_S_jk.expandDims(0).add(1e-8)); // (numApples, numDots)
// Loss for each apple: negative sum of its soft ownership probabilities over all dots
const lossesPerApple = tf.neg(tf.sum(softOwnershipProbs, 1)); // (numApples,)
// Total loss for the optimizer is the sum of individual apple losses
const totalLoss = tf.sum(lossesPerApple);
// We also want softOwnershipProbs for drawing, but it's generated here.
// It's generally better to return only the loss from the `minimize` function.
// We'll recompute softOwnershipProbs for drawing outside of `tf.tidy`
// if we need it after the optimization step, or just pass `apples.arraySync()`
// and compute the colors directly in draw.
// For simplicity and avoiding recomputation, we'll return it here for drawing.
// However, this means `softOwnershipProbs` is NOT disposed by `tf.tidy`.
// A more TF.js idiomatic way is to compute it *after* optimization is done,
// perhaps in a separate tf.tidy block for drawing.
// Let's stick to the idiomatic way. The `draw` function will recompute.
return totalLoss;
});
}
// --- Drawing Logic ---
async function draw() {
ctx.clearRect(0, 0, GRID_SIZE, GRID_SIZE);
// Get current apple and dot positions from tensors
const currentApples = await apples.array(); // Get JS array from tf.Variable
const currentDots = await dots.array(); // Get JS array from tf.tensor
// Calculate soft ownership probabilities for coloring dots
const softOwnershipProbs = tf.tidy(() => {
const diffs = tf.sub(apples.expandDims(1), dots.expandDims(0));
const distancesSq = tf.sum(tf.square(diffs), -1);
const influenceScores = tf.exp(tf.mul(beta, tf.neg(distancesSq)));
const sumJ_S_jk = tf.sum(influenceScores, 0);
return tf.div(influenceScores, sumJ_S_jk.expandDims(0).add(1e-8));
});
const softProbsArray = await softOwnershipProbs.array();
softOwnershipProbs.dispose(); // Dispose after getting array
// Draw dots (colored by dominant apple)
currentDots.forEach((dotPos, k) => {
let dominantAppleIndex = 0;
let maxProb = -1;
for (let i = 0; i < numApples; i++) {
if (softProbsArray[i][k] > maxProb) {
maxProb = softProbsArray[i][k];
dominantAppleIndex = i;
}
}
const dotColor = appleColors[dominantAppleIndex % appleColors.length];
ctx.beginPath();
ctx.arc(dotPos[0], dotPos[1], 3, 0, Math.PI * 2); // Dot radius
ctx.fillStyle = dotColor;
ctx.fill();
});
// Draw apples
currentApples.forEach((applePos, i) => {
ctx.beginPath();
ctx.arc(applePos[0], applePos[1], 10, 0, Math.PI * 2); // Apple radius
ctx.fillStyle = appleColors[i % appleColors.length];
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.fill();
ctx.stroke();
});
}
// --- Animation Loop ---
async function gameLoop() {
// Apply gradient descent step
optimizer.minimize(calculateLoss, true, [apples]); // `true` for `retain` means the loss tensor isn't disposed immediately
// Clip apple positions to stay within grid boundaries
apples.assign(tf.clipByValue(apples, 0, GRID_SIZE));
await draw(); // Redraw scene
// Update status (e.g., current loss value)
const currentLosses = await tf.tidy(() => tf.neg(tf.sum(tf.div(tf.exp(tf.mul(beta, tf.neg(tf.sum(tf.square(tf.sub(apples.expandDims(1), dots.expandDims(0))), -1)))), tf.sum(tf.exp(tf.mul(beta, tf.neg(tf.sum(tf.square(tf.sub(apples.expandDims(1), dots.expandDims(0))), -1)))), 0).expandDims(0).add(1e-8)), 1))).array();
const totalLossValue = await tf.tidy(() => tf.sum(tf.neg(tf.sum(tf.div(tf.exp(tf.mul(beta, tf.neg(tf.sum(tf.square(tf.sub(apples.expandDims(1), dots.expandDims(0))), -1)))), tf.sum(tf.exp(tf.mul(beta, tf.neg(tf.sum(tf.square(tf.sub(apples.expandDims(1), dots.expandDims(0))), -1)))), 0).expandDims(0).add(1e-8)), 1)))).array();
// Calculate actual dot counts for reporting
const softOwnershipProbsReport = tf.tidy(() => {
const diffs = tf.sub(apples.expandDims(1), dots.expandDims(0));
const distancesSq = tf.sum(tf.square(diffs), -1);
const influenceScores = tf.exp(tf.mul(beta, tf.neg(distancesSq)));
const sumJ_S_jk = tf.sum(influenceScores, 0);
return tf.div(influenceScores, sumJ_S_jk.expandDims(0).add(1e-8));
});
const softProbsReportArray = await softOwnershipProbsReport.array();
softOwnershipProbsReport.dispose();
let dotCounts = new Array(numApples).fill(0);
for (let k = 0; k < numDots; k++) {
let dominantAppleIndex = 0;
let maxProb = -1;
for (let i = 0; i < numApples; i++) {
if (softProbsReportArray[i][k] > maxProb) {
maxProb = softProbsReportArray[i][k];
dominantAppleIndex = i;
}
}
dotCounts[dominantAppleIndex]++;
}
statusDiv.innerHTML = `Total Loss: ${totalLossValue.toFixed(4)} | ` +
`Dots per Apple: ${dotCounts.join(', ')}<br>` +
`Current TF.js Memory: ${tf.memory().numBytes / 1024 / 1024} MB (${tf.memory().numTensors} tensors)`;
animationFrameId = requestAnimationFrame(gameLoop);
}
// --- UI Event Handlers ---
function startSimulation() {
if (animationFrameId) cancelAnimationFrame(animationFrameId); // Clear any existing loop
startButton.disabled = true;
stopButton.disabled = false;
resetButton.disabled = true;
animationFrameId = requestAnimationFrame(gameLoop);
}
function stopSimulation() {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
startButton.disabled = false;
stopButton.disabled = true;
resetButton.disabled = false;
statusDiv.textContent = "Simulation stopped. Adjust settings or click 'Start Simulation'.";
}
function resetSimulation() {
stopSimulation(); // Stop current animation
// Update configuration from input fields
numDots = parseInt(numDotsInput.value);
numApples = parseInt(numApplesInput.value);
learningRate = parseFloat(learningRateInput.value);
beta = parseFloat(betaInput.value);
// Re-setup everything
setupSimulation();
draw(); // Initial draw
startButton.disabled = false;
resetButton.disabled = false; // Ensure reset button is active after reset
}
// Attach event listeners
startButton.addEventListener('click', startSimulation);
stopButton.addEventListener('click', stopSimulation);
resetButton.addEventListener('click', resetSimulation);
numDotsInput.addEventListener('change', resetSimulation);
numApplesInput.addEventListener('change', resetSimulation);
learningRateInput.addEventListener('change', resetSimulation);
betaInput.addEventListener('change', resetSimulation);
// --- Initialization ---
window.onload = () => {
setupSimulation();
draw(); // Initial draw of random dots and apples
};
</script>
</body>
</html>
How to use it:
Save: Copy the entire code above and save it as an .html file (e.g., apple_territories.html).
Open: Open this HTML file in your web browser.
Explanation of the Code:
HTML Structure:
A canvas element is where all the drawing happens.
Input fields allow you to tweak numDots, numApples, learningRate, and beta.
Buttons control the simulation flow.
JavaScript Setup (<script> tag):
Global Variables:dots (your 100 fixed points) and apples (the 4 moving points). apples is specifically declared as a tf.Variable because its values will be updated by the optimizer.
GRID_SIZE: Matches the canvas dimensions.
appleColors: An array of colors to differentiate the apples and the dots they claim.
setupSimulation():
Called on page load and when "Reset Simulation" is clicked.
tf.randomUniform creates numDots and numAppples random [x, y] coordinates within the GRID_SIZE.
tf.variable(apples_tensor) is crucial: it tells TF.js that apples are trainable parameters.
optimizer = tf.train.adam(learningRate): Adam is a popular and effective optimization algorithm for gradient descent.
calculateLoss():
This function implements the loss formula: Li=−∑k=1NdotsPik
tf.tidy(() => { ... }): This is extremely important for TF.js. It automatically disposes of all intermediate tensors created within its scope, preventing memory leaks in loops.
Distance Calculation:
apples.expandDims(1) makes apples(numApples, 1, 2).
dots.expandDims(0) makes dots(1, numDots, 2).
tf.sub performs broadcasting to get (numApples, numDots, 2) (difference vector for every apple-dot pair).
.square() and .sum(-1) calculate the squared Euclidean distance (numApples, numDots).
Soft Ownership Probabilities (P_ik):tf.div(influenceScores, sumJ_S_jk.expandDims(0).add(1e-8)) performs the normalization. The .add(1e-8) prevents division by zero.
Loss:tf.neg(tf.sum(softOwnershipProbs, 1)) sums the probabilities for each apple (along numDots dimension) and takes the negative, as we want to maximize this sum, which is equivalent to minimizing its negative.
tf.sum(lossesPerApple): The optimizer.minimize function typically expects a single scalar loss to minimize, so we sum the individual apple losses.
draw():
Clears the canvas.
Retrieves the current numerical positions of apples and dots using await .array(). This pulls the data from the GPU back to the CPU for drawing.
Recalculates softOwnershipProbs within a tf.tidy() block specifically for drawing purposes.
Dot Coloring: For each dot, it finds which apple has the highest P_ik for that dot and colors it accordingly. This gives you the visual "territories".
Draws the apples as larger circles.
gameLoop():
optimizer.minimize(calculateLoss, true, [apples]): This is the core of TF.js.
It calls calculateLoss() to get the current total loss.
It then automatically computes the gradients of this totalLoss with respect to all tf.Variables passed in the third argument ([apples]).
Finally, it applies these gradients to update the apples variable's values in the direction that minimizes the loss.
true as the second argument means retain (the loss tensor itself is not disposed, which can be useful if you want to inspect it directly after minimize).
apples.assign(tf.clipByValue(apples, 0, GRID_SIZE)): Keeps the apples within the canvas boundaries.
await draw(): Redraws the scene with the updated apple positions.
Updates the status div with current loss and hard-assigned dot counts.
requestAnimationFrame(gameLoop): Creates a smooth animation loop, ensuring the gameLoop runs continuously in the browser's rendering cycle.
This setup should give you a robust and visually compelling simulation of competing apples claiming territories based on your specified loss function!
Competition/Repulsion from other apples: If another apple Aj moves closer to a dot Dk, its Sjk increases, which increases the denominator ∑Sjk for Pik. This decreasesPik (apple Ai's share of that dot), thus increasing Li for Ai. To reduce its loss, Ai must either move closer to Dk itself (to re-claim its share) or move to another part of the grid where it can claim more dots. This implicitly creates the competitive "territory" behavior.
Automatic balancing: There's only one term, Pik, which inherently combines the desire to be close to dots with the need to compete with other apples for those dots. You don't need to manually balance weights between different loss components.
Convergence: Gradient descent on this loss will push each apple towards a local minimum where it has maximized its "claim" on dots, leading to a stable partitioning of the grid, similar to how Voronoi diagrams are formed, but with soft boundaries.