File: vtkSEPReader.cxx

package info (click to toggle)
paraview 5.13.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 544,220 kB
  • sloc: cpp: 3,374,605; ansic: 1,332,409; python: 150,381; xml: 122,166; sql: 65,887; sh: 7,317; javascript: 5,262; yacc: 4,417; java: 3,977; perl: 2,363; lex: 1,929; f90: 1,397; makefile: 170; objc: 153; tcl: 59; pascal: 50; fortran: 29
file content (568 lines) | stat: -rw-r--r-- 17,731 bytes parent folder | download | duplicates (3)
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
// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause

#include "vtkSEPReader.h"

#include <vtkByteSwap.h>
#include <vtkDataArray.h>
#include <vtkDoubleArray.h>
#include <vtkExtentTranslator.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkInformation.h>
#include <vtkInformationIntegerRequestKey.h>
#include <vtkInformationVector.h>
#include <vtkIntArray.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkStringArray.h>
#include <vtksys/FStream.hxx>
#include <vtksys/SystemTools.hxx>

#include <algorithm>
#include <cstdint>

namespace details
{
VTK_ABI_NAMESPACE_BEGIN
static constexpr std::size_t DataFormatSize[] = { 4, 4, 8 };

inline void SwapByteOrder4(char* data)
{
  std::swap(data[0], data[3]);
  std::swap(data[1], data[2]);
}
inline void SwapByteOrder8(char* data)
{
  std::swap(data[0], data[7]);
  std::swap(data[1], data[6]);
  std::swap(data[2], data[5]);
  std::swap(data[3], data[4]);
}

void TrimString(std::string& s)
{
  // trim trailing spaces
  std::size_t pos = s.find_last_not_of(" \t");
  if (pos != std::string::npos)
  {
    s = s.substr(0, pos + 1);
  }
  // trim leading spaces
  pos = s.find_first_not_of(" \t");
  if (pos != std::string::npos)
  {
    s = s.substr(pos);
  }
}

constexpr EndiannessType GetEndianessType()
{
#ifdef VTK_WORDS_BIGENDIAN
  return EndiannessType::SEP_BIG_ENDIAN;
#else
  return EndiannessType::SEP_LITTLE_ENDIAN;
#endif
}

bool DimensionIsInRange(int dim)
{
  return dim >= 0 && dim < SEP_READER_MAX_DIMENSION;
}
VTK_ABI_NAMESPACE_END
}

VTK_ABI_NAMESPACE_BEGIN

std::ostream& operator<<(std::ostream& os, details::EndiannessType& type)
{
  switch (type)
  {
    case details::EndiannessType::SEP_BIG_ENDIAN:
      os << "Big Endian";
      break;
    case details::EndiannessType::SEP_LITTLE_ENDIAN:
      os << "Little Endian";
      break;
  }
  return os;
}

vtkStandardNewMacro(vtkSEPReader);

//----------------------------------------------------------------------------
vtkSEPReader::vtkSEPReader()
{
  std::fill_n(this->DataSpacing, details::SEP_READER_MAX_DIMENSION, 1.0);
  std::fill_n(
    this->Dimensions, details::SEP_READER_MAX_DIMENSION, details::SEP_READER_MAX_DIMENSION);

  this->SetNumberOfInputPorts(0);
}

//----------------------------------------------------------------------------
void vtkSEPReader::PrintSelf(ostream& os, vtkIndent indent)
{
  const auto PrintDataType = [](const DataFormatType type) {
    switch (type)
    {
      case DataFormatType::XDR_DOUBLE:
        return "float32 [double]";
      case DataFormatType::XDR_FLOAT:
        return "float16 [float]";
      case DataFormatType::XDR_INT:
      default:
        return "int32";
    }
  };

  this->Superclass::PrintSelf(os, indent);

  os << indent << "FileName: " << (!this->FileName.empty() ? this->FileName : "(none)")
     << std::endl;

  os << indent << "Endianness: " << this->Endianness << std::endl;
  os << indent << "DataType: " << PrintDataType(this->DataFormat) << std::endl;
  os << indent << "ESize: " << this->ESize << std::endl;
  os << indent << "DataFileType: " << this->DataFileType << std::endl;
  os << indent << "BinaryFilename: " << this->BinaryFilename << std::endl;
  os << indent << "FixedDimension1ArrayId: " << this->FixedDimension1ArrayId << std::endl;
  os << indent << "FixedDimension2ArrayId: " << this->FixedDimension1ArrayId << std::endl;
  os << indent << "FixedDimension1: " << this->FixedDimension1 << std::endl;
  os << indent << "FixedDimension2: " << this->FixedDimension2 << std::endl;

  os << indent << "Dimensions: (" << this->Dimensions[0] << ", " << this->Dimensions[1] << ", "
     << this->Dimensions[2] << ")" << std::endl;

  os << indent << "DataSpacing: (" << this->DataSpacing[0] << ", " << this->DataSpacing[1] << ", "
     << this->DataSpacing[2] << ")" << std::endl;

  os << indent << "DataOrigin: (" << this->DataOrigin[0] << ", " << this->DataOrigin[1] << ", "
     << this->DataOrigin[2] << ")" << std::endl;

  os << indent << "ExtentSplitMode: " << this->ExtentSplitMode << std::endl;

  os << indent << "Labels: (" << this->Label[0] << ", " << this->Label[1] << ", " << this->Label[2]
     << ")" << std::endl;
}

//----------------------------------------------------------------------------
int vtkSEPReader::RequestInformation(vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector)
{
  this->ReadHeader();

  this->AllDimensions->SetNumberOfValues(this->ESize);
  this->AllRanges->SetNumberOfValues(this->ESize * 2 + 2);
  this->AllRanges->SetValue(0, "Dimension");
  this->AllRanges->SetValue(1, "Size");
  for (int i = 0; i < this->ESize; i++)
  {
    this->AllDimensions->SetValue(i, this->Label[i]);
    this->AllRanges->SetValue((i + 1) * 2, this->Label[i]);
    this->AllRanges->SetValue((i + 1) * 2 + 1, std::to_string(this->Dimensions[i]));
    this->FixedDimRange[1] = std::max(this->FixedDimRange[1], this->Dimensions[i]);
  }

  const auto AssignDimensionId = [this](const std::string& Name) -> int {
    auto iter = std::find(std::begin(this->Label), std::end(this->Label), Name);
    return std::distance(this->Label, iter);
  };

  this->XArrayId = AssignDimensionId(this->XDimension);
  this->YArrayId = AssignDimensionId(this->YDimension);
  this->ZArrayId = AssignDimensionId(this->ZDimension);

  this->FixedDimension1ArrayId = AssignDimensionId(this->FixedDimension1);
  this->FixedDimension2ArrayId = AssignDimensionId(this->FixedDimension2);

  this->OutputSpacing[0] = this->DataSpacing[this->XArrayId];
  this->OutputSpacing[1] = this->DataSpacing[this->YArrayId];
  this->OutputSpacing[2] = this->DataSpacing[this->ZArrayId];

  this->OutputOrigin[0] = this->DataOrigin[this->XArrayId];
  this->OutputOrigin[1] = this->DataOrigin[this->YArrayId];
  this->OutputOrigin[2] = this->DataOrigin[this->ZArrayId];

  auto extent = this->ComputeExtent();

  vtkInformation* outInfo = outputVector->GetInformationObject(0);
  outInfo->Set(vtkAlgorithm::CAN_PRODUCE_SUB_EXTENT(), 1);
  outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent.data(), 6);
  outInfo->Set(vtkDataObject::SPACING(), this->OutputSpacing, 3);
  outInfo->Set(vtkDataObject::ORIGIN(), this->OutputOrigin, 3);
  outInfo->Set(vtkExtentTranslator::UPDATE_SPLIT_MODE(), this->ExtentSplitMode);

  return true;
}

//----------------------------------------------------------------------------
std::array<std::int32_t, 6> vtkSEPReader::ComputeExtent() const
{
  std::array<std::int32_t, 6> extent = {
    0,
    this->Dimensions[this->XArrayId] - 1,
    0,
    this->Dimensions[this->YArrayId] - 1,
    0,
    this->Dimensions[this->ZArrayId] - 1,
  };

  if (this->OutputGridDimension == 2)
  {
    extent[5] = 0;
  }

  return extent;
}

//----------------------------------------------------------------------------
int vtkSEPReader::RequestData(vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector)
{
  // get the info objects
  vtkInformation* outInfo = outputVector->GetInformationObject(0);

  vtkImageData* imageData = vtkImageData::GetData(outputVector, 0);

  int* updateExtent = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT());

  return this->ReadData(imageData, updateExtent);
}

//----------------------------------------------------------------------------
bool vtkSEPReader::ReadHeader()
{
  if (this->FileName.empty())
  {
    vtkErrorMacro(<< "A FileName must be specified.");
    return false;
  }

  // Open the new file
  vtkDebugMacro(<< "Initialize: opening file " << this->FileName);
  vtksys::ifstream file;
  vtksys::SystemTools::Stat_t fs;
  if (!vtksys::SystemTools::Stat(this->FileName, &fs))
  {
#ifdef _WIN32
    file.open(this->FileName.c_str(), ios::in | ios::binary);
#else
    file.open(this->FileName.c_str(), ios::in);
#endif
  }

  if (file.fail())
  {
    vtkErrorMacro(<< "Initialize: Could not open file " << this->FileName);
    return false;
  }

  std::string line;
  while (vtksys::SystemTools::GetLineFromStream(file, line))
  {
    std::vector<std::string> splittedLine = vtksys::SystemTools::SplitString(line, '=');
    if (splittedLine.size() == 2)
    {
      std::string key = splittedLine[0];
      std::string value = splittedLine[1];
      details::TrimString(key);
      details::TrimString(value);
      if (key.length() == 2 && key[0] == 'n')
      {
        this->Dimensions[key[1] - '0' - 1] = atoi(value.c_str());
      }
      else if (key.length() == 2 && key[0] == 'd')
      {
        this->DataSpacing[key[1] - '0' - 1] = atof(value.c_str());
      }
      else if (key.length() == 2 && key[0] == 'o')
      {
        this->DataOrigin[key[1] - '0' - 1] = atof(value.c_str());
      }
      else if (vtksys::SystemTools::StringStartsWith(key.c_str(), "label"))
      {
        value.erase(std::remove(value.begin(), value.end(), '\"'), value.end());
        this->Label[key[5] - '0' - 1] = value;
      }
      else if (key == "esize")
      {
        this->ESize = atoi(value.c_str());
      }
      else if (key == "data_format")
      {
        vtksys::SystemTools::ReplaceString(value, "\"", "");
        if (value == "xdr_float" || value == "native_float")
        {
          this->DataFormat = DataFormatType::XDR_FLOAT;
        }
        else if (value == "xdr_double" || value == "native_double")
        {
          this->DataFormat = DataFormatType::XDR_DOUBLE;
        }
        else if (value == "xdr_int" || value == "native_int")
        {
          this->DataFormat = DataFormatType::XDR_INT;
        }
        if (value.substr(0, 3) == "xdr")
        {
          this->Endianness = details::EndiannessType::SEP_BIG_ENDIAN;
        }
      }
      else if (key == "endian")
      {
        vtksys::SystemTools::ReplaceString(value, "\"", "");
        if (value == "little")
        {
          this->Endianness = details::EndiannessType::SEP_LITTLE_ENDIAN;
        }
        else if (value == "big")
        {
          this->Endianness = details::EndiannessType::SEP_BIG_ENDIAN;
        }
      }
      else if (key == "data_filetype")
      {
        this->DataFileType = value;
      }
      else if (key == "in")
      {
        std::string path = vtksys::SystemTools::GetFilenamePath(this->FileName);
        if (path.empty())
        {
          this->BinaryFilename = value;
        }
        else
        {
          this->BinaryFilename = path + "/" + value;
        }
      }
    }
  }

  if (this->Label[0].empty())
  {
    vtkWarningMacro("Could not find the 1st dimension Label in "
      << this->FileName << ". Assigning default value " << this->XDimension);
    this->Label[0] = this->XDimension;
  }
  if (this->Label[1].empty())
  {
    vtkWarningMacro("Could not find the 2nd dimension Label in "
      << this->FileName << ". Assigning default value " << this->YDimension);
    this->Label[1] = this->YDimension;
  }

  if (this->OutputGridDimension == 3)
  {
    if (this->Label[2].empty())
    {
      vtkWarningMacro("Could not find the 3rd dimension Label in "
        << this->FileName << ". Assigning default value " << this->ZDimension);
      this->Label[2] = this->ZDimension;
    }
    if (this->Label[3].empty())
    {
      vtkWarningMacro("Could not find the 1st fixed dimension Label in "
        << this->FileName << ". Assigning default value " << this->FixedDimension1);
      this->Label[3] = this->FixedDimension1;
    }
  }
  else
  {
    if (this->Label[2].empty())
    {
      vtkWarningMacro("Could not find the 1st fixed dimension Label in "
        << this->FileName << ". Assigning default value " << this->FixedDimension1);
      this->Label[2] = this->FixedDimension1;
    }
    if (this->Label[3].empty())
    {
      vtkWarningMacro("Could not find the 2nd fixed dimension Label in "
        << this->FileName << ". Assigning default value " << this->FixedDimension2);
      this->Label[3] = this->FixedDimension2;
    }
  }

  for (int i = 4; i < details::SEP_READER_MAX_DIMENSION; ++i)
  {
    if (this->Label[i].empty())
    {
      this->Label[i] = "Dimension " + std::to_string(i + 1);
    }
  }

  file.close();

  return true;
}

//----------------------------------------------------------------------------
bool vtkSEPReader::ReadData(vtkImageData* imageData, int updateExtents[6])
{
  vtkDebugMacro(<< "Read data: opening file " << this->BinaryFilename);

  FILE* dataFile = vtksys::SystemTools::Fopen(this->BinaryFilename, "rb");

  if (!dataFile)
  {
    vtkErrorMacro(<< "Unable to open " << this->BinaryFilename << "!");
    return false;
  }

  vtkSmartPointer<vtkDataArray> scalars;
  switch (this->DataFormat)
  {
    case DataFormatType::XDR_FLOAT:
      scalars = vtkSmartPointer<vtkFloatArray>::New();
      break;
    case DataFormatType::XDR_INT:
      scalars = vtkSmartPointer<vtkIntArray>::New();
      break;
    case DataFormatType::XDR_DOUBLE:
      scalars = vtkSmartPointer<vtkDoubleArray>::New();
      break;
    default:
      vtkErrorMacro(<< "Unknown data type!");
      return false;
  }

  imageData->SetExtent(updateExtents);
  imageData->SetSpacing(this->OutputSpacing);
  imageData->SetOrigin(this->OutputOrigin);

  // compute the image dimensions
  int imgDims[3];
  imageData->GetDimensions(imgDims);

  // get the piece of data corresponding to the update extents
  std::size_t nbPoints = imageData->GetNumberOfPoints();
  char* data =
    new char[nbPoints * details::DataFormatSize[static_cast<std::size_t>(this->DataFormat)]];

  int DimensionsOffset[details::SEP_READER_MAX_DIMENSION];
  uint64_t acc = 1;
  for (int t = 0; t < details::SEP_READER_MAX_DIMENSION; t++)
  {
    DimensionsOffset[t] = acc;
    acc *= this->Dimensions[t];
  }

  const auto GetConstantOffsetValue = [this](const int fixedValue, const int dimensionArrayId) {
    if (details::DimensionIsInRange(fixedValue))
    {
      if (fixedValue >= dimensionArrayId)
      {
        vtkWarningMacro("Value entered for fixed dimension 1 (" + std::to_string(fixedValue) +
          ") is greater than the size of the chosen dimension (" +
          std::to_string(dimensionArrayId) + ").");
        return dimensionArrayId;
      }

      return fixedValue;
    }

    return 0;
  };

  const int fixedValue1 = GetConstantOffsetValue(
    this->FixedDimensionValue1, this->Dimensions[this->FixedDimension1ArrayId]);

  bool enableIDim = (this->XArrayId != this->FixedDimension1ArrayId);
  bool enableJDim =
    (this->YArrayId != this->FixedDimension1ArrayId && this->YArrayId != this->XArrayId);
  bool enableKDim = (this->ZArrayId != this->FixedDimension1ArrayId &&
    this->ZArrayId != this->XArrayId && this->ZArrayId != this->YArrayId);

  int minK = updateExtents[4], maxK = updateExtents[5];
  int fixedValue2 = 0;
  if (this->OutputGridDimension == 2)
  {
    // In 2D, there is no  varying k dimension, but a second fixed scalar
    minK = maxK = 0;
    enableIDim &= this->XArrayId != this->FixedDimension2ArrayId;
    enableJDim &= this->YArrayId != this->FixedDimension2ArrayId;
    enableKDim = false;
    fixedValue2 = GetConstantOffsetValue(
      this->FixedDimensionValue2, this->Dimensions[this->FixedDimension2ArrayId]);
  }

  char* dataPtr = data;
  for (int k = minK; k <= maxK; k++)
  {
    const int kVal = enableKDim ? k : 0;
    for (int j = updateExtents[2]; j <= updateExtents[3]; j++)
    {
      const int jVal = enableJDim ? j : 0;
      for (int i = updateExtents[0]; i <= updateExtents[1]; i++)
      {
        const int iVal = enableIDim ? i : 0;
        const int offset = iVal * DimensionsOffset[this->XArrayId] +
          jVal * DimensionsOffset[this->YArrayId] + kVal * DimensionsOffset[this->ZArrayId] +
          fixedValue1 * DimensionsOffset[this->FixedDimension1ArrayId] +
          fixedValue2 * DimensionsOffset[this->FixedDimension2ArrayId];
        this->ReadDataPiece(dataFile, dataPtr, offset, 1);
      }
    }
  }

  fclose(dataFile);

  // manage the endian
  if (scalars && details::GetEndianessType() != this->Endianness)
  {
    if (this->DataFormat == DataFormatType::XDR_FLOAT ||
      this->DataFormat == DataFormatType::XDR_INT)
    {
      for (std::size_t i = 0; i < nbPoints; i++)
      {
        details::SwapByteOrder4(data + i * 4);
      }
    }
    else if (this->DataFormat == DataFormatType::XDR_DOUBLE)
    {
      for (std::size_t i = 0; i < nbPoints; i++)
      {
        details::SwapByteOrder8(data + i * 8);
      }
    }
  }

  scalars->SetVoidArray(
    data, static_cast<vtkIdType>(nbPoints), 0, vtkAbstractArray::VTK_DATA_ARRAY_DELETE);
  scalars->SetName("ImageScalars");
  imageData->GetPointData()->SetScalars(scalars);

  return true;
}

//----------------------------------------------------------------------------
void vtkSEPReader::ReadDataPiece(FILE* file, char*& dataOutput, vtkIdType offset, vtkIdType range)
{
  std::size_t len = details::DataFormatSize[static_cast<std::size_t>(this->DataFormat)];
  static_cast<void>(fseek(file, static_cast<long int>(offset * len), SEEK_SET));

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
#endif

  size_t amountRead = fread(dataOutput, len, range, file);
  static_cast<void>(amountRead);

#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

  dataOutput += range * len;
}

//------------------------------------------------------------------------------
bool vtkSEPReader::CanReadFile(const char* filename)
{
  std::string extension = vtksys::SystemTools::GetFilenameLastExtension(filename);
  return extension == ".H";
}
VTK_ABI_NAMESPACE_END