File size: 86,233 Bytes
b55bace | 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 1789 1790 1791 | """
Separate test classes for each BranchSBM experiment with specific plotting styles.
Each class handles testing and visualization for: LiDAR, Mouse, Clonidine, Trametinib, Veres.
"""
import os
import json
import csv
import torch
import numpy as np
import matplotlib.pyplot as plt
import pytorch_lightning as pl
import random
import ot
from torchdyn.core import NeuralODE
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import LineCollection
from .networks.utils import flow_model_torch_wrapper
from .branch_flow_net_train import BranchFlowNetTrainBase
from .branch_growth_net_train import GrowthNetTrain
from .utils import wasserstein, mix_rbf_mmd2, plot_lidar
import json
def evaluate_model(gt_data, model_data, a, b):
# ensure inputs are tensors
if not isinstance(gt_data, torch.Tensor):
gt_data = torch.tensor(gt_data, dtype=torch.float32)
if not isinstance(model_data, torch.Tensor):
model_data = torch.tensor(model_data, dtype=torch.float32)
# choose device: prefer model_data's device if it's not CPU, otherwise use gt_data's device
try:
model_dev = model_data.device
except Exception:
model_dev = torch.device('cpu')
try:
gt_dev = gt_data.device
except Exception:
gt_dev = torch.device('cpu')
device = model_dev if model_dev.type != 'cpu' else gt_dev
gt = gt_data.to(device=device, dtype=torch.float32)
md = model_data.to(device=device, dtype=torch.float32)
M = torch.cdist(gt, md, p=2).cpu().numpy()
if np.isnan(M).any() or np.isinf(M).any():
return np.nan
return ot.emd2(a, b, M, numItermax=1e7)
def compute_distribution_distances(pred, true, pred_full=None, true_full=None):
w1 = wasserstein(pred, true, power=1)
w2 = wasserstein(pred, true, power=2)
# Use full dimensions for MMD if provided, otherwise use same as W1/W2
mmd_pred = pred_full if pred_full is not None else pred
mmd_true = true_full if true_full is not None else true
# MMD requires same number of samples — randomly subsample the larger set
n_pred, n_true = mmd_pred.shape[0], mmd_true.shape[0]
if n_pred > n_true:
perm = torch.randperm(n_pred)[:n_true]
mmd_pred = mmd_pred[perm]
elif n_true > n_pred:
perm = torch.randperm(n_true)[:n_pred]
mmd_true = mmd_true[perm]
mmd = mix_rbf_mmd2(mmd_pred, mmd_true, sigma_list=[0.01, 0.1, 1, 10, 100]).item()
return {"W1": w1, "W2": w2, "MMD": mmd}
def compute_tmv_from_mass_over_time(mass_over_time, all_endpoints, time_points=None, timepoint_data=None, time_index=None, target_time=None, gt_key_template='t1_{}', weights_over_time=None):
if weights_over_time is not None or mass_over_time is not None:
if time_index is None:
if target_time is not None and time_points is not None:
arr = np.array(time_points)
time_index = int(np.argmin(np.abs(arr - float(target_time))))
else:
# default to last index
ref_list = weights_over_time if weights_over_time is not None else mass_over_time
time_index = len(ref_list[0]) - 1
else:
# neither available; time_index not used
if time_index is None:
time_index = -1
n_branches = len(all_endpoints)
# initial total cells for normalization
n_initial = None
if timepoint_data is not None and 't0' in timepoint_data:
try:
n_initial = int(timepoint_data['t0'].shape[0])
except Exception:
n_initial = None
pred_masses = []
for i in range(n_branches):
# Use sum of actual particle weights if available, otherwise mean_weight * num_particles
if weights_over_time is not None:
try:
weights_tensor = weights_over_time[i][time_index]
# Sum all particle weights to get total mass for this branch
total_mass = float(weights_tensor.sum().item())
pred_masses.append(total_mass)
continue
except Exception:
pass # Fall through to mean weight calculation
# Fallback: mean weight from mass_over_time if available, otherwise assume weight=1
mean_w = 1.0
if mass_over_time is not None:
try:
mean_w = float(mass_over_time[i][time_index])
except Exception:
mean_w = 1.0
# determine number of particles for this branch
num_particles = 0
try:
if hasattr(all_endpoints[i], 'shape'):
num_particles = int(all_endpoints[i].shape[0])
else:
num_particles = int(len(all_endpoints[i]))
except Exception:
num_particles = 0
pred_masses.append(mean_w * float(num_particles))
# ground-truth masses per branch
gt_masses = []
if timepoint_data is not None:
for i in range(n_branches):
key1 = gt_key_template.format(i)
if key1 in timepoint_data:
gt_masses.append(float(timepoint_data[key1].shape[0]))
else:
base_key = gt_key_template.split("_")[0] if '_' in gt_key_template else gt_key_template
if base_key in timepoint_data:
gt_masses.append(float(timepoint_data[base_key].shape[0]))
else:
gt_masses.append(0.0)
else:
gt_masses = [0.0 for _ in range(n_branches)]
# determine normalization denominator
if n_initial is None:
s = float(sum(gt_masses))
if s > 0:
n_initial = s
else:
n_initial = float(sum(pred_masses)) if sum(pred_masses) > 0 else 1.0
pred_fracs = [m / float(n_initial) for m in pred_masses]
gt_fracs = [m / float(n_initial) for m in gt_masses]
tmv = 0.5 * float(np.sum(np.abs(np.array(pred_fracs) - np.array(gt_fracs))))
return {
'time_index': time_index,
'pred_masses': pred_masses,
'gt_masses': gt_masses,
'pred_fracs': pred_fracs,
'gt_fracs': gt_fracs,
'tmv': tmv,
}
class FlowNetTestLidar(GrowthNetTrain):
def test_step(self, batch, batch_idx):
# Unwrap CombinedLoader outer tuple if needed
if isinstance(batch, (list, tuple)) and len(batch) == 1:
batch = batch[0]
if isinstance(batch, dict) and "test_samples" in batch:
test_samples = batch["test_samples"]
metric_samples = batch["metric_samples"]
if isinstance(test_samples, (list, tuple)) and len(test_samples) >= 2 and isinstance(test_samples[-1], int):
test_samples = test_samples[0]
if isinstance(metric_samples, (list, tuple)) and len(metric_samples) >= 2 and isinstance(metric_samples[-1], int):
metric_samples = metric_samples[0]
if isinstance(test_samples, (list, tuple)) and len(test_samples) == 1:
test_samples = test_samples[0]
main_batch = test_samples
if isinstance(metric_samples, dict):
metric_batch = list(metric_samples.values())
elif isinstance(metric_samples, (list, tuple)):
metric_batch = [m[0] if isinstance(m, (list, tuple)) and len(m) == 1 else m for m in metric_samples]
else:
metric_batch = [metric_samples]
elif isinstance(batch, (list, tuple)) and len(batch) == 2:
# Old tuple format: (test_samples, metric_samples)
# Each could be dict or list
test_samples = batch[0]
metric_samples = batch[1]
if isinstance(test_samples, dict):
main_batch = test_samples
elif isinstance(test_samples, (list, tuple)):
main_batch = test_samples[0]
else:
main_batch = test_samples
if isinstance(metric_samples, dict):
metric_batch = list(metric_samples.values())
elif isinstance(metric_samples, (list, tuple)):
metric_batch = [m[0] if isinstance(m, (list, tuple)) and len(m) == 1 else m for m in metric_samples]
else:
metric_batch = [metric_samples]
else:
# Fallback
main_batch = batch
metric_batch = []
timepoint_data = self.trainer.datamodule.get_timepoint_data()
# main_batch is a dict like {"x0": (tensor, weights), ...}
if isinstance(main_batch, dict):
device = main_batch["x0"][0].device
else:
device = main_batch[0]["x0"][0].device
x0_all = self.trainer.datamodule.val_dataloaders["x0"].dataset.tensors[0].to(device)
w0_all = torch.ones(x0_all.shape[0], 1, dtype=torch.float32).to(device)
full_batch = {"x0": (x0_all, w0_all)}
time_points, all_endpoints, all_trajs, mass_over_time, energy_over_time, weights_over_time = self.get_mass_and_position(full_batch, metric_batch)
cloud_points = main_batch["dataset"][0] # [N, 3]
# Run 5 trials with random subsampling for robust metrics
n_trials = 5
# Compute per-branch metrics
metrics_dict = {}
for i, endpoints in enumerate(all_endpoints):
true_data_key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
true_data = torch.tensor(timepoint_data[true_data_key], dtype=torch.float32).to(endpoints.device)
w1_br, w2_br, mmd_br = [], [], []
for trial in range(n_trials):
n_min = min(endpoints.shape[0], true_data.shape[0])
perm_pred = torch.randperm(endpoints.shape[0])[:n_min]
perm_gt = torch.randperm(true_data.shape[0])[:n_min]
m = compute_distribution_distances(
endpoints[perm_pred, :2], true_data[perm_gt, :2],
pred_full=endpoints[perm_pred], true_full=true_data[perm_gt]
)
w1_br.append(m["W1"]); w2_br.append(m["W2"]); mmd_br.append(m["MMD"])
metrics_dict[f"branch_{i+1}"] = {
"W1_mean": float(np.mean(w1_br)), "W1_std": float(np.std(w1_br, ddof=1)),
"W2_mean": float(np.mean(w2_br)), "W2_std": float(np.std(w2_br, ddof=1)),
"MMD_mean": float(np.mean(mmd_br)), "MMD_std": float(np.std(mmd_br, ddof=1)),
}
self.log(f"test/W1_branch{i+1}", np.mean(w1_br), on_epoch=True)
print(f"Branch {i+1} — W1: {np.mean(w1_br):.6f}±{np.std(w1_br, ddof=1):.6f}, "
f"W2: {np.mean(w2_br):.6f}±{np.std(w2_br, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br):.6f}±{np.std(mmd_br, ddof=1):.6f}")
# Compute combined metrics across all branches (5 trials)
all_pred_combined = torch.cat(list(all_endpoints), dim=0)
all_true_list = []
for i in range(len(all_endpoints)):
true_data_key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
all_true_list.append(torch.tensor(timepoint_data[true_data_key], dtype=torch.float32).to(all_pred_combined.device))
all_true_combined = torch.cat(all_true_list, dim=0)
w1_trials, w2_trials, mmd_trials = [], [], []
for trial in range(n_trials):
n_min = min(all_pred_combined.shape[0], all_true_combined.shape[0])
perm_pred = torch.randperm(all_pred_combined.shape[0])[:n_min]
perm_gt = torch.randperm(all_true_combined.shape[0])[:n_min]
m = compute_distribution_distances(
all_pred_combined[perm_pred, :2], all_true_combined[perm_gt, :2],
pred_full=all_pred_combined[perm_pred], true_full=all_true_combined[perm_gt]
)
w1_trials.append(m["W1"]); w2_trials.append(m["W2"]); mmd_trials.append(m["MMD"])
w1_mean, w1_std = np.mean(w1_trials), np.std(w1_trials, ddof=1)
w2_mean, w2_std = np.mean(w2_trials), np.std(w2_trials, ddof=1)
mmd_mean, mmd_std = np.mean(mmd_trials), np.std(mmd_trials, ddof=1)
self.log("test/W1_combined", w1_mean, on_epoch=True)
self.log("test/W2_combined", w2_mean, on_epoch=True)
self.log("test/MMD_combined", mmd_mean, on_epoch=True)
metrics_dict["combined"] = {
"W1_mean": float(w1_mean), "W1_std": float(w1_std),
"W2_mean": float(w2_mean), "W2_std": float(w2_std),
"MMD_mean": float(mmd_mean), "MMD_std": float(mmd_std),
"n_trials": n_trials,
}
print(f"\n=== Combined ===")
print(f"W1: {w1_mean:.6f} ± {w1_std:.6f}")
print(f"W2: {w2_mean:.6f} ± {w2_std:.6f}")
print(f"MMD: {mmd_mean:.6f} ± {mmd_std:.6f}")
# Inverse-transform cloud points for visualization
if self.whiten:
cloud_points = torch.tensor(
self.trainer.datamodule.scaler.inverse_transform(
cloud_points.cpu().detach().numpy()
)
)
# Create results directory structure
run_name = self.args.run_name if hasattr(self.args, 'run_name') and self.args.run_name else self.args.data_name
results_dir = os.path.join(self.args.working_dir, 'results', run_name)
figures_dir = f'{results_dir}/figures'
os.makedirs(figures_dir, exist_ok=True)
# Save metrics to JSON
metrics_path = f'{results_dir}/metrics.json'
with open(metrics_path, 'w') as f:
json.dump(metrics_dict, f, indent=2)
print(f"Metrics saved to {metrics_path}")
# Save detailed per-branch metrics to CSV
detailed_csv_path = f'{results_dir}/metrics_detailed.csv'
with open(detailed_csv_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Metric_Group', 'W1_Mean', 'W1_Std', 'W2_Mean', 'W2_Std', 'MMD_Mean', 'MMD_Std'])
for key in sorted(metrics_dict.keys()):
m = metrics_dict[key]
writer.writerow([key,
f'{m.get("W1_mean", m.get("W1", 0)):.6f}', f'{m.get("W1_std", 0):.6f}',
f'{m.get("W2_mean", m.get("W2", 0)):.6f}', f'{m.get("W2_std", 0):.6f}',
f'{m.get("MMD_mean", m.get("MMD", 0)):.6f}', f'{m.get("MMD_std", 0):.6f}'])
print(f"Detailed metrics CSV saved to {detailed_csv_path}")
# Convert all_trajs from list of lists to stacked tensors for plotting
# all_trajs[i] is a list of T tensors of shape [B, D]
# Stack to get shape [B, T, D]
stacked_trajs = []
for traj_list in all_trajs:
# Stack along time dimension (dim=1) to get [B, T, D]
stacked_traj = torch.stack(traj_list, dim=1)
stacked_trajs.append(stacked_traj)
# Inverse-transform trajectories to match cloud_points coordinates
if self.whiten:
stacked_trajs_original = []
for traj in stacked_trajs:
B, T, D = traj.shape
# Reshape to [B*T, D] for inverse transform
traj_flat = traj.reshape(-1, D).cpu().detach().numpy()
traj_inv = self.trainer.datamodule.scaler.inverse_transform(traj_flat)
# Reshape back to [B, T, D]
traj_inv = torch.tensor(traj_inv).reshape(B, T, D)
stacked_trajs_original.append(traj_inv)
stacked_trajs = stacked_trajs_original
# ===== Plot all branches together =====
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d", computed_zorder=False)
ax.view_init(elev=30, azim=-115, roll=0)
for i, traj in enumerate(stacked_trajs):
plot_lidar(ax, cloud_points, xs=traj, branch_idx=i)
plt.savefig(f'{figures_dir}/{self.args.data_name}_all_branches.png', dpi=300)
plt.close()
# ===== Plot each branch separately =====
for i, traj in enumerate(stacked_trajs):
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d", computed_zorder=False)
ax.view_init(elev=30, azim=-115, roll=0)
plot_lidar(ax, cloud_points, xs=traj, branch_idx=i)
plt.savefig(f'{figures_dir}/{self.args.data_name}_branch_{i + 1}.png', dpi=300)
plt.close()
print(f"LiDAR figures saved to {figures_dir}")
class FlowNetTestMouse(GrowthNetTrain):
def test_step(self, batch, batch_idx):
# Handle both tuple and dict batch formats from CombinedLoader
if isinstance(batch, dict):
main_batch = batch.get("test_samples", batch)
if isinstance(main_batch, tuple):
main_batch = main_batch[0]
elif isinstance(batch, (list, tuple)) and len(batch) >= 1:
if isinstance(batch[0], dict):
main_batch = batch[0].get("test_samples", batch[0])
if isinstance(main_batch, tuple):
main_batch = main_batch[0]
else:
main_batch = batch[0][0]
else:
main_batch = batch
device = main_batch["x0"][0].device
# Use val x0 as initial conditions
x0 = self.trainer.datamodule.val_dataloaders["x0"].dataset.tensors[0].to(device)
# Get timepoint data for ground truth
timepoint_data = self.trainer.datamodule.get_timepoint_data()
# Ground truth at t1 (intermediate timepoint)
data_t1 = torch.tensor(timepoint_data['t1'], dtype=torch.float32)
# Define color schemes for mouse (2 branches)
custom_colors_1 = ["#05009E", "#A19EFF", "#B83CFF"]
custom_colors_2 = ["#05009E", "#A19EFF", "#50B2D7"]
custom_cmap_1 = LinearSegmentedColormap.from_list("cmap1", custom_colors_1)
custom_cmap_2 = LinearSegmentedColormap.from_list("cmap2", custom_colors_2)
t_span_full = torch.linspace(0, 1.0, 100).to(device)
all_trajs = []
for i, flow_net in enumerate(self.flow_nets):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
).to(device)
with torch.no_grad():
traj = node.trajectory(x0, t_span_full).cpu() # [T, B, D]
traj = torch.transpose(traj, 0, 1) # [B, T, D]
all_trajs.append(traj)
t_span_metric_t1 = torch.linspace(0, 0.5, 50).to(device)
t_span_metric_t2 = torch.linspace(0, 1.0, 100).to(device)
n_trials = 5
# Gather t2 branch ground truth
data_t2_branches = []
for i in range(len(self.flow_nets)):
key = f't2_{i+1}'
if key in timepoint_data:
data_t2_branches.append(torch.tensor(timepoint_data[key], dtype=torch.float32))
elif i == 0 and 't2' in timepoint_data:
data_t2_branches.append(torch.tensor(timepoint_data['t2'], dtype=torch.float32))
else:
data_t2_branches.append(None)
# Combined t2 ground truth (all branches merged)
data_t2_all_list = [d for d in data_t2_branches if d is not None]
data_t2_combined = torch.cat(data_t2_all_list, dim=0) if data_t2_all_list else None
# ---- t1 combined metrics (all branches pooled, compared to t1) ----
w1_t1_trials, w2_t1_trials, mmd_t1_trials = [], [], []
for trial in range(n_trials):
all_preds = []
for i, flow_net in enumerate(self.flow_nets):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
).to(device)
with torch.no_grad():
traj = node.trajectory(x0, t_span_metric_t1) # [T, B, D]
x_final = traj[-1].cpu() # [B, D]
all_preds.append(x_final)
preds = torch.cat(all_preds, dim=0)
target_size = preds.shape[0]
perm = torch.randperm(data_t1.shape[0])[:target_size]
data_t1_reduced = data_t1[perm]
metrics = compute_distribution_distances(
preds[:, :2], data_t1_reduced[:, :2]
)
w1_t1_trials.append(metrics["W1"])
w2_t1_trials.append(metrics["W2"])
mmd_t1_trials.append(metrics["MMD"])
# ---- t2 per-branch metrics (each branch endpoint vs its own t2 cluster) ----
branch_t2_metrics = {}
for i, flow_net in enumerate(self.flow_nets):
if data_t2_branches[i] is None:
continue
w1_br, w2_br, mmd_br = [], [], []
for trial in range(n_trials):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
).to(device)
with torch.no_grad():
traj = node.trajectory(x0, t_span_metric_t2)
x_final = traj[-1].cpu()
gt = data_t2_branches[i]
n_min = min(x_final.shape[0], gt.shape[0])
perm_pred = torch.randperm(x_final.shape[0])[:n_min]
perm_gt = torch.randperm(gt.shape[0])[:n_min]
m = compute_distribution_distances(
x_final[perm_pred, :2], gt[perm_gt, :2]
)
w1_br.append(m["W1"])
w2_br.append(m["W2"])
mmd_br.append(m["MMD"])
branch_t2_metrics[f"branch_{i+1}_t2"] = {
"W1_mean": float(np.mean(w1_br)), "W1_std": float(np.std(w1_br, ddof=1)),
"W2_mean": float(np.mean(w2_br)), "W2_std": float(np.std(w2_br, ddof=1)),
"MMD_mean": float(np.mean(mmd_br)), "MMD_std": float(np.std(mmd_br, ddof=1)),
}
print(f"Branch {i+1} @ t2 — W1: {np.mean(w1_br):.6f}±{np.std(w1_br, ddof=1):.6f}, "
f"W2: {np.mean(w2_br):.6f}±{np.std(w2_br, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br):.6f}±{np.std(mmd_br, ddof=1):.6f}")
# ---- t2 combined metrics (all branches pooled, compared to all t2) ----
w1_t2_trials, w2_t2_trials, mmd_t2_trials = [], [], []
if data_t2_combined is not None:
for trial in range(n_trials):
all_preds = []
for i, flow_net in enumerate(self.flow_nets):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
).to(device)
with torch.no_grad():
traj = node.trajectory(x0, t_span_metric_t2)
all_preds.append(traj[-1].cpu())
preds = torch.cat(all_preds, dim=0)
n_min = min(preds.shape[0], data_t2_combined.shape[0])
perm_pred = torch.randperm(preds.shape[0])[:n_min]
perm_gt = torch.randperm(data_t2_combined.shape[0])[:n_min]
m = compute_distribution_distances(
preds[perm_pred, :2], data_t2_combined[perm_gt, :2]
)
w1_t2_trials.append(m["W1"])
w2_t2_trials.append(m["W2"])
mmd_t2_trials.append(m["MMD"])
# Compute mean and std
w1_t1_mean, w1_t1_std = np.mean(w1_t1_trials), np.std(w1_t1_trials, ddof=1)
w2_t1_mean, w2_t1_std = np.mean(w2_t1_trials), np.std(w2_t1_trials, ddof=1)
mmd_t1_mean, mmd_t1_std = np.mean(mmd_t1_trials), np.std(mmd_t1_trials, ddof=1)
# Log metrics
self.log("test/W1_combined_t1", w1_t1_mean, on_epoch=True)
self.log("test/W2_combined_t1", w2_t1_mean, on_epoch=True)
self.log("test/MMD_combined_t1", mmd_t1_mean, on_epoch=True)
metrics_dict = {
"combined_t1": {
"W1_mean": float(w1_t1_mean), "W1_std": float(w1_t1_std),
"W2_mean": float(w2_t1_mean), "W2_std": float(w2_t1_std),
"MMD_mean": float(mmd_t1_mean), "MMD_std": float(mmd_t1_std),
"n_trials": n_trials,
}
}
metrics_dict.update(branch_t2_metrics)
if w1_t2_trials:
w1_t2_mean, w1_t2_std = np.mean(w1_t2_trials), np.std(w1_t2_trials, ddof=1)
w2_t2_mean, w2_t2_std = np.mean(w2_t2_trials), np.std(w2_t2_trials, ddof=1)
mmd_t2_mean, mmd_t2_std = np.mean(mmd_t2_trials), np.std(mmd_t2_trials, ddof=1)
self.log("test/W1_combined_t2", w1_t2_mean, on_epoch=True)
self.log("test/W2_combined_t2", w2_t2_mean, on_epoch=True)
self.log("test/MMD_combined_t2", mmd_t2_mean, on_epoch=True)
metrics_dict["combined_t2"] = {
"W1_mean": float(w1_t2_mean), "W1_std": float(w1_t2_std),
"W2_mean": float(w2_t2_mean), "W2_std": float(w2_t2_std),
"MMD_mean": float(mmd_t2_mean), "MMD_std": float(mmd_t2_std),
"n_trials": n_trials,
}
print(f"\n=== Combined @ t1 ===")
print(f"W1: {w1_t1_mean:.6f} ± {w1_t1_std:.6f}")
print(f"W2: {w2_t1_mean:.6f} ± {w2_t1_std:.6f}")
print(f"MMD: {mmd_t1_mean:.6f} ± {mmd_t1_std:.6f}")
if w1_t2_trials:
print(f"\n=== Combined @ t2 ===")
print(f"W1: {w1_t2_mean:.6f} ± {w1_t2_std:.6f}")
print(f"W2: {w2_t2_mean:.6f} ± {w2_t2_std:.6f}")
print(f"MMD: {mmd_t2_mean:.6f} ± {mmd_t2_std:.6f}")
# Create results directory structure
run_name = self.args.run_name if hasattr(self.args, 'run_name') and self.args.run_name else self.args.data_name
results_dir = os.path.join(self.args.working_dir, 'results', run_name)
figures_dir = f'{results_dir}/figures'
os.makedirs(figures_dir, exist_ok=True)
# Save metrics to JSON
metrics_path = f'{results_dir}/metrics.json'
with open(metrics_path, 'w') as f:
json.dump(metrics_dict, f, indent=2)
print(f"Metrics saved to {metrics_path}")
# Save detailed metrics to CSV
detailed_csv_path = f'{results_dir}/metrics_detailed.csv'
with open(detailed_csv_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Metric_Group', 'W1_Mean', 'W1_Std', 'W2_Mean', 'W2_Std', 'MMD_Mean', 'MMD_Std'])
for key in sorted(metrics_dict.keys()):
m = metrics_dict[key]
writer.writerow([key,
f'{m.get("W1_mean", 0):.6f}', f'{m.get("W1_std", 0):.6f}',
f'{m.get("W2_mean", 0):.6f}', f'{m.get("W2_std", 0):.6f}',
f'{m.get("MMD_mean", 0):.6f}', f'{m.get("MMD_std", 0):.6f}'])
print(f"Detailed metrics CSV saved to {detailed_csv_path}")
# ===== Plot individual branches (using full t_span trajectories) =====
self._plot_mouse_branches(all_trajs, timepoint_data, figures_dir, custom_cmap_1, custom_cmap_2)
# ===== Plot all branches together =====
self._plot_mouse_combined(all_trajs, timepoint_data, figures_dir, custom_cmap_1, custom_cmap_2)
print(f"Mouse figures saved to {figures_dir}")
def _plot_mouse_branches(self, all_trajs, timepoint_data, save_dir, cmap1, cmap2):
"""Plot each branch separately with timepoint background."""
n_branches = len(all_trajs)
branch_names = [f'Branch {i+1}' for i in range(n_branches)]
branch_colors = ['#B83CFF', '#50B2D7'][:n_branches]
cmaps = [cmap1, cmap2][:n_branches]
# Stack list-of-tensors into [B, T, D] numpy arrays
all_trajs_np = []
for traj in all_trajs:
if isinstance(traj, list):
traj = torch.stack(traj, dim=1) # list of [B,D] -> [B,T,D]
all_trajs_np.append(traj.cpu().detach().numpy())
all_trajs = all_trajs_np
# Move timepoint data to numpy
for key in list(timepoint_data.keys()):
if torch.is_tensor(timepoint_data[key]):
timepoint_data[key] = timepoint_data[key].cpu().numpy()
# Compute global axis limits
all_coords = []
for key in ['t0', 't1', 't2', 't2_1', 't2_2']:
if key in timepoint_data:
all_coords.append(timepoint_data[key][:, :2])
for traj_np in all_trajs:
all_coords.append(traj_np.reshape(-1, traj_np.shape[-1])[:, :2])
all_coords = np.concatenate(all_coords, axis=0)
x_min, x_max = all_coords[:, 0].min(), all_coords[:, 0].max()
y_min, y_max = all_coords[:, 1].min(), all_coords[:, 1].max()
# Add margin
x_margin = 0.05 * (x_max - x_min)
y_margin = 0.05 * (y_max - y_min)
x_min -= x_margin
x_max += x_margin
y_min -= y_margin
y_max += y_margin
for i, traj in enumerate(all_trajs):
fig, ax = plt.subplots(figsize=(10, 8))
cmap = cmaps[i]
c_end = branch_colors[i]
# Plot timepoint background
t2_key = f't2_{i+1}' if f't2_{i+1}' in timepoint_data else 't2'
coords_list = [timepoint_data['t0'], timepoint_data['t1'], timepoint_data[t2_key]]
tp_colors = ['#05009E', '#A19EFF', c_end]
tp_labels = ["t=0", "t=1", f"t=2 (branch {i+1})"]
for coords, color, label in zip(coords_list, tp_colors, tp_labels):
alpha = 0.8 if color == '#05009E' else 0.6
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=alpha, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot continuous trajectories with LineCollection for speed
traj_2d = traj[:, :, :2]
n_time = traj_2d.shape[1]
color_vals = cmap(np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j] # [T, 2]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
# Start and end points
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o', label='Trajectory Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o', label='Trajectory End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel("PC1", fontsize=12)
ax.set_ylabel("PC2", fontsize=12)
ax.set_title(f"{branch_names[i]}: Trajectories with Timepoint Background", fontsize=14)
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=12, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_branch{i+1}.png', dpi=300)
plt.close()
def _plot_mouse_combined(self, all_trajs, timepoint_data, save_dir, cmap1, cmap2):
"""Plot all branches together."""
n_branches = len(all_trajs)
branch_names = [f'Branch {i+1}' for i in range(n_branches)]
branch_colors = ['#B83CFF', '#50B2D7'][:n_branches]
# Build timepoint key/color/label lists depending on branching
if 't2_1' in timepoint_data:
tp_keys = ['t0', 't1', 't2_1', 't2_2']
tp_colors = ['#05009E', '#A19EFF', '#B83CFF', '#50B2D7']
tp_labels = ['t=0', 't=1', 't=2 (branch 1)', 't=2 (branch 2)']
else:
tp_keys = ['t0', 't1', 't2']
tp_colors = ['#05009E', '#A19EFF', '#B83CFF']
tp_labels = ['t=0', 't=1', 't=2']
# Stack list-of-tensors into [B, T, D] numpy arrays
all_trajs_np = []
for traj in all_trajs:
if isinstance(traj, list):
traj = torch.stack(traj, dim=1)
if torch.is_tensor(traj):
traj = traj.cpu().detach().numpy()
all_trajs_np.append(traj)
all_trajs = all_trajs_np
# Move timepoint data to numpy
for key in list(timepoint_data.keys()):
if torch.is_tensor(timepoint_data[key]):
timepoint_data[key] = timepoint_data[key].cpu().numpy()
fig, ax = plt.subplots(figsize=(12, 10))
# Plot timepoint background
for idx, (t_key, color, label) in enumerate(zip(
tp_keys,
tp_colors,
tp_labels
)):
if t_key in timepoint_data:
coords = timepoint_data[t_key]
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=0.4, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot trajectories with color gradients
cmaps = [cmap1, cmap2]
for i, traj in enumerate(all_trajs):
traj_2d = traj[:, :, :2]
c_end = branch_colors[i]
cmap = cmaps[i]
n_time = traj_2d.shape[1]
color_vals = cmap(np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o',
label=f'{branch_names[i]} Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o',
label=f'{branch_names[i]} End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlabel("PC1", fontsize=14)
ax.set_ylabel("PC2", fontsize=14)
ax.set_title("All Branch Trajectories with Timepoint Background",
fontsize=16, weight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=12, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_combined.png', dpi=300)
plt.close()
class FlowNetTestClonidine(BranchFlowNetTrainBase):
"""Test class for Clonidine perturbation experiment (1 or 2 branches)."""
def test_step(self, batch, batch_idx):
# Handle both dict and tuple batch formats from CombinedLoader
if isinstance(batch, dict) and "test_samples" in batch:
# New format: {"test_samples": {...}, "metric_samples": {...}}
main_batch = batch["test_samples"]
elif isinstance(batch, (list, tuple)) and len(batch) >= 1:
# Old format with nested structure
test_samples = batch[0]
if isinstance(test_samples, dict) and "test_samples" in test_samples:
main_batch = test_samples["test_samples"][0]
else:
main_batch = test_samples
else:
# Fallback
main_batch = batch
# Get timepoint data
timepoint_data = self.trainer.datamodule.get_timepoint_data()
device = main_batch["x0"][0].device
# Use val x0 as initial conditions
x0 = self.trainer.datamodule.val_dataloaders["x0"].dataset.tensors[0].to(device)
t_span = torch.linspace(0, 1, 100).to(device)
# Define color schemes for clonidine (2 branches)
custom_colors_1 = ["#05009E", "#A19EFF", "#B83CFF"]
custom_colors_2 = ["#05009E", "#A19EFF", "#50B2D7"]
custom_cmap_1 = LinearSegmentedColormap.from_list("cmap1", custom_colors_1)
custom_cmap_2 = LinearSegmentedColormap.from_list("cmap2", custom_colors_2)
all_trajs = []
all_endpoints = []
for i, flow_net in enumerate(self.flow_nets):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
)
with torch.no_grad():
traj = node.trajectory(x0, t_span).cpu() # [T, B, D]
traj = torch.transpose(traj, 0, 1) # [B, T, D]
all_trajs.append(traj)
all_endpoints.append(traj[:, -1, :])
# Run 5 trials with random subsampling for robust metrics
n_trials = 5
n_branches = len(self.flow_nets)
# Gather per-branch ground truth
gt_data_per_branch = []
for i in range(n_branches):
if n_branches == 1:
key = 't1'
else:
key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
gt_data_per_branch.append(torch.tensor(timepoint_data[key], dtype=torch.float32))
gt_all = torch.cat(gt_data_per_branch, dim=0)
# Per-branch metrics (5 trials)
metrics_dict = {}
for i in range(n_branches):
w1_br, w2_br, mmd_br = [], [], []
pred = all_endpoints[i]
gt = gt_data_per_branch[i]
for trial in range(n_trials):
n_min = min(pred.shape[0], gt.shape[0])
perm_pred = torch.randperm(pred.shape[0])[:n_min]
perm_gt = torch.randperm(gt.shape[0])[:n_min]
m = compute_distribution_distances(pred[perm_pred, :2], gt[perm_gt, :2])
w1_br.append(m["W1"]); w2_br.append(m["W2"]); mmd_br.append(m["MMD"])
metrics_dict[f"branch_{i+1}"] = {
"W1_mean": float(np.mean(w1_br)), "W1_std": float(np.std(w1_br, ddof=1)),
"W2_mean": float(np.mean(w2_br)), "W2_std": float(np.std(w2_br, ddof=1)),
"MMD_mean": float(np.mean(mmd_br)), "MMD_std": float(np.std(mmd_br, ddof=1)),
}
self.log(f"test/W1_branch{i+1}", np.mean(w1_br), on_epoch=True)
print(f"Branch {i+1} — W1: {np.mean(w1_br):.6f}±{np.std(w1_br, ddof=1):.6f}, "
f"W2: {np.mean(w2_br):.6f}±{np.std(w2_br, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br):.6f}±{np.std(mmd_br, ddof=1):.6f}")
# Combined metrics (5 trials)
pred_all = torch.cat(all_endpoints, dim=0)
w1_trials, w2_trials, mmd_trials = [], [], []
for trial in range(n_trials):
n_min = min(pred_all.shape[0], gt_all.shape[0])
perm_pred = torch.randperm(pred_all.shape[0])[:n_min]
perm_gt = torch.randperm(gt_all.shape[0])[:n_min]
m = compute_distribution_distances(pred_all[perm_pred, :2], gt_all[perm_gt, :2])
w1_trials.append(m["W1"]); w2_trials.append(m["W2"]); mmd_trials.append(m["MMD"])
w1_mean, w1_std = np.mean(w1_trials), np.std(w1_trials, ddof=1)
w2_mean, w2_std = np.mean(w2_trials), np.std(w2_trials, ddof=1)
mmd_mean, mmd_std = np.mean(mmd_trials), np.std(mmd_trials, ddof=1)
self.log("test/W1_t1_combined", w1_mean, on_epoch=True)
self.log("test/W2_t1_combined", w2_mean, on_epoch=True)
self.log("test/MMD_t1_combined", mmd_mean, on_epoch=True)
metrics_dict['t1_combined'] = {
"W1_mean": float(w1_mean), "W1_std": float(w1_std),
"W2_mean": float(w2_mean), "W2_std": float(w2_std),
"MMD_mean": float(mmd_mean), "MMD_std": float(mmd_std),
"n_trials": n_trials,
}
print(f"\n=== Combined @ t1 ===")
print(f"W1: {w1_mean:.6f} ± {w1_std:.6f}")
print(f"W2: {w2_mean:.6f} ± {w2_std:.6f}")
print(f"MMD: {mmd_mean:.6f} ± {mmd_std:.6f}")
# Create results directory structure
run_name = self.args.run_name if hasattr(self.args, 'run_name') and self.args.run_name else self.args.data_name
results_dir = os.path.join(self.args.working_dir, 'results', run_name)
figures_dir = f'{results_dir}/figures'
os.makedirs(figures_dir, exist_ok=True)
# Save metrics to JSON
metrics_path = f'{results_dir}/metrics.json'
with open(metrics_path, 'w') as f:
json.dump(metrics_dict, f, indent=2)
print(f"Metrics saved to {metrics_path}")
# Save detailed metrics to CSV
detailed_csv_path = f'{results_dir}/metrics_detailed.csv'
with open(detailed_csv_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Metric_Group', 'W1_Mean', 'W1_Std', 'W2_Mean', 'W2_Std', 'MMD_Mean', 'MMD_Std'])
for key in sorted(metrics_dict.keys()):
m = metrics_dict[key]
writer.writerow([key,
f'{m.get("W1_mean", m.get("W1", 0)):.6f}', f'{m.get("W1_std", 0):.6f}',
f'{m.get("W2_mean", m.get("W2", 0)):.6f}', f'{m.get("W2_std", 0):.6f}',
f'{m.get("MMD_mean", m.get("MMD", 0)):.6f}', f'{m.get("MMD_std", 0):.6f}'])
print(f"Detailed metrics CSV saved to {detailed_csv_path}")
# ===== Plot branches =====
self._plot_clonidine_branches(all_trajs, timepoint_data, figures_dir, custom_cmap_1, custom_cmap_2)
self._plot_clonidine_combined(all_trajs, timepoint_data, figures_dir)
print(f"Clonidine figures saved to {figures_dir}")
def _plot_clonidine_branches(self, all_trajs, timepoint_data, save_dir, cmap1, cmap2):
"""Plot each branch separately."""
branch_names = ['Branch 1', 'Branch 2']
branch_colors = ['#B83CFF', '#50B2D7']
cmaps = [cmap1, cmap2]
# Compute global axis limits – handle single vs multi branch keys
all_coords = []
if 't1_1' in timepoint_data:
tp_keys = ['t0'] + [f't1_{i+1}' for i in range(len(all_trajs))]
else:
tp_keys = ['t0', 't1']
for key in tp_keys:
all_coords.append(timepoint_data[key][:, :2])
for traj in all_trajs:
all_coords.append(traj.reshape(-1, traj.shape[-1])[:, :2])
all_coords = np.concatenate(all_coords, axis=0)
x_min, x_max = all_coords[:, 0].min(), all_coords[:, 0].max()
y_min, y_max = all_coords[:, 1].min(), all_coords[:, 1].max()
x_margin = 0.05 * (x_max - x_min)
y_margin = 0.05 * (y_max - y_min)
x_min -= x_margin
x_max += x_margin
y_min -= y_margin
y_max += y_margin
for i, traj in enumerate(all_trajs):
fig, ax = plt.subplots(figsize=(10, 8))
c_end = branch_colors[i]
# Plot timepoint background
t1_key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
coords_list = [timepoint_data['t0'], timepoint_data[t1_key]]
tp_colors = ['#05009E', c_end]
t1_label = f"t=1 (branch {i+1})" if len(all_trajs) > 1 else "t=1"
tp_labels = ["t=0", t1_label]
for coords, color, label in zip(coords_list, tp_colors, tp_labels):
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=0.4, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot continuous trajectories with LineCollection for speed
traj_2d = traj[:, :, :2]
n_time = traj_2d.shape[1]
color_vals = cmaps[i](np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
# Start and end points
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o', label='Trajectory Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o', label='Trajectory End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel("PC1", fontsize=12)
ax.set_ylabel("PC2", fontsize=12)
ax.set_title(f"{branch_names[i]}: Trajectories with Timepoint Background", fontsize=14)
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=16, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_branch{i+1}.png', dpi=300)
plt.close()
def _plot_clonidine_combined(self, all_trajs, timepoint_data, save_dir):
"""Plot all branches together."""
branch_names = ['Branch 1', 'Branch 2']
branch_colors = ['#B83CFF', '#50B2D7']
fig, ax = plt.subplots(figsize=(12, 10))
# Build timepoint keys/colors/labels depending on single vs multi branch
if 't1_1' in timepoint_data:
tp_keys = ['t0'] + [f't1_{j+1}' for j in range(len(all_trajs))]
tp_labels_list = ['t=0'] + [f't=1 (branch {j+1})' for j in range(len(all_trajs))]
else:
tp_keys = ['t0', 't1']
tp_labels_list = ['t=0', 't=1']
tp_colors = ['#05009E', '#B83CFF', '#50B2D7'][:len(tp_keys)]
# Plot timepoint background
for t_key, color, label in zip(tp_keys, tp_colors, tp_labels_list):
coords = timepoint_data[t_key]
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=0.4, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot trajectories with color gradients
custom_colors_1 = ["#05009E", "#A19EFF", "#B83CFF"]
custom_colors_2 = ["#05009E", "#A19EFF", "#50B2D7"]
cmaps = [
LinearSegmentedColormap.from_list("clon_cmap1", custom_colors_1),
LinearSegmentedColormap.from_list("clon_cmap2", custom_colors_2),
]
for i, traj in enumerate(all_trajs):
traj_2d = traj[:, :, :2]
c_end = branch_colors[i]
cmap = cmaps[i]
n_time = traj_2d.shape[1]
color_vals = cmap(np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o',
label=f'{branch_names[i]} Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o',
label=f'{branch_names[i]} End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlabel("PC1", fontsize=14)
ax.set_ylabel("PC2", fontsize=14)
ax.set_title("All Branch Trajectories with Timepoint Background",
fontsize=16, weight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=12, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_combined.png', dpi=300)
plt.close()
class FlowNetTestTrametinib(BranchFlowNetTrainBase):
"""Test class for Trametinib perturbation experiment (1 or 3 branches)."""
def test_step(self, batch, batch_idx):
# Handle both dict and tuple batch formats from CombinedLoader
if isinstance(batch, dict) and "test_samples" in batch:
# New format: {"test_samples": {...}, "metric_samples": {...}}
main_batch = batch["test_samples"]
elif isinstance(batch, (list, tuple)) and len(batch) >= 1:
# Old format with nested structure
test_samples = batch[0]
if isinstance(test_samples, dict) and "test_samples" in test_samples:
main_batch = test_samples["test_samples"][0]
else:
main_batch = test_samples
else:
# Fallback
main_batch = batch
# Get timepoint data
timepoint_data = self.trainer.datamodule.get_timepoint_data()
device = main_batch["x0"][0].device
# Use val x0 as initial conditions
x0 = self.trainer.datamodule.val_dataloaders["x0"].dataset.tensors[0].to(device)
t_span = torch.linspace(0, 1, 100).to(device)
# Define color schemes for trametinib (3 branches)
custom_colors_1 = ["#05009E", "#A19EFF", "#9793F8"]
custom_colors_2 = ["#05009E", "#A19EFF", "#50B2D7"]
custom_colors_3 = ["#05009E", "#A19EFF", "#B83CFF"]
custom_cmap_1 = LinearSegmentedColormap.from_list("cmap1", custom_colors_1)
custom_cmap_2 = LinearSegmentedColormap.from_list("cmap2", custom_colors_2)
custom_cmap_3 = LinearSegmentedColormap.from_list("cmap3", custom_colors_3)
all_trajs = []
all_endpoints = []
for i, flow_net in enumerate(self.flow_nets):
node = NeuralODE(
flow_model_torch_wrapper(flow_net),
solver="euler",
sensitivity="adjoint",
)
with torch.no_grad():
traj = node.trajectory(x0, t_span).cpu() # [T, B, D]
traj = torch.transpose(traj, 0, 1) # [B, T, D]
all_trajs.append(traj)
all_endpoints.append(traj[:, -1, :])
# Run 5 trials with random subsampling for robust metrics
n_trials = 5
n_branches = len(self.flow_nets)
# Gather per-branch ground truth
gt_data_per_branch = []
for i in range(n_branches):
if n_branches == 1:
key = 't1'
else:
key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
gt_data_per_branch.append(torch.tensor(timepoint_data[key], dtype=torch.float32))
gt_all = torch.cat(gt_data_per_branch, dim=0)
# Per-branch metrics (5 trials)
metrics_dict = {}
for i in range(n_branches):
w1_br, w2_br, mmd_br = [], [], []
pred = all_endpoints[i]
gt = gt_data_per_branch[i]
for trial in range(n_trials):
n_min = min(pred.shape[0], gt.shape[0])
perm_pred = torch.randperm(pred.shape[0])[:n_min]
perm_gt = torch.randperm(gt.shape[0])[:n_min]
m = compute_distribution_distances(pred[perm_pred, :2], gt[perm_gt, :2])
w1_br.append(m["W1"]); w2_br.append(m["W2"]); mmd_br.append(m["MMD"])
metrics_dict[f"branch_{i+1}"] = {
"W1_mean": float(np.mean(w1_br)), "W1_std": float(np.std(w1_br, ddof=1)),
"W2_mean": float(np.mean(w2_br)), "W2_std": float(np.std(w2_br, ddof=1)),
"MMD_mean": float(np.mean(mmd_br)), "MMD_std": float(np.std(mmd_br, ddof=1)),
}
self.log(f"test/W1_branch{i+1}", np.mean(w1_br), on_epoch=True)
print(f"Branch {i+1} — W1: {np.mean(w1_br):.6f}±{np.std(w1_br, ddof=1):.6f}, "
f"W2: {np.mean(w2_br):.6f}±{np.std(w2_br, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br):.6f}±{np.std(mmd_br, ddof=1):.6f}")
# Combined metrics (5 trials)
pred_all = torch.cat(all_endpoints, dim=0)
w1_trials, w2_trials, mmd_trials = [], [], []
for trial in range(n_trials):
n_min = min(pred_all.shape[0], gt_all.shape[0])
perm_pred = torch.randperm(pred_all.shape[0])[:n_min]
perm_gt = torch.randperm(gt_all.shape[0])[:n_min]
m = compute_distribution_distances(pred_all[perm_pred, :2], gt_all[perm_gt, :2])
w1_trials.append(m["W1"]); w2_trials.append(m["W2"]); mmd_trials.append(m["MMD"])
w1_mean, w1_std = np.mean(w1_trials), np.std(w1_trials, ddof=1)
w2_mean, w2_std = np.mean(w2_trials), np.std(w2_trials, ddof=1)
mmd_mean, mmd_std = np.mean(mmd_trials), np.std(mmd_trials, ddof=1)
self.log("test/W1_t1_combined", w1_mean, on_epoch=True)
self.log("test/W2_t1_combined", w2_mean, on_epoch=True)
self.log("test/MMD_t1_combined", mmd_mean, on_epoch=True)
metrics_dict['t1_combined'] = {
"W1_mean": float(w1_mean), "W1_std": float(w1_std),
"W2_mean": float(w2_mean), "W2_std": float(w2_std),
"MMD_mean": float(mmd_mean), "MMD_std": float(mmd_std),
"n_trials": n_trials,
}
print(f"\n=== Combined @ t1 ===")
print(f"W1: {w1_mean:.6f} ± {w1_std:.6f}")
print(f"W2: {w2_mean:.6f} ± {w2_std:.6f}")
print(f"MMD: {mmd_mean:.6f} ± {mmd_std:.6f}")
# Create results directory structure
run_name = self.args.run_name if hasattr(self.args, 'run_name') and self.args.run_name else self.args.data_name
results_dir = os.path.join(self.args.working_dir, 'results', run_name)
figures_dir = f'{results_dir}/figures'
os.makedirs(figures_dir, exist_ok=True)
# Save metrics to JSON
metrics_path = f'{results_dir}/metrics.json'
with open(metrics_path, 'w') as f:
json.dump(metrics_dict, f, indent=2)
print(f"Metrics saved to {metrics_path}")
# Save detailed metrics to CSV
detailed_csv_path = f'{results_dir}/metrics_detailed.csv'
with open(detailed_csv_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Metric_Group', 'W1_Mean', 'W1_Std', 'W2_Mean', 'W2_Std', 'MMD_Mean', 'MMD_Std'])
for key in sorted(metrics_dict.keys()):
m = metrics_dict[key]
writer.writerow([key,
f'{m.get("W1_mean", m.get("W1", 0)):.6f}', f'{m.get("W1_std", 0):.6f}',
f'{m.get("W2_mean", m.get("W2", 0)):.6f}', f'{m.get("W2_std", 0):.6f}',
f'{m.get("MMD_mean", m.get("MMD", 0)):.6f}', f'{m.get("MMD_std", 0):.6f}'])
print(f"Detailed metrics CSV saved to {detailed_csv_path}")
# ===== Plot branches =====
self._plot_trametinib_branches(all_trajs, timepoint_data, figures_dir,
custom_cmap_1, custom_cmap_2, custom_cmap_3)
self._plot_trametinib_combined(all_trajs, timepoint_data, figures_dir)
print(f"Trametinib figures saved to {figures_dir}")
def _plot_trametinib_branches(self, all_trajs, timepoint_data, save_dir,
cmap1, cmap2, cmap3):
"""Plot each branch separately."""
branch_names = ['Branch 1', 'Branch 2', 'Branch 3']
branch_colors = ['#9793F8', '#50B2D7', '#B83CFF']
cmaps = [cmap1, cmap2, cmap3]
# Compute global axis limits – handle single vs multi branch keys
all_coords = []
if 't1_1' in timepoint_data:
tp_keys = ['t0'] + [f't1_{i+1}' for i in range(len(all_trajs))]
else:
tp_keys = ['t0', 't1']
for key in tp_keys:
all_coords.append(timepoint_data[key][:, :2])
for traj in all_trajs:
all_coords.append(traj.reshape(-1, traj.shape[-1])[:, :2])
all_coords = np.concatenate(all_coords, axis=0)
x_min, x_max = all_coords[:, 0].min(), all_coords[:, 0].max()
y_min, y_max = all_coords[:, 1].min(), all_coords[:, 1].max()
x_margin = 0.05 * (x_max - x_min)
y_margin = 0.05 * (y_max - y_min)
x_min -= x_margin
x_max += x_margin
y_min -= y_margin
y_max += y_margin
for i, traj in enumerate(all_trajs):
fig, ax = plt.subplots(figsize=(10, 8))
c_end = branch_colors[i]
# Plot timepoint background
t1_key = f't1_{i+1}' if f't1_{i+1}' in timepoint_data else 't1'
coords_list = [timepoint_data['t0'], timepoint_data[t1_key]]
tp_colors = ['#05009E', c_end]
t1_label = f"t=1 (branch {i+1})" if len(all_trajs) > 1 else "t=1"
tp_labels = ["t=0", t1_label]
for coords, color, label in zip(coords_list, tp_colors, tp_labels):
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=0.4, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot continuous trajectories with LineCollection for speed
traj_2d = traj[:, :, :2]
n_time = traj_2d.shape[1]
color_vals = cmaps[i](np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
# Start and end points
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o', label='Trajectory Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o', label='Trajectory End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel("PC1", fontsize=12)
ax.set_ylabel("PC2", fontsize=12)
ax.set_title(f"{branch_names[i]}: Trajectories with Timepoint Background", fontsize=14)
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=16, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_branch{i+1}.png', dpi=300)
plt.close()
def _plot_trametinib_combined(self, all_trajs, timepoint_data, save_dir):
"""Plot all 3 branches together."""
branch_names = ['Branch 1', 'Branch 2', 'Branch 3']
branch_colors = ['#9793F8', '#50B2D7', '#B83CFF']
fig, ax = plt.subplots(figsize=(12, 10))
# Build timepoint keys/colors/labels depending on single vs multi branch
if 't1_1' in timepoint_data:
tp_keys = ['t0'] + [f't1_{j+1}' for j in range(len(all_trajs))]
tp_labels_list = ['t=0'] + [f't=1 (branch {j+1})' for j in range(len(all_trajs))]
else:
tp_keys = ['t0', 't1']
tp_labels_list = ['t=0', 't=1']
tp_colors = ['#05009E', '#9793F8', '#50B2D7', '#B83CFF'][:len(tp_keys)]
# Plot timepoint background
for t_key, color, label in zip(tp_keys, tp_colors, tp_labels_list):
coords = timepoint_data[t_key]
ax.scatter(coords[:, 0], coords[:, 1],
c=color, s=80, alpha=0.4, marker='x',
label=f'{label} cells', linewidth=1.5)
# Plot trajectories with color gradients
custom_colors_1 = ["#05009E", "#A19EFF", "#9793F8"]
custom_colors_2 = ["#05009E", "#A19EFF", "#50B2D7"]
custom_colors_3 = ["#05009E", "#A19EFF", "#D577FF"]
cmaps = [
LinearSegmentedColormap.from_list("tram_cmap1", custom_colors_1),
LinearSegmentedColormap.from_list("tram_cmap2", custom_colors_2),
LinearSegmentedColormap.from_list("tram_cmap3", custom_colors_3),
]
for i, traj in enumerate(all_trajs):
traj_2d = traj[:, :, :2]
c_end = branch_colors[i]
cmap = cmaps[i]
n_time = traj_2d.shape[1]
color_vals = cmap(np.linspace(0, 1, n_time))
segments = []
seg_colors = []
for j in range(traj_2d.shape[0]):
pts = traj_2d[j]
segs = np.stack([pts[:-1], pts[1:]], axis=1)
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o',
label=f'{branch_names[i]} Start',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o',
label=f'{branch_names[i]} End',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlabel("PC1", fontsize=14)
ax.set_ylabel("PC2", fontsize=14)
ax.set_title("All Branch Trajectories with Timepoint Background",
fontsize=16, weight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=12, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_combined.png', dpi=300)
plt.close()
class FlowNetTestVeres(GrowthNetTrain):
"""Test class for Veres pancreatic endocrinogenesis experiment (3 or 5 branches)."""
def test_step(self, batch, batch_idx):
# Handle both tuple and dict batch formats from CombinedLoader
if isinstance(batch, dict):
main_batch = batch["test_samples"][0]
metric_batch = batch["metric_samples"][0]
else:
# batch is a list/tuple
if isinstance(batch[0], dict):
# batch[0] contains the dict with test_samples and metric_samples
main_batch = batch[0]["test_samples"][0]
metric_batch = batch[0]["metric_samples"][0]
else:
# batch is a tuple: (test_samples, metric_samples)
main_batch = batch[0][0]
metric_batch = batch[1][0]
# Get timepoint data (full datasets, not just val split)
timepoint_data = self.trainer.datamodule.get_timepoint_data()
device = main_batch["x0"][0].device
# Use val x0 as initial conditions
x0_all = self.trainer.datamodule.val_dataloaders["x0"].dataset.tensors[0].to(device)
w0_all = torch.ones(x0_all.shape[0], 1, dtype=torch.float32).to(device)
full_batch = {"x0": (x0_all, w0_all)}
time_points, all_endpoints, all_trajs, mass_over_time, energy_over_time, weights_over_time = self.get_mass_and_position(full_batch, metric_batch)
n_branches = len(self.flow_nets)
# trajectory time grid
t_span = torch.linspace(0, 1, 101).to(device)
# `all_trajs` returned from `get_mass_and_position` is expected to be a list where each
# element is a sequence of per-timepoint tensors for that branch (shape [B, D] each).
# Convert each branch to [T, B, D] then to [B, T, D] for downstream processing.
trajs_TBD = [torch.stack(branch_list, dim=0) for branch_list in all_trajs] # each is [T, B, D]
trajs_BTD = [t.permute(1, 0, 2) for t in trajs_TBD] # each -> [B, T, D]
all_trajs = []
all_endpoints = []
# will store per-branch intermediate frames: each entry -> tensor [B, n_intermediate, D]
all_intermediates = []
for traj in trajs_BTD:
# traj is [B, T, D]
# optionally inverse-transform if whitened
if self.whiten:
traj_np = traj.detach().cpu().numpy()
n_samples, n_time, n_dims = traj_np.shape
traj_flat = traj_np.reshape(-1, n_dims)
traj_inv_flat = self.trainer.datamodule.scaler.inverse_transform(traj_flat)
traj_inv = traj_inv_flat.reshape(n_samples, n_time, n_dims)
traj = torch.tensor(traj_inv, dtype=torch.float32)
all_trajs.append(traj)
# Collect six evenly spaced intermediate frames between t=0 and t=1 (exclude endpoints)
n_T = traj.shape[1]
# choose 8 points including endpoints -> take inner 6 as intermediates
inter_times = np.linspace(0.0, 1.0, 8)[1:-1] # 6 values
inter_indices = [int(round(t * (n_T - 1))) for t in inter_times]
# stack per-branch intermediate frames -> [B, 6, D]
intermediates = torch.stack([traj[:, idx, :] for idx in inter_indices], dim=1)
all_intermediates.append(intermediates)
# Final endpoints (t=1)
all_endpoints.append(traj[:, -1, :])
# Run 5 trials with random subsampling for robust metrics
n_trials = 5
metrics_dict = {}
# --- Intermediate timepoints (t1-t6) combined metrics ---
intermediate_keys = sorted([k for k in timepoint_data.keys()
if k.startswith('t') and '_' not in k and k != 't0'])
if intermediate_keys:
n_evals = min(6, len(intermediate_keys))
for j in range(n_evals):
intermediate_key = intermediate_keys[j]
true_data_intermediate = torch.tensor(timepoint_data[intermediate_key], dtype=torch.float32)
# Gather predicted intermediates across all branches
raw_intermediates = [branch[:, j, :] for branch in all_intermediates]
all_raw_concat = torch.cat(raw_intermediates, dim=0).cpu() # [n_branches*B, D]
w1_t, w2_t, mmd_t = [], [], []
w1_t_full, w2_t_full, mmd_t_full = [], [], []
for trial in range(n_trials):
n_min = min(all_raw_concat.shape[0], true_data_intermediate.shape[0])
perm_pred = torch.randperm(all_raw_concat.shape[0])[:n_min]
perm_gt = torch.randperm(true_data_intermediate.shape[0])[:n_min]
# 2D metrics (PC1-PC2)
m = compute_distribution_distances(
all_raw_concat[perm_pred, :2], true_data_intermediate[perm_gt, :2])
w1_t.append(m["W1"]); w2_t.append(m["W2"]); mmd_t.append(m["MMD"])
# Full-dimensional metrics (all PCs)
m_full = compute_distribution_distances(
all_raw_concat[perm_pred], true_data_intermediate[perm_gt])
w1_t_full.append(m_full["W1"]); w2_t_full.append(m_full["W2"]); mmd_t_full.append(m_full["MMD"])
metrics_dict[f'{intermediate_key}_combined'] = {
"W1_mean": float(np.mean(w1_t)), "W1_std": float(np.std(w1_t, ddof=1)),
"W2_mean": float(np.mean(w2_t)), "W2_std": float(np.std(w2_t, ddof=1)),
"MMD_mean": float(np.mean(mmd_t)), "MMD_std": float(np.std(mmd_t, ddof=1)),
"W1_full_mean": float(np.mean(w1_t_full)), "W1_full_std": float(np.std(w1_t_full, ddof=1)),
"W2_full_mean": float(np.mean(w2_t_full)), "W2_full_std": float(np.std(w2_t_full, ddof=1)),
"MMD_full_mean": float(np.mean(mmd_t_full)), "MMD_full_std": float(np.std(mmd_t_full, ddof=1)),
}
self.log(f"test/W1_{intermediate_key}_combined", np.mean(w1_t), on_epoch=True)
self.log(f"test/W1_full_{intermediate_key}_combined", np.mean(w1_t_full), on_epoch=True)
print(f"{intermediate_key} combined — W1: {np.mean(w1_t):.6f}±{np.std(w1_t, ddof=1):.6f}, "
f"W2: {np.mean(w2_t):.6f}±{np.std(w2_t, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_t):.6f}±{np.std(mmd_t, ddof=1):.6f}")
print(f"{intermediate_key} combined (full) — W1: {np.mean(w1_t_full):.6f}±{np.std(w1_t_full, ddof=1):.6f}, "
f"W2: {np.mean(w2_t_full):.6f}±{np.std(w2_t_full, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_t_full):.6f}±{np.std(mmd_t_full, ddof=1):.6f}")
# --- Final timepoint per-branch metrics ---
gt_keys = sorted([k for k in timepoint_data.keys() if k.startswith('t7_')])
for i, endpoints in enumerate(all_endpoints):
true_data_key = f"t7_{i}"
if true_data_key not in timepoint_data:
print(f"Warning: {true_data_key} not found in timepoint_data")
continue
gt = torch.tensor(timepoint_data[true_data_key], dtype=torch.float32)
pred = endpoints.cpu()
w1_br, w2_br, mmd_br = [], [], []
w1_br_full, w2_br_full, mmd_br_full = [], [], []
for trial in range(n_trials):
n_min = min(pred.shape[0], gt.shape[0])
perm_pred = torch.randperm(pred.shape[0])[:n_min]
perm_gt = torch.randperm(gt.shape[0])[:n_min]
# 2D metrics (PC1-PC2)
m = compute_distribution_distances(pred[perm_pred, :2], gt[perm_gt, :2])
w1_br.append(m["W1"]); w2_br.append(m["W2"]); mmd_br.append(m["MMD"])
# Full-dimensional metrics (all PCs)
m_full = compute_distribution_distances(pred[perm_pred], gt[perm_gt])
w1_br_full.append(m_full["W1"]); w2_br_full.append(m_full["W2"]); mmd_br_full.append(m_full["MMD"])
metrics_dict[f"branch_{i}"] = {
"W1_mean": float(np.mean(w1_br)), "W1_std": float(np.std(w1_br, ddof=1)),
"W2_mean": float(np.mean(w2_br)), "W2_std": float(np.std(w2_br, ddof=1)),
"MMD_mean": float(np.mean(mmd_br)), "MMD_std": float(np.std(mmd_br, ddof=1)),
"W1_full_mean": float(np.mean(w1_br_full)), "W1_full_std": float(np.std(w1_br_full, ddof=1)),
"W2_full_mean": float(np.mean(w2_br_full)), "W2_full_std": float(np.std(w2_br_full, ddof=1)),
"MMD_full_mean": float(np.mean(mmd_br_full)), "MMD_full_std": float(np.std(mmd_br_full, ddof=1)),
}
self.log(f"test/W1_branch{i}", np.mean(w1_br), on_epoch=True)
self.log(f"test/W1_full_branch{i}", np.mean(w1_br_full), on_epoch=True)
print(f"Branch {i} — W1: {np.mean(w1_br):.6f}±{np.std(w1_br, ddof=1):.6f}, "
f"W2: {np.mean(w2_br):.6f}±{np.std(w2_br, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br):.6f}±{np.std(mmd_br, ddof=1):.6f}")
print(f"Branch {i} (full) — W1: {np.mean(w1_br_full):.6f}±{np.std(w1_br_full, ddof=1):.6f}, "
f"W2: {np.mean(w2_br_full):.6f}±{np.std(w2_br_full, ddof=1):.6f}, "
f"MMD: {np.mean(mmd_br_full):.6f}±{np.std(mmd_br_full, ddof=1):.6f}")
# --- Final timepoint combined metrics ---
gt_list = [torch.tensor(timepoint_data[k], dtype=torch.float32) for k in gt_keys]
if len(gt_list) > 0 and len(all_endpoints) > 0:
gt_all = torch.cat(gt_list, dim=0)
pred_all = torch.cat([e.cpu() for e in all_endpoints], dim=0)
w1_trials, w2_trials, mmd_trials = [], [], []
w1_trials_full, w2_trials_full, mmd_trials_full = [], [], []
for trial in range(n_trials):
n_min = min(pred_all.shape[0], gt_all.shape[0])
perm_pred = torch.randperm(pred_all.shape[0])[:n_min]
perm_gt = torch.randperm(gt_all.shape[0])[:n_min]
# 2D metrics (PC1-PC2)
m = compute_distribution_distances(pred_all[perm_pred, :2], gt_all[perm_gt, :2])
w1_trials.append(m["W1"]); w2_trials.append(m["W2"]); mmd_trials.append(m["MMD"])
# Full-dimensional metrics (all PCs)
m_full = compute_distribution_distances(pred_all[perm_pred], gt_all[perm_gt])
w1_trials_full.append(m_full["W1"]); w2_trials_full.append(m_full["W2"]); mmd_trials_full.append(m_full["MMD"])
w1_mean, w1_std = np.mean(w1_trials), np.std(w1_trials, ddof=1)
w2_mean, w2_std = np.mean(w2_trials), np.std(w2_trials, ddof=1)
mmd_mean, mmd_std = np.mean(mmd_trials), np.std(mmd_trials, ddof=1)
w1_mean_f, w1_std_f = np.mean(w1_trials_full), np.std(w1_trials_full, ddof=1)
w2_mean_f, w2_std_f = np.mean(w2_trials_full), np.std(w2_trials_full, ddof=1)
mmd_mean_f, mmd_std_f = np.mean(mmd_trials_full), np.std(mmd_trials_full, ddof=1)
self.log("test/W1_t7_combined", w1_mean, on_epoch=True)
self.log("test/W2_t7_combined", w2_mean, on_epoch=True)
self.log("test/MMD_t7_combined", mmd_mean, on_epoch=True)
self.log("test/W1_full_t7_combined", w1_mean_f, on_epoch=True)
self.log("test/W2_full_t7_combined", w2_mean_f, on_epoch=True)
self.log("test/MMD_full_t7_combined", mmd_mean_f, on_epoch=True)
metrics_dict['t7_combined'] = {
"W1_mean": float(w1_mean), "W1_std": float(w1_std),
"W2_mean": float(w2_mean), "W2_std": float(w2_std),
"MMD_mean": float(mmd_mean), "MMD_std": float(mmd_std),
"W1_full_mean": float(w1_mean_f), "W1_full_std": float(w1_std_f),
"W2_full_mean": float(w2_mean_f), "W2_full_std": float(w2_std_f),
"MMD_full_mean": float(mmd_mean_f), "MMD_full_std": float(mmd_std_f),
"n_trials": n_trials,
}
print(f"\n=== Combined @ t7 ===")
print(f"W1: {w1_mean:.6f} ± {w1_std:.6f}")
print(f"W2: {w2_mean:.6f} ± {w2_std:.6f}")
print(f"MMD: {mmd_mean:.6f} ± {mmd_std:.6f}")
print(f"W1 (full): {w1_mean_f:.6f} ± {w1_std_f:.6f}")
print(f"W2 (full): {w2_mean_f:.6f} ± {w2_std_f:.6f}")
print(f"MMD (full): {mmd_mean_f:.6f} ± {mmd_std_f:.6f}")
# Create results directory structure
run_name = self.args.run_name if hasattr(self.args, 'run_name') and self.args.run_name else self.args.data_name
results_dir = os.path.join(self.args.working_dir, 'results', run_name)
figures_dir = f'{results_dir}/figures'
os.makedirs(figures_dir, exist_ok=True)
# Save metrics to JSON
metrics_path = f'{results_dir}/metrics.json'
with open(metrics_path, 'w') as f:
json.dump(metrics_dict, f, indent=2)
print(f"Metrics saved to {metrics_path}")
# Save detailed metrics to CSV
detailed_csv_path = f'{results_dir}/metrics_detailed.csv'
with open(detailed_csv_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Metric_Group',
'W1_Mean', 'W1_Std', 'W2_Mean', 'W2_Std', 'MMD_Mean', 'MMD_Std',
'W1_Full_Mean', 'W1_Full_Std', 'W2_Full_Mean', 'W2_Full_Std', 'MMD_Full_Mean', 'MMD_Full_Std'])
for key in sorted(metrics_dict.keys()):
m = metrics_dict[key]
writer.writerow([key,
f'{m.get("W1_mean", 0):.6f}', f'{m.get("W1_std", 0):.6f}',
f'{m.get("W2_mean", 0):.6f}', f'{m.get("W2_std", 0):.6f}',
f'{m.get("MMD_mean", 0):.6f}', f'{m.get("MMD_std", 0):.6f}',
f'{m.get("W1_full_mean", 0):.6f}', f'{m.get("W1_full_std", 0):.6f}',
f'{m.get("W2_full_mean", 0):.6f}', f'{m.get("W2_full_std", 0):.6f}',
f'{m.get("MMD_full_mean", 0):.6f}', f'{m.get("MMD_full_std", 0):.6f}'])
print(f"Detailed metrics CSV saved to {detailed_csv_path}")
# ===== Plot branches =====
self._plot_veres_branches(all_trajs, timepoint_data, figures_dir, n_branches)
self._plot_veres_combined(all_trajs, timepoint_data, figures_dir, n_branches)
print(f"Veres figures saved to {figures_dir}")
def _plot_veres_branches(self, all_trajs, timepoint_data, save_dir, n_branches):
"""Plot each branch separately in PCA space (PC1 vs PC2)."""
branch_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DFE6E9',
'#74B9FF', '#A29BFE', '#FFB74D', '#AED581', '#F06292', '#BA68C8',
'#4DB6AC', '#81C784', '#FFD54F', '#90A4AE', '#F48FB1', '#CE93D8',
'#64B5F6', '#C5E1A5']
# Project to first 2 PCs (data is already in PCA space)
t0_2d = timepoint_data['t0'].cpu().numpy()[:, :2]
t7_2d = [timepoint_data[f't7_{i}'].cpu().numpy()[:, :2] for i in range(n_branches)]
# Slice trajectories to first 2 PCs
trajs_2d = []
for traj in all_trajs:
trajs_2d.append(traj.cpu().numpy()[:, :, :2]) # [n_samples, n_time, 2]
# Compute global axis limits
all_coords = [t0_2d] + t7_2d
for traj_2d in trajs_2d:
all_coords.append(traj_2d.reshape(-1, 2))
all_coords = np.concatenate(all_coords, axis=0)
x_min, x_max = all_coords[:, 0].min(), all_coords[:, 0].max()
y_min, y_max = all_coords[:, 1].min(), all_coords[:, 1].max()
x_margin = 0.05 * (x_max - x_min)
y_margin = 0.05 * (y_max - y_min)
x_min -= x_margin
x_max += x_margin
y_min -= y_margin
y_max += y_margin
for i, traj_2d in enumerate(trajs_2d):
fig, ax = plt.subplots(figsize=(10, 8))
c_end = branch_colors[i % len(branch_colors)]
# Plot timepoint background
ax.scatter(t0_2d[:, 0], t0_2d[:, 1],
c='#05009E', s=80, alpha=0.4, marker='x',
label='t=0 cells', linewidth=1.5)
ax.scatter(t7_2d[i][:, 0], t7_2d[i][:, 1],
c=c_end, s=80, alpha=0.4, marker='x',
label=f't=7 (branch {i+1}) cells', linewidth=1.5)
# Plot continuous trajectories with LineCollection for speed
cmap_colors = ["#05009E", "#A19EFF", c_end]
cmap = LinearSegmentedColormap.from_list(f"veres_cmap_{i}", cmap_colors)
n_time = traj_2d.shape[1]
segments = []
seg_colors = []
color_vals = cmap(np.linspace(0, 1, n_time))
for j in range(traj_2d.shape[0]):
pts = traj_2d[j] # [T, 2]
segs = np.stack([pts[:-1], pts[1:]], axis=1) # [T-1, 2, 2]
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=2, alpha=0.8)
ax.add_collection(lc)
# Start and end points
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=30, marker='o', label='Trajectory start (t=0)',
zorder=5, edgecolors='white', linewidth=1)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=30, marker='o', label='Trajectory end (t=1)',
zorder=5, edgecolors='white', linewidth=1)
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel("PC 1", fontsize=12)
ax.set_ylabel("PC 2", fontsize=12)
ax.set_title(f"Branch {i+1}: Trajectories (PCA)", fontsize=14)
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=9, frameon=False)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_branch{i+1}.png', dpi=300)
plt.close()
def _plot_veres_combined(self, all_trajs, timepoint_data, save_dir, n_branches):
"""Plot all branches together in PCA space (PC1 vs PC2)."""
branch_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DFE6E9',
'#74B9FF', '#A29BFE', '#FFB74D', '#AED581', '#F06292', '#BA68C8',
'#4DB6AC', '#81C784', '#FFD54F', '#90A4AE', '#F48FB1', '#CE93D8',
'#64B5F6', '#C5E1A5']
# Project to first 2 PCs (data is already in PCA space)
t0_2d = timepoint_data['t0'].cpu().numpy()[:, :2]
t7_2d = [timepoint_data[f't7_{i}'].cpu().numpy()[:, :2] for i in range(n_branches)]
# Slice trajectories to first 2 PCs
trajs_2d = []
for traj in all_trajs:
trajs_2d.append(traj.cpu().numpy()[:, :, :2]) # [n_samples, n_time, 2]
# Compute axis limits from REAL CELLS ONLY
all_coords_real = [t0_2d] + t7_2d
all_coords_real = np.concatenate(all_coords_real, axis=0)
x_min, x_max = all_coords_real[:, 0].min(), all_coords_real[:, 0].max()
y_min, y_max = all_coords_real[:, 1].min(), all_coords_real[:, 1].max()
x_margin = 0.05 * (x_max - x_min)
y_margin = 0.05 * (y_max - y_min)
x_min -= x_margin
x_max += x_margin
y_min -= y_margin
y_max += y_margin
fig, ax = plt.subplots(figsize=(14, 12))
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
# Plot t=0 cells
ax.scatter(t0_2d[:, 0], t0_2d[:, 1],
c='#05009E', s=60, alpha=0.3, marker='x',
label='t=0 cells', linewidth=1.5)
# Plot each branch's cells and trajectories
for i, traj_2d in enumerate(trajs_2d):
c_end = branch_colors[i % len(branch_colors)]
# Plot t=7 cells for this branch
ax.scatter(t7_2d[i][:, 0], t7_2d[i][:, 1],
c=c_end, s=60, alpha=0.3, marker='x',
label=f't=7 (branch {i+1})', linewidth=1.5)
# Plot continuous trajectories with LineCollection for speed
cmap_colors = ["#05009E", "#A19EFF", c_end]
cmap = LinearSegmentedColormap.from_list(f"veres_combined_cmap_{i}", cmap_colors)
n_time = traj_2d.shape[1]
segments = []
seg_colors = []
color_vals = cmap(np.linspace(0, 1, n_time))
for j in range(traj_2d.shape[0]):
pts = traj_2d[j] # [T, 2]
segs = np.stack([pts[:-1], pts[1:]], axis=1) # [T-1, 2, 2]
segments.append(segs)
seg_colors.append(color_vals[:-1])
segments = np.concatenate(segments, axis=0)
seg_colors = np.concatenate(seg_colors, axis=0)
lc = LineCollection(segments, colors=seg_colors, linewidths=1.5, alpha=0.6)
ax.add_collection(lc)
# Start and end points
ax.scatter(traj_2d[:, 0, 0], traj_2d[:, 0, 1],
c='#05009E', s=20, marker='o',
zorder=5, edgecolors='white', linewidth=0.5, alpha=0.7)
ax.scatter(traj_2d[:, -1, 0], traj_2d[:, -1, 1],
c=c_end, s=20, marker='o',
zorder=5, edgecolors='white', linewidth=0.5, alpha=0.7)
ax.set_xlabel("PC 1", fontsize=14)
ax.set_ylabel("PC 2", fontsize=14)
ax.set_title(f"All {n_branches} Branch Trajectories (Veres) - PCA Projection",
fontsize=16, weight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='upper right', fontsize=10, frameon=False, ncol=2)
plt.tight_layout()
plt.savefig(f'{save_dir}/{self.args.data_name}_combined.png', dpi=300)
plt.close() |