Spaces:
Sleeping
Sleeping
File size: 66,438 Bytes
641b66a e7b5170 641b66a e7b5170 641b66a a5ef90e 641b66a a5ef90e 641b66a a5ef90e 641b66a e7b5170 641b66a e7b5170 641b66a a5ef90e 641b66a a5ef90e 641b66a a5ef90e 641b66a 51a065e 641b66a f295cc5 641b66a 9bb3b01 ab139fb 641b66a 9bb3b01 ab139fb 641b66a 4d9b367 641b66a ab139fb 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a ce2e151 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 641b66a 9bb3b01 92600d7 9bb3b01 ab139fb 92600d7 ab139fb 92600d7 ab139fb 641b66a c91eac6 641b66a 51a065e 641b66a 51a065e 641b66a c91eac6 641b66a a628638 641b66a 51a065e 641b66a |
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 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 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 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 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 |
"""
© Benjamin R. Berton 2025 Polytechnique Montreal
"""
import dash
from dash import html, dcc, dash_table, Input, Output, State, callback_context
import plotly.graph_objects as go
import pandas as pd
import os
import base64
import io
app = dash.Dash(__name__)
DATA_FILE = "table_hat_game.csv"
if os.path.exists(DATA_FILE):
df = pd.read_csv(DATA_FILE)
# Update agent columns
agent_columns = ["Human*", "UGV", "UAV", "UGV*", "UAV*", "Human"]
editable_columns = agent_columns
# Update dropdowns for new agent columns
color_options = ["red", "yellow", "green", "orange"]
dropdowns = {
col: {
'options': [{'label': c.capitalize(), 'value': c} for c in color_options]
}
for col in agent_columns
}
# Update columns definition
columns = [
{"name": "Row", "id": "Row", "editable": False},
{"name": "Procedure", "id": "Procedure", "editable": True},
{"name": "Task", "id": "Task", "editable": True},
{"name": "Human*", "id": "Human*", "editable": True, "presentation": "dropdown"},
{"name": "UGV", "id": "UGV", "editable": True, "presentation": "dropdown"},
{"name": "UAV", "id": "UAV", "editable": True, "presentation": "dropdown"},
{"name": "UGV*", "id": "UGV*", "editable": True, "presentation": "dropdown"},
{"name": "UAV*", "id": "UAV*", "editable": True, "presentation": "dropdown"},
{"name": "Human", "id": "Human", "editable": True, "presentation": "dropdown"},
{"name": "Observability", "id": "Observability", "editable": True},
{"name": "Predictability", "id": "Predictability", "editable": True},
{"name": "Directability", "id": "Directability", "editable": True},
]
def wrap_text(text, max_width=30):
import textwrap
if not isinstance(text, str):
return ""
return '<br>'.join(textwrap.wrap(text, width=max_width))
def style_table(df):
styles = []
for i, row in df.iterrows():
for col in editable_columns:
value = row[col]
color = value.lower() if isinstance(value, str) else "white"
styles.append({
'if': {'row_index': i, 'column_id': col},
'backgroundColor': color if color != "white" else "#ffffff",
'color': color,
'textAlign': 'center'
})
return styles
df = df.assign(Row=lambda x: x.index + 1)
editable_columns = ["Human*", "UGV", "UAV", "UGV*", "UAV*", "Human"]
table = dash_table.DataTable(
id='responsibility-table',
columns=[
{"name": col, "id": col, "editable": col in editable_columns}
for col in df.columns
],
data=df.assign(Row=lambda x: x.index + 1).to_dict("records"),
editable=True,
row_deletable=True,
dropdown=dropdowns,
style_data_conditional=style_table(df),
style_cell={'textAlign': 'left', 'padding': '5px', 'whiteSpace': 'normal'},
style_cell_conditional=[
{
'if': {'column_id': 'Human*'},
'borderLeft': '3px solid black'
},
{
'if': {'column_id': 'Human'},
'borderRight': '3px solid black'
},
{
'if': {'column_id': 'TARS'},
'borderRight': '2px solid black'
}
],
style_header={'fontWeight': 'bold', 'backgroundColor': '#f0f0f0'},
style_table={'overflowX': 'auto', 'border': '1px solid lightgrey'},
active_cell={"row": 0, "column_id":"Objective", "column":1}
)
def build_interdependence_figures(df, highlight_track=None):
agents = ["Human*", "UGV", "UAV", "UGV*", "UAV*", "Human"]
VALID_COLORS = {"red", "yellow", "green", "orange"}
figures = {}
for procedure, proc_df in df.groupby("Procedure"):
tasks = proc_df["Task"].tolist()
height = 300 + len(tasks) * 100
proc_df = proc_df.reset_index(drop=True)
proc_df["task_idx"] = proc_df.index
dots = []
black_to_black_arrows = []
grey_to_black_arrows = []
horizontal_bidirectional_arrows = []
most_reliable_track = []
all_task_performers = []
for idx, row in proc_df.iterrows():
task_idx = row["task_idx"]
black_points = []
agent_colors = {
"Human*": str(row.get("Human*", "") or "").strip().lower(),
"UGV*": str(row.get("UGV*", "") or "").strip().lower(),
"UAV*": str(row.get("UAV*", "") or "").strip().lower(),
}
# Most reliable path logic (green > yellow > orange)
chosen_agent = None
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "green":
chosen_agent = agent
break
if not chosen_agent:
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "yellow":
chosen_agent = agent
break
if not chosen_agent:
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "orange":
chosen_agent = agent
break
if chosen_agent:
most_reliable_track.append((task_idx, chosen_agent))
# Team alternative 1: Human* performer, UGV/UAV supporters
val_human_star = str(row.get("Human*", "") or "").strip().lower()
if val_human_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "Human*", "color": val_human_star})
if val_human_star != "red":
black_points.append("Human*")
val_ugv = str(row.get("UGV", "") or "").strip().lower()
if val_ugv in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UGV", "color": val_ugv})
if val_human_star != "red" and val_ugv != "red":
grey_to_black_arrows.append({
"start_agent": "UGV",
"end_agent": "Human*",
"task": task_idx
})
val_uav = str(row.get("UAV", "") or "").strip().lower()
if val_uav in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UAV", "color": val_uav})
if val_human_star != "red" and val_uav != "red":
grey_to_black_arrows.append({
"start_agent": "UAV",
"end_agent": "Human*",
"task": task_idx
})
# Team alternative 2: UGV* or UAV* performer, Human supporter
val_ugv_star = str(row.get("UGV*", "") or "").strip().lower()
val_uav_star = str(row.get("UAV*", "") or "").strip().lower()
performer_candidates = []
performer_grade = None
# Find best grade for UGV* and UAV*
for grade in ["green", "yellow", "orange"]:
if val_ugv_star == grade or val_uav_star == grade or val_human_star == grade:
performer_grade = grade
break
# Collect all possible performers for this task
task_performers = []
for agent, val in [("Human*", val_human_star), ("UGV*", val_ugv_star), ("UAV*", val_uav_star)]:
if val == performer_grade and val != "red":
task_performers.append(agent)
all_task_performers.append(task_performers)
if val_ugv_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UGV*", "color": val_ugv_star})
if val_uav_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UAV*", "color": val_uav_star})
val_human = str(row.get("Human", "") or "").strip().lower()
if val_human in VALID_COLORS:
dots.append({"task": task_idx, "agent": "Human", "color": val_human})
if val_ugv_star in VALID_COLORS and val_ugv_star != "red":
grey_to_black_arrows.append({
"start_agent": "Human",
"end_agent": "UGV*",
"task": task_idx
})
if val_uav_star in VALID_COLORS and val_uav_star != "red":
grey_to_black_arrows.append({
"start_agent": "Human",
"end_agent": "UAV*",
"task": task_idx
})
# If both UGV* and UAV* are performers with same grade, draw horizontal bidirectional arrow
if "UGV*" in task_performers and "UAV*" in task_performers:
horizontal_bidirectional_arrows.append({
"left_agent": "UGV*",
"right_agent": "UAV*",
"task": task_idx
})
# Draw solid arrows for performer transitions (from previous to current)
for i in range(1, len(proc_df)):
prev_performers = all_task_performers[i-1]
curr_performers = all_task_performers[i]
# If both UGV* and UAV* are top performers in the PREVIOUS task, only use UGV* as source
if "UGV*" in prev_performers and "UAV*" in prev_performers:
filtered_prev_performers = [p for p in prev_performers if p != "UAV*"]
else:
filtered_prev_performers = prev_performers
# If both UGV* and UAV* are top performers in the CURRENT task, only draw arrows to UGV*
if "UGV*" in curr_performers and "UAV*" in curr_performers:
filtered_curr_performers = [p for p in curr_performers if p != "UAV*"]
else:
filtered_curr_performers = curr_performers
for prev_agent in filtered_prev_performers:
for curr_agent in filtered_curr_performers:
black_to_black_arrows.append({
"start_task": i-1,
"start_agent": prev_agent,
"end_task": i,
"end_agent": curr_agent
})
agent_pos = {agent: i for i, agent in enumerate(agents)}
fig = go.Figure()
for dot in dots:
row = proc_df.iloc[dot["task"]]
hover_text = (
f"<b>Task:</b> {wrap_text(row['Task'])}<br>"
f"<b>Agent:</b> {dot['agent']}<br><br>"
f"<b>Observability:</b><br>{wrap_text(row.get('Observability', ''))}<br><br>"
f"<b>Predictability:</b><br>{wrap_text(row.get('Predictability', ''))}<br><br>"
f"<b>Directability:</b><br>{wrap_text(row.get('Directability', ''))}"
)
fig.add_trace(go.Scatter(
x=[agent_pos[dot["agent"]]],
y=[dot["task"]],
mode="markers",
marker=dict(size=20, color=dot["color"], symbol="circle"),
showlegend=False,
hoverinfo="text",
hovertext=hover_text
))
for arrow in grey_to_black_arrows:
fig.add_shape(
type="line",
x0=agent_pos[arrow["start_agent"]],
y0=arrow["task"],
x1=agent_pos[arrow["end_agent"]],
y1=arrow["task"],
line=dict(
color="black",
width=2,
dash="dot"
)
)
for arrow in black_to_black_arrows:
is_highlighted = False
if highlight_track == "most_reliable":
is_highlighted = (
(arrow["start_task"], arrow["start_agent"]) in most_reliable_track and
(arrow["end_task"], arrow["end_agent"]) in most_reliable_track
)
fig.add_annotation(
x=agent_pos[arrow["end_agent"]],
y=arrow["end_task"],
ax=agent_pos[arrow["start_agent"]],
ay=arrow["start_task"],
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=3,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
for arrow in horizontal_bidirectional_arrows:
y = arrow["task"]
x_left = agent_pos[arrow["left_agent"]]
x_right = agent_pos[arrow["right_agent"]]
# Check if most reliable track goes through UGV* for this task
is_highlighted = False
if highlight_track == "most_reliable":
is_highlighted = (y, "UGV*") in most_reliable_track
# Draw left-to-right arrow
fig.add_annotation(
x=x_right, y=y, ax=x_left, ay=y,
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=2,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
# Draw right-to-left arrow
fig.add_annotation(
x=x_left, y=y, ax=x_right, ay=y,
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=2,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
fig.update_layout(
title=f"Workflow for {procedure}",
xaxis=dict(
tickvals=list(agent_pos.values()),
ticktext=list(agent_pos.keys()),
title="Agent",
showgrid=True,
gridcolor='lightgrey'
),
yaxis=dict(
tickvals=list(range(len(tasks))),
ticktext=[wrap_text(task) for task in tasks],
title="Task",
autorange="reversed",
showgrid=True,
gridcolor='lightgrey'
),
height=height,
margin=dict(l=200, r=50, t=50, b=50),
plot_bgcolor='white',
paper_bgcolor='white',
)
figures[procedure] = fig
return figures
def build_combined_interdependence_figure(df, highlight_track=None):
agents = ["Human*", "UGV", "UAV", "UGV*", "UAV*", "Human"]
VALID_COLORS = {"red", "yellow", "green", "orange"}
tasks = df["Task"].tolist()
height = 600 + len(tasks) * 100
dots = []
black_to_black_arrows = []
grey_to_black_arrows = []
horizontal_bidirectional_arrows = []
df = df.reset_index(drop=True)
df["task_idx"] = df.index
most_reliable_track = []
# Store all possible performers for each task
all_task_performers = []
for idx, row in df.iterrows():
task_idx = row["task_idx"]
black_points = []
# Get performer colors for both alternatives
agent_colors = {
"Human*": str(row.get("Human*", "") or "").strip().lower(),
"UGV*": str(row.get("UGV*", "") or "").strip().lower(),
"UAV*": str(row.get("UAV*", "") or "").strip().lower(),
}
# Most reliable path logic (green > yellow > orange)
chosen_agent = None
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "green":
chosen_agent = agent
break
if not chosen_agent:
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "yellow":
chosen_agent = agent
break
if not chosen_agent:
for agent in ["Human*", "UGV*", "UAV*"]:
if agent_colors[agent] == "orange":
chosen_agent = agent
break
if chosen_agent:
most_reliable_track.append((task_idx, chosen_agent))
# Team alternative 1: Human* performer, UGV/UAV supporters
val_human_star = str(row.get("Human*", "") or "").strip().lower()
if val_human_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "Human*", "color": val_human_star})
black_points.append("Human*")
val_ugv = str(row.get("UGV", "") or "").strip().lower()
if val_ugv in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UGV", "color": val_ugv})
if val_human_star != "red" and val_ugv != "red":
grey_to_black_arrows.append({
"start_agent": "UGV",
"end_agent": "Human*",
"task": task_idx
})
val_uav = str(row.get("UAV", "") or "").strip().lower()
if val_uav in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UAV", "color": val_uav})
if val_human_star != "red" and val_uav != "red":
grey_to_black_arrows.append({
"start_agent": "UAV",
"end_agent": "Human*",
"task": task_idx
})
# Team alternative 2: UGV* or UAV* performer, Human supporter
val_ugv_star = str(row.get("UGV*", "") or "").strip().lower()
val_uav_star = str(row.get("UAV*", "") or "").strip().lower()
performer_candidates = []
performer_grade = None
# Find best grade for UGV* and UAV*
for grade in ["green", "yellow", "orange"]:
if val_ugv_star == grade or val_uav_star == grade or val_human_star == grade:
performer_grade = grade
break
# Collect all possible performers for this task
task_performers = []
for agent, val in [("Human*", val_human_star), ("UGV*", val_ugv_star), ("UAV*", val_uav_star)]:
if val == performer_grade and val != "red":
task_performers.append(agent)
all_task_performers.append(task_performers)
if val_ugv_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UGV*", "color": val_ugv_star})
if val_uav_star in VALID_COLORS:
dots.append({"task": task_idx, "agent": "UAV*", "color": val_uav_star})
val_human = str(row.get("Human", "") or "").strip().lower()
if val_human in VALID_COLORS:
dots.append({"task": task_idx, "agent": "Human", "color": val_human})
# Supporter arrows
if val_ugv_star in VALID_COLORS and val_ugv_star != "red":
grey_to_black_arrows.append({
"start_agent": "Human",
"end_agent": "UGV*",
"task": task_idx
})
if val_uav_star in VALID_COLORS and val_uav_star != "red":
grey_to_black_arrows.append({
"start_agent": "Human",
"end_agent": "UAV*",
"task": task_idx
})
# If both UGV* and UAV* are performers with same grade, draw horizontal bidirectional arrow
if "UGV*" in task_performers and "UAV*" in task_performers:
horizontal_bidirectional_arrows.append({
"left_agent": "UGV*",
"right_agent": "UAV*",
"task": task_idx
})
# Draw solid arrows for performer transitions (from previous to current)
for i in range(1, len(df)):
prev_performers = all_task_performers[i-1]
curr_performers = all_task_performers[i]
# If both UGV* and UAV* are top performers in the PREVIOUS task, only use UGV* as source
if "UGV*" in prev_performers and "UAV*" in prev_performers:
filtered_prev_performers = [p for p in prev_performers if p != "UAV*"]
else:
filtered_prev_performers = prev_performers
# If both UGV* and UAV* are top performers in the CURRENT task, only draw arrows to UGV*
if "UGV*" in curr_performers and "UAV*" in curr_performers:
filtered_curr_performers = [p for p in curr_performers if p != "UAV*"]
else:
filtered_curr_performers = curr_performers
for prev_agent in filtered_prev_performers:
for curr_agent in filtered_curr_performers:
black_to_black_arrows.append({
"start_task": i-1,
"start_agent": prev_agent,
"end_task": i,
"end_agent": curr_agent
})
agent_pos = {agent: i for i, agent in enumerate(agents)}
fig = go.Figure()
for dot in dots:
row = df.iloc[dot["task"]]
hover_text = (
f"<b>Task:</b> {wrap_text(row['Task'])}<br>"
f"<b>Agent:</b> {dot['agent']}<br><br>"
f"<b>Observability:</b><br>{wrap_text(row.get('Observability', ''))}<br><br>"
f"<b>Predictability:</b><br>{wrap_text(row.get('Predictability', ''))}<br><br>"
f"<b>Directability:</b><br>{wrap_text(row.get('Directability', ''))}"
)
fig.add_trace(go.Scatter(
x=[agent_pos[dot["agent"]]],
y=[dot["task"]],
mode="markers",
marker=dict(size=20, color=dot["color"], symbol="circle"),
showlegend=False,
hoverinfo="text",
hovertext=hover_text
))
for arrow in grey_to_black_arrows:
fig.add_shape(
type="line",
x0=agent_pos[arrow["start_agent"]],
y0=arrow["task"],
x1=agent_pos[arrow["end_agent"]],
y1=arrow["task"],
line=dict(
color="black",
width=2,
dash="dot"
)
)
for arrow in black_to_black_arrows:
is_highlighted = False
if highlight_track == "most_reliable":
is_highlighted = (
(arrow["start_task"], arrow["start_agent"]) in most_reliable_track and
(arrow["end_task"], arrow["end_agent"]) in most_reliable_track
)
fig.add_annotation(
x=agent_pos[arrow["end_agent"]],
y=arrow["end_task"],
ax=agent_pos[arrow["start_agent"]],
ay=arrow["start_task"],
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=3,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
for arrow in horizontal_bidirectional_arrows:
y = arrow["task"]
x_left = agent_pos[arrow["left_agent"]]
x_right = agent_pos[arrow["right_agent"]]
# Check if most reliable track goes through UGV* for this task
is_highlighted = False
if highlight_track == "most_reliable":
is_highlighted = (y, "UGV*") in most_reliable_track
# Draw left-to-right arrow
fig.add_annotation(
x=x_right, y=y, ax=x_left, ay=y,
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=2,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
# Draw right-to-left arrow
fig.add_annotation(
x=x_left, y=y, ax=x_right, ay=y,
xref="x", yref="y", axref="x", ayref="y",
showarrow=True,
arrowhead=2,
arrowsize=1,
arrowwidth=4 if is_highlighted else 2,
arrowcolor="crimson" if is_highlighted else "black",
opacity=0.9
)
fig.update_layout(
title="Combined Workflow Graph (All Procedures)",
xaxis=dict(
tickvals=list(agent_pos.values()),
ticktext=list(agent_pos.keys()),
title="Agent",
showgrid=True,
gridcolor='lightgrey'
),
yaxis=dict(
tickvals=list(df["task_idx"]),
ticktext=[wrap_text(f"{p} | {t}") for p, t in zip(df["Procedure"], df["Task"])],
title="Procedure | Task",
autorange="reversed",
showgrid=True,
gridcolor='lightgrey'
),
margin=dict(l=250, r=50, t=50, b=50),
height=height,
plot_bgcolor='white',
paper_bgcolor='white',
)
return fig
app.layout = html.Div([
html.Div(
"© Benjamin R. Berton 2025 Polytechnique Montreal",
style={
"textAlign": "center",
"color": "#888",
"fontSize": "14px",
"marginBottom": "10px"
}
),
# The table goes here
html.H2("Interdependence Analysis Table", style={"textAlign": "center"}),
html.Div(id="table-wrapper", children=[table]),
html.Div([
html.Div([
# Left-aligned buttons
html.Div([
dcc.Upload(
id='upload-data',
children=html.Button('📂 Load Table', id='load-button', n_clicks=0),
multiple=False,
style={
'display': 'inline-block',
'marginRight': '10px'
}
),
html.Button("➕ Add Row", id="add-row-button", n_clicks=0),
html.Button("⬇️ Copy Cell Down", id="copy-down-button", n_clicks=0),
], style={"display": "flex", "gap": "10px"}),
# Right-aligned Save button
html.Div([
html.Button("💾 Save Table", disabled=False, id="save-button", n_clicks=0),
dcc.Download(id="download-csv")
], style={"marginLeft": "auto"}) # pushes this div to the right
], style={"display": "flex", "width": "100%"}),
html.Div(id="save-confirmation", style={"marginTop": "10px", "fontStyle": "italic"})
]),
html.H2("Interdependence Workflow Graph", style={"textAlign": "center"}),
# Dropdown menu to select procedure
html.Div([
dcc.Dropdown(
id="procedure-dropdown",
options=[{"label": proc, "value": proc} for proc in df["Procedure"].unique()],
value=None,
placeholder="Select a procedure to filter the graph...",
clearable=True,
style={"width": "50%", "margin": "0 auto"}
)
]),
dcc.RadioItems(
id="highlight-selector",
options=[
{"label": "No highlight", "value": "none"},
{"label": "Most reliable path", "value": "most_reliable"}
],
value="none",
labelStyle={'display': 'inline-block', 'margin-right': '20px'},
style={"textAlign": "center", "marginTop": "20px"}
),
# Graph
dcc.Graph(id="interdependence-graph", config={
"displayModeBar": False
}),
# Labels
html.Div([
html.Div("Team Alternative 1", style={
"width": "50%", "display": "inline-block", "textAlign": "center", "marginTop": "10px", "marginLeft": "150px"
}),
html.Div("Team Alternative 2", style={
"width": "50%", "display": "inline-block", "textAlign": "center", "marginTop": "10px"
}),
], style={"display": "flex", "width": "100%"}),
# Bar chart for most reliable path color counts
html.Div([
dcc.Graph(id="overall-scenario-bar-chart"),
dcc.Graph(id="most-reliable-bar-chart"),
dcc.Graph(id="allocation-type-bar-chart"),
dcc.Graph(id="agent-autonomy-bar-chart")
]),
# Footer with copyright
html.Footer(
"© Benjamin R. Berton 2025 Polytechnique Montreal",
style={
"textAlign": "center",
"marginTop": "40px",
"padding": "10px 0",
"color": "#888",
"fontSize": "14px"
}
),
], style={"fontFamily": "'Roboto', 'Helvetica', 'Arial', sans-serif"})
@app.callback(
Output("interdependence-graph", "figure"),
Output("overall-scenario-bar-chart", "figure"),
Output("most-reliable-bar-chart", "figure"),
Output("allocation-type-bar-chart", "figure"),
Output("agent-autonomy-bar-chart", "figure"),
Input("procedure-dropdown", "value"),
Input("highlight-selector", "value"),
Input("responsibility-table", "data")
)
def update_graph_and_bar(procedure, highlight_track, data):
df = pd.DataFrame(data)
if df.empty:
return go.Figure(), go.Figure(), go.Figure(), go.Figure(), go.Figure()
if highlight_track == "none":
highlight_track = None
# --- Workflow Graph ---
if procedure is None:
workflow_fig = build_combined_interdependence_figure(df, highlight_track)
df_bar = df
else:
figures = build_interdependence_figures(df, highlight_track)
workflow_fig = figures.get(procedure, go.Figure())
df_bar = df[df["Procedure"] == procedure]
# --- Bar Chart for the whole scenario---
performer_green = 0
performer_yellow = 0
performer_orange = 0
supporter_green = 0
supporter_yellow = 0
supporter_orange = 0
human_performer_green = 0
human_performer_yellow = 0
human_performer_orange = 0
human_supporter_green = 0
human_supporter_yellow = 0
human_supporter_orange = 0
ugv_performer_green = 0
ugv_performer_yellow = 0
ugv_performer_orange = 0
ugv_supporter_green = 0
ugv_supporter_yellow = 0
ugv_supporter_orange = 0
uav_performer_green = 0
uav_performer_yellow = 0
uav_performer_orange = 0
uav_supporter_green = 0
uav_supporter_yellow = 0
uav_supporter_orange = 0
for idx, row in df_bar.iterrows():
agent_colors = {
"HUMAN*": str(row.get("Human*", "") or "").strip().lower(),
"UGV*": str(row.get("UGV*", "") or "").strip().lower(),
"UAV*": str(row.get("UAV*", "") or "").strip().lower(),
}
supporter_colors = {
"HUMAN": str(row.get("Human", "") or "").strip().lower(),
"UGV": str(row.get("UGV", "") or "").strip().lower(),
"UAV": str(row.get("UAV", "") or "").strip().lower(),
}
# Find performer (most reliable)
for agent in ["HUMAN*", "UGV*", "UAV*"]:
if agent_colors[agent] == "green":
if agent == "HUMAN*":
human_performer_green += 1
if agent == "UGV*":
ugv_performer_green += 1
if agent == "UAV*":
uav_performer_green += 1
performer_green += 1
if agent_colors[agent] == "yellow":
if agent == "HUMAN*":
human_performer_yellow += 1
if agent == "UGV*":
ugv_performer_yellow += 1
if agent == "UAV*":
uav_performer_yellow += 1
performer_yellow += 1
if agent_colors[agent] == "orange":
if agent == "HUMAN*":
human_performer_orange += 1
if agent == "UGV*":
ugv_performer_orange += 1
if agent == "UAV*":
uav_performer_orange += 1
performer_orange += 1
for agent in ["HUMAN", "UGV", "UAV"]:
if supporter_colors[agent] == "green":
if agent == "HUMAN":
human_supporter_green += 1
if agent == "UGV":
ugv_supporter_green += 1
if agent == "UAV":
uav_supporter_green += 1
supporter_green += 1
if supporter_colors[agent] == "yellow":
if agent == "HUMAN":
human_supporter_yellow += 1
if agent == "UGV":
ugv_supporter_yellow += 1
if agent == "UAV":
uav_supporter_yellow += 1
supporter_yellow += 1
if supporter_colors[agent] == "orange":
if agent == "HUMAN":
human_supporter_orange += 1
if agent == "UGV":
ugv_supporter_orange += 1
if agent == "UAV":
uav_supporter_orange += 1
supporter_orange += 1
bar_fig_whole_scenario = go.Figure()
# Individual bars for each agent and color - Performers
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Performer Green"],
y=[human_performer_green],
marker_color="seagreen",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Performer Green"],
y=[ugv_performer_green],
marker_color="limegreen",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Performer Green"],
y=[uav_performer_green],
marker_color="mediumspringgreen",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Performer Yellow"],
y=[human_performer_yellow],
marker_color="gold",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Performer Yellow"],
y=[ugv_performer_yellow],
marker_color="khaki",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Performer Yellow"],
y=[uav_performer_yellow],
marker_color="lemonchiffon",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Performer Orange"],
y=[human_performer_orange],
marker_color="darkorange",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Performer Orange"],
y=[ugv_performer_orange],
marker_color="orange",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Performer Orange"],
y=[uav_performer_orange],
marker_color="coral",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
# Individual bars for each agent and color - Supporters
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Supporter Green"],
y=[human_supporter_green],
marker_color="seagreen",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Supporter Green"],
y=[ugv_supporter_green],
marker_color="limegreen",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Supporter Green"],
y=[uav_supporter_green],
marker_color="mediumspringgreen",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Supporter Yellow"],
y=[human_supporter_yellow],
marker_color="gold",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Supporter Yellow"],
y=[ugv_supporter_yellow],
marker_color="khaki",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Supporter Yellow"],
y=[uav_supporter_yellow],
marker_color="lemonchiffon",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="Human",
x=["Supporter Orange"],
y=[human_supporter_orange],
marker_color="darkorange",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UGV",
x=["Supporter Orange"],
y=[ugv_supporter_orange],
marker_color="orange",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.add_trace(go.Bar(
name="UAV",
x=["Supporter Orange"],
y=[uav_supporter_orange],
marker_color="coral",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig_whole_scenario.update_layout(
title="Performer and Supporter Capacities",
xaxis_title="Role and Capacity",
yaxis_title="Number of Tasks",
barmode='group',
bargap=0.15,
bargroupgap=0.1,
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False
)
# --- Bar Chart for Most Reliable Path ---
performer_green = 0
performer_yellow = 0
performer_orange = 0
supporter_green = 0
supporter_yellow = 0
supporter_orange = 0
human_performer_green = 0
human_performer_yellow = 0
human_performer_orange = 0
human_supporter_green = 0
human_supporter_yellow = 0
human_supporter_orange = 0
ugv_performer_green = 0
ugv_performer_yellow = 0
ugv_performer_orange = 0
ugv_supporter_green = 0
ugv_supporter_yellow = 0
ugv_supporter_orange = 0
uav_performer_green = 0
uav_performer_yellow = 0
uav_performer_orange = 0
uav_supporter_green = 0
uav_supporter_yellow = 0
uav_supporter_orange = 0
for idx, row in df_bar.iterrows():
agent_colors = {
"HUMAN*": str(row.get("Human*", "") or "").strip().lower(),
"UGV*": str(row.get("UGV*", "") or "").strip().lower(),
"UAV*": str(row.get("UAV*", "") or "").strip().lower(),
}
supporter_colors = {
"HUMAN": str(row.get("Human", "") or "").strip().lower(),
"UGV": str(row.get("UGV", "") or "").strip().lower(),
"UAV": str(row.get("UAV", "") or "").strip().lower(),
}
performer = None
# Find performer (most reliable)
if agent_colors["HUMAN*"] == "green":
performer = "HUMAN*"
performer_green += 1
human_performer_green += 1
elif agent_colors["UGV*"] == "green":
performer = "UGV*"
performer_green += 1
ugv_performer_green += 1
if agent_colors["UAV*"] == "green":
performer += ";UAV*"
performer_green += 1
uav_performer_green += 1
elif agent_colors["UAV*"] == "green":
performer = "UAV*"
performer_green += 1
uav_performer_green += 1
elif agent_colors["HUMAN*"] == "yellow":
performer = "HUMAN*"
performer_yellow += 1
human_performer_yellow += 1
elif agent_colors["UGV*"] == "yellow":
performer = "UGV*"
performer_yellow += 1
ugv_performer_yellow += 1
if agent_colors["UAV*"] == "yellow":
performer += ";UAV*"
performer_yellow += 1
uav_performer_yellow += 1
elif agent_colors["UAV*"] == "yellow":
performer = "UAV*"
performer_yellow += 1
uav_performer_yellow += 1
elif agent_colors["HUMAN*"] == "orange":
performer = "HUMAN*"
performer_orange += 1
human_performer_orange += 1
elif agent_colors["UGV*"] == "orange":
performer = "UGV*"
performer_orange += 1
ugv_performer_orange += 1
if agent_colors["UAV*"] == "orange":
performer += ";UAV*"
performer_orange += 1
uav_performer_orange += 1
elif agent_colors["UAV*"] == "orange":
performer = "UAV*"
performer_orange += 1
uav_performer_orange += 1
# Now check for supporter (the other agent)
if performer == "HUMAN*":
if supporter_colors["UGV"] == "green" or supporter_colors['UGV'] == "yellow" or supporter_colors['UGV'] == "orange":
supporter_color = supporter_colors["UGV"]
if supporter_color == "green":
supporter_green += 1
ugv_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
ugv_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
ugv_supporter_orange += 1
if supporter_colors["UAV"] == "green" or supporter_colors['UAV'] == "yellow" or supporter_colors['UAV'] == "orange":
supporter_color = supporter_colors["UAV"]
if supporter_color == "green":
supporter_green += 1
uav_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
uav_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
uav_supporter_orange += 1
elif performer == "UGV*" :
if supporter_colors["UAV"] == "green" or supporter_colors['UAV'] == "yellow" or supporter_colors['UAV'] == "orange":
supporter_color = supporter_colors["UAV"]
if supporter_color == "green":
supporter_green += 1
uav_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
uav_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
uav_supporter_orange += 1
supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
uav_supporter_orange += 1
if supporter_colors["HUMAN"] == "green" or supporter_colors['HUMAN'] == "yellow" or supporter_colors['HUMAN'] == "orange":
supporter_color = supporter_colors["HUMAN"]
if supporter_color == "green":
supporter_green += 1
human_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
human_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
human_supporter_orange += 1
elif performer == "UAV*":
if supporter_colors["UGV"] == "green" or supporter_colors['UGV'] == "yellow" or supporter_colors['UGV'] == "orange":
supporter_color = supporter_colors["UGV"]
if supporter_color == "green":
supporter_green += 1
ugv_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
ugv_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
ugv_supporter_orange += 1
if supporter_colors["HUMAN"] == "green" or supporter_colors['HUMAN'] == "yellow" or supporter_colors['HUMAN'] == "orange":
supporter_color = supporter_colors["HUMAN"]
if supporter_color == "green":
supporter_green += 1
human_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
human_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
human_supporter_orange += 1
elif performer == "UGV*;UAV*":
if supporter_colors["HUMAN"] == "green" or supporter_colors['HUMAN'] == "yellow" or supporter_colors['HUMAN'] == "orange":
supporter_color = supporter_colors["HUMAN"]
if supporter_color == "green":
supporter_green += 1
human_supporter_green += 1
elif supporter_color == "yellow":
supporter_yellow += 1
human_supporter_yellow += 1
elif supporter_color == "orange":
supporter_orange += 1
human_supporter_orange += 1
bar_fig = go.Figure()
# Individual bars for each agent and color - Performers
bar_fig.add_trace(go.Bar(
name="Human",
x=["Performer Green"],
y=[human_performer_green],
marker_color="seagreen",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Performer Green"],
y=[ugv_performer_green],
marker_color="limegreen",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Performer Green"],
y=[uav_performer_green],
marker_color="mediumspringgreen",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="Human",
x=["Performer Yellow"],
y=[human_performer_yellow],
marker_color="gold",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Performer Yellow"],
y=[ugv_performer_yellow],
marker_color="khaki",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Performer Yellow"],
y=[uav_performer_yellow],
marker_color="lemonchiffon",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="Human",
x=["Performer Orange"],
y=[human_performer_orange],
marker_color="darkorange",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Performer Orange"],
y=[ugv_performer_orange],
marker_color="orange",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Performer Orange"],
y=[uav_performer_orange],
marker_color="coral",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
# Individual bars for each agent and color - Supporters
bar_fig.add_trace(go.Bar(
name="Human",
x=["Supporter Green"],
y=[human_supporter_green],
marker_color="seagreen",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Supporter Green"],
y=[ugv_supporter_green],
marker_color="limegreen",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Supporter Green"],
y=[uav_supporter_green],
marker_color="mediumspringgreen",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="Human",
x=["Supporter Yellow"],
y=[human_supporter_yellow],
marker_color="gold",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Supporter Yellow"],
y=[ugv_supporter_yellow],
marker_color="khaki",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Supporter Yellow"],
y=[uav_supporter_yellow],
marker_color="lemonchiffon",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="Human",
x=["Supporter Orange"],
y=[human_supporter_orange],
marker_color="darkorange",
showlegend=False,
text=["Human"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UGV",
x=["Supporter Orange"],
y=[ugv_supporter_orange],
marker_color="orange",
showlegend=False,
text=["UGV"],
textposition='outside',
textangle=0
))
bar_fig.add_trace(go.Bar(
name="UAV",
x=["Supporter Orange"],
y=[uav_supporter_orange],
marker_color="coral",
showlegend=False,
text=["UAV"],
textposition='outside',
textangle=0
))
bar_fig.update_layout(
title="Most Reliable Path: Performer and Supporter Capacities",
xaxis_title="Role and Capacity",
yaxis_title="Number of Tasks",
barmode='group',
bargap=0.15,
bargroupgap=0.1,
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False
)
# --- Allocation Type Analysis ---
single_allocation_independent = 0
multiple_allocation_independent = 0
interdependent = 0
for idx, row in df_bar.iterrows():
# Get all performer and supporter values
human_star = str(row.get("Human*", "") or "").strip().lower()
ugv_star = str(row.get("UGV*", "") or "").strip().lower()
uav_star = str(row.get("UAV*", "") or "").strip().lower()
human = str(row.get("Human", "") or "").strip().lower()
ugv = str(row.get("UGV", "") or "").strip().lower()
uav = str(row.get("UAV", "") or "").strip().lower()
VALID_COLORS = {"red", "yellow", "green", "orange"}
# Count valid performers (not red)
performers = []
if human_star in VALID_COLORS and human_star != "red":
performers.append("Human*")
if ugv_star in VALID_COLORS and ugv_star != "red":
performers.append("UGV*")
if uav_star in VALID_COLORS and uav_star != "red":
performers.append("UAV*")
# Count valid supporters (not red)
supporters = []
if human in VALID_COLORS and human != "red":
supporters.append("Human")
if ugv in VALID_COLORS and ugv != "red":
supporters.append("UGV")
if uav in VALID_COLORS and uav != "red":
supporters.append("UAV")
# Determine task type
if len(supporters) > 0:
# Has support available = interdependent
interdependent += 1
elif len(performers) == 1:
# Only one performer, no support = single allocation independent
single_allocation_independent += 1
elif len(performers) > 1:
# Multiple performers, no support = multiple allocation independent
multiple_allocation_independent += 1
total_tasks = len(df_bar)
# Create horizontal stacked bar chart
allocation_fig = go.Figure()
allocation_fig.add_trace(go.Bar(
name='Single Allocation Independent',
y=['Task Allocation Types'],
x=[single_allocation_independent],
orientation='h',
marker=dict(color='lightcoral'),
text=[f'Single Allocation Independent: {single_allocation_independent} ({single_allocation_independent/total_tasks*100:.1f}%)' if total_tasks > 0 and single_allocation_independent > 0 else ''],
textposition='inside',
textfont=dict(color='black', size=12),
hovertemplate='Single Allocation Independent<br>Count: %{x}<br>Percentage: ' + (f'{single_allocation_independent/total_tasks*100:.1f}%' if total_tasks > 0 else '0%') + '<extra></extra>'
))
allocation_fig.add_trace(go.Bar(
name='Multiple Allocation Independent',
y=['Task Allocation Types'],
x=[multiple_allocation_independent],
orientation='h',
marker=dict(color='lightskyblue'),
text=[f'Multiple Allocation Independent: {multiple_allocation_independent} ({multiple_allocation_independent/total_tasks*100:.1f}%)' if total_tasks > 0 and multiple_allocation_independent > 0 else ''],
textposition='inside',
textfont=dict(color='black', size=12),
hovertemplate='Multiple Allocation Independent<br>Count: %{x}<br>Percentage: ' + (f'{multiple_allocation_independent/total_tasks*100:.1f}%' if total_tasks > 0 else '0%') + '<extra></extra>'
))
allocation_fig.add_trace(go.Bar(
name='Interdependent (Support Available)',
y=['Task Allocation Types'],
x=[interdependent],
orientation='h',
marker=dict(color='lightgreen'),
text=[f'Interdependent: {interdependent} ({interdependent/total_tasks*100:.1f}%)' if total_tasks > 0 and interdependent > 0 else ''],
textposition='inside',
textfont=dict(color='black', size=12),
hovertemplate='Interdependent (Support Available)<br>Count: %{x}<br>Percentage: ' + (f'{interdependent/total_tasks*100:.1f}%' if total_tasks > 0 else '0%') + '<extra></extra>'
))
allocation_fig.update_layout(
title="Task Type Distribution",
xaxis_title="Number of Tasks",
barmode='stack',
height=200,
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False,
margin=dict(l=50, r=50, t=50, b=100),
annotations = [
dict(
text= "*Single Allocation Independent: Only one agent can perform the task no support available<br>*Multiple Allocation Independent: Multiple agents can perform the task no support available<br>*Interdependent: At least one agent can perform the task with opportunistic or required support from another agent",
xref="paper",
yref="paper",
x=0,
y=-1.5,
showarrow=False,
align="left",
font=dict(size=12)
)
]
)
# --- Agent Autonomy Analysis ---
# Track tasks by agent and autonomy across the entire scenario
agent_autonomy = {
"Human*": {"autonomous": 0, "non_autonomous": 0},
"UGV*": {"autonomous": 0, "non_autonomous": 0},
"UAV*": {"autonomous": 0, "non_autonomous": 0}
}
# Process all tasks in sequence (not grouped by procedure)
prev_performers = []
for idx, row in df_bar.iterrows():
# Get current task performers
human_star = str(row.get("Human*", "") or "").strip().lower()
ugv_star = str(row.get("UGV*", "") or "").strip().lower()
uav_star = str(row.get("UAV*", "") or "").strip().lower()
VALID_COLORS = {"red", "yellow", "green", "orange"}
# Map agents to their colors for this task
agent_colors = {
"Human*": human_star,
"UGV*": ugv_star,
"UAV*": uav_star
}
current_performers = []
if human_star in VALID_COLORS and human_star != "red":
current_performers.append("Human*")
if ugv_star in VALID_COLORS and ugv_star != "red":
current_performers.append("UGV*")
if uav_star in VALID_COLORS and uav_star != "red":
current_performers.append("UAV*")
# For each agent that can perform this task
for agent in current_performers:
# Orange tasks are always non-autonomous
if agent_colors[agent] == "orange":
agent_autonomy[agent]["non_autonomous"] += 1
elif idx == 0 or agent not in prev_performers:
# First task or agent couldn't perform previous task
agent_autonomy[agent]["non_autonomous"] += 1
else:
# Agent could also perform previous task = autonomous (green or yellow only)
agent_autonomy[agent]["autonomous"] += 1
prev_performers = current_performers
# Create horizontal stacked bar chart for agent autonomy
autonomy_fig = go.Figure()
agents = ["Human*", "UGV*", "UAV*"]
colors_autonomous = {"Human*": "lightgreen", "UGV*": "lightgreen", "UAV*": "lightgreen"}
colors_non_autonomous = {"Human*": "lightcoral", "UGV*": "lightcoral", "UAV*": "lightcoral"}
for agent in agents:
autonomous = agent_autonomy[agent]["autonomous"]
non_autonomous = agent_autonomy[agent]["non_autonomous"]
total = autonomous + non_autonomous
# Non-autonomous tasks (first section)
autonomy_fig.add_trace(go.Bar(
name=f'{agent} Non-Autonomous',
y=[agent],
x=[non_autonomous],
orientation='h',
marker=dict(color=colors_non_autonomous[agent]),
text=[f'Non-Autonomous: {non_autonomous} ({non_autonomous/total*100:.1f}%)' if total > 0 and non_autonomous > 0 else ''],
textposition='inside',
textfont=dict(color='black', size=11),
hovertemplate=f'{agent}<br>Non-Autonomous Tasks: {non_autonomous}<br>Percentage: ' + (f'{non_autonomous/total*100:.1f}%' if total > 0 else '0%') + '<extra></extra>',
showlegend=False
))
# Autonomous tasks (second section)
autonomy_fig.add_trace(go.Bar(
name=f'{agent} Autonomous',
y=[agent],
x=[autonomous],
orientation='h',
marker=dict(color=colors_autonomous[agent]),
text=[f'Autonomous: {autonomous} ({autonomous/total*100:.1f}%)' if total > 0 and autonomous > 0 else ''],
textposition='inside',
textfont=dict(color='black', size=11),
hovertemplate=f'{agent}<br>Autonomous Tasks: {autonomous}<br>Percentage: ' + (f'{autonomous/total*100:.1f}%' if total > 0 else '0%') + '<extra></extra>',
showlegend=False
))
autonomy_fig.update_layout(
title="Agent Autonomy: Task Continuity",
xaxis_title="Number of Tasks",
yaxis_title="Agent",
barmode='stack',
height=300,
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False,
margin=dict(l=100, r=50, t=50, b=50),
annotations = [
dict(
text= "*A task is considered autonomous for an agent if that agent could also perform the previous task in sequence and it did not require approval from other agents (orange)",
xref="paper",
yref="paper",
x=0,
y=-0.2,
showarrow=False,
align="left",
font=dict(size=12)
)
]
)
return workflow_fig, bar_fig_whole_scenario, bar_fig, allocation_fig, autonomy_fig
def ensure_all_columns(df, columns):
for col in columns:
if col not in df.columns:
df[col] = ""
return df
def normalize_and_validate_colors(df):
"""
Normalize color values to lowercase and validate them.
Returns tuple: (normalized_df, error_messages_list)
"""
color_columns = ["Human*", "UGV", "UAV", "UGV*", "UAV*", "Human"]
valid_colors = {"red", "yellow", "green", "orange", ""}
errors = []
for col in color_columns:
if col in df.columns:
for idx, value in df[col].items():
if pd.notna(value):
# Convert to lowercase string
normalized = str(value).strip().lower()
df.at[idx, col] = normalized
# Check if valid
if normalized and normalized not in valid_colors:
errors.append(f"Row {idx + 1}, Column '{col}': Invalid color '{value}' (expected: red, yellow, green, orange, or empty)")
else:
df.at[idx, col] = ""
return df, errors
@app.callback(
Output("table-wrapper", "children"),
Output("save-confirmation", "children"),
Output("download-csv", "data"),
Input("responsibility-table", "data"),
Input("save-button", "n_clicks"),
Input("upload-data", "contents"),
Input("add-row-button", "n_clicks"),
Input("copy-down-button", "n_clicks"),
State("responsibility-table", "active_cell"),
State("upload-data", "filename"),
prevent_initial_call=True
)
def handle_table(data, save_clicks, upload_contents, add_row_clicks, copy_clicks, active_cell, upload_filename):
ctx = callback_context
triggered = ctx.triggered[0]["prop_id"].split(".")[0]
color_options = ["red", "yellow", "green", "orange"]
dropdowns = {
col: {
'options': [{'label': c.capitalize(), 'value': c} for c in color_options]
}
for col in agent_columns
}
save_message = ""
# Case 1: Save button clicked
if triggered == "save-button":
df = pd.DataFrame(data)
df = ensure_all_columns(df, [col["id"] for col in columns])
save_message = f"✅ Table downloaded as table_hat_game.csv"
# Case 2: File uploaded
elif triggered == "upload-data" and upload_contents is not None:
content_type, content_string = upload_contents.split(',')
decoded = base64.b64decode(content_string)
try:
df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
df = ensure_all_columns(df, [col["id"] for col in columns])
# Normalize colors to lowercase and validate
df, validation_errors = normalize_and_validate_colors(df)
if validation_errors:
error_msg = "⚠️ File loaded with warnings:\n" + "\n".join(validation_errors[:5])
if len(validation_errors) > 5:
error_msg += f"\n... and {len(validation_errors) - 5} more errors"
save_message = error_msg
else:
save_message = f"✅ Loaded {upload_filename}"
except Exception as e:
return dash.no_update, f"⚠️ Error loading file: {str(e)}", None
# Case 3: Add Row button clicked
elif triggered == "add-row-button":
df = pd.DataFrame(data)
df = ensure_all_columns(df, [col["id"] for col in columns])
new_row = {col: "" for col in df.columns}
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
# Case 4: Copy Down clicked
elif triggered == "copy-down-button":
df = pd.DataFrame(data)
df = ensure_all_columns(df, [col["id"] for col in columns])
if active_cell and "row" in active_cell and "column_id" in active_cell:
row = active_cell["row"]
col = active_cell["column_id"]
if row is not None and col is not None and row + 1 < len(df):
df.at[row + 1, col] = df.at[row, col]
# Case 5: Table edited directly
else:
df = pd.DataFrame(data)
df = ensure_all_columns(df, [col["id"] for col in columns])
updated_table = dash_table.DataTable(
id='responsibility-table',
columns=columns,
data=df.assign(Row=lambda x: x.index + 1).to_dict("records"),
editable=True,
dropdown=dropdowns,
style_data_conditional=style_table(df),
style_cell={'textAlign': 'left', 'padding': '5px', 'whiteSpace': 'normal'},
style_cell_conditional=[
{
'if': {'column_id': 'Human*'},
'borderLeft': '3px solid black'
},
{
'if': {'column_id': 'Human'},
'borderRight': '3px solid black'
},
{
'if': {'column_id': 'TARS'},
'borderRight': '2px solid black'
}
],
style_header={'fontWeight': 'bold', 'backgroundColor': '#f0f0f0'},
style_table={'overflowX': 'auto', 'border': '1px solid lightgrey'},
row_deletable=True,
)
# Trigger download if save button was clicked
download_data = None
if triggered == "save-button":
df_to_download = pd.DataFrame(data)
df_to_download = ensure_all_columns(df_to_download, [col["id"] for col in columns])
download_data = dcc.send_data_frame(df_to_download.to_csv, "table_hat_game.csv", index=False)
return updated_table, save_message, download_data
# Expose server for gunicorn
server = app.server
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8050, debug=False) |