File: BrainModelSurfaceTopologyCorrector.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 (460 lines) | stat: -rw-r--r-- 14,661 bytes parent folder | download | duplicates (2)
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

/*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 <algorithm>
#include <iostream>
#include <limits>

#include <QDateTime>

#include "vtkTriangle.h"
#include "vtkPointLocator.h"
#include "vtkPoints.h"

#include "BrainModelSurface.h"
#include "BrainModelSurfaceDistortion.h"
#include "BrainModelSurfaceROINodeSelection.h"
#include "BrainModelSurfaceSmoothing.h"
#include "BrainModelSurfaceSphericalTessellator.h"
#include "BrainModelSurfaceTopologyCorrector.h"
#include "BrainSet.h"
#include "DebugControl.h"
#include "MathUtilities.h"
#include "PointLocator.h"
#include "SurfaceShapeFile.h"
#include "TopologyFile.h"
#include "TopologyHelper.h"

/**
 * Constructor.
 */
BrainModelSurfaceTopologyCorrector::BrainModelSurfaceTopologyCorrector(
                                                     BrainSet* bsIn,
                                                     const BrainModelSurface* fiducialSurfaceIn,
                                                     const int numberOfSmoothingCyclesIn,
                                                     const bool removeHighlyCompressedNodesIn,
                                                     const float compressedNodesArealDistortionThresholdIn)
   : BrainModelAlgorithm(bsIn) 
{
   fiducialSurface = new BrainModelSurface(*fiducialSurfaceIn);
   sphericalSurface = new BrainModelSurface(*fiducialSurfaceIn);
   numberOfSmoothingCycles = numberOfSmoothingCyclesIn;
   removeHighlyCompressedNodes = removeHighlyCompressedNodesIn;
   compressedNodesArealDistortionThreshold = compressedNodesArealDistortionThresholdIn;
   numNodes = 0;
   copyOfOriginalTopologyFile = NULL;
   workingTopologyFile = NULL;
   skipCorrectedSurfaceGeneration = false;
}

/**
 * Destructor.
 */
BrainModelSurfaceTopologyCorrector::~BrainModelSurfaceTopologyCorrector()
{
   if (copyOfOriginalTopologyFile != NULL) {
      delete copyOfOriginalTopologyFile;
      copyOfOriginalTopologyFile = NULL;
   }
   if (workingTopologyFile != NULL) {
      delete workingTopologyFile;
      workingTopologyFile = NULL;
   }
}

/**
 * Smooth the spherical surface.
 */
void 
BrainModelSurfaceTopologyCorrector::smoothSphericalSurfaceToMinimizeCrossovers() throw (BrainModelAlgorithmException)
{
   int cycleNumber = 0;
   while (cycleNumber < numberOfSmoothingCycles) {
      //
      // Translate to center of mass
      //
      sphericalSurface->translateToCenterOfMass();
   
      //
      // Do spherical smoothing
      //
      const int smoothingIterations = 100;
      BrainModelSurfaceSmoothing smoothing(brainSet,
                                           sphericalSurface,
                                           BrainModelSurfaceSmoothing::SMOOTHING_TYPE_LINEAR,
                                           1.0,
                                           smoothingIterations,
                                           0,
                                           0,
                                           NULL,
                                           NULL,
                                           10,
                                           0);
      smoothing.execute(); 
                                          
      //
      // Do a crossover check
      //
      int numNodeCrossovers, numTileCrossovers;
      sphericalSurface->crossoverCheck(numNodeCrossovers, 
                                       numTileCrossovers,
                                       BrainModelSurface::SURFACE_TYPE_SPHERICAL);
                                       
      int crossoverCount = 0;
      for (int j = 0; j < numNodes; j++) {
         BrainSetNodeAttribute* bna = brainSet->getNodeAttributes(j);
         if (bna->getCrossover() == BrainSetNodeAttribute::CROSSOVER_YES) {
            crossoverCount++;
         }
      }
      if (DebugControl::getDebugOn()) {
         std::cout << "Crossovers at smoothing cycle " << cycleNumber
                   << ": " << crossoverCount << std::endl;
      }
      if (crossoverCount <= 0) {
         break;
      }
      
      cycleNumber++;
   }
}

/**
 * Flag nodes in highly compressed tiles as unavailable.
 */
void 
BrainModelSurfaceTopologyCorrector::removeNodesInHighlyCompressedTilesFromAvailableNodes() throw (BrainModelAlgorithmException)
{
   //
   // Calculate areal distortion
   //
   SurfaceShapeFile ssf;
   BrainModelSurfaceDistortion bmsd(brainSet,
                                    sphericalSurface,
                                    fiducialSurface,
                                    fiducialSurface->getTopologyFile(),
                                    &ssf,
                                    BrainModelSurfaceDistortion::DISTORTION_COLUMN_CREATE_NEW,
                                    BrainModelSurfaceDistortion::DISTORTION_COLUMN_DO_NOT_GENERATE,
                                    "Areal",
                                    "");
   bmsd.execute();
   if (ssf.getNumberOfColumns() != 1) {
      throw BrainModelAlgorithmException("Calculation of areal distortion failed.");
   }
   
   //
   // Get a topology helper for finding connected nodes to use in tessellation
   //
   const TopologyHelper* th = workingTopologyFile->getTopologyHelper(false, true, false);

   //
   // Mark nodes that exceed areal distortion threshold
   //
   std::vector<bool> distortedNodes(numNodes, false);
   for (int i = 0; i < numNodes; i++) {
      if (ssf.getValue(i, 0) < compressedNodesArealDistortionThreshold) {
         if (th->getNodeHasNeighbors(i)) {
            distortedNodes[i] = true;
         }
      }
   }
   
   //
   // Delete tiles using distorted nodes
   //
   workingTopologyFile->deleteTilesWithMarkedNodes(distortedNodes);
}
      
/**
 * Flag the crossover nodes as unavailable.
 */
void
BrainModelSurfaceTopologyCorrector::removeCrossoverNodesFromAvailableNodes()
{
   //
   // Do a crossover check
   //
   int numNodeCrossovers, numTileCrossovers;
   sphericalSurface->crossoverCheck(numNodeCrossovers, 
                                 numTileCrossovers,
                                 BrainModelSurface::SURFACE_TYPE_SPHERICAL);
   
   //
   // Mark crossovers
   //
   std::vector<bool> nodeIsCrossover(numNodes, false);
   for (int j = 0; j < numNodes; j++) {
      BrainSetNodeAttribute* bna = brainSet->getNodeAttributes(j);
      if (bna->getCrossover() == BrainSetNodeAttribute::CROSSOVER_YES) {
         nodeIsCrossover[j] = true;
      }
   }
   
   //
   // Delete tiles using crossover nodes
   //
   workingTopologyFile->deleteTilesWithMarkedNodes(nodeIsCrossover);
}

/**
 * retessellate the sphere.
 */
BrainModelSurface* 
BrainModelSurfaceTopologyCorrector::retessellateTheSphericalSurface() throw (BrainModelAlgorithmException)
{
   //
   // Get a topology helper for finding connected nodes to use in tessellation
   //
   const TopologyHelper* th = workingTopologyFile->getTopologyHelper(false, true, false);

   //
   // nodes that are to be added to the sphere
   //
   std::vector<bool> nodeAvailableFlags(numNodes, false);
   for (int i = 0; i < numNodes; i++) {
      if (th->getNodeHasNeighbors(i)) {
         nodeAvailableFlags[i] = true;
      }
   }
      
   //
   // Tessllate the available nodes
   //
   BrainModelSurfaceSphericalTessellator tess(brainSet,
                                              sphericalSurface,
                                              nodeAvailableFlags);
   tess.execute();
   
   return tess.getPointerToNewSphericalSurface();
}
      
/**
 * get a list of node numbers that were removed.
 */
void
BrainModelSurfaceTopologyCorrector::getListOfNodesThatWereRemoved(std::vector<int>& nodesRemoved) const
{
   nodesRemoved.clear();
   
   //
   // Get a topology helper for finding connected nodes to use in tessellation
   //
   const TopologyHelper* origTH = copyOfOriginalTopologyFile->getTopologyHelper(false, true, false);
   const TopologyHelper* correctedTH = workingTopologyFile->getTopologyHelper(false, true, false);
   
   //
   // Determine which nodes were disconnected
   //
   for (int i = 0; i < numNodes; i++) {
      if ((origTH->getNodeHasNeighbors(i)) &&
          (correctedTH->getNodeHasNeighbors(i) == false)) {
         nodesRemoved.push_back(i);
      }
   }
}

/**
 * get a list of node numbers that were removed.
 */
void 
BrainModelSurfaceTopologyCorrector::getListOfNodesThatWereRemoved(
                       BrainModelSurfaceROINodeSelection& nodesRemovedROI) const
{
   nodesRemovedROI.update();
   nodesRemovedROI.deselectAllNodes();
   
   std::vector<int> nodesRemoved;
   getListOfNodesThatWereRemoved(nodesRemoved);
   const int num = static_cast<int>(nodesRemoved.size());
   for (int i = 0; i < num; i++) {
      nodesRemovedROI.setNodeSelected(nodesRemoved[i], true);
   }
}      

/**
 * smooth around removed nodes.
 */
void 
BrainModelSurfaceTopologyCorrector::smoothAroundRemovedNodes()
{
   //
   // Get nodes that were removed
   //
   std::vector<int> removedNodeNumbers;
   getListOfNodesThatWereRemoved(removedNodeNumbers);
   const int numRemovedNodes = static_cast<int>(removedNodeNumbers.size());
   
   //
   // Use the original topology file to find nodes for smoothing
   //
   const int neighborDepth = 3;
   std::vector<bool> smoothThisNode(numNodes, false);
   const TopologyHelper* th = copyOfOriginalTopologyFile->getTopologyHelper(false, true, false);
   for (int i = 0; i < numRemovedNodes; i++) {
      const int nodeNum = removedNodeNumbers[i];
      std::vector<int> neighbors;
      th->getNodeNeighborsToDepth(nodeNum,
                                  neighborDepth,
                                  neighbors);
      const int numNeighbors = static_cast<int>(neighbors.size());
      for (int j = 0; j < numNeighbors; j++) {
         smoothThisNode[neighbors[j]] = true;
      }
   }
   
   //
   // copy the corrected fiducial surface
   //
   BrainModelSurface* smoothedFiducialSurface = new BrainModelSurface(*fiducialSurface);
   
   //
   // Smooth the surface
   //
   const int numSmoothingIterations = 10;
   BrainModelSurfaceSmoothing bmss(brainSet,
                                   smoothedFiducialSurface,
                                   BrainModelSurfaceSmoothing::SMOOTHING_TYPE_AREAL,
                                   1.0,
                                   numSmoothingIterations,
                                   0,
                                   0,
                                   &smoothThisNode,
                                   NULL,
                                   0,
                                   0);
   bmss.execute();
   
   //
   // Rename and add to brain set
   //
   smoothedFiducialSurface->getCoordinateFile()->replaceFileNameDescription("FIDUCIAL_CORRECTED_SMOOTHED");
   brainSet->addBrainModel(smoothedFiducialSurface);
   
}
      
/**
 * execute the algorithm.
 */
void 
BrainModelSurfaceTopologyCorrector::execute() throw (BrainModelAlgorithmException)
{
   QTime timer;
   timer.start();

   //
   // Get the number of nodes
   //
   numNodes = sphericalSurface->getNumberOfNodes();
      
   sphericalSurface->setSurfaceType(BrainModelSurface::SURFACE_TYPE_SPHERICAL);
   
   //
   // Make a copy of the topology file which will be used to maintain connected nodes
   //
   copyOfOriginalTopologyFile = new TopologyFile(*(sphericalSurface->getTopologyFile()));
   workingTopologyFile        = new TopologyFile(*(sphericalSurface->getTopologyFile()));
   
   try {
      //
      // Smooth the sphere to unfold it
      //
      smoothSphericalSurfaceToMinimizeCrossovers();

      //
      // Remove crossover nodes from the available nodes
      //
      removeCrossoverNodesFromAvailableNodes();
      
      //
      // Remove nodes that are part of tiles that become highly compressed due to smoothing
      //
      if (removeHighlyCompressedNodes) {
         removeNodesInHighlyCompressedTilesFromAvailableNodes();
      }
      
      //
      // Remove any islands from the working topology file that were caused by node/tile deletion
      //
      workingTopologyFile->disconnectIslands();
      
      //
      // Should corrected surfaces be generated
      //
      BrainModelSurface* retessellatedSphereSurface = NULL;
      if (skipCorrectedSurfaceGeneration == false) {
         //
         // Create a newly tessellated sphere
         //
         retessellatedSphereSurface = retessellateTheSphericalSurface();
         
         //
         // Apply the spherical surface's new topology to the fiducial surface
         //
         fiducialSurface->setTopologyFile(retessellatedSphereSurface->getTopologyFile());
         
         //
         // Rename the fiducial to FiducialCorrected
         //
         fiducialSurface->getCoordinateFile()->replaceFileNameDescription("FIDUCIAL_CORRECTED");
      
         //
         // Add the fiducial to the brain set
         //
         brainSet->addBrainModel(fiducialSurface);
         
         //
         // Create a second fiducial smoothed around removed nodes
         //
         //smoothAroundRemovedNodes();
      }
      
      if (DebugControl::getDebugOn()) {
         sphericalSurface->getCoordinateFile()->replaceFileNameDescription("SPHERE_SMOOTHED_UNCORRECTED");
         brainSet->addBrainModel(sphericalSurface);   
         std::cout << "Time to correct surface: " << timer.elapsed() * 0.001 << std::endl; 
      }
      else {
         //
         // Delete the smoothed sphere
         //
         delete sphericalSurface;
         sphericalSurface = NULL;
         
         //
         // Delete the retessellated sphere
         //
         if (retessellatedSphereSurface != NULL) {
            brainSet->deleteBrainModel(retessellatedSphereSurface);
         }
      }
   }
   catch (TessellationException& te) {
      throw BrainModelAlgorithmException(te.whatQString());
   }
}