vtkMPIImageReader.cxx 17.2 KB
Newer Older
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
// -*- c++ -*-
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMPIImageReader.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) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

#include "vtkMPIImageReader.h"

#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkToolkits.h"

// Include the MPI headers and then determine if MPIIO is available.
#include "vtkMPI.h"

#ifdef MPI_VERSION
#  if (MPI_VERSION >= 2)
#    define VTK_USE_MPI_IO 1
#  endif
#endif
#if !defined(VTK_USE_MPI_IO) && defined(ROMIO_VERSION)
#  define VTK_USE_MPI_IO 1
#endif
#if !defined(VTK_USE_MPI_IO) && defined(MPI_SEEK_SET)
#  define VTK_USE_MPI_IO 1
#endif

// If VTK_USE_MPI_IO is set, that means we will read the data ourself using
// MPIIO.  Otherwise, just delegate everything to the superclass.

#ifdef VTK_USE_MPI_IO

// We only need these includes if we are actually loading the data.
#include "vtkByteSwap.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMPIController.h"
#include "vtkPointData.h"
#include "vtkTransform.h"
#include "vtkType.h"
55
#include <algorithm>
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

// This macro can be wrapped around MPI function calls to easily report errors.
// Reporting errors is more important with file I/O because, unlike network I/O,
// they usually don't terminate the program.
#define MPICall(funcall) \
  { \
  int __my_result = funcall; \
  if (__my_result != MPI_SUCCESS) \
    { \
    char errormsg[MPI_MAX_ERROR_STRING]; \
    int dummy; \
    MPI_Error_string(__my_result, errormsg, &dummy); \
    vtkErrorMacro(<< "Received error when calling" << endl \
                  << #funcall << endl << endl \
                  << errormsg); \
    } \
  }

#endif // VTK_USE_MPI_IO

//=============================================================================
vtkStandardNewMacro(vtkMPIImageReader);

vtkCxxSetObjectMacro(vtkMPIImageReader, Controller, vtkMultiProcessController);
vtkCxxSetObjectMacro(vtkMPIImageReader, GroupedController,
                     vtkMultiProcessController);

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
template<class T>
inline void vtkMPIImageReaderMaskBits(T *data, vtkIdType length,
                                      vtkTypeUInt64 _mask)
{
  T mask = (T)_mask;

  // If the mask is the identity, just return.
  if ((_mask == (vtkTypeUInt64)~0UL) || (mask == (T)~0) || (_mask == 0)) return;

  for (vtkIdType i = 0; i < length; i++)
    {
    data[i] &= mask;
    }
}

// Override float and double because masking bits for them makes no sense.
101
template<>
102 103 104 105
void vtkMPIImageReaderMaskBits(float *, vtkIdType, vtkTypeUInt64)
{
  return;
}
106
template<>
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
void vtkMPIImageReaderMaskBits(double *, vtkIdType, vtkTypeUInt64)
{
  return;
}
#endif //VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
namespace {
  template<class T>
  inline T MY_ABS(T x) { return (x < 0) ? -x : x; }

  template<class T>
  inline T MY_MIN(T x, T y) { return (x < y) ? x : y; }
};
#endif //VTK_USE_MPI_IO

//=============================================================================
vtkMPIImageReader::vtkMPIImageReader()
{
  this->Controller = NULL;
  this->SetController(vtkMultiProcessController::GetGlobalController());

  this->GroupedController = NULL;
}

vtkMPIImageReader::~vtkMPIImageReader()
{
  this->SetController(NULL);
  this->SetGroupedController(NULL);
}

void vtkMPIImageReader::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "Controller: " << this->Controller << endl;
}

//-----------------------------------------------------------------------------
int vtkMPIImageReader::GetDataScalarTypeSize()
{
  switch (this->GetDataScalarType())
    {
    vtkTemplateMacro(return sizeof(VTK_TT));
    default:
      vtkErrorMacro("Unknown data type.");
      return 0;
    }
}

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::PartitionController(const int extent[6])
{
  // Number of points in the z direction of the whole data.
  int numZ = this->DataExtent[5] - this->DataExtent[4] + 1;

  if ((this->GetFileDimensionality() == 3) || (numZ == 1))
    {
    // Everyone reads from the same single file.  No need to partion controller.
    this->SetGroupedController(this->Controller);
    return;
    }

  // The following algorithm will have overflow problems if there are more
  // than 2^15 files.  I doubt anyone will ever be crazy enough to set up a
  // large 3D image with that many slice files, but just in case...
  if (numZ >= 32768)
    {
    vtkErrorMacro("I do not support more than 32768 files.");
    return;
    }

  // Hash the Z extent.  This is guaranteed to be unique for any pair of
  // extents (within the constraint given above).
  int extentHash = (  extent[4]+this->DataExtent[4]
                    + (extent[5]+this->DataExtent[4])*numZ );

  vtkMultiProcessController *subController
    = this->Controller->PartitionController(extentHash, 0);
  this->SetGroupedController(subController);
  subController->Delete();
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::PartitionController(const int *)
{
  vtkErrorMacro(<< "vtkMPIImageReader::PartitionController() called when MPIIO "
                << "not available.");
}
#endif // VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
// Technically we should be returning a 64 bit number, but I doubt any header
// will be bigger than the value stored in an unsigned int.  Thus, we just
// follow the convention of the superclass.
#ifdef VTK_USE_MPI_IO
unsigned long vtkMPIImageReader::GetHeaderSize(vtkMPIOpaqueFileHandle &file)
{
  if (this->ManualHeaderSize)
    {
    return this->HeaderSize;
    }
  else
    {
    this->ComputeDataIncrements();

    MPI_Offset size;
    MPICall(MPI_File_get_size(file.Handle, &size));
    return static_cast<unsigned long>
      (size - this->DataIncrements[this->GetFileDimensionality()]);
    }
}
#else // VTK_USE_MPI_IO
unsigned long vtkMPIImageReader::GetHeaderSize(vtkMPIOpaqueFileHandle &)
{
  vtkErrorMacro(<< "vtkMPIImageReader::GetHeaderSize() called when MPIIO "
                << "not available.");
  return 0;
}
#endif // VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::SetupFileView(vtkMPIOpaqueFileHandle &file,
                                      const int extent[6])
{
  int arrayOfSizes[3];
  int arrayOfSubSizes[3];
  int arrayOfStarts[3];

  for (int i = 0; i < this->GetFileDimensionality(); i++)
    {
    arrayOfSizes[i] = this->DataExtent[i*2+1] - this->DataExtent[i*2] + 1;
    arrayOfSubSizes[i] = extent[i*2+1] - extent[i*2] + 1;
    arrayOfStarts[i] = extent[i*2];
    }
  // Adjust for base size of data type and tuple size.
  int baseSize = this->GetDataScalarTypeSize() * this->NumberOfScalarComponents;
  arrayOfSizes[0] *= baseSize;
  arrayOfSubSizes[0] *= baseSize;
  arrayOfStarts[0] *= baseSize;

  // Create a view in MPIIO.
  MPI_Datatype view;
  MPICall(MPI_Type_create_subarray(this->GetFileDimensionality(),
                                   arrayOfSizes, arrayOfSubSizes, arrayOfStarts,
                                   MPI_ORDER_FORTRAN, MPI_BYTE, &view));
  MPICall(MPI_Type_commit(&view));
  MPICall(MPI_File_set_view(file.Handle, this->GetHeaderSize(file), MPI_BYTE,
                            view, const_cast<char *>("native"), MPI_INFO_NULL));
  MPICall(MPI_Type_free(&view));
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::SetupFileView(vtkMPIOpaqueFileHandle &, const int[6])
{
  vtkErrorMacro(<< "vtkMPIImageReader::SetupFileView() called when MPIIO "
                << "not available.");
}
#endif // VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::ReadSlice(int slice, const int extent[6], void *buffer)
{
  this->ComputeInternalFileName(slice);

  vtkMPICommunicator *mpiComm = vtkMPICommunicator::SafeDownCast(
                                    this->GroupedController->GetCommunicator());

  // Open the file for this slice.
  vtkMPIOpaqueFileHandle file;
  int result;
  result = MPI_File_open(*mpiComm->GetMPIComm()->GetHandle(),
                         this->InternalFileName, MPI_MODE_RDONLY,
                         MPI_INFO_NULL, &file.Handle);
  if (!(result == MPI_SUCCESS))
    {
    vtkErrorMacro("Could not open file: " << this->InternalFileName);
    return;
    }

  // Set up the file view based on the extents.
  this->SetupFileView(file, extent);

  // Figure out how many bytes to read.
  vtkIdType length = this->GetDataScalarTypeSize();
  length *= this->NumberOfScalarComponents;
  length *= extent[1]-extent[0]+1;
  length *= extent[3]-extent[2]+1;
  if (this->GetFileDimensionality() == 3) length *= extent[5]-extent[4]+1;

299 300
  vtkIdType pos = 0;
  while (length > pos)
301
    {
302 303 304 305 306 307 308 309 310 311 312 313 314 315
    MPI_Status stat;
    // we know this will fit in an int because it can't exceed VTK_INT_MAX.
   const int remaining = static_cast<int>(std::min(length - pos,
                                  static_cast<vtkIdType>(VTK_INT_MAX)));
   MPICall(MPI_File_read(file.Handle, (static_cast<char*>(buffer)) + pos, remaining,
                         MPI_BYTE, &stat));
   int rd = 0;
   MPICall(MPI_Get_elements(&stat, MPI_BYTE, &rd));
   if (MPI_UNDEFINED == rd)
      {
      vtkErrorMacro("Error obtaining number of values read in " << remaining <<
      "-byte read.");
      }
      pos += static_cast<vtkIdType>(rd);
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
    }

  MPICall(MPI_File_close(&file.Handle));
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::ReadSlice(int, const int [6], void *)
{
  vtkErrorMacro(<< "vtkMPIImageReader::ReadSlice() called with MPIIO "
                << "not available.");
}
#endif // VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
// This method could be made a lot more efficient.
void vtkMPIImageReader::TransformData(vtkImageData *data)
{
  if (!this->Transform) return;

  vtkDataArray *fileData = data->GetPointData()->GetScalars();
  vtkDataArray *dataData = fileData->NewInstance();
  dataData->SetName(fileData->GetName());
  dataData->SetNumberOfComponents(fileData->GetNumberOfComponents());
  dataData->SetNumberOfTuples(fileData->GetNumberOfTuples());

  int dataExtent[6];
  data->GetExtent(dataExtent);

  int fileExtent[6];
  this->ComputeInverseTransformedExtent(dataExtent, fileExtent);

  vtkIdType dataMinExtent[3];
  vtkIdType fileMinExtent[3];
  vtkIdType dataExtentSize[3];
  vtkIdType fileExtentSize[3];
  for (int i = 0; i < 3; i++)
    {
    dataMinExtent[i] = MY_MIN(dataExtent[2*i], dataExtent[2*i+1]);
    fileMinExtent[i] = MY_MIN(fileExtent[2*i], fileExtent[2*i+1]);
    dataExtentSize[i] = MY_ABS(dataExtent[2*i+1] - dataExtent[2*i]) + 1;
    fileExtentSize[i] = MY_ABS(fileExtent[2*i+1] - fileExtent[2*i]) + 1;
    }

  for (vtkIdType file_k = 0; file_k < fileExtentSize[2]; file_k++)
    {
    for (vtkIdType file_j = 0; file_j < fileExtentSize[1]; file_j++)
      {
      for (vtkIdType file_i = 0; file_i < fileExtentSize[0]; file_i++)
        {
        double fileXYZ[3];
        fileXYZ[0] = file_i + fileMinExtent[0];
        fileXYZ[1] = file_j + fileMinExtent[1];
        fileXYZ[2] = file_k + fileMinExtent[2];
        double dataXYZ[3];
        this->Transform->TransformPoint(fileXYZ, dataXYZ);
371 372 373
        vtkIdType data_i = static_cast<vtkIdType>(dataXYZ[0])-dataMinExtent[0];
        vtkIdType data_j = static_cast<vtkIdType>(dataXYZ[1])-dataMinExtent[1];
        vtkIdType data_k = static_cast<vtkIdType>(dataXYZ[2])-dataMinExtent[2];
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

        vtkIdType fileTuple
          = ((file_k*fileExtentSize[1] + file_j)*fileExtentSize[0]) + file_i;
        vtkIdType dataTuple
          = ((data_k*dataExtentSize[1] + data_j)*dataExtentSize[0]) + data_i;

        dataData->SetTuple(dataTuple, fileTuple, fileData);
        }
      }
    }

  data->GetPointData()->SetScalars(dataData);
  dataData->Delete();
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::TransformData(vtkImageData *)
{
  vtkErrorMacro(<< "vtkMPIImageReader::TransformData() called with MPIIO "
                << "not available.");
}
#endif // VTK_USE_MPI_IO

//-----------------------------------------------------------------------------
397 398
void vtkMPIImageReader::ExecuteDataWithInformation(vtkDataObject *output,
                                                   vtkInformation *outInfo)
399 400 401 402 403 404
{
#ifdef VTK_USE_MPI_IO
  vtkMPIController *MPIController
    = vtkMPIController::SafeDownCast(this->Controller);
  if (!MPIController)
    {
405
    this->Superclass::ExecuteDataWithInformation(output, outInfo);
406 407 408
    return;
    }

409
  vtkImageData *data = this->AllocateOutputData(output, outInfo);
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

  if (!this->FileName && !this->FilePattern && !this->FileNames)
    {
    vtkErrorMacro("Either a valid FileName, FileNames, or FilePattern"
                  " must be specified.");
    return;
    }

  // VTK stores images in traditional "right handed" coordinates.  That is, the
  // origin is in the lower left corner.  Many images, especially those with RGB
  // colors, have the origin in the upper right corner.  In this case, we have
  // to flip the y axis.
  vtkTransform *saveTransform = this->Transform;
  if (!this->FileLowerLeft)
    {
    vtkTransform *newTransform = vtkTransform::New();
    if (this->Transform)
      {
      newTransform->Concatenate(this->Transform);
      }
    else
      {
      newTransform->Identity();
      }
    newTransform->Scale(1.0, -1.0, 1.0);
    this->Transform = newTransform;
    }

  // Get information on data partion requested.
  int inExtent[6];
  vtkIdType inIncrements[3];
  data->GetExtent(inExtent);
  data->GetIncrements(inIncrements);
  vtkDataArray *outputDataArray = data->GetPointData()->GetScalars();
  vtkIdType numValues = (  outputDataArray->GetNumberOfComponents()
                         + outputDataArray->GetNumberOfTuples() );

  outputDataArray->SetName(this->ScalarArrayName);

  vtkDebugMacro("Reading extent: "
                << inExtent[0] << ", " << inExtent[1] << ", "
                << inExtent[2] << ", " << inExtent[3] << ", "
                << inExtent[4] << ", " << inExtent[5]);

  // Respect the Transform.
  int outExtent[6];
  vtkIdType outIncrements[3];
  this->ComputeInverseTransformedExtent(inExtent, outExtent);

  // The superclass' ComputeInverseTransformedIncrements does not give us
  // increments we can use.  It just reorders the inIncrements, (offsets in the
  // target data structure).  This does not give us valid offsets for the file.
  // Instead, we just recompute them.
  //this->ComputeInverseTransformedIncrements(inIncrements, outIncrements);
  outIncrements[0] = inIncrements[0];
  outIncrements[1] = outIncrements[0]*(MY_ABS(outExtent[1]-outExtent[0])+1);
  outIncrements[2] = outIncrements[1]*(MY_ABS(outExtent[3]-outExtent[2])+1);

  this->ComputeDataIncrements();

  // Get information on data type.
  int typeSize = this->GetDataScalarTypeSize();

  // Group processes based on which files they read.
  this->PartitionController(outExtent);

  // Get the pointer to the data buffer.  Don't worry.  We support all the
  // data types.  I am just casting it to a char (byte) so that I can do
  // byte arithmetic on the data.
  char *dataBuffer = reinterpret_cast<char *>(data->GetScalarPointer());

  if (this->GetFileDimensionality() == 3)
    {
    // Everything is in one big file.  Read it all in one shot.
    this->ReadSlice(0, outExtent, dataBuffer);
    }
  else // this->GetFileDimensionality() == 2
    {
    // Read everything slice-by-slice.
    char *ptr = dataBuffer;
    for (int slice = outExtent[4]; slice <= outExtent[5]; slice++)
      {
      this->UpdateProgress(  (0.9*(slice-outExtent[4]))
                           / (outExtent[5]-outExtent[4]+1));
      this->ReadSlice(slice, outExtent, ptr);
      ptr += typeSize*outIncrements[2];
      }
    }

  this->UpdateProgress(0.9);

  // Swap bytes as necessary.
  if (this->GetSwapBytes() && typeSize > 1)
    {
    vtkByteSwap::SwapVoidRange(dataBuffer, numValues, typeSize);
    }

  // Mask bits as necessary.
  switch (this->GetDataScalarType())
    {
    vtkTemplateMacro(vtkMPIImageReaderMaskBits((VTK_TT *)dataBuffer, numValues,
                                               this->DataMask));
    }

  // Perform permutation transformation of data if necessary.
  this->TransformData(data);

  if (!this->FileLowerLeft)
    {
    this->Transform->Delete();
    this->Transform = saveTransform;
    }

  // Done with this for now.
  this->SetGroupedController(NULL);
#else // VTK_USE_MPI_IO
526
  this->Superclass::ExecuteDataWithInformation(output, outInfo);
527 528
#endif // VTK_USE_MPI_IO
}