File: BrainModelSurfaceMetricGradient.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 (666 lines) | stat: -rw-r--r-- 24,152 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
/*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 "BrainModelSurfaceMetricGradient.h"
#include "BrainSet.h"
#include "BrainModelSurface.h"
#include "CoordinateFile.h"
#include "TopologyFile.h"
#include "TopologyHelper.h"
#include "VectorFile.h"
#include "MetricFile.h"
#include <cmath>
#include <iostream>

#ifdef _OPENMP
#include <omp.h>
#endif

void BrainModelSurfaceMetricGradient::crossProd(const float in1[3], const double in2[3], double out[3])
{//avoid loops for speed
   out[0] = in1[1] * in2[2] - in1[2] * in2[1];
   out[1] = in1[2] * in2[0] - in1[0] * in2[2];
   out[2] = in1[0] * in2[1] - in1[1] * in2[0];
}

void BrainModelSurfaceMetricGradient::crossProd(const double in1[3], const double in2[3], double out[3])
{//avoid loops for speed
   out[0] = in1[1] * in2[2] - in1[2] * in2[1];
   out[1] = in1[2] * in2[0] - in1[0] * in2[2];
   out[2] = in1[0] * in2[1] - in1[1] * in2[0];
}

double BrainModelSurfaceMetricGradient::dotProd(const double in1[3], const double in2[3])
{
   return in1[0] * in2[0] + in1[1] * in2[1] + in1[2] * in2[2];
}

double BrainModelSurfaceMetricGradient::dotProd(const float in1[3], const double in2[3])
{
   return in1[0] * in2[0] + in1[1] * in2[1] + in1[2] * in2[2];
}

void BrainModelSurfaceMetricGradient::normalize(double in[3])
{
   double mag = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]);
   in[0] /= mag;
   in[1] /= mag;
   in[2] /= mag;
}

void BrainModelSurfaceMetricGradient::coordDiff(const float* coord1, const float* coord2, double out[3])
{
   out[0] = coord1[0] - coord2[0];
   out[1] = coord1[1] - coord2[1];
   out[2] = coord1[2] - coord2[2];
}

void BrainModelSurfaceMetricGradient::calcrref(double* matrix[], int rows, int cols)
{//assumes more cols than rows
   int i, j, k, temp;
   double tempd, tempd2;
   for (i = 0; i < rows; ++i)
   {
      tempd = std::abs(matrix[i][i]);//search for pivot
      temp = i;
      for (j = i + 1; j < rows; ++j)
      {
         tempd2 = std::abs(matrix[j][i]);
         if (tempd2 > tempd)
         {
            tempd = tempd2;
            temp = j;
         }
      }
      if (i != temp)
      {
         for (j = i; j < cols; ++j)
         {//skip the waste that will end up 0's and 1's
            tempd = matrix[i][j];
            matrix[i][j] = matrix[temp][j];
            matrix[temp][j] = tempd;
         }
      }
      tempd = matrix[i][i];//pivot
      for (j = i + 1; j < cols; ++j)
      {//again, skip the 0's and 1's
         matrix[i][j] /= tempd;
         for (k = 0; k < i; ++k)
         {
            matrix[k][j] -= matrix[k][i] * matrix[i][j];
         }
         for (++k; k < rows; ++k)
         {
            matrix[k][j] -= matrix[k][i] * matrix[i][j];
         }
      }
   }//rref complete for all cols >= rows, just pretend rowsXrows is I
}

double BrainModelSurfaceMetricGradient::det3(double* matrix[], int column)
{//diagonals trick for 3x3, unrolled
   int column1 = column + 1, column2 = column + 2;
   double ret = matrix[0][column] * matrix[1][column1] * matrix[2][column2];
   ret += matrix[1][column] * matrix[2][column1] * matrix[0][column2];
   ret += matrix[2][column] * matrix[0][column1] * matrix[1][column2];
   ret -= matrix[2][column] * matrix[1][column1] * matrix[0][column2];
   ret -= matrix[1][column] * matrix[0][column1] * matrix[2][column2];
   ret -= matrix[0][column] * matrix[2][column1] * matrix[1][column2];
   return ret;
}

/**
 * Constructor.
 */
BrainModelSurfaceMetricGradient::BrainModelSurfaceMetricGradient(
                                               BrainSet* bs,
                                               int bsIndexIn,
                                               MetricFile* valuesIn,
                                               int metricIndexIn,
                                               VectorFile* gradOutIn,
                                               MetricFile* gradMagOutIn,
                                               int magOutIndexIn,
                                               bool avgNormalsIn)
   : BrainModelAlgorithm(bs)
{
   initialize();
   
   setIndex   = bsIndexIn;
   values     = valuesIn;
   metricIndex = metricIndexIn;
   gradOut    = gradOutIn;
   gradMagOut = gradMagOutIn;
   magOutIndex = magOutIndexIn;
   avgNormals = avgNormalsIn;
   
}
                                      
/**
 * Constructor for execution of all columns.
 */
BrainModelSurfaceMetricGradient::BrainModelSurfaceMetricGradient(BrainSet* bs,
                                  int bsIndexIn,
                                  MetricFile* valuesIn,
                                  MetricFile* gradMagOutIn,
                                  bool avgNormalsIn,
                                  bool parallelFlagIn) 
   : BrainModelAlgorithm(bs)
{
   initialize();
   
   setIndex   = bsIndexIn;
   values     = valuesIn;
   gradMagOut = gradMagOutIn;
   avgNormals = avgNormalsIn;
   
   allColumnsFlag = true;
   parallelFlag = parallelFlagIn;
}

/**
 * Destructor.
 */
BrainModelSurfaceMetricGradient::~BrainModelSurfaceMetricGradient()
{
}

void 
BrainModelSurfaceMetricGradient::initialize()
{
   allColumnsFlag = false;
   parallelFlag = false;
   haveWarned = false;
   haveFailed = false;
}
                                            
/**
 * execute the algorithm.
 */
void 
BrainModelSurfaceMetricGradient::execute() throw (BrainModelAlgorithmException)
{
   if (allColumnsFlag) {
       executeAllColumns();
   }
   else {
       executeSingleColumn();
   }
}

/**
 * execute the algorithm on a single metric column.
 */
void 
BrainModelSurfaceMetricGradient::executeSingleColumn() throw (BrainModelAlgorithmException)
{
   //
   // Verify files exist, are valid, etc.
   //
   BrainModelSurface* mysurf = brainSet->getBrainModelSurface(setIndex);//reference
   CoordinateFile* source = mysurf->getCoordinateFile();//reference
   TopologyFile* topo = mysurf->getTopologyFile();
   const TopologyHelper* myhelper = topo->getTopologyHelper(false, true, false);
   mysurf->computeNormals();
   mysurf->orientNormalsOut();
   if (source == NULL) {
      throw BrainModelAlgorithmException("Invalid coordinate file.");
   }
   if (values == NULL) {
      throw BrainModelAlgorithmException("Invalid metric file.");
   }
   if (source->getNumberOfCoordinates() < 1)
   {
      throw BrainModelAlgorithmException("Not enough nodes in coordinate file.");
   }
   if (source->getNumberOfCoordinates() != values->getNumberOfNodes())
   {
      throw BrainModelAlgorithmException("Node numbers do not match.");
   }
   //
   // Check output files exist
   //
   bool saveMag = true, saveVec = true;
   if (gradMagOut == NULL) {
      saveMag = false;
   } else {
      if (source->getNumberOfCoordinates() != gradMagOut->getNumberOfNodes())
      {
         gradMagOut->setNumberOfNodesAndColumns(source->getNumberOfCoordinates(), 1);//clear existing data because node numbers don't match
         magOutIndex = 0;
      }
      if (magOutIndex < 0 || magOutIndex >= gradMagOut->getNumberOfColumns())
      {
         magOutIndex = gradMagOut->getNumberOfColumns();
         gradMagOut->addColumns(1);
      }
      gradMagOut->setColumnName(magOutIndex, "surface gradient");
   }
   if (gradOut == NULL) {
      saveVec = false;
   } else {
      if (source->getNumberOfCoordinates() != gradOut->getNumberOfVectors())
      {
         gradOut->setNumberOfVectors(source->getNumberOfCoordinates());
      }
   }
   if (!saveMag && !saveVec)
   {
      throw BrainModelAlgorithmException("No valid output file.");
   }
   int numNodes = source->getNumberOfCoordinates();
   int i, j, k, numNeigh, whichnode;
   double xhat[3], yhat[3], somevec[3];
   float nodemetric, somevecf[3];
   double xmag, ymag,tempd, sanity;
   double* rrefb[3];
   float* sourceData = new float[numNodes * 3];
   source->getAllCoordinates(sourceData);
   float* metricData = new float[numNodes];
   float* magData = NULL;
   std::vector<int> neighbors;
   if (saveMag)
   {
      magData = new float[numNodes];
   }
   values->getColumnForAllNodes(metricIndex, metricData);
   rrefb[0] = new double[4];
   rrefb[1] = new double[4];
   rrefb[2] = new double[4];
   float* allnormals = new float[numNodes * 3];
   for (i = 0; i < numNodes; ++i)
   {
      j = i * 3;
      const float* mynormal = mysurf->getNormal(i);
      allnormals[j] = mynormal[0];
      allnormals[j + 1] = mynormal[1];
      allnormals[j + 2] = mynormal[2];
   }
   if (avgNormals)
   {//assume normals have identical length
      for (i = 0; i < numNodes; ++i)
      {
         const float* mynormal = mysurf->getNormal(i);
         myhelper->getNodeNeighbors(i, neighbors);
         numNeigh = neighbors.size();
         for (j = 0; j < numNeigh; ++j)
         {
            k = neighbors[j] * 3;
            allnormals[k] += mynormal[0];
            allnormals[k + 1] += mynormal[1];
            allnormals[k + 2] += mynormal[2];
         }
      }
   }//WARNING: normals are not normalized, nor identical length - below algorithm normalizes after every use of a normal though
   for (i = 0; i < numNodes; ++i)
   {
      float* mynormal = allnormals + i * 3;
      somevec[2] = 0.0;
      if (mynormal[0] > mynormal[1])
      {//generate a vector not parallel to normal
         somevec[0] = 0.0;
         somevec[1] = 1.0;
      } else {
         somevec[0] = 1.0;
         somevec[1] = 0.0;
      }
      crossProd(mynormal, somevec, xhat);
      normalize(xhat);//use cross products to generate a 2d coordinate system orthogonal to normal
      crossProd(mynormal, xhat, yhat);
      normalize(yhat);//xhat, yhat are orthogonal unit vectors describing the coord system with k = surface normal
      for (j = 0; j < 4; ++j)
      {
         rrefb[0][j] = 0.0;
         rrefb[1][j] = 0.0;
         rrefb[2][j] = 0.0;
      }
      nodemetric = metricData[i];//uses metric difference for 2 reasons: makes rref cumulate smaller values, and makes root node not matter to calculation
      myhelper->getNodeNeighbors(i, neighbors);//intelligently detects depth == 1 (and invalid depth)
      numNeigh = neighbors.size();
      if (numNeigh >= 2)//dont attempt regression if the system is underdetermined
      {
         for (j = 0; j < numNeigh; ++j)
         {
            whichnode = neighbors[j];
            tempd = metricData[whichnode] - nodemetric;//metric difference
            coordDiff(&sourceData[whichnode * 3], &sourceData[i * 3], somevec);//position delta vector
            xmag = dotProd(xhat, somevec);//project to 2d plane tangent to surface
            ymag = dotProd(yhat, somevec);
            rrefb[0][0] += xmag * xmag;//gather A'A and A'b sums for regression
            rrefb[0][1] += xmag * ymag;
            rrefb[0][2] += xmag;
            rrefb[1][1] += ymag * ymag;
            rrefb[1][2] += ymag;
            rrefb[2][2] += 1.0f;
            rrefb[0][3] += xmag * tempd;
            rrefb[1][3] += ymag * tempd;
            rrefb[2][3] += tempd;
         }
         rrefb[1][0] = rrefb[0][1];//complete the symmetric elements
         rrefb[2][0] = rrefb[0][2];
         rrefb[2][1] = rrefb[1][2];
         rrefb[2][2] += 1.0f;//include center (metric and coord differences will be zero, so this is all that is needed)
         calcrref(rrefb, 3, 4);
         somevecf[0] = (float)(somevec[0] = xhat[0] * rrefb[0][3] + yhat[0] * rrefb[1][3]);
         somevecf[1] = (float)(somevec[1] = xhat[1] * rrefb[0][3] + yhat[1] * rrefb[1][3]);
         somevecf[2] = (float)(somevec[2] = xhat[2] * rrefb[0][3] + yhat[2] * rrefb[1][3]);//somevec is now our surface gradient
         sanity = somevec[0] + somevec[1] + somevec[2];
      }
      if (numNeigh < 2 || !(sanity == sanity))
      {
         if (!haveWarned) std::cerr << "WARNING: gradient calculation found a NaN/inf with regression method" << endl;
         haveWarned = true;
         if (numNeigh != 0)
         {
            somevecf[0] = 0.0f;
            somevecf[1] = 0.0f;
            somevecf[2] = 0.0f;
            somevec[0] = 0.0;
            somevec[1] = 0.0;
            somevec[2] = 0.0;
            for (j = 0; j < numNeigh; ++j)
            {
               whichnode = neighbors[j];
               coordDiff(&sourceData[whichnode * 3], &sourceData[i * 3], xhat);//xhat repurposed as a temp variable
               for (k = 0; k < 3; ++k)
                  yhat[k] = xhat[k];
               normalize(xhat);
               tempd = (metricData[whichnode] - nodemetric) / sqrt(yhat[0] * yhat[0] + yhat[1] * yhat[1] + yhat[2] * yhat[2]);//difference over distance gives gradient magnitude
               for (k = 0; k < 3; ++k)
                  somevec[k] += tempd * xhat[k];//magnitude times unit vector parallel to distance vector gives crude estimate
            }
            for (j = 0; j < 3; ++j)
            {
               somevec[j] /= numNeigh;//now we have the 3d gradient, time to subtract the dot product with normal
               xhat[j] = mynormal[j];
            }
            normalize(xhat);//for sanity, in case your normals aren't unit vectors somehow
            tempd = dotProd(somevec, xhat);
            sanity = 0.0;
            for (j = 0; j < 3; ++j)
               sanity += (somevecf[j] = (float)(somevec[j] -= tempd * xhat[j]));
         }
         if (numNeigh == 0 || !(sanity == sanity))
         {
            if (!haveFailed)
            {
               std::cerr << "WARNING: gradient calculation found a NaN/inf with fallback method, outputting ZERO" << endl;
               std::cerr << "check your coordinate/topo files for isolated nodes and nodes with identical coords" << endl;
            }
            haveFailed = true;
            somevecf[0] = 0.0f;
            somevecf[1] = 0.0f;
            somevecf[2] = 0.0f;
            somevec[0] = 0.0;
            somevec[1] = 0.0;
            somevec[2] = 0.0;
         }
      }
      if (saveVec)
      {
         gradOut->setVectorOrigin(i, &sourceData[i * 3]);
         gradOut->setVectorUnitComponents(i, somevecf);//gradient complete!
      }
      if (saveMag)
      {
         magData[i] = (float)sqrt(somevec[0] * somevec[0] + somevec[1] * somevec[1] + somevec[2] * somevec[2]);
      }
   }
   if (saveMag)
   {
      gradMagOut->setColumnForAllNodes(magOutIndex, magData);
      delete[] magData;
   }
   delete[] sourceData;
   delete[] metricData;
   delete[] rrefb[0];
   delete[] rrefb[1];
   delete[] rrefb[2];
   delete[] allnormals;
}

/**
 * execute the all metric columns.
 */
void 
BrainModelSurfaceMetricGradient::executeAllColumns() throw (BrainModelAlgorithmException)
{
   //
   // Verify files exist, are valid, etc.
   //
   BrainModelSurface* mysurf = brainSet->getBrainModelSurface(setIndex);//reference
   CoordinateFile* source = mysurf->getCoordinateFile();//reference
   TopologyFile* topo = mysurf->getTopologyFile();
   const TopologyHelper* myhelper = topo->getTopologyHelper(false, true, false);
   mysurf->computeNormals();
   mysurf->orientNormalsOut();
   if (source == NULL) {
      throw BrainModelAlgorithmException("Invalid coordinate file.");
   }
   if (values == NULL) {
      throw BrainModelAlgorithmException("Invalid metric file.");
   }
   if (source->getNumberOfCoordinates() < 1)
   {
      throw BrainModelAlgorithmException("Not enough nodes in coordinate file.");
   }
   if (source->getNumberOfCoordinates() != values->getNumberOfNodes())
   {
      throw BrainModelAlgorithmException("Node numbers do not match.");
   }
   int numNodes = source->getNumberOfCoordinates();
   int numColumns = values->getNumberOfColumns();
   
   float* allnormals = new float[numNodes * 3];
   for (int i = 0; i < numNodes; ++i)
   {
      int j = i * 3;
      const float* mynormal = mysurf->getNormal(i);
      allnormals[j] = mynormal[0];
      allnormals[j + 1] = mynormal[1];
      allnormals[j + 2] = mynormal[2];
   }
   std::vector<int> neighbors;
   if (avgNormals)
   {//assume normals have identical length
      for (int i = 0; i < numNodes; ++i)
      {
         const float* mynormal = mysurf->getNormal(i);
         myhelper->getNodeNeighbors(i, neighbors);
         const int numNeigh = neighbors.size();
         for (int j = 0; j < numNeigh; ++j)
         {
            int k = neighbors[j] * 3;
            allnormals[k] += mynormal[0];
            allnormals[k + 1] += mynormal[1];
            allnormals[k + 2] += mynormal[2];
         }
      }
   }//WARNING: normals are not normalized, nor identical length - below algorithm normalizes after every use of a normal though
   float* sourceData = new float[numNodes * 3];
   source->getAllCoordinates(sourceData);
   
   if (parallelFlag) {
      #pragma omp parallel for
      for (int i = 0; i < numColumns; i++) {
         processSingleColumn(myhelper,
                             allnormals,
                             sourceData,
                             i,
                             numNodes);
      }
   }
   else {
      for (int i = 0; i < numColumns; i++) {
         processSingleColumn(myhelper,
                             allnormals,
                             sourceData,
                             i,
                             numNodes);
      }
   }
   delete[] allnormals;
   delete[] sourceData;
}

/**
 * process single column.
 */
void 
BrainModelSurfaceMetricGradient::processSingleColumn(const TopologyHelper* myhelper,
                                                     const float* allnormals, 
                                                     const float* sourceData,
                                                     const int columnIndex,
                                                     const int numNodes) throw (BrainModelAlgorithmException)
{
   double xhat[3], yhat[3], somevec[3];
   float nodemetric, somevecf[3];
   double xmag, ymag,tempd, sanity;
   double* rrefb[3];
   float* metricData = new float[numNodes];
   float* magData = new float[numNodes];
   rrefb[0] = new double[4];
   rrefb[1] = new double[4];
   rrefb[2] = new double[4];
 
   std::vector<int> neighbors;

   values->getColumnForAllNodes(columnIndex, metricData);
   for (int i = 0; i < numNodes; ++i)
   {
      const float* mynormal = allnormals + i * 3;
      somevec[2] = 0.0;
      if (mynormal[0] > mynormal[1])
      {//generate a vector not parallel to normal
         somevec[0] = 0.0;
         somevec[1] = 1.0;
      } else {
         somevec[0] = 1.0;
         somevec[1] = 0.0;
      }
      crossProd(mynormal, somevec, xhat);
      normalize(xhat);//use cross products to generate a 2d coordinate system orthogonal to normal
      crossProd(mynormal, xhat, yhat);
      normalize(yhat);//xhat, yhat are orthogonal unit vectors describing the coord system with k = surface normal
      for (int j = 0; j < 4; ++j)
      {
         rrefb[0][j] = 0.0;
         rrefb[1][j] = 0.0;
         rrefb[2][j] = 0.0;
      }
      nodemetric = metricData[i];//uses metric difference for 2 reasons: makes rref cumulate smaller values, and makes root node not matter to calculation
      myhelper->getNodeNeighbors(i, neighbors);//intelligently detects depth == 1 (and invalid depth)
      const int numNeigh = neighbors.size();
      if (numNeigh >= 2)//dont attempt regression if the system is underdetermined
      {
         for (int j = 0; j < numNeigh; ++j)
         {
            const int whichnode = neighbors[j];
            tempd = metricData[whichnode] - nodemetric;//metric difference
            coordDiff(&sourceData[whichnode * 3], &sourceData[i * 3], somevec);//position delta vector
            xmag = dotProd(xhat, somevec);//project to 2d plane tangent to surface
            ymag = dotProd(yhat, somevec);
            rrefb[0][0] += xmag * xmag;//gather A'A and A'b sums for regression
            rrefb[0][1] += xmag * ymag;
            rrefb[0][2] += xmag;
            rrefb[1][1] += ymag * ymag;
            rrefb[1][2] += ymag;
            rrefb[2][2] += 1.0f;
            rrefb[0][3] += xmag * tempd;
            rrefb[1][3] += ymag * tempd;
            rrefb[2][3] += tempd;
         }
         rrefb[1][0] = rrefb[0][1];//complete the symmetric elements
         rrefb[2][0] = rrefb[0][2];
         rrefb[2][1] = rrefb[1][2];
         rrefb[2][2] += 1.0f;//include center (metric and coord differences will be zero, so this is all that is needed)
         calcrref(rrefb, 3, 4);
         somevecf[0] = (float)(somevec[0] = xhat[0] * rrefb[0][3] + yhat[0] * rrefb[1][3]);
         somevecf[1] = (float)(somevec[1] = xhat[1] * rrefb[0][3] + yhat[1] * rrefb[1][3]);
         somevecf[2] = (float)(somevec[2] = xhat[2] * rrefb[0][3] + yhat[2] * rrefb[1][3]);//somevec is now our surface gradient
         sanity = somevec[0] + somevec[1] + somevec[2];
      }
      if (numNeigh < 2 || !(sanity == sanity))
      {
         if (!haveWarned) std::cerr << "WARNING: gradient calculation found a NaN/inf with regression method" << endl;
         haveWarned = true;
         if (numNeigh != 0)
         {
            somevecf[0] = 0.0f;
            somevecf[1] = 0.0f;
            somevecf[2] = 0.0f;
            somevec[0] = 0.0;
            somevec[1] = 0.0;
            somevec[2] = 0.0;
            for (int j = 0; j < numNeigh; ++j)
            {
               const int whichnode = neighbors[j];
               coordDiff(&sourceData[whichnode * 3], &sourceData[i * 3], xhat);//xhat repurposed as a temp variable
               for (int k = 0; k < 3; ++k)
                  yhat[k] = xhat[k];
               normalize(xhat);
               tempd = (metricData[whichnode] - nodemetric) / sqrt(yhat[0] * yhat[0] + yhat[1] * yhat[1] + yhat[2] * yhat[2]);//difference over distance gives gradient magnitude
               for (int k = 0; k < 3; ++k)
                  somevec[k] += tempd * xhat[k];//magnitude times unit vector parallel to distance vector gives crude estimate
            }
            for (int j = 0; j < 3; ++j)
            {
               somevec[j] /= numNeigh;//now we have the 3d gradient, time to subtract the dot product with normal
               xhat[j] = mynormal[j];
            }
            normalize(xhat);//for sanity, in case your normals aren't unit vectors somehow
            tempd = dotProd(somevec, xhat);
            sanity = 0.0;
            for (int j = 0; j < 3; ++j)
               sanity += (somevecf[j] = (float)(somevec[j] -= tempd * xhat[j]));
         }
         if (numNeigh == 0 || !(sanity == sanity))
         {
            if (!haveFailed)
            {
               std::cerr << "WARNING: gradient calculation found a NaN/inf with fallback method, outputting ZERO" << endl;
               std::cerr << "check your coordinate/topo files for isolated nodes and nodes with identical coords" << endl;
            }
            haveFailed = true;
            somevecf[0] = 0.0f;
            somevecf[1] = 0.0f;
            somevecf[2] = 0.0f;
            somevec[0] = 0.0;
            somevec[1] = 0.0;
            somevec[2] = 0.0;
         }
      }
      magData[i] = (float)sqrt(somevec[0] * somevec[0] + somevec[1] * somevec[1] + somevec[2] * somevec[2]);
   }
   gradMagOut->setColumnForAllNodes(columnIndex, magData);
   gradMagOut->setColumnName(columnIndex, "surface gradient");
   delete[] magData;
   delete[] metricData;
   delete[] rrefb[0];
   delete[] rrefb[1];
   delete[] rrefb[2];
}