Spaces:
Running
Running
File size: 44,047 Bytes
9227b81 ca323d4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 |
<!-- PPO Simulation By Pejman Ebrahimi -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PPO Reinforcement Learning Simulation</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
line-height: 1.6;
color: #333;
background-color: #f8f9fa;
}
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1,
h2,
h3 {
color: #2c3e50;
}
h1 {
text-align: center;
margin-bottom: 30px;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.grid-container {
display: grid;
grid-template-columns: repeat(10, 1fr);
gap: 2px;
margin: 20px 0;
}
.cell {
width: 100%;
aspect-ratio: 1;
background-color: #ecf0f1;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
position: relative;
transition: all 0.3s;
}
.agent {
background-color: #3498db;
border-radius: 50%;
width: 80%;
height: 80%;
position: absolute;
}
.goal {
background-color: #2ecc71;
width: 80%;
height: 80%;
position: absolute;
}
.obstacle {
background-color: #e74c3c;
width: 80%;
height: 80%;
position: absolute;
}
.panel {
background-color: #f5f7f9;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
border: 1px solid #ddd;
}
.controls {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin: 20px 0;
}
button {
padding: 8px 15px;
background-color: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #2980b9;
}
button:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
.sliders {
display: flex;
flex-direction: column;
gap: 10px;
margin: 15px 0;
}
.slider-container {
display: flex;
align-items: center;
}
.slider-container label {
flex: 1;
min-width: 180px;
}
.slider-container input {
flex: 2;
}
.slider-value {
flex: 0 0 50px;
text-align: right;
}
#log-container {
max-height: 200px;
overflow-y: auto;
background-color: #2c3e50;
color: #ecf0f1;
padding: 10px;
border-radius: 4px;
margin-top: 20px;
font-family: monospace;
}
.log-entry {
margin: 5px 0;
}
.tab-container {
margin-top: 20px;
}
.tab-buttons {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-button {
padding: 10px 20px;
background-color: #f1f1f1;
border: none;
cursor: pointer;
transition: background-color 0.3s;
}
.tab-button.active {
background-color: #3498db;
color: white;
}
.tab-content {
display: none;
padding: 15px;
border: 1px solid #ddd;
border-top: none;
animation: fadeIn 0.5s;
}
.tab-content.active {
display: block;
}
#policy-display {
width: 100%;
height: 300px;
overflow: auto;
margin-top: 10px;
}
.policy-grid {
display: grid;
grid-template-columns: repeat(10, 1fr);
gap: 2px;
}
.policy-cell {
aspect-ratio: 1;
border: 1px solid #ddd;
padding: 2px;
font-size: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.arrow {
width: 0;
height: 0;
border-style: solid;
margin: 2px;
}
.arrow-up {
border-width: 0 4px 8px 4px;
border-color: transparent transparent #3498db transparent;
}
.arrow-right {
border-width: 4px 0 4px 8px;
border-color: transparent transparent transparent #3498db;
}
.arrow-down {
border-width: 8px 4px 0 4px;
border-color: #3498db transparent transparent transparent;
}
.arrow-left {
border-width: 4px 8px 4px 0;
border-color: transparent #3498db transparent transparent;
}
.progress-container {
margin-top: 10px;
background-color: #f1f1f1;
border-radius: 5px;
height: 20px;
position: relative;
}
.progress-bar {
height: 100%;
background-color: #3498db;
border-radius: 5px;
width: 0%;
transition: width 0.3s;
}
.chart-container {
height: 300px;
margin: 15px 0;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.popup {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
z-index: 1000;
max-width: 80%;
max-height: 80%;
overflow-y: auto;
}
.popup-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.reward-display {
font-weight: bold;
font-size: 1.2em;
text-align: center;
margin: 10px 0;
}
.explanation {
background-color: #e8f4fc;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #3498db;
}
.highlight {
background-color: #fffacd;
padding: 2px 4px;
border-radius: 3px;
}
.concept-box {
border: 1px solid #ddd;
margin: 15px 0;
border-radius: 5px;
overflow: hidden;
}
.concept-title {
background-color: #3498db;
color: white;
padding: 10px;
margin: 0;
}
.concept-content {
padding: 15px;
}
</style>
</head>
<body>
<div class="container">
<h1>Proximal Policy Optimization (PPO) Simulation</h1>
<div class="explanation">
<p>
This simulation demonstrates how an agent learns to navigate to a goal
using <strong>Proximal Policy Optimization (PPO)</strong>. PPO is an
on-policy reinforcement learning algorithm that uses a "clipping"
mechanism to prevent large policy updates, making training more stable
and efficient.
</p>
</div>
<div class="tab-container">
<div class="tab-buttons">
<button class="tab-button active" onclick="openTab('simulation-tab')">
Simulation
</button>
<button class="tab-button" onclick="openTab('concepts-tab')">
PPO Concepts
</button>
<button class="tab-button" onclick="openTab('metrics-tab')">
Training Metrics
</button>
</div>
<div id="simulation-tab" class="tab-content active">
<div class="panel">
<h3>Environment</h3>
<p>
The agent (blue) must navigate to the goal (green) while avoiding
obstacles (red).
</p>
<div class="grid-container" id="grid"></div>
<div class="reward-display">
Total Reward: <span id="reward-value">0</span>
</div>
</div>
<div class="controls">
<button id="start-btn" onclick="startTraining()">
Start Training
</button>
<button id="reset-btn" onclick="resetEnvironment()">
Reset Environment
</button>
<button id="step-btn" onclick="stepTraining()" disabled>
Step Forward
</button>
<button id="place-obstacle-btn" onclick="toggleObstaclePlacement()">
Place Obstacles
</button>
<button id="animation-speed-btn" onclick="toggleAnimationSpeed()">
Animation Speed: Normal
</button>
</div>
<div class="panel">
<h3>PPO Parameters</h3>
<div class="sliders">
<div class="slider-container">
<label for="clip-ratio">Clip Ratio (ε):</label>
<input
type="range"
id="clip-ratio"
min="0.05"
max="0.5"
step="0.05"
value="0.2"
oninput="updateSliderValue('clip-ratio')"
/>
<span class="slider-value" id="clip-ratio-value">0.2</span>
</div>
<div class="slider-container">
<label for="learning-rate">Learning Rate:</label>
<input
type="range"
id="learning-rate"
min="0.01"
max="1"
step="0.01"
value="0.1"
oninput="updateSliderValue('learning-rate')"
/>
<span class="slider-value" id="learning-rate-value">0.1</span>
</div>
<div class="slider-container">
<label for="epochs">PPO Epochs per Update:</label>
<input
type="range"
id="epochs"
min="1"
max="10"
step="1"
value="4"
oninput="updateSliderValue('epochs')"
/>
<span class="slider-value" id="epochs-value">4</span>
</div>
</div>
</div>
<div class="panel">
<h3>Policy Visualization</h3>
<p>
This shows the current policy of the agent (arrows indicate
preferred actions in each state).
</p>
<div id="policy-display">
<div class="policy-grid" id="policy-grid"></div>
</div>
</div>
<div id="log-container"></div>
</div>
<div id="concepts-tab" class="tab-content">
<div class="concept-box">
<h3 class="concept-title">What is PPO?</h3>
<div class="concept-content">
<p>
Proximal Policy Optimization (PPO) is a policy gradient method
for reinforcement learning developed by OpenAI in 2017. It has
become one of the most popular RL algorithms due to its
simplicity and effectiveness.
</p>
<p>PPO aims to balance two objectives:</p>
<ul>
<li>Improving the agent's policy to maximize rewards</li>
<li>
Preventing large policy updates that could destabilize
training
</li>
</ul>
</div>
</div>
<div class="concept-box">
<h3 class="concept-title">Key Innovations in PPO</h3>
<div class="concept-content">
<p>
The central innovation in PPO is the
<strong>clipped surrogate objective function</strong>:
</p>
<p style="text-align: center">
L<sup>CLIP</sup>(θ) = E[min(r<sub>t</sub>(θ)A<sub>t</sub>,
clip(r<sub>t</sub>(θ), 1-ε, 1+ε)A<sub>t</sub>)]
</p>
<p>where:</p>
<ul>
<li>
<strong>r<sub>t</sub>(θ)</strong> is the ratio of
probabilities under new and old policies
</li>
<li>
<strong>A<sub>t</sub></strong> is the advantage estimate
</li>
<li>
<strong>ε</strong> is the clipping parameter (usually 0.1 or
0.2)
</li>
</ul>
<p>
The clipping mechanism ensures that the policy update stays
within a "trust region" by limiting how much the new policy can
deviate from the old one.
</p>
</div>
</div>
<div class="concept-box">
<h3 class="concept-title">How PPO Works in This Simulation</h3>
<div class="concept-content">
<ol>
<li>
The agent collects experience by interacting with the
environment using its current policy
</li>
<li>Advantages are computed for each state-action pair</li>
<li>
The policy is updated using the clipped surrogate objective
</li>
<li>
Multiple optimization epochs are performed on the same batch
of data
</li>
<li>The process repeats with the new policy</li>
</ol>
<p>
You can observe these steps in action in the simulation tab by
watching the policy visualization and training metrics.
</p>
</div>
</div>
<div class="concept-box">
<h3 class="concept-title">PPO vs. Other RL Algorithms</h3>
<div class="concept-content">
<p>PPO improves upon earlier algorithms in several ways:</p>
<ul>
<li>
<strong>vs. REINFORCE:</strong> More stable training due to
advantage estimation and clipping
</li>
<li>
<strong>vs. TRPO:</strong> Simpler implementation while
maintaining similar performance
</li>
<li>
<strong>vs. A2C/A3C:</strong> Better sample efficiency and
more stable policy updates
</li>
<li>
<strong>vs. Off-policy algorithms (DQN, DDPG):</strong> Less
sensitive to hyperparameters and often more stable
</li>
</ul>
</div>
</div>
</div>
<div id="metrics-tab" class="tab-content">
<div class="panel">
<h3>Training Progress</h3>
<div class="progress-container">
<div class="progress-bar" id="training-progress"></div>
</div>
<p id="episode-counter">Episodes: 0 / 100</p>
</div>
<div class="panel">
<h3>Reward Over Time</h3>
<div class="chart-container" id="reward-chart"></div>
</div>
<div class="panel">
<h3>Policy Loss</h3>
<div class="chart-container" id="policy-loss-chart"></div>
</div>
<div class="panel">
<h3>Value Loss</h3>
<div class="chart-container" id="value-loss-chart"></div>
</div>
</div>
</div>
</div>
<div class="popup-overlay" id="popup-overlay"></div>
<div class="popup" id="popup">
<h2 id="popup-title">Title</h2>
<div id="popup-content">Content</div>
<button onclick="closePopup()">Close</button>
</div>
<script>
// Environment configuration
const GRID_SIZE = 10;
let grid = [];
let agentPos = { x: 0, y: 0 };
let goalPos = { x: 9, y: 9 };
let obstacles = [];
let placingObstacles = false;
// Agent and PPO parameters
let policyNetwork = {};
let valueNetwork = {};
let clipRatio = 0.2;
let learningRate = 0.1; // Default learning rate (0-1 range)
let ppoEpochs = 4;
let gamma = 0.99; // Discount factor
let lambda = 0.95; // GAE parameter
// Training state
let isTraining = false;
let episode = 0;
let maxEpisodes = 100;
let episodeSteps = 0;
let maxStepsPerEpisode = 100; // Increased max steps to allow more exploration
let totalReward = 0;
let episodeRewards = [];
let policyLosses = [];
let valueLosses = [];
// Tracking for visualization
let trajectories = [];
let oldPolicy = {};
// Exploration parameters
let explorationRate = 0.2; // Probability of taking a random action (exploration)
// Initialize the environment
function initializeEnvironment() {
grid = [];
obstacles = [];
// Create the grid UI
const gridContainer = document.getElementById("grid");
gridContainer.innerHTML = "";
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const cell = document.createElement("div");
cell.classList.add("cell");
cell.dataset.x = x;
cell.dataset.y = y;
cell.addEventListener("click", handleCellClick);
gridContainer.appendChild(cell);
}
}
// Place agent and goal
agentPos = { x: 0, y: 0 };
goalPos = { x: 9, y: 9 };
renderGrid();
// Initialize policy and value networks
initializeNetworks();
renderPolicy();
updateReward(0);
}
// Initialize policy and value networks
function initializeNetworks() {
policyNetwork = {};
valueNetwork = {};
// Initialize learning rate
learningRate = parseFloat(
document.getElementById("learning-rate").value
);
// Initialize policy and value for each state (cell)
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const stateKey = `${x},${y}`;
// Initialize policy with random probabilities
policyNetwork[stateKey] = {
up: 0.25,
right: 0.25,
down: 0.25,
left: 0.25,
};
// Initialize value to zero
valueNetwork[stateKey] = 0;
}
}
}
function renderGrid() {
// Clear all cells
const cells = document.querySelectorAll(".cell");
cells.forEach((cell) => {
cell.innerHTML = "";
});
// Place agent
const agentCell = document.querySelector(
`.cell[data-x="${agentPos.x}"][data-y="${agentPos.y}"]`
);
const agentElement = document.createElement("div");
agentElement.classList.add("agent");
agentCell.appendChild(agentElement);
// Place goal
const goalCell = document.querySelector(
`.cell[data-x="${goalPos.x}"][data-y="${goalPos.y}"]`
);
const goalElement = document.createElement("div");
goalElement.classList.add("goal");
goalCell.appendChild(goalElement);
// Place obstacles
obstacles.forEach((obstacle) => {
const obstacleCell = document.querySelector(
`.cell[data-x="${obstacle.x}"][data-y="${obstacle.y}"]`
);
const obstacleElement = document.createElement("div");
obstacleElement.classList.add("obstacle");
obstacleCell.appendChild(obstacleElement);
});
}
function renderPolicy() {
const policyGrid = document.getElementById("policy-grid");
policyGrid.innerHTML = "";
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const cell = document.createElement("div");
cell.classList.add("policy-cell");
const stateKey = `${x},${y}`;
const policy = policyNetwork[stateKey];
// Skip rendering policy for obstacles
if (isObstacle(x, y)) {
cell.style.backgroundColor = "#e74c3c";
policyGrid.appendChild(cell);
continue;
}
// If it's the goal, mark it green
if (x === goalPos.x && y === goalPos.y) {
cell.style.backgroundColor = "#2ecc71";
policyGrid.appendChild(cell);
continue;
}
// Create arrows for each action probability
for (const [action, prob] of Object.entries(policy)) {
if (prob > 0.2) {
// Only show significant probabilities
const arrow = document.createElement("div");
arrow.classList.add("arrow", `arrow-${action}`);
arrow.style.opacity = Math.min(1, prob * 2); // Scale opacity with probability
cell.appendChild(arrow);
}
}
// Add state value indication using background color intensity
const value = valueNetwork[stateKey];
const normalizedValue = (value + 10) / 20; // Normalize to [0,1] range assuming values between -10 and 10
const intensity = Math.max(
0,
Math.min(255, Math.floor(normalizedValue * 255))
);
cell.style.backgroundColor = `rgba(236, 240, 241, ${normalizedValue})`;
policyGrid.appendChild(cell);
}
}
}
function handleCellClick(event) {
const x = parseInt(event.currentTarget.dataset.x);
const y = parseInt(event.currentTarget.dataset.y);
if (placingObstacles) {
// Don't allow obstacles on agent or goal
if (
(x === agentPos.x && y === agentPos.y) ||
(x === goalPos.x && y === goalPos.y)
) {
return;
}
const obstacleIndex = obstacles.findIndex(
(o) => o.x === x && o.y === y
);
if (obstacleIndex === -1) {
obstacles.push({ x, y });
} else {
obstacles.splice(obstacleIndex, 1);
}
renderGrid();
renderPolicy();
}
}
function toggleObstaclePlacement() {
placingObstacles = !placingObstacles;
const btn = document.getElementById("place-obstacle-btn");
btn.textContent = placingObstacles ? "Done Placing" : "Place Obstacles";
btn.style.backgroundColor = placingObstacles ? "#e74c3c" : "#3498db";
}
function isObstacle(x, y) {
return obstacles.some((o) => o.x === x && o.y === y);
}
function resetEnvironment() {
initializeEnvironment();
episodeRewards = [];
policyLosses = [];
valueLosses = [];
episode = 0;
updateEpisodeCounter();
updateReward(0);
// Reset training state
isTraining = false;
document.getElementById("start-btn").textContent = "Start Training";
document.getElementById("step-btn").disabled = true;
// Clear charts
// In a real implementation, you would update the charts here
logMessage("Environment reset. Ready for training!");
}
function startTraining() {
if (isTraining) {
// Stop training
isTraining = false;
document.getElementById("start-btn").textContent = "Start Training";
document.getElementById("step-btn").disabled = true;
} else {
// Start training
isTraining = true;
document.getElementById("start-btn").textContent = "Stop Training";
document.getElementById("step-btn").disabled = false;
// If we're at the end of training, reset first
if (episode >= maxEpisodes) {
resetEnvironment();
}
runTrainingLoop();
}
}
function stepTraining() {
if (episode < maxEpisodes) {
runEpisode();
updateTrainingProgress();
} else {
logMessage("Training complete! Reset to train again.");
}
}
async function runTrainingLoop() {
while (isTraining && episode < maxEpisodes) {
await runEpisode();
updateTrainingProgress();
// Add a small delay to visualize the process
await new Promise((resolve) => setTimeout(resolve, 200));
}
if (episode >= maxEpisodes) {
logMessage("Training complete!");
isTraining = false;
document.getElementById("start-btn").textContent = "Start Training";
}
}
async function runEpisode() {
// Reset agent position and episodic variables
agentPos = { x: 0, y: 0 };
episodeSteps = 0;
totalReward = 0;
trajectories = [];
// Decay exploration rate over time (important for improving policy)
explorationRate = Math.max(0.05, 0.2 * Math.pow(0.99, episode));
renderGrid();
updateReward(totalReward);
// Save old policy for PPO ratio calculation
oldPolicy = JSON.parse(JSON.stringify(policyNetwork));
// Run episode until termination
let done = false;
while (!done && episodeSteps < maxStepsPerEpisode) {
done = await executeStep();
episodeSteps++;
// Small delay for visualization
await new Promise((resolve) =>
setTimeout(resolve, animationSpeeds[animationSpeed] / 2)
);
}
// Add episode reward to history
episodeRewards.push(totalReward);
// Run PPO update if we have enough steps
if (trajectories.length > 0) {
const [policyLoss, valueLoss] = updatePPO();
policyLosses.push(policyLoss);
valueLosses.push(valueLoss);
}
// Update UI
renderPolicy();
episode++;
updateEpisodeCounter();
logMessage(
`Episode ${episode}: Reward=${totalReward.toFixed(
2
)}, Steps=${episodeSteps}, Exploration=${explorationRate.toFixed(2)}`
);
return new Promise((resolve) => setTimeout(resolve, 10));
}
async function executeStep() {
const stateKey = `${agentPos.x},${agentPos.y}`;
const policy = policyNetwork[stateKey];
// Choose action based on policy
const action = sampleAction(policy);
// Store old position
const oldPos = { ...agentPos };
// Move agent
moveAgent(action);
// Calculate reward
const reward = calculateReward(oldPos);
totalReward += reward;
updateReward(totalReward);
// Check if episode is done
const done =
(agentPos.x === goalPos.x && agentPos.y === goalPos.y) ||
isObstacle(agentPos.x, agentPos.y);
// If agent hit obstacle, move it back for visualization
if (isObstacle(agentPos.x, agentPos.y)) {
agentPos = { ...oldPos };
}
// Render the grid
renderGrid();
// Store trajectory
const newStateKey = `${agentPos.x},${agentPos.y}`;
trajectories.push({
state: stateKey,
action,
reward,
nextState: newStateKey,
done,
});
return done;
}
function sampleAction(policy) {
// Use exploration rate to decide whether to take random action or follow policy
if (Math.random() < explorationRate) {
// Take random action with exploration probability
const actions = Object.keys(policy);
const randomIndex = Math.floor(Math.random() * actions.length);
return actions[randomIndex];
}
// Otherwise sample from policy distribution
const actions = Object.keys(policy);
const probs = actions.map((a) => policy[a]);
const rand = Math.random();
let cumProb = 0;
for (let i = 0; i < actions.length; i++) {
cumProb += probs[i];
if (rand < cumProb) {
return actions[i];
}
}
return actions[actions.length - 1];
}
function moveAgent(action) {
// Save previous position
const prevPos = { ...agentPos };
// Attempt to move agent
switch (action) {
case "up":
agentPos.y = Math.max(0, agentPos.y - 1);
break;
case "right":
agentPos.x = Math.min(GRID_SIZE - 1, agentPos.x + 1);
break;
case "down":
agentPos.y = Math.min(GRID_SIZE - 1, agentPos.y + 1);
break;
case "left":
agentPos.x = Math.max(0, agentPos.x - 1);
break;
}
// Check if new position is an obstacle
if (isObstacle(agentPos.x, agentPos.y)) {
// Revert to previous position if it hit an obstacle
agentPos.x = prevPos.x;
agentPos.y = prevPos.y;
return false; // Indicate movement was blocked
}
return true; // Movement successful
}
function calculateReward(oldPos, movementSuccessful) {
// Reward for reaching goal
if (agentPos.x === goalPos.x && agentPos.y === goalPos.y) {
return 10;
}
// Penalty for attempting to move into an obstacle (but not actually moving into it)
if (!movementSuccessful) {
return -1; // Reduced penalty to avoid too much negative learning
}
// Small penalty for each step to encourage efficiency
let stepPenalty = -0.1;
// Small reward for getting closer to goal (using Manhattan distance)
const oldDistance =
Math.abs(oldPos.x - goalPos.x) + Math.abs(oldPos.y - goalPos.y);
const newDistance =
Math.abs(agentPos.x - goalPos.x) + Math.abs(agentPos.y - goalPos.y);
const proximityReward = oldDistance > newDistance ? 0.3 : -0.1; // Stronger reward for progress
return stepPenalty + proximityReward;
}
function updatePPO() {
// Get parameters from sliders
clipRatio = parseFloat(document.getElementById("clip-ratio").value);
learningRate = parseFloat(
document.getElementById("learning-rate").value
);
ppoEpochs = parseInt(document.getElementById("epochs").value);
// Compute returns and advantages
const returns = [];
const advantages = [];
// Compute returns (discounted sum of future rewards)
let discountedReturn = 0;
for (let i = trajectories.length - 1; i >= 0; i--) {
const transition = trajectories[i];
discountedReturn =
transition.reward +
gamma * (transition.done ? 0 : discountedReturn);
returns.unshift(discountedReturn);
}
// Compute advantages using Generalized Advantage Estimation (GAE)
let lastGaeAdvantage = 0;
for (let i = trajectories.length - 1; i >= 0; i--) {
const transition = trajectories[i];
const stateKey = transition.state;
const nextStateKey = transition.nextState;
const currentValue = valueNetwork[stateKey];
const nextValue = transition.done ? 0 : valueNetwork[nextStateKey];
// TD error
const delta = transition.reward + gamma * nextValue - currentValue;
// GAE
lastGaeAdvantage = delta + gamma * lambda * lastGaeAdvantage;
advantages.unshift(lastGaeAdvantage);
}
// Normalize advantages for more stable learning
const meanAdvantage =
advantages.reduce((a, b) => a + b, 0) / advantages.length;
const stdAdvantage =
Math.sqrt(
advantages.reduce((a, b) => a + Math.pow(b - meanAdvantage, 2), 0) /
advantages.length
) || 1; // Avoid division by zero
for (let i = 0; i < advantages.length; i++) {
advantages[i] =
(advantages[i] - meanAdvantage) / (stdAdvantage + 1e-8);
}
// Store losses for metrics
let totalPolicyLoss = 0;
let totalValueLoss = 0;
// Backup old policy for PPO ratio calculation
const oldPolicyBackup = JSON.parse(JSON.stringify(policyNetwork));
// Multiple epochs of optimization on the same data (key PPO feature)
for (let epoch = 0; epoch < ppoEpochs; epoch++) {
// Update policy and value networks for each step in the trajectory
for (let i = 0; i < trajectories.length; i++) {
const transition = trajectories[i];
const stateKey = transition.state;
const action = transition.action;
// Get old action probability
const oldActionProb = oldPolicy[stateKey][action];
// Get current action probability
const currentActionProb = policyNetwork[stateKey][action];
// Compute probability ratio (crucial for PPO)
const ratio = currentActionProb / Math.max(oldActionProb, 1e-8);
// Get advantage for this action
const advantage = advantages[i];
// Compute unclipped and clipped surrogate objectives
const unclippedObjective = ratio * advantage;
const clippedRatio = Math.max(
Math.min(ratio, 1 + clipRatio),
1 - clipRatio
);
const clippedObjective = clippedRatio * advantage;
// PPO's clipped surrogate objective (core of PPO)
const surrogateObjective = Math.min(
unclippedObjective,
clippedObjective
);
// Compute policy gradient
// Note: In PPO, we maximize the objective, so negative for gradient ascent
const policyLoss = -surrogateObjective;
totalPolicyLoss += policyLoss;
// Value loss (using returns as targets)
const valueTarget = returns[i];
const valuePrediction = valueNetwork[stateKey];
const valueLoss = 0.5 * Math.pow(valueTarget - valuePrediction, 2);
totalValueLoss += valueLoss;
// Update value network with gradient descent
valueNetwork[stateKey] +=
learningRate * (valueTarget - valuePrediction);
// Compute policy update based on whether we're using clipped or unclipped objective
const useClippedObjective = unclippedObjective > clippedObjective;
const policyGradient =
learningRate * advantage * (useClippedObjective ? 0 : 1);
// Apply policy gradient update
// Increase probability of the taken action if it was good (positive advantage)
// Decrease probability if it was bad (negative advantage)
let newProb = policyNetwork[stateKey][action] + policyGradient;
// Ensure probability stays positive (important for ratio calculation)
newProb = Math.max(newProb, 0.01);
policyNetwork[stateKey][action] = newProb;
// Normalize probabilities to ensure they sum to 1
const sumProb = Object.values(policyNetwork[stateKey]).reduce(
(a, b) => a + b,
0
);
for (const a in policyNetwork[stateKey]) {
policyNetwork[stateKey][a] /= sumProb;
}
// Add some exploration (entropy bonus)
// This is crucial for avoiding local optima
if (i % 5 === 0) {
// Apply periodically to maintain some exploration
for (const a in policyNetwork[stateKey]) {
// Slightly nudge probabilities toward uniform
policyNetwork[stateKey][a] =
0.95 * policyNetwork[stateKey][a] + 0.05 * 0.25;
}
// Re-normalize
const sumProb = Object.values(policyNetwork[stateKey]).reduce(
(a, b) => a + b,
0
);
for (const a in policyNetwork[stateKey]) {
policyNetwork[stateKey][a] /= sumProb;
}
}
}
}
// Calculate average losses
const avgPolicyLoss =
totalPolicyLoss / (trajectories.length * ppoEpochs);
const avgValueLoss = totalValueLoss / (trajectories.length * ppoEpochs);
// Log progress periodically
if (episode % 5 === 0) {
logMessage(
`Episode ${episode}: Average Policy Loss = ${avgPolicyLoss.toFixed(
4
)}, Value Loss = ${avgValueLoss.toFixed(4)}`
);
}
return [avgPolicyLoss, avgValueLoss];
}
function updateReward(reward) {
document.getElementById("reward-value").textContent = reward.toFixed(2);
}
function updateEpisodeCounter() {
document.getElementById(
"episode-counter"
).textContent = `Episodes: ${episode} / ${maxEpisodes}`;
document.getElementById("training-progress").style.width = `${
(episode / maxEpisodes) * 100
}%`;
}
function updateTrainingProgress() {
// Update charts with the latest data
// In a real implementation, you would update charts here
// Show progress
updateEpisodeCounter();
}
function updateSliderValue(id) {
const slider = document.getElementById(id);
const valueDisplay = document.getElementById(`${id}-value`);
valueDisplay.textContent = slider.value;
// Update corresponding variables
if (id === "clip-ratio") clipRatio = parseFloat(slider.value);
if (id === "learning-rate") learningRate = parseFloat(slider.value);
if (id === "epochs") ppoEpochs = parseInt(slider.value);
}
function logMessage(message) {
const logContainer = document.getElementById("log-container");
const logEntry = document.createElement("div");
logEntry.classList.add("log-entry");
logEntry.textContent = message;
logContainer.appendChild(logEntry);
logContainer.scrollTop = logContainer.scrollHeight;
}
function openTab(tabId) {
// Hide all tab contents
const tabContents = document.getElementsByClassName("tab-content");
for (let i = 0; i < tabContents.length; i++) {
tabContents[i].classList.remove("active");
}
// Remove active class from tab buttons
const tabButtons = document.getElementsByClassName("tab-button");
for (let i = 0; i < tabButtons.length; i++) {
tabButtons[i].classList.remove("active");
}
// Show selected tab content and mark button as active
document.getElementById(tabId).classList.add("active");
const activeButton = document.querySelector(
`.tab-button[onclick="openTab('${tabId}')"]`
);
activeButton.classList.add("active");
}
function showPopup(title, content) {
document.getElementById("popup-title").textContent = title;
document.getElementById("popup-content").innerHTML = content;
document.getElementById("popup-overlay").style.display = "block";
document.getElementById("popup").style.display = "block";
}
function closePopup() {
document.getElementById("popup-overlay").style.display = "none";
document.getElementById("popup").style.display = "none";
}
// Initialize the environment when the page loads
window.onload = function () {
initializeEnvironment();
logMessage('Environment initialized. Click "Start Training" to begin!');
// Show concept popup with a delay
setTimeout(() => {
showPopup(
"Welcome to PPO Simulation",
`
<p>This simulation demonstrates Proximal Policy Optimization (PPO), a reinforcement learning algorithm.</p>
<p>In this grid world:</p>
<ul>
<li>The agent (blue circle) must learn to navigate to the goal (green square)</li>
<li>You can place obstacles (red squares) by clicking the "Place Obstacles" button</li>
<li>The agent receives rewards for approaching the goal and penalties for hitting obstacles</li>
<li>PPO helps the agent learn efficiently by preventing large policy updates</li>
</ul>
<p>Try experimenting with different parameters to see how they affect learning!</p>
`
);
}, 1000);
};
// Animation speed control
let animationSpeed = "normal";
const animationSpeeds = {
slow: 300,
normal: 100,
fast: 20,
};
function toggleAnimationSpeed() {
const speedBtn = document.getElementById("animation-speed-btn");
if (animationSpeed === "slow") {
animationSpeed = "normal";
speedBtn.textContent = "Animation Speed: Normal";
} else if (animationSpeed === "normal") {
animationSpeed = "fast";
speedBtn.textContent = "Animation Speed: Fast";
} else {
animationSpeed = "slow";
speedBtn.textContent = "Animation Speed: Slow";
}
}
// Update animation speed in relevant functions
async function runTrainingLoop() {
while (isTraining && episode < maxEpisodes) {
await runEpisode();
updateTrainingProgress();
// Use dynamic animation speed
await new Promise((resolve) =>
setTimeout(resolve, animationSpeeds[animationSpeed])
);
}
if (episode >= maxEpisodes) {
logMessage("Training complete!");
isTraining = false;
document.getElementById("start-btn").textContent = "Start Training";
}
}
async function executeStep() {
const stateKey = `${agentPos.x},${agentPos.y}`;
const policy = policyNetwork[stateKey];
// Choose action based on policy
const action = sampleAction(policy);
// Store old position
const oldPos = { ...agentPos };
// Move agent
const movementSuccessful = moveAgent(action);
// Calculate reward
const reward = calculateReward(oldPos, movementSuccessful);
totalReward += reward;
updateReward(totalReward);
// Check if episode is done
const done = agentPos.x === goalPos.x && agentPos.y === goalPos.y;
// Render the grid
renderGrid();
// Store trajectory
const newStateKey = `${agentPos.x},${agentPos.y}`;
trajectories.push({
state: stateKey,
action,
reward,
nextState: newStateKey,
done,
});
// Use dynamic animation speed
await new Promise((resolve) =>
setTimeout(resolve, animationSpeeds[animationSpeed] / 2)
);
return done;
}
</script>
<footer
style="
text-align: center;
margin-top: 30px;
padding: 15px;
background-color: #f8f9fa;
border-top: 1px solid #ddd;
"
>
© 2025 Pejman Ebrahimi - All Rights Reserved
</footer>
</body>
</html>
|