File: BrainModelSurfaceMorphing.cxx

package info (click to toggle)
caret 5.6.4~dfsg.1-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 31,904 kB
  • ctags: 28,901
  • sloc: cpp: 378,050; python: 6,718; ansic: 5,507; makefile: 333; sh: 46
file content (1612 lines) | stat: -rw-r--r-- 53,962 bytes parent folder | download
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
/*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>  // needed for Q_OS_WIN32
#ifdef Q_OS_WIN32     // required for M_PI in <cmath>
#define NOMINMAX
#define _USE_MATH_DEFINES
#endif

#include <QFile>
#include <QTextStream>
#include <QTime>

#include <algorithm>
#include <cmath>
#include <iostream>
#include <sstream>

#include "BrainModelSurfaceDistortion.h"
#include "BrainSetNodeAttribute.h"
#include "BrainSet.h"
#include "BrainModelSurfaceMorphing.h"
#include "DebugControl.h"
#include "FileUtilities.h"
#include "MathUtilities.h"
#include "StatisticsUtilities.h"
#include "StringUtilities.h"
#include "SurfaceShapeFile.h"
#include "TopologyHelper.h"

#include "vtkMath.h"
#include "vtkTriangle.h"

/**
 * Constructor
 */
BrainModelSurfaceMorphing::BrainModelSurfaceMorphing(BrainSet* brainSetIn,
                                           BrainModelSurface* referenceSurfaceIn,
                                           BrainModelSurface* morphingSurfaceIn,
                                           const MORPHING_SURFACE_TYPE morphingSurfaceTypeIn,
                                           const int numberOfThreadsIn)
   : BrainModelAlgorithmMultiThreaded(brainSetIn, NULL, -1, false)
{
   initialize();
   referenceSurface = referenceSurfaceIn;
   morphingSurface  = morphingSurfaceIn;
   morphingSurfaceType = morphingSurfaceTypeIn;
   
   numberOfNodes = 0;
   if (morphingSurface != NULL) {
      numberOfNodes = morphingSurface->getNumberOfNodes();
      nodeShouldBeMorphed = new int[numberOfNodes];
      for (int i = 0; i < numberOfNodes; i++) {
         nodeShouldBeMorphed[i] = true;
      }
   }
   
   PreferencesFile* pf = brainSet->getPreferencesFile();
   int numThreads = pf->getMaximumNumberOfThreads();
   if (numThreads <= 0) {
      numThreads = 1;
   }
   if (numberOfThreadsIn > 0) {
      numThreads = numberOfThreadsIn;
   }
   setNumberOfThreadsToRun(numThreads);
}

/**
 * Constructor for a thread instance.
 */
BrainModelSurfaceMorphing::BrainModelSurfaceMorphing(BrainSet* brainSetIn,
                                           BrainModelSurface* referenceSurfaceIn,
                                           BrainModelSurface* morphingSurfaceIn,
                                           const MORPHING_SURFACE_TYPE morphingSurfaceTypeIn,
                                           NeighborInformation* morphNodeInfoIn,
                                           int* nodeShouldBeMorphedIn,
                                           const float noMorphStepSizeIn,
                                           const int startNodeIndexIn,
                                           const int endNodeIndexIn,
                                           const float sphericalSurfaceRadiusIn,
                                           BrainModelSurfaceMorphing* parentOfThisThreadIn,
                                           const int threadNumberIn)
   : BrainModelAlgorithmMultiThreaded(brainSetIn, parentOfThisThreadIn, threadNumberIn, true)
{
   referenceSurface    = referenceSurfaceIn;
   morphingSurface     = morphingSurfaceIn;
   morphingSurfaceType = morphingSurfaceTypeIn;
   morphNodeInfo       = morphNodeInfoIn;
   nodeShouldBeMorphed = nodeShouldBeMorphedIn;
   noMorphNeighborStepSize = noMorphStepSizeIn;
   startNodeIndex = startNodeIndexIn;
   endNodeIndex   = endNodeIndexIn;
   sphericalSurfaceRadius = sphericalSurfaceRadiusIn;
}                                           
                                           
/**
 * Initialize variables for this instance.
 */
void
BrainModelSurfaceMorphing::initialize()
{
   doStatisticsEachPass = false;
   
   coordsArray1 = NULL;
   coordsArray2 = NULL;
   morphNodeInfo = NULL;
   referenceSurface = NULL;
   morphingSurface  = NULL;
   iterations      = 1;
   linearForce  = 0.50;
   angularForce = 0.30;
   stepSize     = 0.5;
   noMorphNeighborStepSize = 0.5;
   
   nodeShouldBeMorphed = NULL;
   numberOfNodes = 0;
   allNodesBeingMorphed = true;

   setNumberOfThreadsToRun(1);
}

/**
 * Destructor
 */
BrainModelSurfaceMorphing::~BrainModelSurfaceMorphing()
{
   if (getImAThread() == false) {
      if (coordsArray1 != NULL) {
         delete[] coordsArray1;
      }
      if (coordsArray2 != NULL) {
         delete[] coordsArray2;
      }
      if (morphNodeInfo != NULL) {
         delete[] morphNodeInfo;
      }
      if (nodeShouldBeMorphed != NULL) {
         delete[] nodeShouldBeMorphed;
      }
      for (unsigned int i = 0; i < threads.size(); i++) {
         if (threads[i] != NULL) {
            delete threads[i];
         }
      }
   }
}

/**
 * get morphing parameters
 */
void 
BrainModelSurfaceMorphing::getMorphingParameters(int& iterationsOut,
                                            float& linearForceOut,
                                            float& angularForceOut,
                                            float& stepSizeOut) const
{
   iterationsOut   = iterations;
   linearForceOut  = linearForce;
   angularForceOut = angularForce;
   stepSizeOut     = stepSize;
}
                           
/**
 * set morphing parameters
 */
void 
BrainModelSurfaceMorphing::setMorphingParameters(const int iterationsIn,
                                            const float linearForceIn,
                                            const float angularForceIn,
                                            const float stepSizeIn)
{
   iterations   = iterationsIn;
   linearForce  = linearForceIn;
   angularForce = angularForceIn;
   stepSize     = stepSizeIn;
}
                           
/**
 * execute the morphing
 */
void
BrainModelSurfaceMorphing::execute() throw (BrainModelAlgorithmException)
{
   BrainModelSurface::SURFACE_TYPES surfaceTypeHint = BrainModelSurface::SURFACE_TYPE_UNKNOWN;
   switch (morphingSurfaceType) {
      case MORPHING_SURFACE_FLAT:
         surfaceTypeHint = BrainModelSurface::SURFACE_TYPE_FLAT;
         break;
      case MORPHING_SURFACE_SPHERICAL:
         surfaceTypeHint = BrainModelSurface::SURFACE_TYPE_SPHERICAL;
         break;
      default:
         break;
   }
   
   if (numberOfNodes <= 0) {
      throw BrainModelAlgorithmException("Morphing surface has no nodes.");
   }
   if (numberOfNodes != referenceSurface->getNumberOfNodes()) {
      throw BrainModelAlgorithmException(
         "Reference and Morphing surfaces have a different number of nodes.");
   }
   
   //
   // Morphing surface coordinate file
   //
   CoordinateFile* morphCoordFile = morphingSurface->getCoordinateFile();
   
   //
   // Get the coordinates and load them into arrays
   //
   float* coordsArray1 = new float[numberOfNodes * 3];
   float* coordsArray2 = new float[numberOfNodes * 3];
   for (int i = 0; i < numberOfNodes; i++) {
      morphCoordFile->getCoordinate(i, &coordsArray1[i*3]);
   }
   
   //
   // Set the input and output coord pointers
   //
   inputCoords  = coordsArray1;
   outputCoords = coordsArray2;
   
   //
   // Generate neighbors, lengths, and angles for reference surface
   //
   generateNeighborInformation();
   
   //
   // Save radius of morphing surface in case it is a sphere
   //
   sphericalSurfaceRadius = morphingSurface->getSphericalSurfaceRadius();
   
   //
   // If no iterations (just calculating forces)
   //
   bool forcesOnlyFlag = false;
   if (iterations == 0) {
      forcesOnlyFlag = true;
      iterations = 1;
   }
   
   //
   // If measuring at each iteration
   //
   QFile statsFile("morph_stats.txt");
   bool statsFileValid = false;
   if (doStatisticsEachPass) {
      if (statsFile.open(QIODevice::WriteOnly)) {
         statsFileValid = true;
      }
   }
   
   //
   // Surface shape file for measurements
   //
   SurfaceShapeFile measurementsShapeFile;
   
   //
   // See if threads are being used, and if so, create them.
   //
   const int numberOfThreads = getNumberOfThreadsToRun();
   if (numberOfThreads > 1) {
      //
      // Number of nodes each thread should smooth
      //
      const int numNodesPerThread = numberOfNodes / numberOfThreads;
      int startNode = 0;
      int endNode   = numNodesPerThread;
      for (int i = 0; i < numberOfThreads; i++) {
         //
         // Limit ending node for last thread
         //
         if (i == (numberOfThreads - 1)) {
            endNode = numberOfNodes - 1;
         }
         if (DebugControl::getDebugOn()) {
            std::cout << "Morphing thread " << i << " nodes " 
                      << startNode << " " << endNode << std::endl;
         }
         
         //
         // Create the threads
         //
         BrainModelSurfaceMorphing* bmsm = new BrainModelSurfaceMorphing(
                                                            brainSet,
                                                            referenceSurface,
                                                            morphingSurface,
                                                            morphingSurfaceType,
                                                            morphNodeInfo,
                                                            nodeShouldBeMorphed,
                                                            noMorphNeighborStepSize,
                                                            startNode,
                                                            endNode,
                                                            sphericalSurfaceRadius,
                                                            this,
                                                            i);
         bmsm->setMorphingParameters(iterations, linearForce, angularForce, stepSize);
         threads.push_back(bmsm);  
         
         //
         // Determine node indices which each thread should smooth
         //
         startNode = endNode + 1;
         endNode   += numNodesPerThread;
      }
   }
   
   //
   // morph for the surface
   //
   for (int i = 1; i <= iterations; i++) {
      const bool firstIterationFlag = (i == 1);
      const bool lastIterationFlag = (i == iterations);
      
      //
      // Update surface normals
      //
      //for (int j = 0; j < numberOfNodes; j++) {
      //   morphCoordFile->setCoordinate(j, &inputCoords[j*3]);
      //}
      //morphingSurface->computeNormals();
      morphingSurface->computeNormals(inputCoords);
      //
      // Set the forces on nodes that are NOT being morphed
      //
      if (allNodesBeingMorphed == false) {
         setForcesOnNoMorphNodes();
      }
      
      //
      // If running threads
      //
      if (numberOfThreads > 1) {
         for (int j = 0; j < numberOfThreads; j++) {
            //
            // Run each thread for an iteration of smoothing
            //
            threads[j]->setInputAndOutputCoords(inputCoords, outputCoords);
            
            //
            // Clear the number of child threads done
            //
            resetNumChildThreadDone();
            
            //
            // Start the threads if this is the first iteration
            //
            if (firstIterationFlag) {
               threads[j]->setThreadKeepLoopingFlag(true);
               threads[j]->setThreadedIterationDoneFlag(true);
               threads[j]->start(QThread::TimeCriticalPriority);
            }
         }
         
         //
         // Wait until all threads have started and in their loop.
         // This is need for the case that there is only one iteration.
         //
         while (getNumChildThreadStarted() < numberOfThreads) {
            msleep(1);
         }
         
         for (int j = 0; j < numberOfThreads; j++) {
            //
            // if the last iteration, clear the keep looping flag for the thread
            //
            if (lastIterationFlag ) {
               threads[j]->setThreadKeepLoopingFlag(false);
            }
            
            //
            // wake the thread so that it executes an iteration
            //
            if (DebugControl::getDebugOn()) {
               std::cout << "Allowing morphing thread " << j << " to run." << std::endl;
            }
            threads[j]->setThreadedIterationDoneFlag(false);
         }
         
         //
         // Wait until all of the threads finish
         //
         while (getNumChildThreadDone() < numberOfThreads) {
            msleep(1);
         }
         if (DebugControl::getDebugOn()) {
            std::cout << "All morphing threads completed iteration." << std::endl;
         }
      }
      else {
         //
         // Smooth for one iteration
         //
         setIndicesOfNodesToMorph(0, numberOfNodes - 1);
         run(i);
      }
      
      //
      // morph one iteration
      //
      //run(i);
      
      if (DebugControl::getDebugOn()) {
         if ((DebugControl::getDebugNodeNumber() >= 0) &&
             (DebugControl::getDebugNodeNumber() < numberOfNodes)) {
            const int node = DebugControl::getDebugNodeNumber();
            std::cout << "DEBUG iter " << i << " NODE "
                      << node << " coords: " 
                      << outputCoords[node*3] << " "
                      << outputCoords[node*3+1] << " "
                      << outputCoords[node*3+2] << std::endl;
         }
      }
      
      bool coordFileUpdated = false;
      
      //
      // If NOT the last iteration
      //
      if (lastIterationFlag == false) {
         //
         // Update the displayed brain model
         //
         if (brainSet->isIterationUpdate(i)) {
            for (int j = 0; j < numberOfNodes; j++) {
               morphCoordFile->setCoordinate(j, &outputCoords[j*3]);
            }
            brainSet->drawBrainModel(morphingSurface, i);
            coordFileUpdated = true;
         }

         //
         // swap input and output coordinate pointers
         //
         std::swap(inputCoords, outputCoords);
      }

      //
      // If just calculating forces, reset iterations
      //
      if (forcesOnlyFlag) {
         iterations = 0;
      }
      
      //
      // If measuring at each iteration
      //
      if (statsFileValid) {
         //
         // If not just doing forces
         //
         if (forcesOnlyFlag == false) {
            updateStatsFile(statsFile,
                            morphCoordFile,
                            measurementsShapeFile,
                            surfaceTypeHint,
                            i,
                            firstIterationFlag);
         } 
      } 
   }  

   //
   //
   //
   if (statsFileValid) {
      statsFile.close();
   }
   
   //
   // Copy the coordinates back to the morphing surface
   //   
   if (forcesOnlyFlag == false) {
      for (int j = 0; j < numberOfNodes; j++) {
         morphCoordFile->setCoordinate(j, &outputCoords[j*3]);
      }
   }
   
   //
   // Copy the force vectors
   //
   BrainSetNodeAttribute* attributes = brainSet->getNodeAttributes(0);
   for (int i = 0; i < numberOfNodes; i++) {
      attributes[i].setMorphingForces(morphNodeInfo[i].linearForce,
                              morphNodeInfo[i].angularForce,
                              morphNodeInfo[i].totalForce);
   }
   if (DebugControl::getDebugOn()) {
      const int node = DebugControl::getDebugNodeNumber();
      if (node >= 0) {
         int start = node - 5;
         int end = node + 5;
         if (start < 0) {
            start = start - start;
            end = start + 10;
         }
         if (end >= numberOfNodes) {
            end = numberOfNodes - 1;
         }
         for (int j = start; j < end; j++) {
            std::cout << j << ": Forces (L, A): " 
                        << morphNodeInfo[j].linearForce[0] << " "
                        << morphNodeInfo[j].linearForce[1] << " "
                        << morphNodeInfo[j].linearForce[2] << "  "
                        << morphNodeInfo[j].angularForce[0] << " "
                        << morphNodeInfo[j].angularForce[1] << " "
                        << morphNodeInfo[j].angularForce[2] << " "
                        << std::endl;
         }
      }
   }
}

/**
 * Update the statistics file used for testing
 */
void
BrainModelSurfaceMorphing::updateStatsFile(QFile& statsFile,
                                           CoordinateFile* morphCoordFile,
                                           SurfaceShapeFile& measurementsShapeFile,
                                           BrainModelSurface::SURFACE_TYPES surfaceTypeHint,
                                           const int iterationNumber,
                                           const bool firstIterationFlag)
{
   //
   // Add columns to surface shape file if first time
   //
   if (measurementsShapeFile.getNumberOfColumns() <= 1) {
      measurementsShapeFile.setNumberOfNodesAndColumns(numberOfNodes, 2);
   }
   
   //
   // Update coordinates since stats taken on surface
   //
   for (int j = 0; j < numberOfNodes; j++) {
      morphCoordFile->setCoordinate(j, &outputCoords[j*3]);
   }
   
   //
   // Determine distortion
   //
   BrainModelSurfaceDistortion bmsd(brainSet,
                                    morphingSurface,
                                    referenceSurface,
                                    morphingSurface->getTopologyFile(),
                                    &measurementsShapeFile,
                                    BrainModelSurfaceDistortion::DISTORTION_COLUMN_CREATE_NEW,
                                    BrainModelSurfaceDistortion::DISTORTION_COLUMN_CREATE_NEW,
                                    "areal-dist",
                                    "linear-dist");
   try {
      //
      // Generate distortion
      //
      bmsd.execute();
      
      //
      // Get areal and linear distortion statistics
      //
      StatisticsUtilities::DescriptiveStatistics arealStats, linearStats;
      bmsd.getArealDistortionStatistics(arealStats);
      bmsd.getLinearDistortionStatistics(linearStats);
      
      //
      // Do a crossover check
      //
      int numTileCrossovers, numNodeCrossovers;
      morphingSurface->crossoverCheck(numTileCrossovers, 
                                       numNodeCrossovers,
                                       surfaceTypeHint);
      
      //
      // Set textstream for file
      //
      QTextStream stream(&statsFile);
      stream.setRealNumberNotation(QTextStream::FixedNotation);
      
      if (firstIterationFlag) {
         stream << ""
                  << "\t" << "Number of"
                  << "\t" << "Areal"
                  << "\t" << "Areal"
                  << "\t" << "Linear"
                  << "\t" << "Linear"
                  << "\n";
         stream << "Iteration"
                  << "\t" << "Tile"
                  << "\t" << "Distortion"
                  << "\t" << "Distortion"
                  << "\t" << "Distortion"
                  << "\t" << "Distortion"
                  << "\n";
         stream << "Number"
                  << "\t" << "Crossovers"
                  << "\t" << "Average"
                  << "\t" << "Deviation"
                  << "\t" << "Average"
                  << "\t" << "Deviation"
                  << "\n";
      }
      
      stream << iterationNumber
               << "\t" << numTileCrossovers
               << "\t" << arealStats.average
               << "\t" << arealStats.standardDeviation
               << "\t" << linearStats.average
               << "\t" << linearStats.standardDeviation
               << "\n";               
   }
   catch (BrainModelAlgorithmException&) {
   }
}

/**
 * Project nodes back to the sphere.
 */
void
BrainModelSurfaceMorphing::projectNodeBackToSphere(const int nodeNumber)
{
   //
   // scale to sphere
   //
   if (morphNodeInfo[nodeNumber].numNeighbors > 0) {
      const int i3 = nodeNumber * 3;
      const float prad = std::sqrt(outputCoords[i3]   * outputCoords[i3] +
                              outputCoords[i3+1] * outputCoords[i3+1] +
                              outputCoords[i3+2] * outputCoords[i3+2]);
      if (prad > 0.0) {
         const float scale = sphericalSurfaceRadius / prad;
         outputCoords[i3]   *= scale;
         outputCoords[i3+1] *= scale;
         outputCoords[i3+2] *= scale;
      }
   }
}

/**
 * Calculate forces on nodes that are NOT BEING MORPHED.
 * This cannot be done inside the threaded execution since these
 * node's forces are needed by other nodes.
 */
void
BrainModelSurfaceMorphing::setForcesOnNoMorphNodes()
{
   //
   // Calculate forces on nodes that are NOT BEING MORPHED
   // This is needed for some "inverse force" calculations needed below
   //
   for (int j = 0; j < numberOfNodes; j++) {
   
      if (nodeShouldBeMorphed[j] == false) {
         //
         // Info for this node and reset forces
         //
         NeighborInformation& nodeInfo = morphNodeInfo[j];
         nodeInfo.resetForces();
         
         if (nodeInfo.numNeighbors > 1) {
         
            const float floatNumNeighbors = static_cast<float>(nodeInfo.numNeighbors);
            //
            // Determine linear forces for node
            //
            if (linearForce > 0.0) {
               for (int k = 0; k < nodeInfo.numNeighbors; k++) {
                  const int n = nodeInfo.neighbors[k];
                  float linearForceComponents[3];
                  computeLinearForce(inputCoords, nodeInfo, j, n, k, linearForceComponents);
                  for (int i = 0; i < 3; i++) {
                     nodeInfo.totalForce[i] +=
                        linearForceComponents[i] / floatNumNeighbors;
                     nodeInfo.linearForce [i] +=
                        linearForceComponents[i] / floatNumNeighbors;
                  }
                  
               }
            }
            
            // Apply angular forces to node
            //
            if (angularForce > 0.0) {
               if (nodeInfo.classification == BrainSetNodeAttribute::CLASSIFICATION_TYPE_CORNER) {
                  float angularForceComponents[3];
                  computeAngularForce(inputCoords, nodeInfo, 0, angularForceComponents);
                  
                  for (int i = 0; i < 3; i++){
                     nodeInfo.totalForce[i] +=
                              angularForceComponents[i] / (floatNumNeighbors - 1.0);
                     nodeInfo.angularForce[i] +=
                              angularForceComponents[i] / (floatNumNeighbors - 1.0);
                  }
               }
               else {
                  for (int k = 0; k < nodeInfo.numNeighbors; k++){
                     float angularForceComponents[3];
                     computeAngularForce(inputCoords, nodeInfo, k, angularForceComponents);
                     for (int i = 0; i < 3; i++){
                        nodeInfo.totalForce[i] +=
                                 angularForceComponents[i] / floatNumNeighbors;
                        nodeInfo.angularForce[i] +=
                                 angularForceComponents[i] / floatNumNeighbors;
                     }
                  }
               }
            } // if (angularForce > 0.0)
         }
      }
   }
   
}

/**
 * Morph the surface
 */
void
BrainModelSurfaceMorphing::run(int iteration)
{
   QTime timer;
   timer.start();

   //
   // set looping flag for non-threaded execution so that we do an iteration
   //
   if (getImAThread() == false) {
      setThreadKeepLoopingFlag(true);
   }
   
   //
   // The threaded execution will stay in the loop since run only gets called once
   //
   while (getThreadKeepLoopingFlag()) {
   
      //
      // Is this a threaded instance
      //
      if (getImAThread()) {
         //
         // let parent know that this thread has started
         //
         getParentOfThisThread()->incrementNumChildThreadStarted();
         
         //
         // Wait until parent says it is okay to go
         //
         while (getThreadedIterationDoneFlag()) {
            msleep(1);
         }
         if (DebugControl::getDebugOn()) {
            std::cout << "Morphing Thread " << getThreadNumber() << " now executing." << std::endl;
         }
      }
      
      //
      // morph each node that should be morphed
      //
      for (int j = startNodeIndex; j <= endNodeIndex; j++) {
         //
         // Save node position
         //
         float nodePos[3] = { inputCoords[j*3], inputCoords[j*3+1], inputCoords[j*3+2] };
         outputCoords[j*3]   = nodePos[0];
         outputCoords[j*3+1] = nodePos[1];
         outputCoords[j*3+2] = nodePos[2];
         
         //
         // Info for this node
         //
         NeighborInformation& nodeInfo = morphNodeInfo[j];
         
         //
         // If this node has neighbors and should be morphed
         //
         if ((nodeInfo.numNeighbors > 1) && nodeShouldBeMorphed[j]) {
            //
            // Initialize forces to zero
            //
            nodeInfo.resetForces();
            
            float linearForceComponents[3];
            float angularForceComponents[3];
         
            const float floatNumNeighbors = static_cast<float>(nodeInfo.numNeighbors);
            //
            // Apply linear forces to node
            //
            if (linearForce > 0.0) {
               for (int k = 0; k < nodeInfo.numNeighbors; k++) {
                  const int n = nodeInfo.neighbors[k];
                  computeLinearForce(inputCoords, nodeInfo, j, n, k, linearForceComponents);
                  for (int i = 0; i < 3; i++) {
                     nodeInfo.totalForce[i] +=
                        linearForceComponents[i] / floatNumNeighbors;
                     nodeInfo.linearForce[i] +=
                        linearForceComponents[i] / floatNumNeighbors;
                  
                     //
                     // If this neighbor is not a morphable node
                     //
                     if (nodeShouldBeMorphed[n] == false) {
                        //
                        //  Add the inverse of the neighbor's linear force
                        //
                        nodeInfo.totalForce[i]  -= (noMorphNeighborStepSize * 
                                                   morphNodeInfo[n].linearForce[i])
                                                   / floatNumNeighbors;
                        nodeInfo.linearForce[i] -= (noMorphNeighborStepSize * 
                                                   morphNodeInfo[n].linearForce[i])
                                                   / floatNumNeighbors;
                     }
                  }
               }
   
               if (DebugControl::getDebugOn()) {
                  if (DebugControl::getDebugNodeNumber() == j) {
                     std::cout << std::endl;
                     std::cout << "Total Linear Force for node: " << j
                              << "(" << nodeInfo.linearForce[0]
                              << ", " << nodeInfo.linearForce[1]
                              << ", " << nodeInfo.linearForce[2] << ")" << std::endl;
                     std::cout << std::endl;
                  }
               }
            }
               
            //
            // Apply angular forces to node
            //
            if (angularForce > 0.0) {
               if (nodeInfo.classification == BrainSetNodeAttribute::CLASSIFICATION_TYPE_CORNER) {
                  computeAngularForce(inputCoords, nodeInfo, 0, angularForceComponents);
                  for (int i = 0; i < 3; i++){
                     nodeInfo.totalForce[i] +=
                              angularForceComponents[i] / (floatNumNeighbors - 1.0);
                     nodeInfo.angularForce[i] +=
                              angularForceComponents[i] / (floatNumNeighbors - 1.0);
                  }
               }
               else {
                  for (int k = 0; k < nodeInfo.numNeighbors; k++){
                     const int n = nodeInfo.neighbors[k];
                     computeAngularForce(inputCoords, nodeInfo, k, angularForceComponents);
                     for (int i = 0; i < 3; i++){
                        nodeInfo.totalForce[i] +=
                                 angularForceComponents[i] / floatNumNeighbors;
                        nodeInfo.angularForce[i] +=
                                 angularForceComponents[i] / floatNumNeighbors;
                  
                        //
                        // If this neighbor is not a morphable node
                        //
                        if (nodeShouldBeMorphed[n] == false) {
                           //
                           //  Add the inverse of the neighbor's linear force
                           //
                           nodeInfo.totalForce[i]   -= (noMorphNeighborStepSize * 
                                                      morphNodeInfo[n].angularForce[i])
                                                      / floatNumNeighbors;
                           nodeInfo.angularForce[i] -= (noMorphNeighborStepSize * 
                                                      morphNodeInfo[n].angularForce[i])
                                                      / floatNumNeighbors;
                        }
                     }
                  }
               }
            } // if (angularForce > 0.0)
            
            //
            // Adjust forces during spherical morphing
            //
            if (morphingSurfaceType == MORPHING_SURFACE_SPHERICAL) {
               mapForcesToPlane(nodePos, nodeInfo.totalForce);
               mapForcesToPlane(nodePos, nodeInfo.angularForce);
               mapForcesToPlane(nodePos, nodeInfo.linearForce);
            }
            
            //
            // Add forces and store in temporary node positions
            //
            outputCoords[j*3]   = nodePos[0] + stepSize * nodeInfo.totalForce[0];
            outputCoords[j*3+1] = nodePos[1] + stepSize * nodeInfo.totalForce[1];
            outputCoords[j*3+2] = nodePos[2] + stepSize * nodeInfo.totalForce[2];
            
            if (DebugControl::getDebugOn()) {
               if (checkNaN(&outputCoords[j*3], 3)) {
                  QString s = "PROGRAM ERROR: NaN detected for coordinate "
                            + QString::number(j)
                            + " iteration "
                            + QString::number(iteration)
                            + " in "
                            + FileUtilities::basename(morphingSurface->getCoordinateFile()->getFileName());
                  throw BrainModelAlgorithmException(s);
               }
            }            
         }  // if (nodeInfo.numNeighbors > 1)
         
         //
         // Project back to sphere if morphing a sphere
         //
         switch (morphingSurfaceType) {
            case MORPHING_SURFACE_FLAT:
               break;
            case MORPHING_SURFACE_SPHERICAL:
               projectNodeBackToSphere(j);
               break;
         }
         
      } // for (j = 0...
      
      if (getImAThread()) {
         if (DebugControl::getDebugOn()) {
            std::cout << "Morphing Thread " << getThreadNumber() << " finished iteration." << std::endl;
         }
         //
         // A threaded instance needs to tell that it has completed an iteration
         //
         setThreadedIterationDoneFlag(true);
         getParentOfThisThread()->incrementNumChildThreadDone();
      }
      else {
         //
         // A non-threaded instance needs to return
         //
         setThreadKeepLoopingFlag(false);
      }
   } // while (keepLooping)

   if (DebugControl::getDebugOn()) {
      std::cout << "   iteration"
                  << iteration
                  << " time: " << (static_cast<float>(timer.elapsed()) / 1000.0)
             << std::endl;
   }
}

/**
 * check for not a number (true if any data are NaN).
 */
bool 
BrainModelSurfaceMorphing::checkNaN(float* data, int numberOfData) const
{
   for (int i = 0; i < numberOfData; i++) {
      if (MathUtilities::isNaN(data[i])) {
         return true;
      }
   }
   return false;
}
      
/**
 * Map forces to a plane (used in spherical morphing).
 */
void
BrainModelSurfaceMorphing::mapForcesToPlane(const float nodeXYZ[3],
                                            float force[3])
{
   //
   // Compute the node's normal
   //
   float nodeNormal[3] = { nodeXYZ[0], nodeXYZ[1], nodeXYZ[2] };
   MathUtilities::normalize(nodeNormal);
   
   //
   // angle between normal and force
   //
   const float dot = MathUtilities::dotProduct(nodeNormal, force);
   
   //
   // Adjust force
   //
   force[0] = force[0] - (dot * nodeNormal[0]);
   force[1] = force[1] - (dot * nodeNormal[1]);
   force[2] = force[2] - (dot * nodeNormal[2]);
}

/**
 * Compute the angular force on a node by its neighbor.
 */
void
BrainModelSurfaceMorphing::computeAngularForce(const float* coords,
                                                const NeighborInformation& nodeInfo,
                                                const int neighborIndex,
                                                float forceOut[3])
{
   //
   // Clear forces
   //
   forceOut[0] = 0.0;
   forceOut[1] = 0.0;
   forceOut[2] = 0.0; 
   
   if (nodeInfo.numNeighbors < 1) {
      return;
   }
   
   //
   // Indices of neighboring nodes
   //
   const int neighborNodeNumber = nodeInfo.neighbors[neighborIndex];
   int nextNeighborIndex = neighborIndex + 1;
   if (nextNeighborIndex >= nodeInfo.numNeighbors) nextNeighborIndex = 0;
   const int nextNeighborNodeNumber = nodeInfo.neighbors[nextNeighborIndex];
   
   //
   // coordinates of this node and the neighbors
   //
   const float* nodeCoords = &coords[nodeInfo.nodeNumber * 3];
   const float* neighborCoords = &coords[neighborNodeNumber * 3];
   const float* nextNeighborCoords = &coords[nextNeighborNodeNumber * 3];
   
   //
   // Compute the normal for the triangle
   //
   float triangleNormal[3];
   MathUtilities::computeNormal((float*)nodeCoords, (float*)neighborCoords, 
                              (float*)nextNeighborCoords, triangleNormal);
  
   //
   // Check for crossovers
   //
   bool crossover = false;
   switch (morphingSurfaceType) {
      case MORPHING_SURFACE_FLAT:
         if (triangleNormal[2] < 0.0) {
            crossover = true;
         }
         break;
      case MORPHING_SURFACE_SPHERICAL:
         {
            float avgNormal[3] = { 
               (nodeCoords[0] + neighborCoords[0] + nextNeighborCoords[0]) / 3.0,
               (nodeCoords[1] + neighborCoords[1] + nextNeighborCoords[1]) / 3.0,
               (nodeCoords[2] + neighborCoords[2] + nextNeighborCoords[2]) / 3.0 
            };
            if (MathUtilities::normalize(avgNormal) > 0.0) {
               const float dot = MathUtilities::dotProduct(avgNormal, triangleNormal);
               if (dot < 0.0) {
                  crossover = true;
               }
            }
         }
         break;
   }
   crossover = false; //*********************************************************
   if (crossover) {
      triangleNormal[0] = -triangleNormal[0];
      triangleNormal[1] = -triangleNormal[1];
      triangleNormal[2] = -triangleNormal[2];
   }
   
   //
   // Angle at neighbor
   //
   const float angle1 = MathUtilities::angle(nodeCoords, neighborCoords, nextNeighborCoords);
   
   //
   // angle difference
   //
   float angleDiff1 = nodeInfo.angle1[neighborIndex] - angle1;
   if (crossover) {
      angleDiff1 = nodeInfo.angle1[neighborIndex] + angle1;
   }
   
   //
   // distance components and distance to neighbor
   //
   float distanceComponents1[3];
   MathUtilities::subtractVectors(neighborCoords, nodeCoords, distanceComponents1);
   const float distance1 = MathUtilities::vectorLength(distanceComponents1);
   
   //
   // Amount (magnitude) node should be moved
   //
   const float mag1 = distance1 * std::sin(angleDiff1);
   
   //
   // Determine vector of node movement
   //
   float direction1[3];
   
   //
   // Determine a vector that points orthogonally from the plane defined
   // by the tile's normal vector and the tiles edge (vector perpendicular to
   // edge pointing outside the tringle but in the triangle's plane).
   //
   MathUtilities::normalizedCrossProduct(distanceComponents1, triangleNormal, direction1);
             
   if (MathUtilities::vectorLength(direction1) > 0.0) {
      float force[3];
      force[0] =  angularForce * mag1 * direction1[0];
      force[1] =  angularForce * mag1 * direction1[1];
      force[2] =  angularForce * mag1 * direction1[2];
      if (DebugControl::getDebugOn()) {
         if (checkNaN(force, 3)) {
            QString s = "PROGRAM ERROR: NaN detected for angular force node  "
                      + QString::number(nodeInfo.nodeNumber)
                      + " in "
                      + FileUtilities::basename(morphingSurface->getCoordinateFile()->getFileName());
            throw BrainModelAlgorithmException(s);
         }
      }
      if (crossover) {
         force[0] = -force[0];
         force[1] = -force[1];
         force[2] = -force[2];
      }
      
      forceOut[0] +=  force[0];
      forceOut[1] +=  force[1];
      forceOut[2] +=  force[2];
      
      if (DebugControl::getDebugOn()) {
         const int node = DebugControl::getDebugNodeNumber();
         if (node == nodeInfo.nodeNumber) {
            std::cout << "Morphing Debugging Node: " << node << std::endl;
            std::cout << "Neighbor: " << neighborNodeNumber << std::endl;
            std::cout << "Angle1 (Fiducial, surface): " 
                      << (nodeInfo.angle1[neighborIndex] * MathUtilities::radiansToDegrees()) 
                      << " " << (angle1  * MathUtilities::radiansToDegrees())
                      << std::endl;
            std::cout << "Force: " << force[0] << ", "
                                   << force[1] << ", "
                                   << force[2] << std::endl;
         }
      }   
   }
   
   //---------------------------------------------------------------------------------------
  
   //
   // Angle at neighbor
   //
   const float angle2 = MathUtilities::angle(neighborCoords, nextNeighborCoords, nodeCoords);
   
   //
   // angle difference
   //
   float angleDiff2 = nodeInfo.angle2[neighborIndex] - angle2;
   if (crossover) {
      angleDiff2 = nodeInfo.angle2[neighborIndex] + angle2;
   }
   
   //
   // distance components and distance to neighbor
   //
   float distanceComponents2[3];
   MathUtilities::subtractVectors(nextNeighborCoords, nodeCoords, distanceComponents2);
   const float distance2 = MathUtilities::vectorLength(distanceComponents2);
   
   //
   // Amount (magnitude) node should be moved
   //
   const float mag2 = distance2 * std::sin(angleDiff2);
   
   //
   // Determine vector of node movement
   //
   float direction2[3];
   
   //
   // Determine a vector that points orthogonally from the plane defined
   // by the tile's normal vector and the tiles edge (vector perpendicular to
   // edge pointing outside the tringle but in the triangle's plane).
   //
   MathUtilities::normalizedCrossProduct(triangleNormal, distanceComponents2, direction2);
             
   if (MathUtilities::vectorLength(direction2) > 0.0) {
      float force[3];
      force[0] =  angularForce * mag2 * direction2[0];
      force[1] =  angularForce * mag2 * direction2[1];
      force[2] =  angularForce * mag2 * direction2[2];
      if (DebugControl::getDebugOn()) {
         if (checkNaN(force, 3)) {
            QString s = "PROGRAM ERROR: NaN detected for angular force node  "
                      + QString::number(nodeInfo.nodeNumber)
                      + " in "
                      + FileUtilities::basename(morphingSurface->getCoordinateFile()->getFileName());
            throw BrainModelAlgorithmException(s);
         }
      }
      if (crossover) {
         force[0] = -force[0];
         force[1] = -force[1];
         force[2] = -force[2];
      }
      
      forceOut[0] +=  force[0];
      forceOut[1] +=  force[1];
      forceOut[2] +=  force[2];
      if (DebugControl::getDebugOn()) {
         const int node = DebugControl::getDebugNodeNumber();
         if (node == nodeInfo.nodeNumber) {
            std::cout << "Morphing Debugging Node: " << node << std::endl;
            std::cout << "Neighbor: " << nextNeighborNodeNumber << std::endl;
            std::cout << "Angle2 (Fiducial, surface): " 
                      << (nodeInfo.angle2[neighborIndex] * MathUtilities::radiansToDegrees())
                      << " " << (angle2 * MathUtilities::radiansToDegrees())
                       << std::endl;
            std::cout << "Force: " << force[0] << ", "
                                   << force[1] << ", "
                                   << force[2] << std::endl;
         }
      }
   }   
}

/**
 * Compute linear force on a node from a neighbor
 */
void
BrainModelSurfaceMorphing::computeLinearForce(const float* coords,
                                              const NeighborInformation& nodeInfo,
                                              const int nodeNum,
                                              const int neighNodeNum,
                                              const int nodeInfoNeighIndex,
                                              float force[3])
{
   //
   // Clear forces
   //
   force[0] = 0.0;
   force[1] = 0.0;
   force[2] = 0.0;
   
   //
   // positions of node and neighbor
   //
   const float* nodePos = &coords[nodeNum * 3];
   const float* neighPos = &coords[neighNodeNum * 3];
   
   //
   // Distance between node and its neighbor in the surface that is being morphed
   //
   const float neighborDistance = MathUtilities::distance3D(nodePos, neighPos);
   
   //
   // If neighbor is very close do not update forces
   // Added back, 01 April 2009 as node and neighbor had
   // identical position resulting in NaN
   //
   if (neighborDistance <= 0.000001) {
      return;
   }
   
   //
   // distance to neighbor in fiducial surface
   //
   const float neighborFiducialDistance = nodeInfo.neighborDistance[nodeInfoNeighIndex];   
   
   //
   // Difference between node & neighbor in the fiducial and morphing surface (the "error")
   //
   float errorDistance = neighborFiducialDistance - neighborDistance;
   
   //
   // ratio of distances in morphing and fiducial surfaces
   //
   float errorDistRatio = 0.0;
   if (neighborFiducialDistance != 0.0) {
      errorDistRatio = neighborDistance / neighborFiducialDistance;
   }
   
   //
   // if compressed, double error
   //
   if (errorDistRatio < 0.50) {
      errorDistance *= 2.0;
   }
   
   //
   // apply linear force strength
   //
   errorDistance *= linearForce;
   
   //
   // get distance between node and neighbor in X, Y, and Z
   // Note: want to push "this" node in relation to its neighbor
   //
   float errorComponents[3];
   MathUtilities::subtractVectors(nodePos, neighPos, errorComponents);
   
   //
   // Determine the linear force components
   //
   force[0] = errorDistance * errorComponents[0] / neighborDistance;
   force[1] = errorDistance * errorComponents[1] / neighborDistance;
   force[2] = errorDistance * errorComponents[2] / neighborDistance;
   
   if (DebugControl::getDebugOn()) {
      if (checkNaN(force, 3)) {
         QString s = "PROGRAM ERROR: NaN detected for linear force node and neighbor "
                   + QString::number(nodeNum)
                   + " & "
                   + QString::number(neighNodeNum)
                   + " in "
                   + FileUtilities::basename(morphingSurface->getCoordinateFile()->getFileName());
         throw BrainModelAlgorithmException(s);
      }
   }
   if (DebugControl::getDebugOn()) {
      if (DebugControl::getDebugNodeNumber() == nodeNum) {
         std::cout << std::endl;
         std::cout << "Linear Force Calculation" << std::endl;
         std::cout << "Node " << nodeNum
                   << " (" << nodePos[0] << ", " << nodePos[1] << ", " << nodePos[2] << ")" 
                   << std::endl;
         std::cout << "Neighbor " << neighNodeNum 
                   << " (" << neighPos[0] << ", " << neighPos[1] << ", " << neighPos[2] << ")" 
                   << std::endl;
         std::cout << "Fiducial Distance: " << neighborFiducialDistance << std::endl;
         std::cout << "Distance: " << neighborDistance << std::endl;
         std::cout << "Error Distance: " << errorDistance << std::endl;
         std::cout << "Linear Force: (" << force[0] << ", " << force[1] << ", " << force[2] << ")"
                   << std::endl;
      }
   }
}

/**
 * Set the indices of the nodes that are to be morphed (inclusive).
 */
void 
BrainModelSurfaceMorphing::setIndicesOfNodesToMorph(const int startNodeIndexIn, 
                                                    const int endNodeIndexIn)
{
   startNodeIndex = startNodeIndexIn;
   endNodeIndex   = endNodeIndexIn;
}

/**
 * Set the input and output coords
 */
void
BrainModelSurfaceMorphing::setInputAndOutputCoords(float* inCoords, float* outCoords)
{
   inputCoords  = inCoords;
   outputCoords = outCoords;
}

/**
 * Generate neighbor information
 */
void
BrainModelSurfaceMorphing::generateNeighborInformation()
{
   //
   // Use topology from morphing surface
   //
   TopologyFile* tf = morphingSurface->getTopologyFile();

   //
   // Classify the nodes as interior or exterior
   //
   BrainSet* bs = morphingSurface->getBrainSet();
   bs->classifyNodes(tf);
   
   //
   // Get the coordinates from the reference surface
   //
   const CoordinateFile* cf = referenceSurface->getCoordinateFile();
   const float* firstCoord = cf->getCoordinate(0);
   
   //
   // Create a topology helper to get node neighbors
   //
   const TopologyHelper* th = tf->getTopologyHelper(true, true, true);
   
   //
   // See if fiducial sphere ratios should be used
   //
   const bool useFiducialSphereRatios = (numberOfNodes == static_cast<int>(fiducialSphereRatios.size()));
   const float inverseDistortionFraction = 1.0 - sphereFiducialDistortionFraction;

   //
   // Get the surface's brain set and see if this node is interior or edge
   //
   const BrainSetNodeAttribute* allNodeAttributes = brainSet->getNodeAttributes(0);
   
   //
   // Generate neighbors, lengths, and angles for reference surface
   //
   morphNodeInfo = new NeighborInformation[numberOfNodes];
   for (int i = 0; i < numberOfNodes; i++) {
      int numNeighbors;
      const int* neighbors = th->getNodeNeighbors(i, numNeighbors);
      
      morphNodeInfo[i].initialize(firstCoord, i, &allNodeAttributes[i], neighbors, numNeighbors);
      
      //
      // If fiducial sphere ratios should be used
      //
      if (useFiducialSphereRatios) {
         const float myRatio = fiducialSphereRatios[i];
         //
         // Scale neighbor distances by David's magic formula
         //
         for (int j = 0; j < morphNodeInfo[i].numNeighbors; j++) {
            const int neigh = morphNodeInfo[i].neighbors[j];
            const float neighRatio = fiducialSphereRatios[neigh];
            morphNodeInfo[i].neighborDistance[j] = inverseDistortionFraction
                                 + (sphereFiducialDistortionFraction * ((myRatio + neighRatio) * 0.5) 
                                    * morphNodeInfo[i].neighborDistance[j]);
         }
      }
   }
}

/**
 * set the nodes that should be morphred.
 */
void 
BrainModelSurfaceMorphing::setNodesThatShouldBeMorphed(const std::vector<bool>& nodesThatShouldBeMorphedIn,
                                                       const float noMorphStepSizeIn)
{
   allNodesBeingMorphed = true;
   const int num = static_cast<int>(nodesThatShouldBeMorphedIn.size());
   for (int i = 0; i < numberOfNodes; i++) {
      nodeShouldBeMorphed[i] = false;
      if (i < num) {
         nodeShouldBeMorphed[i] = nodesThatShouldBeMorphedIn[i];
      }
      if (nodeShouldBeMorphed[i] == false) {
         allNodesBeingMorphed = false;
      }
   }
   noMorphNeighborStepSize = noMorphStepSizeIn;
}

/**
 * set the fiducial sphere distortion corrections.
 */
void 
BrainModelSurfaceMorphing::setFiducialSphereDistortionCorrections(
                                             const std::vector<float>& fiducialSphereRatiosIn,
                                             const float sphereFiducialDistortionFractionIn)
{
   fiducialSphereRatios = fiducialSphereRatiosIn;
   sphereFiducialDistortionFraction = sphereFiducialDistortionFractionIn;
}                                                  

//--------------------------------------------------------------------------------

/**
 * Constructor.
 */
BrainModelSurfaceMorphing::NeighborInformation::NeighborInformation()
{
   numNeighbors = 0;
   neighbors = NULL;
   neighborDistance = NULL;
   angle1 = NULL;
   angle2 = NULL;
}

/**
 * Destructor.
 */
BrainModelSurfaceMorphing::NeighborInformation::~NeighborInformation()
{
   if (neighbors != NULL) {
      delete neighbors;
   }
   if (neighborDistance != NULL) {
      delete neighborDistance;
   }
   if (angle1 != NULL) {
      delete angle1;
   }
   if (angle2 != NULL) {
      delete angle2;
   }
}

/**
 * Initialize neighbor information
 */
void
BrainModelSurfaceMorphing::NeighborInformation::initialize(const float* coords, 
                                                const int nodeNumberIn,
                                                const BrainSetNodeAttribute* nodeAttribute,
                                                const int* neighborsIn,
                                                const int numNeighborsIn)
{
   //
   // Index of this node
   //
   nodeNumber = nodeNumberIn;
   
   //
   // Set this nodes interior flag
   //
   classification = nodeAttribute->getClassification();
   
   //
   // Allocate items to number of neighbors
   //
   numNeighbors = numNeighborsIn;
   if (numNeighbors > 0) {
      neighbors = new int[numNeighbors];
      for (int i = 0; i < numNeighbors; i++) {
         neighbors[i] = neighborsIn[i];
      }
      neighborDistance = new float[numNeighbors];
      angle1 = new float[numNeighbors];
      angle2 = new float[numNeighbors];
   
      const float* myCoord = &coords[nodeNumber * 3];
      
      if (numNeighbors > 1) {
         //
         // Compute distances and angles to neighbors
         //      
         for (int i = 0; i < numNeighbors; i++) {
            //
            // length to neighbor
            //
            neighborDistance[i] = MathUtilities::distance3D(myCoord, &coords[neighbors[i] * 3]);
            
            //
            // indices for next and previous neighbors
            //
            int nextIndex = i + 1;
            if (nextIndex >= numNeighbors) nextIndex = 0;
            
            //
            // Coordinates of current and previous neighbor
            //
            const float* currNeighborCoord = &coords[neighbors[i] * 3];
            const float* nextNeighborCoord = &coords[neighbors[nextIndex] * 3];
            
            //
            // Compute angles
            //
            if (classification == BrainSetNodeAttribute::CLASSIFICATION_TYPE_CORNER) {
               //
               // Only compute for first neighbor
               //
               if (i == 0) {
                  angle1[0] = MathUtilities::angle(myCoord, currNeighborCoord, nextNeighborCoord);
                  angle2[0] = MathUtilities::angle(currNeighborCoord, nextNeighborCoord, myCoord);
                  angle1[1] = 0.0;
                  angle2[1] = 0.0;
               }
            }
            else {
               //
               // Angle at current neighbor
               //
               angle1[i] = MathUtilities::angle(myCoord, currNeighborCoord, nextNeighborCoord);
               
               //
               // Angle at next neighbor
               //
               angle2[i] = MathUtilities::angle(currNeighborCoord, nextNeighborCoord, myCoord);               
            }
         }
         if (DebugControl::getDebugOn()) {
            if (nodeNumber == DebugControl::getDebugNodeNumber()) {
               std::cout << "\nNode Number : " << nodeNumber << std::endl;
               for (int i = 0; i < numNeighbors; i++) {
                  std::cout << "Neighbor[" << i << "] " << neighbors[i]
                           << " angle1 (radians, degrees): " << angle1[i] 
                           << " " << angle1[i] * MathUtilities::radiansToDegrees() << std::endl
                           << " angle2 (radians, degrees): " << angle2[i] 
                           << " " << angle2[i] * MathUtilities::radiansToDegrees()
                           << std::endl;
               }
            }
         }
      }
   }
}

/**
 * Initialize neighbor information
 */
void
BrainModelSurfaceMorphing::NeighborInformation::resetForces()
{
   totalForce[0]   = 0.0;
   totalForce[1]   = 0.0;
   totalForce[2]   = 0.0;
   linearForce[0]  = 0.0;
   linearForce[1]  = 0.0;
   linearForce[2]  = 0.0;
   angularForce[0] = 0.0;
   angularForce[1] = 0.0;
   angularForce[2] = 0.0;
}