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 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
|
/*LICENSE_START*/
/*
* Copyright 1995-2002 Washington University School of Medicine
*
* http://brainmap.wustl.edu
*
* This file is part of CARET.
*
* CARET is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* CARET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CARET; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*LICENSE_END*/
#include <QGlobalStatic>
#ifdef Q_OS_WIN32 // required for M_PI in <cmath>
#define _USE_MATH_DEFINES
#define NOMINMAX
#endif
#include <QApplication>
#include <QDateTime>
#include <QFile>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <sstream>
#include <QDir>
#include "BorderFile.h"
#include "BorderProjectionFile.h"
#include "BrainModelBorderSet.h"
#include "BrainModelSurfaceDistortion.h"
#include "BrainModelSurfaceFlatHexagonalSubsample.h"
#include "BrainModelSurfaceMultiresolutionMorphing.h"
#include "BrainModelSurfacePointProjector.h"
#include "BrainSet.h"
#include "DebugControl.h"
#include "FileUtilities.h"
#include "StatisticDataGroup.h"
#include "StringUtilities.h"
#include "TopologyHelper.h"
#include "TransformationMatrixFile.h"
#include "vtkMath.h"
#include "vtkTriangle.h"
/**
* Constructor
*/
BrainModelSurfaceMultiresolutionMorphing::BrainModelSurfaceMultiresolutionMorphing(
BrainSet* brainSetIn,
BrainModelSurface* referenceSurfaceIn,
BrainModelSurface* morphingSurfaceIn,
const BrainModelSurfaceMorphing::MORPHING_SURFACE_TYPE morphingSurfaceTypeIn,
const BorderProjection* centralSulcusBorderProjectionIn)
: BrainModelAlgorithm(brainSetIn),
referenceSurface(referenceSurfaceIn),
morphingSurface(morphingSurfaceIn),
morphingSurfaceType(morphingSurfaceTypeIn),
centralSulcusBorderProjection(centralSulcusBorderProjectionIn)
{
autoSaveFilesFlag = true;
currentCycle = std::numeric_limits<int>::max();
brainModelSurfaceType = BrainModelSurface::SURFACE_TYPE_UNKNOWN;
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
brainModelSurfaceType = BrainModelSurface::SURFACE_TYPE_FLAT;
this->multiResMorphFile.initializeParametersFlat();
crossoverSmoothStrength = 1.0;
crossoverSmoothCycles = 10;
crossoverSmoothIterations = 50;
crossoverSmoothEdgeIterations = 10;
crossoverSmoothProjectToSphereIterations = 0;
crossoverSmoothNeighborDepth = 5;
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
brainModelSurfaceType = BrainModelSurface::SURFACE_TYPE_SPHERICAL;
this->multiResMorphFile.initializeParametersSpherical();
crossoverSmoothStrength = 1.0;
crossoverSmoothCycles = 10;
crossoverSmoothIterations = 10;
crossoverSmoothEdgeIterations = 0;
crossoverSmoothProjectToSphereIterations = 10;
crossoverSmoothNeighborDepth = 30;
break;
}
outputFileNamePrefix = "";
outputFileNameSuffix = "";
intermediateFiles.clear();
//
// Get name of original coordinate file
//
if (morphingSurface != NULL) {
const CoordinateFile* origCoord = morphingSurface->getCoordinateFile();
origCoordFileName = origCoord->getFileName();
}
}
/**
* Destructor
*/
BrainModelSurfaceMultiresolutionMorphing::~BrainModelSurfaceMultiresolutionMorphing()
{
}
/**
* Copy parameters from another object
*/
void
BrainModelSurfaceMultiresolutionMorphing::copyParameters(
const BrainModelSurfaceMultiresolutionMorphing& bmsm)
{
this->multiResMorphFile = bmsm.multiResMorphFile;
}
/**
* Setup the the output file name prefix and suffix
*/
void
BrainModelSurfaceMultiresolutionMorphing::setUpOutputFileNaming()
{
outputFileNamePrefix = "";
outputFileNameSuffix = "";
//
// Get the name of the input coordinate file
//
const CoordinateFile* cf = morphingSurface->getCoordinateFile();
QString morphFileName(cf->getFileName());
if (morphFileName.isEmpty()) {
const TopologyFile* tf = morphingSurface->getTopologyFile();
morphFileName = tf->getFileName();
}
if (morphFileName.isEmpty()) {
morphFileName = brainSet->getSpecFileName();
}
if (morphFileName.isEmpty()) {
outputFileNamePrefix = "morphing_output";
outputFileNameSuffix = SpecFile::getCoordinateFileExtension();
}
else {
//
// Parse the file name
//
QString directory, species, casename, anatomy, hemisphere, description, descriptionNoType;
QString theDate, numNodes, extension;
if (FileUtilities::parseCaretDataFileName(morphFileName,
directory,
species,
casename,
anatomy,
hemisphere,
description,
descriptionNoType,
theDate,
numNodes,
extension)) {
if (species.isEmpty() == false) {
outputFileNamePrefix.append(species);
outputFileNamePrefix.append(".");
}
if (casename.isEmpty() == false) {
outputFileNamePrefix.append(casename);
outputFileNamePrefix.append(".");
}
if (anatomy.isEmpty() == false) {
outputFileNamePrefix.append(anatomy);
outputFileNamePrefix.append(".");
}
if (hemisphere.isEmpty() == false) {
outputFileNamePrefix.append(hemisphere);
outputFileNamePrefix.append(".");
}
if (descriptionNoType.isEmpty() == false) {
outputFileNamePrefix.append(descriptionNoType);
outputFileNamePrefix.append(".");
}
if (theDate.isEmpty() == false) {
outputFileNameSuffix.append(theDate);
outputFileNameSuffix.append(".");
}
if (numNodes.isEmpty() == false) {
outputFileNameSuffix.append(numNodes);
}
// extension has period at beginning if (outputFileNameSuffix.isEmpty()) {
// outputFileNameSuffix.append(".");
//}
outputFileNameSuffix.append(SpecFile::getCoordinateFileExtension());
}
else {
outputFileNamePrefix = FileUtilities::filenameWithoutExtension(morphFileName);
if (StringUtilities::endsWith(outputFileNamePrefix, ".") == false) {
outputFileNamePrefix.append(".");
}
outputFileNameSuffix = FileUtilities::filenameExtension(morphFileName);
}
}
if (outputFileNameSuffix.startsWith('.') == false) {
outputFileNameSuffix.insert(0, '.');
}
}
/**
* run the multiresolution morphing
*/
void
BrainModelSurfaceMultiresolutionMorphing::execute() throw (BrainModelAlgorithmException)
{
QString morphTypeString;
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
morphTypeString = "Flat ";
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
morphTypeString = "Spherical ";
break;
}
std::ostringstream str;
str << "\n"
<< "Multiresolution Morphing "
<< morphTypeString.toAscii().constData()
<< ": "
<< " reference surface="
<< FileUtilities::basename(referenceSurface->getFileName()).toAscii().constData()
<< "\n"
<< " morphing surface="
<< FileUtilities::basename(morphingSurface->getFileName()).toAscii().constData()
<< "\n";
int numberOfCycles = this->multiResMorphFile.getNumberOfCycles();
for (int j = 0; j < numberOfCycles; j++) {
MultiResolutionMorphingCycle* cycle = this->getMultiResMorphParametersFile()->getCycle(j);
str << "cycle "
<< j
<< ":"
<< " iterations=";
int iterationsPerLevel[MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS];
cycle->getIterationsAll(iterationsPerLevel);
for (int i = 0; i < MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS; i++) {
str << iterationsPerLevel[i] << " ";
}
str << "\n"
<< " linear force=" << cycle->getLinearForce()
<< " angular force=" << cycle->getAngularForce()
<< " step size=" << cycle->getStepSize()
<< "\n"
<< "smoothing strength=" << cycle->getSmoothingStrength()
<< " iterations=" << cycle->getSmoothingIterations()
<< " edge iterations=" << cycle->getSmoothingIterationEdges()
<< "\n";
}
const QString fileComment(str.str().c_str());
//
// Surfaces that will be scaled after the process is finished
//
std::vector<BrainModelSurface*> surfacesToScale;
//
// Get modified status of existing brain models
//
std::vector<unsigned long> brainModelModified;
for (int i = 0; i < brainSet->getNumberOfBrainModels(); i++) {
BrainModelSurface* bms = brainSet->getBrainModelSurface(i);
if (bms != NULL) {
CoordinateFile* cf = bms->getCoordinateFile();
brainModelModified.push_back(cf->getModified());
}
else {
brainModelModified.push_back(0);
}
}
//
// Check for stragglers
//
std::vector<int> cornerTiles;
morphingSurface->getTopologyFile()->findCornerTiles(2, cornerTiles);
if (cornerTiles.empty() == false) {
throw BrainModelAlgorithmException(
"Straggler tile(s) were found (tiles that have two nodes that are\n"
"only used by a single tile). These tiles will cause problems\n"
"with Multi-resolution Morphing. Use the Surface:Topology:\n"
"Remove Corner and Straggler Tiles menu item with \"Delete Stragglers\n"
"Only\" to eliminate them. After doing so, save both the Topology \n"
"and Coordinate files.");
}
int numberOfLevels = this->multiResMorphFile.getNumberOfLevels();
//
// Create the progress dialog
//
QString title("Flat Multiresolution Morphing");
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
title = "Spherical Multiresolution Morphing";
}
createProgressDialog(title,
numberOfCycles + 1,
"multiresMorphProgressDialog");
try {
//
// Setup filename prefix and suffix for output file naming
//
setUpOutputFileNaming();
//
// Save the original topology file for spherical morphing since it might get modified
//
TopologyFile* originalTopologyFile = NULL;
TopologyFile* newTopologyFile = NULL;
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
if (this->multiResMorphFile.isPointSphericalTrianglesOutward()) {
originalTopologyFile = morphingSurface->getTopologyFile();
newTopologyFile = new TopologyFile(*originalTopologyFile);
morphingSurface->setTopologyFile(newTopologyFile);
}
break;
}
//
// Use the morphing surface's topology file
//
TopologyFile* topologyFile = morphingSurface->getTopologyFile();
//
// Classify the nodes using the morphing surface's topology file
//
brainSet->clearNodeAttributes();
brainSet->classifyNodes(topologyFile);
const int numTiles = topologyFile->getNumberOfTiles();
std::vector<int> dummy1, dummy2, dummy3;
const int numPiecesOfSurface = topologyFile->findIslands(dummy1, dummy2, dummy3);
if (numPiecesOfSurface > 1) {
throw BrainModelAlgorithmException(
"There are multiple pieces of surface. Use Surface: Topology: Remove Islands\n"
"to remove them and verify that the surface remains correct.");
}
//
// Set the references surface area
//
const float referenceSurfaceArea = referenceSurface->getSurfaceArea(topologyFile);
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
//
// Scale surface of sphere 02/26/2004
//
morphingSurface->convertToSphereWithSurfaceArea(referenceSurfaceArea);
break;
}
//
// Get the radius of the spherical morphing surface
//
const float sphericalRadius = morphingSurface->getSphericalSurfaceRadius();
//
// Measure the surface
//
measureSurface(-1, 0.0);
//
// Get the hemisphere being morphed
//
brainStruct = brainSet->getStructure().getType();
if (DebugControl::getDebugOn()) {
try {
BrainModelSurface tempr(*referenceSurface);
tempr.getCoordinateFile()->writeFile("debug_morph_input_refererence.coord");
BrainModelSurface tempm(*morphingSurface);
tempm.getCoordinateFile()->writeFile("debug_morph_input_morphing.coord");
TopologyFile tempt(*topologyFile);
tempt.writeFile("debug_morph_input_topology.topo");
SpecFile sp;
sp.addToSpecFile(SpecFile::getFiducialCoordFileTag(),
tempr.getCoordinateFile()->getFileName(), "", false);
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
sp.addToSpecFile(SpecFile::getFlatCoordFileTag(),
tempm.getCoordinateFile()->getFileName(), "", false);
sp.addToSpecFile(SpecFile::getCutTopoFileTag(),
tempt.getFileName(), "", false);
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
sp.addToSpecFile(SpecFile::getSphericalCoordFileTag(),
tempm.getCoordinateFile()->getFileName(), "", false);
sp.addToSpecFile(SpecFile::getClosedTopoFileTag(),
tempt.getFileName(), "", false);
break;
}
sp.writeFile("debug_morph_input.spec");
}
catch (FileException&) {
}
}
//
// Loop number of cycles
//
for (currentCycle = 0; currentCycle < numberOfCycles; currentCycle++) {
const bool lastCycleFlag = (currentCycle == (numberOfCycles - 1));
//
// Set progress dialog
//
{
std::ostringstream str;
QString typeString("Flat");
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
typeString = "Spherical";
}
str << "Running "
<< typeString.toAscii().constData()
<< " Cycle "
<< (currentCycle + 1)
<< " of "
<< numberOfCycles;
updateProgressDialog(str.str().c_str(), currentCycle + 1);
}
//
// Start a timer
//
QTime timer;
timer.start();
//
// set the prefix for naming intermediate files and spec file naming
//
QString morphTypeString("none");
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
morphTypeString = "flatmorph";
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
morphTypeString = "spheremorph";
break;
}
QString cycleNumberString = QString::number(currentCycle + 1);
for (int i = 0; i < numberOfLevels; i++) {
std::ostringstream ostr;
ostr << morphTypeString.toAscii().constData()
<< ".cycle"
<< (currentCycle + 1)
<< ".level"
<< (i + 1);
intermediateFileNamePrefix[i] = ostr.str().c_str();
intermediateCoordFileNamePrefix[i] = intermediateFileNamePrefix[i];
switch(morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
intermediateCoordFileNamePrefix[i].append(".flat");
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
intermediateCoordFileNamePrefix[i].append(".sphere");
break;
}
intermediateSpecFileNames[i] = intermediateFileNamePrefix[i];
intermediateSpecFileNames[i].append(".spec");
intermediateFiles.push_back(intermediateSpecFileNames[i]);
}
std::vector<BrainSet*> brains;
brains.push_back(brainSet); // one passed to this objects constructor
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
{
//
// Set resampling number of tiles
//
const int numberOfResamplingTiles = static_cast<int>(numTiles * 0.3);
//
// Create a flat hexagonal subsampled surface
//
BrainModelSurfaceFlatHexagonalSubsample hexSubSample(brainSet,
referenceSurface,
morphingSurface,
numberOfResamplingTiles);
hexSubSample.execute();
BrainSet* subSampledBrainSet = hexSubSample.getSubsampledBrainSet();
if (subSampledBrainSet != NULL) {
subSampledBrainSet->setSpecFileName("InitialFlatHex_Cycle"
+ cycleNumberString
+ ".spec");
BrainModelSurface* flatHexSurface = subSampledBrainSet->getBrainModelSurface(1);
subSampledBrainSet->writeCoordinateFile("InitialFlatHex_Cycle"
+ cycleNumberString
+ ".coord",
BrainModelSurface::SURFACE_TYPE_FLAT,
flatHexSurface->getCoordinateFile(),
true);
subSampledBrainSet->writeTopologyFile("InitialFlatHex_Cycle"
+ cycleNumberString
+ ".topo",
TopologyFile::TOPOLOGY_TYPE_CUT,
flatHexSurface->getTopologyFile());
intermediateFiles.push_back(flatHexSurface->getCoordinateFile()->getFileName());
intermediateFiles.push_back(flatHexSurface->getTopologyFile()->getFileName());
BrainModelSurface* fiducialHexSurface = subSampledBrainSet->getBrainModelSurface(0);
subSampledBrainSet->writeCoordinateFile("InitialFiducialHex_Cycle"
+ cycleNumberString
+ ".coord",
BrainModelSurface::SURFACE_TYPE_FIDUCIAL,
fiducialHexSurface->getCoordinateFile(),
true);
intermediateFiles.push_back(fiducialHexSurface->getCoordinateFile()->getFileName());
//
// Create the non-morphed surface
//
BrainModelSurface* bms = subSampledBrainSet->getBrainModelSurface(1);
subSampledBrainSet->setStructure(brainStruct);
subSampledBrainSet->addBrainModel(new BrainModelSurface(*bms));
}
if (subSampledBrainSet == NULL) {
throw BrainModelAlgorithmException("Failed to create equilateral grid surface");
}
brains.push_back(subSampledBrainSet);
//
// multiresolution downsample the surface
//
multiresolutionDownsample(brains);
//
// Write the multiresolution surfaces
//
writeMultiresolutionSurfaces(brains);
//
// Morph the surfaces
//
multiresolutionMorph(brains);
//
// smooth to eliminate crossovers
//
smoothOutCrossovers(morphingSurface, 0.0);
//
// Update surface normals
//
morphingSurface->computeNormals();
//
// Translate to center of mass and scale to fit the window
//
morphingSurface->translateToCenterOfMass();
morphingSurface->updateForDefaultScaling();
}
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
{
//
// Create the multiresolution spheres and mappings between them
//
constructTemplateSpheres(brains);
createSphereDownsampleMapping(brains);
//
// Write the multiresolution surfaces
//
writeMultiresolutionSurfaces(brains);
//
// Morph the surfaces
//
multiresolutionMorph(brains);
//
// smooth to eliminate crossovers
//
smoothOutCrossovers(morphingSurface, sphericalRadius);
//
// Update surface normals
//
morphingSurface->computeNormals();
}
break;
} // switch(morphingSurfaceType)
//
// Free memory of multiresolution surfaces. Note that index 0 is
// the brain passed to this objects constructor so do not delete it.
//
for (int i = 1; i < static_cast<int>(brains.size()); i++) {
delete brains[i];
}
//
// if flat surface
//
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
//
// Save the coordinates
//
morphingSurface->pushCoordinates();
//
// scale to match reference surface area
//
morphingSurface->scaleSurfaceToArea(referenceSurfaceArea, true);
//
// Add to surfaces that should be scaled
//
surfacesToScale.push_back(morphingSurface);
}
//
// If spherical surface
//
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
morphingSurface->convertToSphereWithRadius(sphericalRadius);
}
//
// Measure the surface
//
measureSurface(currentCycle, (timer.elapsed() * 0.001));
if (currentCycle == 0) {
CoordinateFile* cf = morphingSurface->getCoordinateFile();
cf->appendToFileComment(fileComment);
cf->appendSoftwareVersionToFileComment("Multiresolution Morphing with");
}
//
// Write the morphed coordinate file (but do not add to spec file just yet)
//
QString cycleType("FLAT_CYCLE");
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
cycleType = "SPHERE_CYCLE";
}
std::ostringstream str;
str << outputFileNamePrefix.toAscii().constData()
<< cycleType.toAscii().constData()
<< (currentCycle + 1)
//<< "."
<< outputFileNameSuffix.toAscii().constData()
<< std::ends;
if (autoSaveFilesFlag) {
try {
CoordinateFile* cf = morphingSurface->getCoordinateFile();
brainSet->writeCoordinateFile(str.str().c_str(), morphingSurface->getSurfaceType(), cf, true);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
}
else {
CoordinateFile* cf = morphingSurface->getCoordinateFile();
cf->setFileName(str.str().c_str());
}
// if flat surface
//
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
//
// Restore the coordinates
//
morphingSurface->popCoordinates();
}
//
// If doing flat registration and smoothing of flat surface overlap
// enabled and doing the last cycle
//
if ((morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) &&
this->multiResMorphFile.isSmoothOutFlatSurfaceOverlap() &&
lastCycleFlag) {
//
// Copy the morphing surface
//
BrainModelSurface* smoothingSurface = new BrainModelSurface(*morphingSurface);
//
// If there was smoothing of overlapped areas
//
if (smoothingSurface->smoothOutFlatSurfaceOverlap()) {
//
// Save the coordinates
//
smoothingSurface->pushCoordinates();
//
// scale to match reference surface area
//
smoothingSurface->scaleSurfaceToArea(referenceSurfaceArea, true);
//
// Add to surfaces that should be scaled
//
surfacesToScale.push_back(smoothingSurface);
//
// Write the smoothed out overlap surface
//
morphingSurface = smoothingSurface;
brainSet->addBrainModel(morphingSurface);
CoordinateFile* cf = morphingSurface->getCoordinateFile();
std::ostringstream str;
str << outputFileNamePrefix.toAscii().constData()
<< "FLAT_CYCLE"
<< (currentCycle + 1)
<< "_OVERLAP_SMOOTH"
//<< "."
<< outputFileNameSuffix.toAscii().constData()
<< std::ends;
if (autoSaveFilesFlag) {
try {
brainSet->writeCoordinateFile(str.str().c_str(), morphingSurface->getSurfaceType(), cf, false);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
}
else {
cf->setFileName(str.str().c_str());
}
//
// Measure the overlap smoothed surface
//
measureSurface(1000, (timer.elapsed() * 0.001));
//
// if flat surface
//
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
//
// Restore the coordinates
//
smoothingSurface->popCoordinates();
}
}
else {
delete smoothingSurface;
}
}
//
// if this is the last cycle
//
if (lastCycleFlag) {
//
// Add the coordinate file to the spec file
//
if (autoSaveFilesFlag) {
brainSet->addToSpecFile(
BrainModelSurface::getCoordSpecFileTagFromSurfaceType(morphingSurface->getSurfaceType()),
morphingSurface->getFileName());
}
//
// If surface should be aligned
//
if (centralSulcusBorderProjection != NULL) {
if (centralSulcusBorderProjection->getNumberOfLinks() > 1) {
const bool flatFlag =
(morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT);
BrainModelSurface* alignmentSurface = new BrainModelSurface(*morphingSurface);
alignmentSurface->alignToStandardOrientation(referenceSurface,
centralSulcusBorderProjection,
false,
false);
brainSet->addBrainModel(alignmentSurface);
if (flatFlag) {
alignmentSurface->scaleSurfaceToArea(referenceSurfaceArea, true);
}
const QString alignmentComment =
"\nAligned to Standard Orientation using "
+ centralSulcusBorderProjection->getName()
+ " from "
+ brainSet->getBorderSet()->getBorderProjectionFileInfo()->getFileName()
+ ".\n";
CoordinateFile* cf = alignmentSurface->getCoordinateFile();
cf->appendToFileComment(alignmentComment);
const QString name(
outputFileNamePrefix
+ (flatFlag
? "FLAT_ALIGNED"
: "SPHERE_ALIGNED")
+ outputFileNameSuffix);
if (autoSaveFilesFlag) {
try {
brainSet->writeCoordinateFile(name, alignmentSurface->getSurfaceType(), cf, true);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
}
else {
cf->setFileName(name);
}
morphingSurface = alignmentSurface;
//
// Measure the overlap smoothed surface
//
measureSurface(2000, (timer.elapsed() * 0.001));
}
}
}
//
// Update the displayed brain model
//
brainSet->drawBrainModel(morphingSurface);
}
//
// If original topology file was saved, restore it to the surfaces.
// This is used in spherical morphing since the topology may be modified
//
if ((originalTopologyFile != NULL) && (newTopologyFile != NULL)) {
//
// Restore the topology file
//
const int numBrainModels = brainSet->getNumberOfBrainModels();
for (int i = 0; i < numBrainModels; i++) {
BrainModelSurface* bms = brainSet->getBrainModelSurface(i);
if (bms != NULL) {
if (bms->getTopologyFile() == newTopologyFile) {
bms->setTopologyFile(originalTopologyFile);
}
}
}
delete newTopologyFile;
}
//
// Delete intermediate files is user wants them deleted
//
if (this->multiResMorphFile.isDeleteTemporaryFiles()) {
for (int i = 0; i < static_cast<int>(intermediateFiles.size()); i++) {
QFile::remove(intermediateFiles[i]);
}
}
//
// Retain modified status of existing brain models
//
for (int i = 0; i < brainSet->getNumberOfBrainModels(); i++) {
BrainModelSurface* bms = brainSet->getBrainModelSurface(i);
if (bms != NULL) {
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
if (std::find(surfacesToScale.begin(), surfacesToScale.end(), bms)
!= surfacesToScale.end()) {
bms->scaleSurfaceToArea(referenceSurfaceArea, true);
if (autoSaveFilesFlag) {
CoordinateFile* cf = bms->getCoordinateFile();
brainSet->writeCoordinateFile(cf->getFileName(),
bms->getSurfaceType(),
cf);
}
}
}
CoordinateFile* cf = bms->getCoordinateFile();
if (i < static_cast<int>(brainModelModified.size())) {
cf->setModifiedCounter(brainModelModified[i]);
}
//else {
// cf->clearModified();
//}
}
}
}
catch (BrainModelAlgorithmException& e) {
removeProgressDialog();
throw e;
}
removeProgressDialog();
}
/**
* Make measurements of surface
*/
void
BrainModelSurfaceMultiresolutionMorphing::measureSurface(const int cycleNumber,
const float elapsedTime)
{
//
// Set the names of the distortion measurements
//
QString arealDistortName("Areal Distortion ");
QString linearDistortName("Linear Distortion ");
QString cycleName;
if (cycleNumber == -1) {
arealDistortName.append("Before Morphing");
linearDistortName.append("Before Morphing");
cycleName = "Before Morphing";
}
else {
std::ostringstream str;
if (cycleNumber == 2000) {
str << "Aligned";
}
else if (cycleNumber == 1000) {
str << "Overlap Smoothed";
}
else {
str << " Cycle "
<< (cycleNumber + 1);
}
arealDistortName.append(str.str().c_str());
linearDistortName.append(str.str().c_str());
cycleName = str.str().c_str();
}
//
// Make the distortion measurements
//
BrainModelSurfaceDistortion bmsd(brainSet, morphingSurface, referenceSurface,
morphingSurface->getTopologyFile(),
&shapeMeasurementsFile,
BrainModelSurfaceDistortion::DISTORTION_COLUMN_CREATE_NEW,
BrainModelSurfaceDistortion::DISTORTION_COLUMN_CREATE_NEW,
arealDistortName,
linearDistortName);
bmsd.execute();
//
// Save the distortion measurements file.
//
QString filename;
switch(morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
filename = "flat_morph_distortion";
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
filename = "spherical_morph_distortion";
break;
}
if (filename.isEmpty() == false) {
filename.append(SpecFile::getSurfaceShapeFileExtension());
try {
shapeMeasurementsFile.writeFile(filename);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
if (cycleNumber < 0) {
//brainSet->addToSpecFile(SpecFile::surfaceShapeFileTag, filename);
}
}
//
// Get columns in surface shape file
//
const int arealDistortColumn = shapeMeasurementsFile.getColumnWithName(arealDistortName);
const int linearDistortColumn = shapeMeasurementsFile.getColumnWithName(linearDistortName);
if (arealDistortColumn < 0) {
std::cout << "PROGRAM ERROR: invalid areal distortion column at "
<< __LINE__ << " in " << __FILE__ << std::endl;
return;
}
if (linearDistortColumn < 0) {
std::cout << "PROGRAM ERROR: invalid linear distortion column at "
<< __LINE__ << " in " << __FILE__ << std::endl;
return;
}
const int numNodes = morphingSurface->getNumberOfNodes();
std::vector<float> linearDistortion(numNodes);
std::vector<float> arealDistortion(numNodes);
for (int i = 0; i < numNodes; i++) {
arealDistortion[i] = shapeMeasurementsFile.getValue(i, arealDistortColumn);
linearDistortion[i] = shapeMeasurementsFile.getValue(i, linearDistortColumn);
}
//
// Statistics for areal distortion
//
StatisticsUtilities::DescriptiveStatistics arealDistortionStats;
StatisticsUtilities::computeStatistics(arealDistortion,
true,
arealDistortionStats);
/*
StatisticDataGroup arealGroup(&arealDistortion,
StatisticDataGroup::DATA_STORAGE_MODE_POINT);
StatisticsUtilities arealDS(StatisticDescriptiveStatistics::DATA_TYPE_SAMPLE);
arealDS.addDataGroup(&arealGroup);
try {
arealDS.execute();
}
catch (StatisticException&) {
}
const StatisticDescriptiveStatistics::DescriptiveStatistics
arealDistortionStats = arealDS.getDescriptiveStatistics();
*/
//
// Statistics for linear distortion
//
StatisticsUtilities::DescriptiveStatistics linearDistortionStats;
StatisticsUtilities::computeStatistics(linearDistortion,
true,
linearDistortionStats);
/*
StatisticDataGroup linearGroup(&linearDistortion,
StatisticDataGroup::DATA_STORAGE_MODE_POINT);
StatisticDescriptiveStatistics linearDS(StatisticDescriptiveStatistics::DATA_TYPE_SAMPLE);
linearDS.addDataGroup(&linearGroup);
try {
linearDS.execute();
}
catch (StatisticException&) {
}
const StatisticDescriptiveStatistics::DescriptiveStatistics
linearDistortionStats = linearDS.getDescriptiveStatistics();
*/
int numTileCrossovers, numNodeCrossovers;
morphingSurface->crossoverCheck(numTileCrossovers, numNodeCrossovers, brainModelSurfaceType);
MorphingMeasurements mm(cycleName,
arealDistortionStats,
linearDistortionStats,
numNodeCrossovers, numTileCrossovers, elapsedTime);
measurements.push_back(mm);
}
/**
* Smooth to eliminate crossovers.
*/
void
BrainModelSurfaceMultiresolutionMorphing::smoothOutCrossovers(BrainModelSurface* bms,
const float sphereRadius)
{
if (DebugControl::getDebugOn()) {
try {
BrainModelSurface temp(*bms);
temp.getCoordinateFile()->writeFile("debug_morph_before_any_smoothing.coord");
} catch (FileException&) {
}
}
int numNodeCrossovers = 10;
MultiResolutionMorphingCycle* cycle = this->multiResMorphFile.getCycle(currentCycle);
int smoothingIterations = cycle->getSmoothingIterations();
float smoothingStrength = cycle->getSmoothingStrength();
int smoothingEdgesIterations = cycle->getSmoothingIterationEdges();
int iterCount = 0;
while ((numNodeCrossovers > 2) && (iterCount < smoothingIterations)) {
int numIters = 10;
if ((smoothingIterations - iterCount) < numIters) {
numIters = (smoothingIterations - iterCount);
}
if (numIters > 0) {
bms->arealSmoothing(smoothingStrength, numIters,
smoothingEdgesIterations);
iterCount += numIters;
}
else {
break;
}
//
// Push nodes on spherical surface back to the sphere
//
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
bms->convertToSphereWithRadius(sphereRadius);
//
// If normals should be pointed outward
//
if (this->multiResMorphFile.isPointSphericalTrianglesOutward()) {
bms->orientTilesOutward(BrainModelSurface::SURFACE_TYPE_SPHERICAL);
}
}
int numTileCrossovers;
bms->crossoverCheck(numTileCrossovers, numNodeCrossovers, brainModelSurfaceType);
}
if (DebugControl::getDebugOn()) {
try {
BrainModelSurface temp2(*bms);
temp2.getCoordinateFile()->writeFile("debug_morph_after_general_smoothing.coord");
} catch (FileException&) {
}
}
if (this->multiResMorphFile.isSmoothOutCrossovers()) {
//
// Set project back to sphere if sphere
//
int projToSphereEveryIter = -1;
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
projToSphereEveryIter = -1;
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
projToSphereEveryIter = 5;
break;
}
//
// Smooth out crossovers
//
// bms->smoothOutSurfaceCrossovers(1.0, 10, 50, 10, projToSphereEveryIter, 3);
bms->smoothOutSurfaceCrossovers(crossoverSmoothStrength,
crossoverSmoothCycles,
crossoverSmoothIterations,
crossoverSmoothEdgeIterations,
crossoverSmoothProjectToSphereIterations,
crossoverSmoothNeighborDepth,
brainModelSurfaceType);
//
// Project back to sphere
//
switch (morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
bms->convertToSphereWithRadius(sphereRadius);
break;
}
int numTileCrossovers;
bms->crossoverCheck(numTileCrossovers, numNodeCrossovers, brainModelSurfaceType);
}
if (DebugControl::getDebugOn()) {
try {
BrainModelSurface temp3(*bms);
temp3.getCoordinateFile()->writeFile("debug_morph_crossover_smoothing.coord");
} catch (FileException&) {
}
}
if (DebugControl::getDebugOn()) {
if (numNodeCrossovers > 0) {
std::cout << "At end of smoothing there are " << numNodeCrossovers
<< " node crossovers." << std::endl;
}
}
}
/**
* Write multiresolution surfaces. Note that spec file is written automatically any
* time a data file is saved.
*/
void
BrainModelSurfaceMultiresolutionMorphing::writeMultiresolutionSurfaces(std::vector<BrainSet*>& brains)
{
//
// surface with index 0 is surface being morphed and do not need to write it
//
const int numBrainSets = static_cast<int>(brains.size());
for (int i = (numBrainSets - 1); i > 0; i--) {
BrainSet* bs = brains[i];
bs->setSpecFileName(intermediateSpecFileNames[i]);
try {
//
// Write the topology file
//
QString topoName(intermediateFileNamePrefix[i]);
topoName.append(SpecFile::getTopoFileExtension());
TopologyFile* tf = bs->getTopologyFile(0);
try {
bs->writeTopologyFile(topoName, tf->getTopologyType(), tf);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
intermediateFiles.push_back(topoName);
//
// Write the fidicual coordinate file
//
QString fiducialName(intermediateFileNamePrefix[i]);
fiducialName.append(".fiducial");
fiducialName.append(SpecFile::getCoordinateFileExtension());
BrainModelSurface* bms = bs->getBrainModelSurface(SURFACE_FIDUCIAL_INDEX);
CoordinateFile* cf = bms->getCoordinateFile();
try {
bs->writeCoordinateFile(fiducialName, bms->getSurfaceType(), cf);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
intermediateFiles.push_back(fiducialName);
//
// Write the flat/spherical coordinate file
//
QString flatName(intermediateCoordFileNamePrefix[i]);
flatName.append(SpecFile::getCoordinateFileExtension());
bms = bs->getBrainModelSurface(SURFACE_MORPHED_INDEX);
cf = bms->getCoordinateFile();
try {
bs->writeCoordinateFile(flatName, bms->getSurfaceType(), cf);
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
intermediateFiles.push_back(flatName);
//
// Convert the surface to a border file to facilitate overlaying surface
// on the original high resolution surface
//
{
QString borderFileName(intermediateCoordFileNamePrefix[i]);
borderFileName.append(SpecFile::getBorderFileExtension());
BorderFile bf(bms->getTopologyFile(), bms->getCoordinateFile());
switch(morphingSurfaceType) {
case BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT:
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getFlatBorderFileTagName());
bs->addToSpecFile(SpecFile::getFlatBorderFileTag(), borderFileName);
break;
case BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL:
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getSphericalBorderFileTagName());
bs->addToSpecFile(SpecFile::getSphericalBorderFileTag(), borderFileName);
break;
}
bf.writeFile(borderFileName);
intermediateFiles.push_back(borderFileName);
}
}
catch (FileException& e) {
std::cerr << "File Write Error: " << e.whatQString().toAscii().constData() << std::endl;
}
}
}
/**
* Create downsampled multiresolution surface(s).
*/
void
BrainModelSurfaceMultiresolutionMorphing::multiresolutionDownsample(
std::vector<BrainSet*>& brains)
{
int numNodes = 1000;
//
// create subsampled surfaces until number of nodes is less than or equal to 100
//
while (numNodes > 100) {
const int brainIndex = brains.size() - 1;
const int prevNumNodes = brains[brainIndex]->getNumberOfNodes();
BrainSet* bs = downsampleEquilateralGridSurface(brains[brainIndex]);
if (bs != NULL) {
brains.push_back(bs);
numNodes = bs->getNumberOfNodes();
if (DebugControl::getDebugOn()) {
std::cout << "Downsampled surface " << brainIndex << " to " << (brainIndex + 1)
<< " nodes reduced from " << prevNumNodes << " to "
<< numNodes << std::endl;
}
}
else {
throw BrainModelAlgorithmException("Failed to downsample surface");
}
//
// limit to maximum number of levels
//
if (brains.size() == MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS) {
break;
}
}
}
/**
* Downsample an equilateral grid surface by selecting every other node in each row and column.
*/
BrainSet*
BrainModelSurfaceMultiresolutionMorphing::downsampleEquilateralGridSurface(BrainSet* brainIn)
{
//
// Surfaces and coordinate files of input brain
//
BrainModelSurface* fiducialSurfaceIn = brainIn->getBrainModelSurface(SURFACE_FIDUCIAL_INDEX);
CoordinateFile* fiducialCoordIn = fiducialSurfaceIn->getCoordinateFile();
BrainModelSurface* flatSurfaceIn = brainIn->getBrainModelSurface(SURFACE_MORPHED_INDEX);
CoordinateFile* flatCoordIn = flatSurfaceIn->getCoordinateFile();
//
// Output brain set
//
BrainSet* brainOut = new BrainSet;
brainOut->setStructure(brainStruct);
//
// Output brain surfaces (fiducial, flat, and a flat that does not get modified)
//
BrainModelSurface* fiducialSurfaceOut = new BrainModelSurface(brainOut);
fiducialSurfaceOut->setSurfaceType(BrainModelSurface::SURFACE_TYPE_FIDUCIAL);
fiducialSurfaceOut->setStructure(brainStruct);
BrainModelSurface* flatSurfaceOut = new BrainModelSurface(brainOut);
flatSurfaceOut->setSurfaceType(BrainModelSurface::SURFACE_TYPE_FLAT);
fiducialSurfaceOut->setStructure(brainStruct);
BrainModelSurface* flatNotMorphSurfaceOut = new BrainModelSurface(brainOut);
flatNotMorphSurfaceOut->setSurfaceType(BrainModelSurface::SURFACE_TYPE_FLAT);
flatNotMorphSurfaceOut->setStructure(brainStruct);
//
// Add brain surfaces to brain
//
brainOut->addBrainModel(fiducialSurfaceOut);
brainOut->addBrainModel(flatSurfaceOut);
brainOut->addBrainModel(flatNotMorphSurfaceOut);
//
// Loop through node of input flat surface for subsampling
//
const int numNodes = flatSurfaceIn->getNumberOfNodes();
for (int nm = 0; nm < numNodes; nm++) {
const BrainSetNodeAttribute* bna = brainIn->getNodeAttributes(nm);
int row, column, node;
bna->getFlatMorphAttributes(row, column, node);
//
// Use node in every other row and column
//
if ( ((row % 2) == 0) && ((column %2) == 0) ) {
flatSurfaceOut->addNode(flatCoordIn->getCoordinate(nm));
flatNotMorphSurfaceOut->addNode(flatCoordIn->getCoordinate(nm));
fiducialSurfaceOut->addNode(fiducialCoordIn->getCoordinate(nm));
brainOut->resetNodeAttributes();
BrainSetNodeAttribute* bna = brainOut->getNodeAttributes(flatSurfaceOut->getNumberOfNodes() - 1);
bna->setFlatMorphAttributes((row/2), (column/2), nm);
}
}
//
// Unable to subsample ?
//
if (flatSurfaceOut->getNumberOfNodes() <= 0) {
delete fiducialSurfaceOut;
delete flatSurfaceOut;
delete flatNotMorphSurfaceOut;
return NULL;
}
//
// Create the topology
//
TopologyFile* topology = createEquilateralGridTopology(brainOut, flatSurfaceOut);
if (topology != NULL) {
fiducialSurfaceOut->setTopologyFile(topology);
flatSurfaceOut->setTopologyFile(topology);
flatNotMorphSurfaceOut->setTopologyFile(topology);
brainOut->addTopologyFile(topology);
}
return brainOut;
}
/**
* Create the topology for an equilateral grid.
*/
TopologyFile*
BrainModelSurfaceMultiresolutionMorphing::createEquilateralGridTopology(BrainSet* brain,
BrainModelSurface* surface)
{
const int numNodes = surface->getNumberOfNodes();
TopologyFile *topology = new TopologyFile();
topology->setTopologyType(TopologyFile::TOPOLOGY_TYPE_CUT);
for (int i = 0; i < numNodes; i++) {
BrainSetNodeAttribute* bna = brain->getNodeAttributes(i);
int row, col, node;
bna->getFlatMorphAttributes(row, col, node);
const int n1 = brain->getNodeWithMorphRowColumn(row, col + 1, i);
const int n2 = brain->getNodeWithMorphRowColumn(row + 1, col, i);
const int n3 = brain->getNodeWithMorphRowColumn(row + 1, col - 1, i);
if ((n1 >= 0) && (n2 >= 0)) {
topology->addTile(i, n1, n2);
}
if ((n2 >= 0) && (n3 >= 0)) {
topology->addTile(i, n2, n3);
}
}
if (topology->getNumberOfTiles() <= 0) {
delete topology;
throw BrainModelAlgorithmException("Failed to create topology");
}
return topology;
}
/**
* Peform the multi-resolution morphing
*/
void
BrainModelSurfaceMultiresolutionMorphing::multiresolutionMorph(std::vector<BrainSet*>& brains)
{
const int numBrains = static_cast<int>(brains.size());
//
// Limit to available levels
//
int startNum = numBrains - 1;
if (startNum >= MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS) {
startNum = MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS - 1;
}
//
// Start with the lowest resolution surface
//
for (int bi = startNum; bi > 0; bi--) {
//
// Get the flat and fiducial surfaces
//
BrainSet* bs = brains[bi];
BrainModelSurface* fiducialSurface = bs->getBrainModelSurface(SURFACE_FIDUCIAL_INDEX);
BrainModelSurface* flatSurface = bs->getBrainModelSurface(SURFACE_MORPHED_INDEX);
//
// Update normals on the flat and fiducial surfaces
//
fiducialSurface->computeNormals();
flatSurface->computeNormals();
MultiResolutionMorphingCycle* morphCycle = this->multiResMorphFile.getCycle(currentCycle);
int iterationsPerLevel[MultiResolutionMorphingCycle::MAXIMUM_NUMBER_OF_LEVELS];
morphCycle->getIterationsAll(iterationsPerLevel);
if (DebugControl::getDebugOn()) {
std::cout << std::endl << "*** Morphing Level surface " << bi
<< ": nodes " << bs->getNumberOfNodes()
<< ", iterations " << iterationsPerLevel[bi] << std::endl;
}
//
// Morph the surface for the specified iterations
//
BrainModelSurfaceMorphing bsm(bs, fiducialSurface, flatSurface, morphingSurfaceType);
MultiResolutionMorphingCycle* cycle =
this->multiResMorphFile.getCycle(this->currentCycle);
bsm.setMorphingParameters(iterationsPerLevel[bi],
cycle->getLinearForce(),
cycle->getAngularForce(),
cycle->getStepSize());
bsm.execute();
//
// Write the morphed file
//
std::ostringstream str;
str << intermediateCoordFileNamePrefix[bi].toAscii().constData()
<< ".Morph"
<< iterationsPerLevel[bi];
intermediateCoordFileNamePrefix[bi] = str.str().c_str();
QString coordName(intermediateCoordFileNamePrefix[bi]);
coordName.append(SpecFile::getCoordinateFileExtension());
try {
bs->writeCoordinateFile(coordName, flatSurface->getSurfaceType(),
flatSurface->getCoordinateFile());
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
intermediateFiles.push_back(coordName);
//
// Convert the morphed surface to a border file for help in debugging
//
{
QString borderFileName(coordName);
borderFileName.append(SpecFile::getBorderFileExtension());
BorderFile bf(flatSurface->getTopologyFile(), flatSurface->getCoordinateFile());
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getFlatBorderFileTagName());
}
else {
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getSphericalBorderFileTagName());
}
bf.writeFile(borderFileName);
intermediateFiles.push_back(borderFileName);
}
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_SPHERICAL) {
//
// If upsampling to original surface, we want sphericalUpsample to update
// a copy of the morphing surface since morphingSurface is initially the
// input surface that should no longer be modified.
//
if (bi == 1) {
//
// Make a copy of the input surface (do not want to modify it)
//
BrainModelSurface* bms = new BrainModelSurface(*morphingSurface);
brains[0]->addBrainModel(bms);
morphingSurface = bms;
}
else {
//
// smooth crossovers
//
const int numNodes = bs->getNumberOfNodes();
int iters = 0;
int depth = 0;
if (numNodes < 100) {
iters = 1;
depth = 1;
}
else if (numNodes < 1000) {
iters = 3;
depth = 2;
}
else if (numNodes < 2000) {
iters = 5;
depth = 2;
}
else if (numNodes < 5000) {
iters = 10;
depth = 3;
}
else {
iters = 20;
depth = 3;
}
if (iters > 0) {
// flatSurface->smoothOutSurfaceCrossovers(1.0, 1, iters, 0, iters, depth);
}
}
//
// upsample to next sphere
//
sphericalUpsample(brains, bi - 1);
//
// Write the upsampled coordinate file
//
std::ostringstream str;
str << intermediateCoordFileNamePrefix[bi-1].toAscii().constData()
<< ".Morph.Up";
intermediateCoordFileNamePrefix[bi-1] = str.str().c_str();
QString coordName(intermediateCoordFileNamePrefix[bi-1]);
coordName.append(SpecFile::getCoordinateFileExtension());
BrainModelSurface* surf = brains[bi-1]->getBrainModelSurface(SURFACE_MORPHED_INDEX);
if (bi != 1) {
try {
brains[bi-1]->writeCoordinateFile(coordName, surf->getSurfaceType(),
surf->getCoordinateFile());
//
// Convert the morphed surface to a border file for help in debugging
//
{
QString borderFileName(coordName);
borderFileName.append(SpecFile::getBorderFileExtension());
BorderFile bf(flatSurface->getTopologyFile(), flatSurface->getCoordinateFile());
if (morphingSurfaceType == BrainModelSurfaceMorphing::MORPHING_SURFACE_FLAT) {
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getFlatBorderFileTagName());
}
else {
bf.setHeaderTag(AbstractFile::headerTagConfigurationID,
SpecFile::getSphericalBorderFileTagName());
}
bf.writeFile(borderFileName);
intermediateFiles.push_back(borderFileName);
}
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
}
intermediateFiles.push_back(coordName);
//
// morph final surface
//
if (bi == 1) {
//
// Morph the surface for the specified iterations
//
BrainModelSurfaceMorphing bsm(brains[0] /*bs*/, referenceSurface, morphingSurface, morphingSurfaceType);
bsm.setMorphingParameters(iterationsPerLevel[0],
cycle->getLinearForce(),
cycle->getAngularForce(),
cycle->getStepSize());
bsm.execute();
}
}
else { // flat morphing
if (bi > 1) {
//
// Upsample one resolution to another
//
flatUpsample(brains[bi],
brains[bi - 1],
brains[bi - 1]->getBrainModelSurface(SURFACE_MORPHED_INDEX),
false);
intermediateCoordFileNamePrefix[bi - 1].append(".U");
QString coordName(intermediateCoordFileNamePrefix[bi - 1]);
coordName.append(SpecFile::getCoordinateFileExtension());
BrainModelSurface* bms = brains[bi - 1]->getBrainModelSurface(SURFACE_MORPHED_INDEX);
try {
brains[bi - 1]->writeCoordinateFile(coordName, bms->getSurfaceType(),
bms->getCoordinateFile());
}
catch (FileException& e) {
throw BrainModelAlgorithmException(e.whatQString());
}
intermediateFiles.push_back(coordName);
}
else if (bi == 1) {
//
// Make a copy of the input surface (do not want to modify it)
//
BrainModelSurface* bms = new BrainModelSurface(*morphingSurface);
brains[0]->addBrainModel(bms);
morphingSurface = bms;
//
// Backsample into original surface
//
flatUpsample(brains[bi], brains[0], morphingSurface, true);
//
// Morph the surface for the specified iterations
//
BrainModelSurfaceMorphing bsm(brains[0] /*bs*/, referenceSurface, morphingSurface, morphingSurfaceType);
bsm.setMorphingParameters(iterationsPerLevel[0],
cycle->getLinearForce(),
cycle->getAngularForce(),
cycle->getStepSize());
bsm.execute();
}
}
} // for (int bi = ...
}
/**
* Upsample from one flat brain surface to another
*/
void
BrainModelSurfaceMultiresolutionMorphing::flatUpsample(BrainSet* fromBrain, BrainSet* toBrain,
BrainModelSurface* toSurface,
const bool backsampleFlag)
{
//
// "from" brain's surface and coordinate files
//
const BrainModelSurface* fromSurface = fromBrain->getBrainModelSurface(SURFACE_MORPHED_INDEX);
const CoordinateFile* fromCoords = fromSurface->getCoordinateFile();
const BrainModelSurface* fromNotMorphedSurface = fromBrain->getBrainModelSurface(SURFACE_NOT_MORPHED_INDEX);
const int numFromNodes = fromNotMorphedSurface->getNumberOfNodes();
//
// Topology for "from" surface
//
const TopologyHelper* fromTopology =
fromNotMorphedSurface->getTopologyFile()->getTopologyHelper(false, true, false);
//
// "to" brain's coordinate file
//
CoordinateFile* toCoords = toSurface->getCoordinateFile();
const int numToNodes = toSurface->getNumberOfNodes();
//
// Mark all of "to" surface's nodes as unvisited
//
toBrain->setAllNodesVisited(false);
if (backsampleFlag == false) {
//
// In the "fromSurface" the morphNode contains the node number in the "toSurface" from
// which this node was downsampled
//
for (int i = 0; i < numFromNodes; i++) {
if (fromTopology->getNodeHasNeighbors(i)) {
//
// Transfer the coordinates from the morphed "from" surface
//
BrainSetNodeAttribute* bna = fromBrain->getNodeAttributes(i);
const float* xyz = fromCoords->getCoordinate(i);
toCoords->setCoordinate(bna->morphNode, xyz);
//
// Use the visited flag to mark this node as being updated
//
BrainSetNodeAttribute* hiResAttr = toBrain->getNodeAttributes(bna->morphNode);
hiResAttr->setVisited(true);
}
}
}
//
// Point Projector to project new surface points into original surface
//
BrainModelSurfacePointProjector* bspp = new BrainModelSurfacePointProjector(fromNotMorphedSurface,
BrainModelSurfacePointProjector::SURFACE_TYPE_HINT_FLAT,
false);
//
// process all nodes in the "to" surface that were not downsampled
//
for (int i = 0; i < numToNodes; i++) {
//
// Was node NOT downsampled ?
//
if (toBrain->getNodeAttributes(i)->getVisited() == false) {
//
// project using non-morphed "from" surface
//
int nearestTile = -1;
int tileNodes[3];
float tileAreas[3];
const int node = bspp->projectBarycentricBestTile2D(toCoords->getCoordinate(i),
nearestTile,
tileNodes,
tileAreas);
if (node >= 0) {
float xyz[3];
BrainModelSurfacePointProjector::unprojectPoint(tileNodes, tileAreas, fromCoords, xyz);
toCoords->setCoordinate(i, xyz);
}
else if (node >= 0) {
std::cout << "WARNING: Using nearest node when upsampling for " << i << std::endl;
toCoords->setCoordinate(i, fromCoords->getCoordinate(node));
}
}
}
}
/**
* Read in the standard spheres and then construct a fiducial surface for each of them.
*/
void
BrainModelSurfaceMultiresolutionMorphing::constructTemplateSpheres(
std::vector<BrainSet*>& brains) throw (BrainModelAlgorithmException)
{
//
// Get radius of the morphing surface
//
const float morphingSurfaceRadius = morphingSurface->getSphericalSurfaceRadius();
//
// Create a point projector for the morphing surface
//
BrainModelSurfacePointProjector mspp(morphingSurface,
BrainModelSurfacePointProjector::SURFACE_TYPE_HINT_SPHERE,
false);
//
// Get the center of gravity of the reference surface
//
float referenceCOG[3];
referenceSurface->getCenterOfMass(referenceCOG);
//
// User's reference surface coordinate file
//
const CoordinateFile* referenceCoordinateFile = referenceSurface->getCoordinateFile();
//
// Do for each level
//
int numberOfLevels = this->multiResMorphFile.getNumberOfLevels();
for (int lvl = (numberOfLevels - 1); lvl > 0; lvl--) {
//
// Create name of standard sphere spec file
//
std::ostringstream ostr;
ostr << brainSet->getCaretHomeDirectory().toAscii().constData()
<< "/data_files/CONSTRUCT.SPHERE/"
<< "sphere.v5."
<< lvl
<< ".spec";
const QString specFileName(ostr.str().c_str());
//
// Save name of current directory since reading a spec file sets the
// current path to the spec file's directory.
//
const QString savedPath(QDir::currentPath());
//
// Read the spec file and select all files in the spec file
//
SpecFile sf;
try {
sf.readFile(specFileName);
sf.setAllFileSelections(SpecFile::SPEC_TRUE);
}
catch (FileException& /*e*/) {
std::ostringstream msg;
msg << "Unable to read file: "
<< specFileName.toAscii().constData()
<< std::endl;
throw BrainModelAlgorithmException(msg.str().c_str());
}
//
// Create a new brain set and load the files listed in the spec file
//
BrainSet* sphereBrain = new BrainSet;
std::vector<QString> errorMessages;
sphereBrain->readSpecFile(BrainSet::SPEC_FILE_READ_MODE_NORMAL,
sf, specFileName, errorMessages, NULL, NULL);
if (errorMessages.size() > 0) {
QString msg("Error reading data files listed in spec file: ");
msg.append(specFileName);
msg.append("\n");
for (unsigned int i = 0; i < errorMessages.size(); i++) {
msg.append(errorMessages[i]);
msg.append("\n");
}
throw BrainModelAlgorithmException(msg);
}
else if (sphereBrain->getNumberOfBrainModels() < 2) {
QString msg(specFileName);
msg.append(" contains\nless than two surface. Should have fiducial and spherical");
throw BrainModelAlgorithmException(msg);
}
//
// Restore the current directory
//
QDir::setCurrent(savedPath);
//
// Get the standard sphere fiducial surface
//
BrainModelSurface* sphereFiducialSurface = sphereBrain->getBrainModelSurface(0);
if (sphereFiducialSurface == NULL) {
QString msg("Spec file: ");
msg.append(specFileName);
msg.append("\nDoes not contains any surfaces.");
throw BrainModelAlgorithmException(msg);
}
CoordinateFile* sphereFiducialCoords = sphereFiducialSurface->getCoordinateFile();
//
// Get the standard sphere surface
//
BrainModelSurface* sphereSurface = sphereBrain->getBrainModelSurface(1);
if (sphereSurface == NULL) {
QString msg("Spec file: ");
msg.append(specFileName);
msg.append("\nDoes not contains less than 1 surface.");
throw BrainModelAlgorithmException(msg);
}
//
// Set the view of this standard sphere surface so that it is the
// same as the surface being morphed (04/27/2009).
//
sphereSurface->copyTransformations(this->morphingSurface,
BrainModel::BRAIN_MODEL_VIEW_MAIN_WINDOW,
BrainModel::BRAIN_MODEL_VIEW_MAIN_WINDOW);
//
// Set the sphere to have the same area as the reference surface
//
sphereSurface->convertToSphereWithRadius(morphingSurfaceRadius);
//
// Rotate the sphere just a little. Higher resolution spheres have points directly
// on edges of the lower resolution sphere which creates a degenerate condition
// when mapping.
//
TransformationMatrix tm;
tm.rotate(TransformationMatrix::ROTATE_X_AXIS, 0.25 * lvl);
tm.rotate(TransformationMatrix::ROTATE_Y_AXIS, 0.25 * lvl);
tm.rotate(TransformationMatrix::ROTATE_Z_AXIS, 0.25 * lvl);
sphereSurface->applyTransformationMatrix(tm);
//
// Project nodes in sphere surface onto morphing surface
//
const int numSphereNodes = sphereSurface->getNumberOfNodes();
if (numSphereNodes != sphereFiducialCoords->getNumberOfCoordinates()) {
QString msg(specFileName);
msg.append("\nfiducial and sphere have a different number of coordinates.\n");
msg.append("Sphere Fiducial number of coordinates: ");
msg.append(StringUtilities::fromNumber(sphereFiducialCoords->getNumberOfCoordinates()));
msg.append("\nSphere number of coordinates: ");
msg.append(StringUtilities::fromNumber(numSphereNodes));
throw BrainModelAlgorithmException(msg);
}
CoordinateFile* sphereCoords = sphereSurface->getCoordinateFile();
std::vector<bool> nodeNotProjected(numSphereNodes, false);
bool haveNotProjectedNodes = false;
for (int i = 0; i < numSphereNodes; i++) {
float xyz[3];
sphereCoords->getCoordinate(i, xyz);
//
// Project point to input surface
//
int nearestNode = -1;
int tileNodes[3];
float tileAreas[3];
const int tile = mspp.projectBarycentric(xyz, nearestNode,
tileNodes, tileAreas, true);
//
// Did point project into the surface
//
if (tile >= 0) {
//
// Set the sphere's reference surface coordinate
//
float refXYZ[3];
BrainModelSurfacePointProjector::unprojectPoint(tileNodes, tileAreas,
referenceCoordinateFile, refXYZ);
sphereFiducialCoords->setCoordinate(i, refXYZ);
}
else {
//
// Medial wall may be missing from user's reference sphere so mark nodes
// as not projected and place them at the origin
//
nodeNotProjected[i] = true;
haveNotProjectedNodes = true;
sphereFiducialCoords->setCoordinate(i, referenceCOG);
}
} // for (i = 0; i < numSphereNodes...
//
// If there are nodes that were not projected. Typically these nodes are in
// the medial wall so smoothing them pulls them from the origin.
//
if (haveNotProjectedNodes) {
sphereFiducialSurface->linearSmoothing(1.0, 300, 0, &nodeNotProjected);
}
//
// save this sphere brain
//
brains.push_back(sphereBrain);
} // for (lvl...
}
/**
* Map each brain to brain + 1
*/
void
BrainModelSurfaceMultiresolutionMorphing::createSphereDownsampleMapping(
std::vector<BrainSet*>& brains) throw (BrainModelAlgorithmException)
{
const int numBrains = static_cast<int>(brains.size());
//
// Map each brain to the next brain
//
for (int i = 0; i < (numBrains - 1); i++) {
//
// Get the brains
//
BrainSet* currentBrain = brains[i];
BrainSet* nextBrain = brains[i + 1];
//
// Get the current sphere's surface and coordinate file
//
BrainModelSurface* currentSphereSurface = NULL;
if (i == 0) {
currentSphereSurface = morphingSurface;
}
else {
currentSphereSurface = currentBrain->getBrainModelSurface(SURFACE_MORPHED_INDEX);
}
const CoordinateFile* currentSphereCoords = currentSphereSurface->getCoordinateFile();
const int numCoords = currentSphereCoords->getNumberOfCoordinates();
//
// Topology helper for current surface
//
const TopologyHelper* currentSphereTopologyHelper = new TopologyHelper(
currentSphereSurface->getTopologyFile(),
false, true, false);
//
// Get the next sphere's surface
//
BrainModelSurface* nextSphereSurface = nextBrain->getBrainModelSurface(SURFACE_MORPHED_INDEX);
//
// Create a point projector for the next sphere surface
//
BrainModelSurfacePointProjector sspp(nextSphereSurface,
BrainModelSurfacePointProjector::SURFACE_TYPE_HINT_SPHERE,
false);
//
// Project each node from current sphere to next sphere
//
for (int i = 0; i < numCoords; i++) {
float xyz[3];
currentSphereCoords->getCoordinate(i, xyz);
//
// Project point to original surface
//
int nearestNode = -1;
int tileNodes[3];
float tileAreas[3];
int tile = -1;
//
// Only try to project if node has neighbors
//
if (currentSphereTopologyHelper->getNodeHasNeighbors(i)) {
//
// Project current sphere node to next sphere
//
tile = sspp.projectBarycentric(xyz, nearestNode,
tileNodes, tileAreas, true);
}
BrainSetNodeAttribute* bna = currentBrain->getNodeAttributes(i);
bna->setSphericalMorphingAttributes(nearestNode, tile, tileNodes, tileAreas);
}
}
}
/**
* Upsample brain + 1 to brain
*/
void
BrainModelSurfaceMultiresolutionMorphing::sphericalUpsample(std::vector<BrainSet*>& brains,
const int targetBrainIndex)
throw (BrainModelAlgorithmException)
{
//
// Get the brains
//
BrainSet* currentBrain = brains[targetBrainIndex];
BrainSet* nextBrain = brains[targetBrainIndex + 1];
//
// Get the current sphere's surface and coordinate file
//
BrainModelSurface* currentSphereSurface = NULL;
if (targetBrainIndex == 0) {
currentSphereSurface = morphingSurface;
}
else {
currentSphereSurface = currentBrain->getBrainModelSurface(SURFACE_MORPHED_INDEX);
}
CoordinateFile* currentSphereCoords = currentSphereSurface->getCoordinateFile();
const int numCoords = currentSphereCoords->getNumberOfCoordinates();
//
// Get the radius of the sphere
//
const float sphereRadius = currentSphereSurface->getSphericalSurfaceRadius();
//
// Get the next sphere's surface
//
BrainModelSurface* nextSphereSurface = nextBrain->getBrainModelSurface(SURFACE_MORPHED_INDEX);
const CoordinateFile* nextSphereCoords = nextSphereSurface->getCoordinateFile();
//
// Make the next sphere the same radius as the current one
//
nextSphereSurface->convertToSphereWithRadius(sphereRadius);
//
// Update the position of each target coordinate
//
for (int i = 0; i < numCoords; i++) {
//
// get the node's morphing information
int nearestNode = -1;
int tileNodes[3];
float tileAreas[3];
int tile = -1;
BrainSetNodeAttribute* bna = currentBrain->getNodeAttributes(i);
bna->getSphericalMorphingAttributes(nearestNode, tile, tileNodes, tileAreas);
if (tile >= 0) {
//
// Unproject using tile information
//
float xyz[3];
BrainModelSurfacePointProjector::unprojectPoint(tileNodes, tileAreas, nextSphereCoords,
xyz);
currentSphereCoords->setCoordinate(i, xyz);
}
else if (nearestNode >= 0) {
//
// unproject to nearest node's position
//
currentSphereCoords->setCoordinate(i, nextSphereCoords->getCoordinate(nearestNode));
}
}
//
// Force nodes to be on the sphere
//
currentSphereSurface->convertToSphereWithRadius(sphereRadius);
}
/**
* constructor
*/
MorphingMeasurements::MorphingMeasurements(const QString& nameIn,
const StatisticsUtilities::DescriptiveStatistics& arealDistortionStatisticsIn,
const StatisticsUtilities::DescriptiveStatistics& linearDistortionStatisticsIn,
const int numberOfNodeCrossoversIn,
const int numberOfTileCrossoversIn,
const float elapsedTimeIn)
{
arealDistortionStatistics = arealDistortionStatisticsIn;
linearDistortionStatistics = linearDistortionStatisticsIn;
name = nameIn;
numberOfNodeCrossovers = numberOfNodeCrossoversIn;
numberOfTileCrossovers = numberOfTileCrossoversIn;
elapsedTime = elapsedTimeIn;
}
/**
* get the measurements
*/
void
MorphingMeasurements::get(QString& nameOut,
StatisticsUtilities::DescriptiveStatistics& arealDistortionStatisticsOut,
StatisticsUtilities::DescriptiveStatistics& linearDistortionStatisticsOut,
int& numberOfNodeCrossoversOut,
int& numberOfTileCrossoversOut,
float& elapsedTimeOut) const
{
nameOut = name;
arealDistortionStatisticsOut = arealDistortionStatistics;
linearDistortionStatisticsOut = linearDistortionStatistics;
numberOfNodeCrossoversOut = numberOfNodeCrossovers;
numberOfTileCrossoversOut = numberOfTileCrossovers;
elapsedTimeOut = elapsedTime;
}
|