forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvtkMINCImageWriter.cxx
2149 lines (1919 loc) · 63.2 KB
/
vtkMINCImageWriter.cxx
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
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMINCImageWriter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*=========================================================================
Copyright (c) 2006 Atamai, Inc.
Use, modification and redistribution of the software, in source or
binary forms, are permitted provided that the following terms and
conditions are met:
1) Redistribution of the source code, in verbatim or modified
form, must retain the above copyright notice, this license,
the following disclaimer, and any notices that refer to this
license and/or the following disclaimer.
2) Redistribution in binary form must include the above copyright
notice, a copy of this license and the following disclaimer
in the documentation or with other materials provided with the
distribution.
3) Modified copies of the source code must be clearly marked as such,
and must not be misrepresented as verbatim copies of the source code.
THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS"
WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE
OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF
THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
=========================================================================*/
#include "vtkMINCImageWriter.h"
#include "vtkObjectFactory.h"
#include "vtkImageData.h"
#include "vtkStringArray.h"
#include "vtkCharArray.h"
#include "vtkSignedCharArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkShortArray.h"
#include "vtkIntArray.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkMatrix4x4.h"
#include "vtkSmartPointer.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkType.h"
#include "vtkMINCImageAttributes.h"
#include "vtkMINC.h"
#include "vtknetcdf/netcdf.h"
#ifdef _WIN32
#include "vtkWindows.h"
#else
#include <sys/types.h>
#include <unistd.h>
#endif
#include <stdlib.h>
#include <float.h>
#include <time.h>
#include <vtkstd/string>
#include <vtkstd/vector>
#include <vtkstd/map>
#define VTK_MINC_MAX_DIMS 8
//--------------------------------------------------------------------------
vtkStandardNewMacro(vtkMINCImageWriter);
vtkCxxSetObjectMacro(vtkMINCImageWriter,DirectionCosines,vtkMatrix4x4);
vtkCxxSetObjectMacro(vtkMINCImageWriter,ImageAttributes,
vtkMINCImageAttributes);
//-------------------------------------------------------------------------
vtkMINCImageWriter::vtkMINCImageWriter()
{
this->DirectionCosines = 0;
this->RescaleIntercept = 0.0;
this->RescaleSlope = 0.0;
this->InternalRescaleIntercept = 0.0;
this->InternalRescaleSlope = 0.0;
this->MINCImageType = 0;
this->MINCImageTypeSigned = 1;
this->MINCImageMinMaxDims = 0;
this->FileDataType = 0;
this->FileValidRange[0] = 0.0;
this->FileValidRange[1] = 1.0;
this->ComputeValidRangeFromScalarRange = 0;
this->DataUpdateExtent[0] = 0;
this->DataUpdateExtent[1] = 0;
this->DataUpdateExtent[2] = 0;
this->DataUpdateExtent[3] = 0;
this->DataUpdateExtent[4] = 0;
this->DataUpdateExtent[5] = 0;
this->FileDimensionNames = vtkStringArray::New();
this->ImageAttributes = 0;
this->StrictValidation = 1;
this->MismatchedInputs = 0;
this->HistoryAddition = 0;
}
//-------------------------------------------------------------------------
vtkMINCImageWriter::~vtkMINCImageWriter()
{
if (this->DirectionCosines)
{
this->DirectionCosines->Delete();
this->DirectionCosines = 0;
}
if (this->FileDimensionNames)
{
this->FileDimensionNames->Delete();
this->FileDimensionNames = 0;
}
if (this->ImageAttributes)
{
this->ImageAttributes->Delete();
this->ImageAttributes = 0;
}
this->SetHistoryAddition(0);
}
//-------------------------------------------------------------------------
void vtkMINCImageWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "DirectionCosines: " << this->DirectionCosines << "\n";
if (this->DirectionCosines)
{
this->DirectionCosines->PrintSelf(os, indent.GetNextIndent());
}
os << indent << "RescaleSlope: " << this->RescaleSlope << "\n";
os << indent << "RescaleIntercept: " << this->RescaleIntercept << "\n";
os << indent << "StrictValidation: " <<
(this->StrictValidation ? "On\n" : "Off\n");
os << indent << "HistoryAddition: " <<
(this->HistoryAddition ? this->HistoryAddition : "(None)") << "\n";
}
//-------------------------------------------------------------------------
void vtkMINCImageWriter::SetFileName(const char *name)
{
this->Superclass::SetFileName(name);
}
//-------------------------------------------------------------------------
int vtkMINCImageWriter::OpenNetCDFFile(const char *filename, int& ncid)
{
int status = 0;
if (filename == 0)
{
vtkErrorMacro("No filename was set");
return 0;
}
status = nc_create(filename, 0, &ncid);
if (status != NC_NOERR)
{
vtkErrorMacro("Could not open the MINC file:\n"
<< nc_strerror(status));
return 0;
}
return 1;
}
//-------------------------------------------------------------------------
int vtkMINCImageWriter::CloseNetCDFFile(int ncid)
{
int status = 0;
status = nc_close(ncid);
if (status != NC_NOERR)
{
vtkErrorMacro("Could not close the MINC file:\n"
<< nc_strerror(status));
return 0;
}
return 1;
}
//-------------------------------------------------------------------------
// this is a macro so the vtkErrorMacro will report a useful line number
#define vtkMINCImageWriterFailAndClose(ncid, status) \
{ \
if (status != NC_NOERR) \
{ \
vtkErrorMacro("There was an error with the MINC file \"" \
<< this->GetFileName() << "\":\n" \
<< nc_strerror(status)); \
} \
nc_close(ncid); \
}
//-------------------------------------------------------------------------
// Function for getting VTK dimension index from file name.
int vtkMINCImageWriter::IndexFromDimensionName(const char *dimName)
{
switch(dimName[0])
{
case 'x':
return this->Permutation[0];
case 'y':
return this->Permutation[1];
case 'z':
return this->Permutation[2];
default:
if (strcmp(dimName, MIvector_dimension) == 0)
{
return -1;
}
break;
}
// Any unrecognized dimensions are returned as index 3
return 3;
}
//-------------------------------------------------------------------------
// Compute the default dimension order from the direction cosines,
// and look for flips.
// The way the permutation should be used is as follows:
// If permutation[0] == 0 then MIxspace is VTK's X dimension.
// If permutation[0] == 2 then MIxspace is VTK's Z dimension.
// If the "flip" is set for a VTK, then that VTK dimension
// and its dircos will have to be flipped before the MINC
// file is written.
// For example, if flip[2] == 1, then the MINC dimension that
// maps to the VTK Z dimension will to be flipped along with
// its dircos.
void vtkMINCImageWriter::ComputePermutationFromOrientation(
int permutation[3], int flip[3])
{
vtkMatrix4x4 *matrix = this->DirectionCosines;
if (matrix == 0)
{
permutation[0] = 0;
permutation[1] = 1;
permutation[2] = 2;
flip[0] = 0;
flip[1] = 0;
flip[2] = 0;
return;
}
// There are 6 permutations for 3 dimensions. In addition,
// if each of those dimensions can be flipped, then there are
// 8 (two to the power of three) possible flips. That would
// give 48 different possibilities, but since we don't consider
// any combinations that result in left-handed rotations, the
// total number of combinations that we test is 24.
// Convert the matrix into three column vectors
double vectors[3][4];
int i = 0;
int j = 0;
for (i = 0; i < 3; i++)
{
double *v = vectors[i];
for (j = 0; j < 4; j++)
{
v[j] = 0.0;
}
v[i] = 1.0;
matrix->MultiplyPoint(v, v);
}
// Here's how the algorithm works. We want to find a matrix
// composed only of permutations and flips that has the closest
// possible orientation (in terms of absolute orientation angle)
// to our DirectionCosines.
// The orientation angle for any matrix A is given by:
//
// cos(angle/2) = sqrt(1 + trace(A))/2
//
// Therefore, the minimum angle occurs when the trace is
// at its maximum.
// So our method is to calculate the traces of all the various
// permutations and flips, and just use the one with the largest
// trace.
// First check if the matrix includes an odd number of flips,
// since if it does, it specifies a left-handed rotation.
double d = vtkMath::Determinant3x3(vectors[0], vectors[1], vectors[2]);
int oddPermutation = (d < 0);
// Calculate all the traces, including any combination of
// permutations and flips that represent right-handed
// orientations.
int imax = 0;
int jmax = 0;
int kmax = 0;
int lmax = 0;
double maxtrace = -1e30;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
double xval = vectors[i][0];
double yval = vectors[(i + 1 + j) % 3][1];
double zval = vectors[(i + 2 - j) % 3][2];
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
// The (1 - 2*k) gives a sign from a boolean.
// For z, we want to set the sign that will
// not change the handedness ("^" is XOR).
double xtmp = xval * (1 - 2*k);
double ytmp = yval * (1 - 2*l);
double ztmp = zval * (1 - 2*(j ^ k ^ l ^ oddPermutation));
double trace = xtmp + ytmp + ztmp;
// Find maximum trace
if (trace > maxtrace)
{
maxtrace = trace;
imax = i;
jmax = j;
kmax = k;
lmax = l;
}
}
}
}
}
// Find the permutation to map each column of the orientation
// matrix to a spatial dimension x, y, or z.
int xidx = imax;
int yidx = (imax + 1 + jmax) % 3;
int zidx = (imax + 2 - jmax) % 3;
permutation[0] = xidx;
permutation[1] = yidx;
permutation[2] = zidx;
flip[xidx] = kmax;
flip[yidx] = lmax;
flip[zidx] = (jmax ^ kmax ^ lmax ^ oddPermutation);
}
//-------------------------------------------------------------------------
// Create an identity string for a file.
vtkstd::string vtkMINCImageWriterCreateIdentString()
{
// A static counter for this process.
static int identx = 1;
// The separator between element.
static const char *itemsep = ":";
// Get username and hostname
const char *username = 0;
const char *hostname = 0;
#ifdef _WIN32
char usernametext[100];
DWORD numchars = sizeof(usernametext);
if (GetUserName(usernametext, &numchars))
{
username = usernametext;
}
char hostnametext[100];
numchars = sizeof(hostnametext);
if (GetComputerName(hostnametext, &numchars))
{
hostname = hostnametext;
}
#else
username = getenv("LOGNAME");
hostname = getenv("HOSTNAME");
#endif
if (username == 0)
{
username = "nobody";
}
if (hostname == 0)
{
hostname = "unknown";
}
vtkstd::string ident = username;
ident.append(itemsep);
ident.append(hostname);
ident.append(itemsep);
// Get the local time
char buf[1024];
time_t t;
time(&t);
strftime(buf, sizeof(buf), "%Y.%m.%d.%H.%M.%S", localtime(&t));
ident.append(buf);
ident.append(itemsep);
// Get the process ID and the counter for this process.
#ifdef _WIN32
int processId = GetCurrentProcessId();
#else
int processId = getpid();
#endif
sprintf(buf, "%i%s%i", processId, itemsep, identx++);
ident.append(buf);
return ident;
}
//-------------------------------------------------------------------------
nc_type vtkMINCImageWriterConvertVTKTypeToMINCType(
int dataType,
int &mincsigned)
{
nc_type minctype = NC_BYTE;
// Get the vtk type of the data.
switch (dataType)
{
case VTK_CHAR:
case VTK_SIGNED_CHAR:
minctype = NC_BYTE;
mincsigned = 1;
break;
case VTK_UNSIGNED_CHAR:
minctype = NC_BYTE;
mincsigned = 0;
break;
case VTK_SHORT:
minctype = NC_SHORT;
mincsigned = 1;
break;
case VTK_UNSIGNED_SHORT:
minctype = NC_SHORT;
mincsigned = 0;
break;
case VTK_INT:
minctype = NC_INT;
mincsigned = 1;
break;
case VTK_UNSIGNED_INT:
minctype = NC_INT;
mincsigned = 0;
break;
case VTK_FLOAT:
minctype = NC_FLOAT;
mincsigned = 1;
break;
case VTK_DOUBLE:
minctype = NC_DOUBLE;
mincsigned = 1;
break;
default:
break;
}
return minctype;
}
//-------------------------------------------------------------------------
// These macro is only for use in WriteMINCFileAttributes
#define vtkMINCImageWriterPutAttributeTextMacro(name, text) \
if (status == NC_NOERR) \
{ \
status = nc_put_att_text(ncid, varid, name, strlen(text)+1, text); \
}
#define vtkMINCImageWriterPutAttributeDoubleMacro(name, count, ptr) \
if (status == NC_NOERR) \
{ \
status = nc_put_att_double(ncid, varid, name, NC_DOUBLE, count, ptr); \
}
//-------------------------------------------------------------------------
// Allowed dimension variable names
static const char *vtkMINCDimVarNames[] = {
MIxspace, MIyspace, MIzspace, MItime,
MIxfrequency, MIyfrequency, MIzfrequency, MItfrequency,
0
};
//-------------------------------------------------------------------------
int vtkMINCImageWriter::CreateMINCDimensions(
vtkImageData *input, int numTimeSteps, int *dimids)
{
int wholeExtent[6];
input->GetWholeExtent(wholeExtent);
int numComponents = input->GetNumberOfScalarComponents();
// Create a default dimension order using the direction cosines.
this->ComputePermutationFromOrientation(this->Permutation, this->Flip);
const char *defaultdims[3];
defaultdims[this->Permutation[0]] = MIxspace;
defaultdims[this->Permutation[1]] = MIyspace;
defaultdims[this->Permutation[2]] = MIzspace;
int hasTimeDim = 0;
vtkstd::vector<vtkstd::string> dimensions;
int nuserdims = 0;
vtkStringArray *dimensionNames = 0;
if (this->ImageAttributes)
{
dimensionNames = this->ImageAttributes->GetDimensionNames();
nuserdims = dimensionNames->GetNumberOfValues();
}
for (int iuserdims = 0; iuserdims < nuserdims; iuserdims++)
{
const char *dimname = dimensionNames->GetValue(iuserdims);
// Remove vector_dimension, we'll add it back if it is needed
if (strcmp(dimname, MIvector_dimension) == 0)
{
continue;
}
// Check for time or tfrequency
if (dimname[0] == 't')
{
hasTimeDim = 1;
}
// Ensure the dimension name is valid
const char **tryname = 0;
for (tryname = vtkMINCDimVarNames; *tryname !=0; tryname++)
{
if (strcmp(dimname, *tryname) == 0)
{
break;
}
}
if (*tryname == 0)
{
vtkErrorMacro("The dimension name " << dimname <<
" is not recognized.");
return 0;
}
// Check for duplicated dimensions
int ndim = static_cast<int>(dimensions.size());
for (int idim = 0; idim < ndim; idim++)
{
if (dimensions[idim][0] == dimname[0])
{
vtkErrorMacro("Tried to create dimension " << dimname <<
" but " << dimensions[idim] << " already exists");
return 0;
}
}
// Add the dimension
dimensions.push_back(dimname);
}
// Make sure number of dimensions matches the dimensionality
int timeDimensions = ( numTimeSteps > 1);
int spatialDimensions = ((wholeExtent[0] < wholeExtent[1]) +
(wholeExtent[2] < wholeExtent[3]) +
(wholeExtent[4] < wholeExtent[5]));
if (spatialDimensions < 2)
{
spatialDimensions = 2;
}
// Insert dimension names until we have all spatial dimensions
while (static_cast<int>(dimensions.size()) < spatialDimensions+hasTimeDim)
{
// Make sure we don't insert a dimension that is already there
for (int i = 0; i < 3; i++)
{
int idim = 0;
int ndims = static_cast<int>(dimensions.size());
for (idim = 0; idim < ndims; idim++)
{
if (defaultdims[i][0] == dimensions[idim][0])
{
break;
}
}
if (idim == ndims)
{
dimensions.insert(dimensions.begin(), defaultdims[i]);
}
}
}
// Make sure we have a time dimension if we need one
if (timeDimensions == 1 && hasTimeDim == 0)
{
dimensions.insert(dimensions.begin(), MItime);
}
// Check for vector_dimension
if (numComponents > 1)
{
dimensions.push_back(MIvector_dimension);
}
// ------------------------
// Create the NetCDF dimensions
int ncid = this->MINCFileId;
int status = NC_NOERR;
int ndim = static_cast<int>(dimensions.size());
this->FileDimensionNames->SetNumberOfValues(ndim);
for (int idim = 0; idim < ndim; idim++)
{
const char *dimname = dimensions[idim].c_str();
this->FileDimensionNames->SetValue(idim, dimname);
int dimIndex = this->IndexFromDimensionName(dimname);
size_t length = numTimeSteps;
if (dimIndex >= 0 && dimIndex < 3)
{
length = wholeExtent[2*dimIndex+1] - wholeExtent[2*dimIndex] + 1;
}
else if (strcmp(dimname, MIvector_dimension) == 0)
{
length = numComponents;
}
status = nc_def_dim(ncid, dimname, length, &dimids[idim]);
if (status != NC_NOERR)
{
vtkMINCImageWriterFailAndClose(ncid, status);
this->MINCFileId = 0;
return 0;
}
}
return 1;
}
//-------------------------------------------------------------------------
int vtkMINCImageWriter::CreateMINCVariables(
vtkImageData *input, int vtkNotUsed(numTimeSteps), int *dimids)
{
// Allowed standard variable names
static const char *stdVarNames[] = {
MIrootvariable, MIimage, MIimagemin, MIimagemax,
MIpatient, MIstudy, MIacquisition,
0
};
vtkstd::vector<vtkstd::string> variables;
// Get the information from the input
double spacing[3];
double origin[3];
int wholeExtent[6];
int numComponents = input->GetNumberOfScalarComponents();
int imageDataType = input->GetScalarType();
input->GetSpacing(spacing);
input->GetOrigin(origin);
input->GetWholeExtent(wholeExtent);
// Add all dimensions onto the list of variables
int ndim = this->FileDimensionNames->GetNumberOfValues();
for (int dimidx = 0; dimidx < ndim; dimidx++)
{
const char *dimname = this->FileDimensionNames->GetValue(dimidx);
// vector_dimension isn't ever included as a variable
if (strcmp(dimname, MIvector_dimension) != 0)
{
variables.push_back(this->FileDimensionNames->GetValue(dimidx));
}
}
// Reset ndim so that it only includes dimensions with variables
ndim = static_cast<int>(variables.size());
variables.push_back(MIimage);
variables.push_back(MIrootvariable);
// Not all MINC images need image-min and image-max.
this->MINCImageMinMaxDims = 0;
if (this->InternalRescaleSlope != 0)
{
// Check whether slice-by-slice rescaling is needed
if ((imageDataType == VTK_FLOAT ||
imageDataType == VTK_DOUBLE) &&
(this->MINCImageType != NC_FLOAT &&
this->MINCImageType != NC_DOUBLE))
{
this->MINCImageMinMaxDims = ndim - 2;
}
variables.push_back(MIimagemin);
variables.push_back(MIimagemax);
}
// Add user-defined variables
int nuservars = 0;
vtkStringArray *variableNames = 0;
if (this->ImageAttributes)
{
variableNames = this->ImageAttributes->GetVariableNames();
nuservars = variableNames->GetNumberOfValues();
}
for (int iuservars = 0; iuservars < nuservars; iuservars++)
{
const char *varname = variableNames->GetValue(iuservars);
int ivar;
int nvars = static_cast<int>(variables.size());
for (ivar = 0; ivar < nvars; ivar++)
{
if (strcmp(variables[ivar].c_str(), varname) == 0)
{
break;
}
}
if (ivar == nvars) // wasn't already in the list
{
// Check if the variable name is a dimension that isn't one
// of the selected dimensions for this image
for (const char **tryname = vtkMINCDimVarNames; *tryname !=0; tryname++)
{
if (strcmp(varname, *tryname) == 0)
{
vtkErrorMacro("The variable " << varname
<< " is not a dimension of this image");
return 0;
}
}
variables.push_back(varname);
}
}
// ------------------------
// Find the children of the root variable
vtkstd::string rootChildren = MI_EMPTY_STRING;
int nvars = static_cast<int>(variables.size());
int ivar = 0;
for (ivar = 0; ivar < nvars; ivar++)
{
const char *varname = variables[ivar].c_str();
if (strcmp(varname, MIrootvariable) == 0 ||
strcmp(varname, MIimagemin) == 0 ||
strcmp(varname, MIimagemax) == 0)
{
continue;
}
for (const char **tryname = stdVarNames; *tryname !=0; tryname++)
{
if (strcmp(varname, *tryname) == 0)
{
if (rootChildren != MI_EMPTY_STRING)
{
rootChildren.append(MI_CHILD_SEPARATOR);
}
rootChildren.append(varname);
break;
}
}
}
// ------------------------
// Create the variables and write the attributes.
// Start at -1, which stands for global attributes.
int ncid = this->MINCFileId;
int status = NC_NOERR;
nvars = static_cast<int>(variables.size());
for (ivar = -1; ivar < nvars; ivar++)
{
const char *varname = MI_EMPTY_STRING;
const char *vartype = MI_EMPTY_STRING;
int varid = -1;
if (ivar >= 0)
{
nc_type cdftype = NC_INT;
varname = variables[ivar].c_str();
const char *parent = MIrootvariable;
const char *children = 0;
int vardims = 0;
// The dimensions are the first variables (note that ndim
// does not include the vector_dimension)
if (ivar < ndim)
{
vartype = MI_DIMENSION;
}
else
{
for (const char **tryname = stdVarNames; *tryname != 0; tryname++)
{
if (strcmp(varname, *tryname) == 0)
{
vartype = MI_GROUP;
}
}
}
// Check if this is an image-related variable
if (strcmp(varname, MIimage) == 0)
{
cdftype = (nc_type)this->MINCImageType;
vardims = ndim + (numComponents > 1);
}
else if (strcmp(varname, MIimagemin) == 0 ||
strcmp(varname, MIimagemax) == 0)
{
parent = MIimage;
vartype = MI_VARATT;
cdftype = NC_DOUBLE;
vardims = this->MINCImageMinMaxDims;
}
// Check if this is the rootvariable
if (strcmp(varname, MIrootvariable) == 0)
{
parent = MI_EMPTY_STRING;
children = rootChildren.c_str();
}
// Create the NetCDF variable
status = nc_def_var(ncid, varname, cdftype, vardims, dimids,
&varid);
if (status != NC_NOERR)
{
vtkMINCImageWriterFailAndClose(ncid, status);
this->MINCFileId = 0;
return 0;
}
// Variables of known type get standard MINC attributes
if (strcmp(vartype, MI_EMPTY_STRING) != 0)
{
vtkMINCImageWriterPutAttributeTextMacro(MIvarid, MI_STDVAR);
vtkMINCImageWriterPutAttributeTextMacro(MIversion, MI_VERSION_1_0);
vtkMINCImageWriterPutAttributeTextMacro(MIvartype, vartype);
}
int dimIndex = 0;
if (strcmp(vartype, MI_DIMENSION) == 0)
{
static const char *dimensionComments[] = {
"X increases from patient left to right",
"Y increases from patient posterior to anterior",
"Z increases from patient inferior to superior",
0
};
dimIndex = this->IndexFromDimensionName(varname);
double start = 0.0;
double step = 1.0;
if (dimIndex >= 0 && dimIndex < 3)
{
vtkMINCImageWriterPutAttributeTextMacro(
MIcomments, dimensionComments[dimIndex]);
start = origin[dimIndex];
step = spacing[dimIndex];
if (this->Flip[dimIndex])
{
// Switch the MIstart to the other end and change sign
double length = (wholeExtent[2*dimIndex+1] -
wholeExtent[2*dimIndex] + 1);
start = -(start + step*(length-1));
}
}
vtkMINCImageWriterPutAttributeDoubleMacro(MIstart, 1, &start);
vtkMINCImageWriterPutAttributeDoubleMacro(MIstep, 1, &step);
vtkMINCImageWriterPutAttributeTextMacro(MIspacing, MI_REGULAR);
vtkMINCImageWriterPutAttributeTextMacro(MIspacetype, MI_NATIVE);
vtkMINCImageWriterPutAttributeTextMacro(MIalignment, MI_CENTRE);
// Extra attributes for spatial dimensions
if (dimIndex >= 0 && dimIndex < 3)
{
vtkMatrix4x4 *matrix = this->GetDirectionCosines();
if (matrix)
{
double dircos[3];
// need to take permutation into account here
dircos[0] = matrix->GetElement(0, dimIndex);
dircos[1] = matrix->GetElement(1, dimIndex);
dircos[2] = matrix->GetElement(2, dimIndex);
if (this->Flip[dimIndex])
{
// Flip the dimension direction
for (int idx = 0; idx < 3; idx++)
{
if (dircos[idx] != 0)
{
dircos[idx] = -dircos[idx];
}
}
}
vtkMINCImageWriterPutAttributeDoubleMacro(MIdirection_cosines,
3, dircos);
}
}
}
else if (strcmp(vartype, MI_VARATT) == 0)
{
vtkMINCImageWriterPutAttributeTextMacro(MIparent, parent);
if (children)
{
vtkMINCImageWriterPutAttributeTextMacro(MIchildren, children);
}
if (strcmp(varname, MIimagemin) == 0)
{
double val = 0.0;
vtkMINCImageWriterPutAttributeDoubleMacro(MI_FillValue, 1, &val);
}
else if (strcmp(varname, MIimagemax) == 0)
{
double val = 1.0;
vtkMINCImageWriterPutAttributeDoubleMacro(MI_FillValue, 1, &val);
}
}
else if (strcmp(vartype, MI_GROUP) == 0)
{
vtkMINCImageWriterPutAttributeTextMacro(MIparent, parent);
if (children)
{
vtkMINCImageWriterPutAttributeTextMacro(MIchildren, children);
}
if (strcmp(varname, MIimage) == 0)
{
const char *signType = MI_SIGNED;
if (this->MINCImageTypeSigned == 0)
{
signType = MI_UNSIGNED;
}
double *validRange = this->FileValidRange;
vtkMINCImageWriterPutAttributeTextMacro(MIcomplete, MI_TRUE);
// Only produce signtype and valid_range for integer data
if (this->MINCImageType != NC_FLOAT &&
this->MINCImageType != NC_DOUBLE)
{
vtkMINCImageWriterPutAttributeTextMacro(MIsigntype, signType);
// Don't set valid_range if the default is suitable
if (this->ComputeValidRangeFromScalarRange ||
(this->ImageAttributes &&
vtkDoubleArray::SafeDownCast(
this->ImageAttributes->GetAttributeValueAsArray(
MIimage, MIvalid_range))))
{
vtkMINCImageWriterPutAttributeDoubleMacro(MIvalid_range,2,
validRange);
}
}
// The image-min, image-max will not always be present
if (this->InternalRescaleSlope != 0)
{
vtkMINCImageWriterPutAttributeTextMacro(
MIimagemin, MI_VARATT_POINTER_PREFIX MIimagemin);
vtkMINCImageWriterPutAttributeTextMacro(
MIimagemax, MI_VARATT_POINTER_PREFIX MIimagemax);
}
}
}
}
else
{
// Set the varid for global variables
varid = -1;
// Global attributes: ident and history
vtkstd::string ident = vtkMINCImageWriterCreateIdentString();
vtkMINCImageWriterPutAttributeTextMacro(MIident, ident.c_str());
// For history, include any previous history
vtkstd::string history = MI_EMPTY_STRING;
const char *previousHistory = 0;
if (this->ImageAttributes)