Analysis API¶
The analysis package exposes course-of-action generation and policy
saliency analysis as a clean Python API.
Quick-start¶
from analysis import COAGenerator, generate_coas, SaliencyAnalyzer
# Generate ranked courses of action
coas = generate_coas(env=env, policy=model, n_episodes=20)
for coa in coas:
print(f"{coa.label}: win_rate={coa.score.win_rate:.1%}")
# Compute saliency for a policy
analyzer = SaliencyAnalyzer(policy=model, env=env)
saliency = analyzer.compute(obs, method="integrated_gradients")
analyzer.plot(saliency)
COA generation¶
analysis.coa_generator.COAGenerator
¶
Generate and rank candidate Courses of Action via Monte-Carlo rollout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
BattalionEnv
|
A :class: |
required |
n_rollouts
|
int
|
Number of Monte-Carlo rollouts per COA (default 20). More rollouts give more stable estimates but take longer. |
20
|
n_coas
|
int
|
Number of distinct COAs to generate (default 5, maximum is the number of built-in strategy archetypes, i.e. 7). |
5
|
seed
|
Optional[int]
|
Base random seed for reproducibility. Each COA uses a deterministic derived seed. |
None
|
strategies
|
Optional[Sequence[str]]
|
Explicit list of strategy labels to use. When |
None
|
Source code in analysis/coa_generator.py
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 | |
generate(policy=None, deterministic=False)
¶
Generate and rank candidate COAs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Optional[Any]
|
Optional trained policy (e.g. a Stable-Baselines3 |
None
|
deterministic
|
bool
|
Passed through to the base policy's |
False
|
Returns:
| Type | Description |
|---|---|
list of :class:`CourseOfAction`
|
Ordered from best to worst by composite score. The list has
exactly |
Source code in analysis/coa_generator.py
analysis.coa_generator.CorpsCOAGenerator
¶
Generate and rank corps-level Courses of Action via Monte-Carlo rollout.
Satisfies the E9.2 requirements:
* Up to 10 COAs generated via :meth:generate.
* COA explanation via :meth:explain_coa (≥ 3 key decisions per COA).
* COA modification and re-evaluation via :meth:modify_and_evaluate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Any
|
A :class: |
required |
n_rollouts
|
int
|
Number of Monte-Carlo rollouts per COA (default 10). |
10
|
n_coas
|
int
|
Number of distinct COAs to generate (1–10, default 10). |
10
|
seed
|
Optional[int]
|
Base random seed for reproducibility. |
None
|
strategies
|
Optional[Sequence[str]]
|
Explicit list of strategy labels to evaluate. When |
None
|
Source code in analysis/coa_generator.py
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 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 | |
explain_coa(coa)
¶
Explain the key decisions that drive a COA's outcome.
Analyses the stored rollout results for coa.label and returns
a :class:COAExplanation with ≥ 3 key decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coa
|
CorpsCourseOfAction
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
class:`COAExplanation`
|
|
Source code in analysis/coa_generator.py
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 1376 | |
generate(policy=None, deterministic=False)
¶
Generate and rank candidate corps-level COAs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Optional[Any]
|
Optional trained policy with
|
None
|
deterministic
|
bool
|
Passed through to the policy's |
False
|
Returns:
| Type | Description |
|---|---|
list of :class:`CorpsCourseOfAction`
|
Ordered best to worst by composite score. |
Source code in analysis/coa_generator.py
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 | |
modify_and_evaluate(coa, modification)
¶
Apply user modifications to a COA and re-simulate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coa
|
CorpsCourseOfAction
|
The original :class: |
required |
modification
|
COAModification
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
A new :class:`CorpsCourseOfAction` with updated score and the
|
|
modified strategy label (or original label if no override).
|
|
Source code in analysis/coa_generator.py
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 | |
analysis.coa_generator.COAScore
dataclass
¶
Scalar metrics summarising the outcomes of one COA's Monte-Carlo rollouts.
Attributes:
| Name | Type | Description |
|---|---|---|
win_rate |
float
|
Fraction of rollouts won by Blue (0–1). |
draw_rate |
float
|
Fraction of rollouts that ended as a draw (0–1). |
loss_rate |
float
|
Fraction of rollouts lost by Blue (0–1). |
blue_casualties |
float
|
Mean normalised Blue strength loss across rollouts (0–1). Higher means more Blue casualties; 0 = no damage taken. |
red_casualties |
float
|
Mean normalised Red strength loss across rollouts (0–1). Higher means Blue dealt more damage to Red. |
terrain_control |
float
|
Mean fraction of steps in which Blue held terrain advantage (closer to map centre than Red), averaged across rollouts (0–1). |
composite |
float
|
Weighted composite score used for ranking (higher is better). |
n_rollouts |
int
|
Number of rollouts used to compute these statistics. |
Source code in analysis/coa_generator.py
analysis.coa_generator.CourseOfAction
dataclass
¶
A candidate tactical plan with associated outcome predictions.
Attributes:
| Name | Type | Description |
|---|---|---|
label |
str
|
Human-readable name of the tactical archetype. |
rank |
int
|
Rank among all generated COAs (1 = best, higher = worse). |
score |
COAScore
|
Aggregated outcome statistics from Monte-Carlo rollouts. |
action_summary |
dict
|
Aggregate action statistics across rollouts:
mean |
seed |
int
|
Base random seed used to initialise this COA's rollouts. |
Source code in analysis/coa_generator.py
as_dict()
¶
Return a JSON-serialisable dict.
analysis.coa_generator.generate_coas(env=None, policy=None, n_rollouts=20, n_coas=5, seed=None, strategies=None, env_kwargs=None)
¶
Generate COAs, optionally creating a temporary environment.
This is a thin convenience wrapper around :class:COAGenerator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Optional[BattalionEnv]
|
An existing :class: |
None
|
policy
|
Optional[Any]
|
Optional trained policy (see :meth: |
None
|
n_rollouts
|
int
|
Number of Monte-Carlo rollouts per COA. |
20
|
n_coas
|
int
|
Number of distinct COAs to generate (1–7). |
5
|
seed
|
Optional[int]
|
Base random seed. |
None
|
strategies
|
Optional[Sequence[str]]
|
Explicit ordered list of strategy labels to evaluate. |
None
|
env_kwargs
|
Optional[dict]
|
Keyword arguments forwarded to :class: |
None
|
Returns:
| Type | Description |
|---|---|
list of :class:`CourseOfAction`, best first.
|
|
Source code in analysis/coa_generator.py
analysis.coa_generator.generate_corps_coas(env=None, policy=None, n_rollouts=10, n_coas=10, seed=None, strategies=None, env_kwargs=None, explain=False)
¶
Generate corps-level COAs, optionally creating a temporary CorpsEnv.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Optional[Any]
|
An existing :class: |
None
|
policy
|
Optional[Any]
|
Optional trained policy. |
None
|
n_rollouts
|
int
|
Monte-Carlo rollouts per COA (default 10). 10 COAs × 10 rollouts runs comfortably within the 120 s budget on CPU. |
10
|
n_coas
|
int
|
Number of COAs to generate (1–10, default 10). |
10
|
seed
|
Optional[int]
|
Base random seed. |
None
|
strategies
|
Optional[Sequence[str]]
|
Explicit ordered list of corps strategy labels to evaluate. |
None
|
env_kwargs
|
Optional[dict]
|
Keyword arguments forwarded to :class: |
None
|
explain
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
list of :class:`CorpsCourseOfAction`, best first.
|
|
Source code in analysis/coa_generator.py
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 | |
Saliency analysis¶
analysis.saliency.SaliencyAnalyzer
¶
Convenience wrapper that bundles all explainability methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Any
|
Trained policy. Accepts an SB3 |
required |
feature_names
|
Optional[Tuple[str, ...]]
|
Override the default :data: |
None
|
Examples:
::
analyzer = SaliencyAnalyzer(ppo_model)
obs, _ = env.reset(seed=0)
sal = analyzer.gradient_saliency(obs)
ig = analyzer.integrated_gradients(obs)
shap = analyzer.shap_importance(obs)
print(analyzer.top_features(sal, k=3))
fig = analyzer.plot_saliency(sal)
Source code in analysis/saliency.py
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 | |
gradient_saliency(obs, *, reduce='mean_abs')
¶
Return gradient saliency scores. See :func:compute_gradient_saliency.
Source code in analysis/saliency.py
integrated_gradients(obs, *, baseline=None, n_steps=50)
¶
Return integrated gradient attributions. See :func:compute_integrated_gradients.
Source code in analysis/saliency.py
plot_importance(importances=None, obs=None, *, title='Feature Importance (SHAP)', **kwargs)
¶
Plot feature importance bar chart.
Either pass pre-computed importances scores, or pass obs
directly to compute SHAP importance automatically.
Source code in analysis/saliency.py
plot_saliency(saliency=None, obs=None, *, title='Gradient Saliency', **kwargs)
¶
Plot saliency map.
Either pass pre-computed saliency scores, or pass obs directly
to compute them automatically.
Source code in analysis/saliency.py
shap_importance(obs, *, background=None, n_samples=100)
¶
Return SHAP feature importance. See :func:compute_shap_importance.
Source code in analysis/saliency.py
summary(obs, *, n_steps=20, n_samples=50)
¶
Compute all three importance metrics and return them as a dict.
Keys: "gradient_saliency", "integrated_gradients",
"shap_importance".
Source code in analysis/saliency.py
top_features(scores, k=3)
¶
Return the top-k feature names and their scores, sorted descending.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
ndarray
|
1-D importance / saliency array. |
required |
k
|
int
|
Number of top features to return. |
3
|
Returns:
| Type | Description |
|---|---|
list of (feature_name, score) tuples
|
|
Source code in analysis/saliency.py
analysis.saliency.compute_gradient_saliency(policy, obs, *, reduce='mean_abs')
¶
Compute gradient-based saliency scores for each observation dimension.
Back-propagates through the policy network and uses the absolute gradient of the summed action output with respect to each input dimension as an importance proxy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Any
|
Trained policy. Accepts SB3 |
required |
obs
|
Union[ndarray, Tensor]
|
Observation array of shape |
required |
reduce
|
str
|
How to aggregate across the action dimension and batch:
- |
'mean_abs'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Saliency scores of shape |
Source code in analysis/saliency.py
analysis.saliency.compute_integrated_gradients(policy, obs, *, baseline=None, n_steps=50)
¶
Compute integrated gradient attributions.
Follows the method of Sundararajan et al. (2017): accumulate gradients
along the straight-line path from baseline to obs, then multiply
element-wise by (obs - baseline). The result satisfies the
completeness axiom: attributions sum to f(obs) - f(baseline).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Any
|
Trained policy (same supported types as :func: |
required |
obs
|
Union[ndarray, Tensor]
|
Single observation of shape |
required |
baseline
|
Optional[Union[ndarray, Tensor]]
|
Reference point. Defaults to the all-zeros observation. |
None
|
n_steps
|
int
|
Number of interpolation steps along the path (higher → more accurate). Must be >= 1. |
50
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Attribution scores of shape |
Source code in analysis/saliency.py
analysis.saliency.compute_shap_importance(policy, obs, *, background=None, n_samples=100)
¶
Compute SHAP-based feature importance scores.
Attempts to use the shap library (GradientExplainer for differentiable
models). When shap is not installed or the model is not compatible,
falls back to a lightweight permutation importance approximation that
estimates each feature's marginal contribution by masking it with the
background mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Any
|
Trained policy. |
required |
obs
|
Union[ndarray, Tensor]
|
Observations of shape |
required |
background
|
Optional[Union[ndarray, Tensor]]
|
Background dataset for SHAP / permutation baseline. Defaults to the all-zeros observation (single sample). |
None
|
n_samples
|
int
|
Number of samples used in the permutation fallback. |
100
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Absolute SHAP values / permutation importances of shape |
Source code in analysis/saliency.py
analysis.saliency.plot_saliency_map(saliency, *, feature_names=None, title='Gradient Saliency', normalise=True, figsize=(9.0, 4.0))
¶
Render a horizontal bar chart of saliency scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
saliency
|
ndarray
|
1-D array of shape |
required |
feature_names
|
Optional[Tuple[str, ...]]
|
Feature labels for each dimension. Defaults to
:data: |
None
|
title
|
str
|
Plot title string. |
'Gradient Saliency'
|
normalise
|
bool
|
When |
True
|
figsize
|
Tuple[float, float]
|
Matplotlib figure size |
(9.0, 4.0)
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Source code in analysis/saliency.py
analysis.saliency.plot_feature_importance(importances, *, feature_names=None, title='Feature Importance', top_k=12, figsize=(9.0, 4.5))
¶
Render a horizontal bar chart of feature importances, sorted by value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importances
|
ndarray
|
1-D importance array of shape |
required |
feature_names
|
Optional[Tuple[str, ...]]
|
Feature labels. Defaults to :data: |
None
|
title
|
str
|
Plot title. |
'Feature Importance'
|
top_k
|
int
|
Show at most this many features (sorted descending). |
12
|
figsize
|
Tuple[float, float]
|
Matplotlib figure size. |
(9.0, 4.5)
|
Returns:
| Type | Description |
|---|---|
Figure
|
|