File: itkStreamingImageIOBase.cxx

package info (click to toggle)
insighttoolkit 3.20.1%2Bgit20120521-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 80,652 kB
  • sloc: cpp: 458,133; ansic: 196,223; fortran: 28,000; python: 3,839; tcl: 1,811; sh: 1,184; java: 583; makefile: 430; csh: 220; perl: 193; xml: 20
file content (483 lines) | stat: -rw-r--r-- 14,494 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkStreamingImageIOBase.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#include "itkStreamingImageIOBase.h"


#include <itksys/SystemTools.hxx>

namespace itk
{

StreamingImageIOBase::StreamingImageIOBase()
  : ImageIOBase()
{
}


void StreamingImageIOBase::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}


bool StreamingImageIOBase
::StreamReadBufferAsBinary(std::istream& file, void *_buffer)
{
  itkDebugMacro( << "StreamingReadBufferAsBinary called" );

  char *buffer = static_cast<char*>(_buffer);
  // Offset into file
  std::streampos dataPos = this->GetDataPosition();

  std::streamsize sizeOfRegion = static_cast<std::streamsize>( m_IORegion.GetNumberOfPixels() )
    *this->GetPixelSize();


  // compute the number of continuous bytes to be read
  std::streamsize sizeOfChunk = 1;
  unsigned int movingDirection = 0;
  do
    {
    sizeOfChunk *= m_IORegion.GetSize(movingDirection);
    ++movingDirection;
    }
  while ( movingDirection < m_IORegion.GetImageDimension() &&
          m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );
  sizeOfChunk *= this->GetPixelSize();

  ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();
  std::streamsize gcount = 0;
  while ( m_IORegion.IsInside(currentIndex) )
    {
    // calculate the position to seek to in the file
    std::streampos seekPos = 0;
    size_t subDimensionQuantity = 1;
    for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )
      {
      seekPos = seekPos + static_cast<std::streamoff> (subDimensionQuantity *
                                                       this->GetPixelSize() *
                                                       currentIndex[i]);
      subDimensionQuantity *= this->GetDimensions(i);
      }


    itkDebugMacro(<< "Reading " << sizeOfChunk << " of " << sizeOfRegion << " bytes for " << m_FileName << " at " << dataPos+seekPos << " position in file");

    file.seekg( dataPos+seekPos, std::ios::beg );
    this->ReadBufferAsBinary( file, buffer, sizeOfChunk );

    // increment the buffer pointer
    buffer += sizeOfChunk;
    gcount += file.gcount();

    if ( file.fail() )
      {
      itkExceptionMacro(<<"Fail reading");
      }

    if (movingDirection == m_IORegion.GetImageDimension())
      break;

    // increment index to next chunk
    ++currentIndex[movingDirection];
    for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)
      {
      // when reaching the end of the moving index dimension carry to
      // higher dimensions
      if (static_cast<ImageIORegion::SizeValueType>(currentIndex[i]  - m_IORegion.GetIndex(i)) >= m_IORegion.GetSize(i) )
        {
        currentIndex[i] = m_IORegion.GetIndex(i);
        ++currentIndex[i+1];
        }
      }
    }

  if ( gcount != sizeOfRegion )
    {
    itkExceptionMacro("Data not read completely. Expected = " << sizeOfRegion << ", but only read " <<  gcount <<  " bytes.");
    }

  return true;
}

bool StreamingImageIOBase::ReadBufferAsBinary( std::istream& is, void *buffer, StreamingImageIOBase::SizeType num )
{

  // some systems have a limit of 2GB to be read at once
  const SizeType maxChunk = 1024*1024*1024;

  std::streamsize bytesRemaining = static_cast<std::streamsize>( num );

  while (bytesRemaining)
    {

    std::streamsize bytesToRead = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;

    itkDebugMacro(<< "Reading " << bytesToRead << " of " << bytesRemaining << " bytes for " << m_FileName);

    is.read( static_cast<char *>( buffer ) ,  bytesToRead );

    if ( (is.gcount() != bytesToRead) || is.fail() )
      {
      return false;
      }
    buffer =  static_cast<char *>( buffer ) + bytesToRead;
    bytesRemaining -= bytesToRead;
    }

  return true;
}


bool StreamingImageIOBase::WriteBufferAsBinary( std::ostream& os, const void *buffer, StreamingImageIOBase::SizeType num )
{
  // some systems have a limit of 2GB to be written at once
  const SizeType maxChunk = 1024*1024*1024;

  std::streamsize bytesRemaining = num;
  while (bytesRemaining)
    {

    SizeType bytesToWrite = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;

    itkDebugMacro(<< "Writing " << bytesToWrite << " of " << bytesRemaining << " bytes for " << m_FileName);

    os.write(static_cast<const char*>(buffer) , bytesToWrite);
    if ( os.fail() )
      {
      return false;
      }

    buffer =  static_cast<const char *>( buffer ) + bytesToWrite;
    bytesRemaining -= bytesToWrite;
    }

  return true;
}


bool StreamingImageIOBase::StreamWriteBufferAsBinary(std::ostream& file, const void *_buffer)
{
  itkDebugMacro( << "StreamingWriteBufferAsBinary called" );

  const char *buffer = static_cast< const char* >( _buffer );
  // Offset into file
  std::streampos dataPos = this->GetDataPosition();

  // compute the number of continuous bytes to be written
  std::streamsize sizeOfChunk = 1;
  unsigned int movingDirection = 0;
  do
    {
    sizeOfChunk *= m_IORegion.GetSize(movingDirection);
    ++movingDirection;
    }
  while ( movingDirection < m_IORegion.GetImageDimension() &&
          m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );
  sizeOfChunk *= this->GetPixelSize();


  ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();
  while ( m_IORegion.IsInside(currentIndex) )
    {
    // calculate the position to seek to in the file
    std::streampos seekPos = 0;
    size_t subDimensionQuantity = 1;
    for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )
      {
      seekPos = seekPos + static_cast<std::streamoff> (subDimensionQuantity *
                                                       this->GetPixelSize() *
                                                       currentIndex[i]);
      subDimensionQuantity *= this->GetDimensions(i);
      }

    file.seekp( dataPos+seekPos, std::ios::beg );
    this->WriteBufferAsBinary( file, buffer, sizeOfChunk );

    // increment the buffer pointer
    buffer += sizeOfChunk;


    itkDebugMacro(<< "Writing " << sizeOfChunk << " of " <<  " ?? bytes for " << m_FileName << " at " << dataPos+seekPos << " position in file");


    if ( file.fail() )
      {
      itkExceptionMacro(<<"Fail writing");
      }

    if (movingDirection == m_IORegion.GetImageDimension())
      break;

    // increment index to next chunk
    ++currentIndex[movingDirection];
    for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)
      {
      // when reaching the end of the movingDirection dimension carry to
      // higher dimensions
      if ( static_cast<ImageIORegion::SizeValueType>(currentIndex[i] - m_IORegion.GetIndex(i))
           >=  m_IORegion.GetSize(i) )
        {
        currentIndex[i] = m_IORegion.GetIndex(i);
        ++currentIndex[i+1];
        }
      }
    }


  return true;
}


void StreamingImageIOBase::OpenFileForReading(std::ifstream& os, const char* filename)
{
  // Make sure that we have a file to
  if ( *filename == 0 )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for reading
  itkDebugMacro(<< "Initialize: opening file " << filename);

  os.open(filename,  std::ios::in | std::ios::binary  );
  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for reading: " << filename);
    }

}

void StreamingImageIOBase::OpenFileForWriting(std::ofstream& os, const char* filename, bool truncate)
{
  // Make sure that we have a file to
  if ( *filename == 0 )
    {
    itkExceptionMacro(<<"A FileName must be specified.");
    }

  // Close file from any previous image
  if ( os.is_open() )
    {
    os.close();
    }

  // Open the new file for writing
  itkDebugMacro(<< "Initialize: opening file " << filename);

 if (truncate)
    {
    // truncate
    os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::trunc );

    }
  else
    {
    os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::in );
    }

  if ( os.fail() )
    {
    itkExceptionMacro(<< "Could not open file for writing: " << filename);
    }

}

bool StreamingImageIOBase::CanStreamRead( void )
{
  return true;
}

bool StreamingImageIOBase::CanStreamWrite( void )
{
  return true;
}


unsigned int
StreamingImageIOBase::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits,
                                               const ImageIORegion &pasteRegion,
                                               const ImageIORegion &largestPossibleRegion)
{
  if (!itksys::SystemTools::FileExists( m_FileName.c_str() ))
    {
    // file doesn't exits so we don't have potential problems
    }
  else if (pasteRegion != largestPossibleRegion)
    {
    // we are going to be pasting (may be streaming too)

    // need to check to see if the file is compatible
    std::string errorMessage;
    Pointer headerImageIOReader = dynamic_cast<StreamingImageIOBase*>(this->CreateAnother().GetPointer());

    try
      {
      headerImageIOReader->SetFileName(m_FileName.c_str());
      headerImageIOReader->ReadImageInformation();
      }
    catch (...)
      {
      errorMessage = "Unable to read information from file: " + m_FileName;
      }

    // we now need to check that the following match:
    // 2)pixel type
    // 3)dimensions
    // 4)size/origin/spacing
    // 5)direction cosines
    //
    // todo check for byte order

    if (errorMessage.size())
      {
      // 0) Can't read file
      }
    // 2)pixel type
    // this->GetPixelType() is not verified becasue the metaio file format
    // stores all multi-component types as arrays, so it does not
    // distinguish between pixel types. Also as long as the compoent
    // and number of compoents match we should be able to paste, that
    // is the numbers should be the same it is just the interpretation
    // that is not matching
    else if ( headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() ||
              headerImageIOReader->GetComponentType() != this->GetComponentType() )
      {
      errorMessage = "Component type does not match in file: " + m_FileName;
      }
    // 3)dimensions/size
    else if (headerImageIOReader->GetNumberOfDimensions() != this->GetNumberOfDimensions())
      {
      errorMessage = "Dimensions does not match in file: " + m_FileName;
      }
    else
      {
      for (unsigned int i = 0; i < this->GetNumberOfDimensions(); ++i)
        {
        // 4)size/origin/spacing
        if (headerImageIOReader->GetDimensions(i) != this->GetDimensions(i) ||
            headerImageIOReader->GetSpacing(i) != this->GetSpacing(i) ||
            headerImageIOReader->GetOrigin(i) != this->GetOrigin(i))
          {
          errorMessage = "Size, spacing or origin does not match in file: " + m_FileName;
          break;
          }
        // 5)direction cosines
        if (headerImageIOReader->GetDirection(i) != this->GetDirection(i))
          {
          errorMessage = "Direction cosines does not match in file: " + m_FileName;
          break;
          }
        }
      }

    if (errorMessage.size())
      {
      itkExceptionMacro("Unable to paste because pasting file exists and is different. " << errorMessage);
      }
    else if ( headerImageIOReader->GetPixelType() != this->GetPixelType() )
      {
      // since there is currently poor support for pixel types in
      // MetaIO we will just warn when it does not match
      itkWarningMacro("Pixel types does not match file, but component type and number of components do.");
      }
    }
  else if (numberOfRequestedSplits != 1)
    {
    // we are going be streaming

    // need to remove the file incase the file doesn't match our
    // current header/meta data information
    if (!itksys::SystemTools::RemoveFile(m_FileName.c_str()))
      itkExceptionMacro("Unable to remove file for streaming: " << m_FileName);
    }

  return GetActualNumberOfSplitsForWritingCanStreamWrite(numberOfRequestedSplits, pasteRegion);

}


ImageIORegion StreamingImageIOBase::GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requestedRegion ) const
{
  // This implementation returns the requestedRegion if
  // "UseStreamedReading" is enabled

  ImageIORegion streamableRegion(this->m_NumberOfDimensions);
  if( !m_UseStreamedReading )
    {
    for( unsigned int i=0; i < this->m_NumberOfDimensions; i++ )
      {
      streamableRegion.SetSize( i, this->m_Dimensions[i] );
      streamableRegion.SetIndex( i, 0 );
      }
    }
  else
    {
    streamableRegion = requestedRegion;
    }

  return streamableRegion;
}


bool StreamingImageIOBase::RequestedToStream( void ) const
{
  // we choose the max dimension and then pad the smaller with ones
  //
  // This enables a 2D request from a 3D volume to get the first slice,
  // and a 4D with a 1-sized 4th dimension to equal the 3D volume
  // aswell.
  unsigned int maxNumberOfDimension = vnl_math_max( this->GetNumberOfDimensions(), this->GetIORegion().GetImageDimension() );

  ImageIORegion ioregion( maxNumberOfDimension );
  ImageIORegion largestRegion( maxNumberOfDimension );
  for(unsigned int i=0; i<maxNumberOfDimension; i++)
    {

    largestRegion.SetIndex(i, 0);
    if ( i < this->GetNumberOfDimensions() )
      {
      largestRegion.SetSize( i, this->GetDimensions(i) );
      }
    else
      {
      largestRegion.SetSize( i, 1 );
      }

    if ( i < this->GetIORegion().GetImageDimension() )
      {
      ioregion.SetIndex( i, this->GetIORegion().GetIndex(i) );
      ioregion.SetSize( i, this->GetIORegion().GetSize(i) );
      }
    else
      {
      ioregion.SetIndex( i, 0 );
      ioregion.SetSize( i, 1 );
      }

    }

  return (largestRegion != ioregion);
}

} // namespace itk