/
DxReader.cpp
602 lines (529 loc) · 19.3 KB
/
DxReader.cpp
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
/* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of BlueQuartz Software, the US Air Force, nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The code contained herein was partially funded by the followig contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "DxReader.h"
#include <QtCore/QDateTime>
#include <QtCore/QFileInfo>
#include "SIMPLib/Common/Constants.h"
#include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h"
#include "SIMPLib/FilterParameters/FloatVec3FilterParameter.h"
#include "SIMPLib/FilterParameters/InputFileFilterParameter.h"
#include "SIMPLib/FilterParameters/SeparatorFilterParameter.h"
#include "SIMPLib/FilterParameters/StringFilterParameter.h"
#include "SIMPLib/Geometry/ImageGeom.h"
#include "ImportExport/ImportExportConstants.h"
#include "ImportExport/ImportExportVersion.h"
/* ############## Start Private Implementation ############################### */
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
class DxReaderPrivate
{
Q_DISABLE_COPY(DxReaderPrivate)
Q_DECLARE_PUBLIC(DxReader)
DxReader* const q_ptr;
DxReaderPrivate(DxReader* ptr);
QVector<size_t> m_Dims;
QString m_InputFile_Cache;
QDateTime m_LastRead;
};
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
DxReaderPrivate::DxReaderPrivate(DxReader* ptr)
: q_ptr(ptr)
, m_InputFile_Cache("")
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
DxReader::DxReader()
: m_VolumeDataContainerName(SIMPL::Defaults::ImageDataContainerName)
, m_CellAttributeMatrixName(SIMPL::Defaults::CellAttributeMatrixName)
, m_InputFile("")
, m_FileWasRead(false)
, m_FeatureIdsArrayName(SIMPL::CellData::FeatureIds)
, d_ptr(new DxReaderPrivate(this))
{
m_Origin.x = 0.0f;
m_Origin.y = 0.0f;
m_Origin.z = 0.0f;
m_Resolution.x = 1.0f;
m_Resolution.y = 1.0f;
m_Resolution.z = 1.0f;
m_Dims[0] = 0;
m_Dims[1] = 0;
m_Dims[2] = 0;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
DxReader::~DxReader() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
SIMPL_PIMPL_PROPERTY_DEF(DxReader, QVector<size_t>, Dims)
SIMPL_PIMPL_PROPERTY_DEF(DxReader, QString, InputFile_Cache)
SIMPL_PIMPL_PROPERTY_DEF(DxReader, QDateTime, LastRead)
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::setupFilterParameters()
{
FileReader::setupFilterParameters();
FilterParameterVector parameters;
parameters.push_back(SIMPL_NEW_INPUT_FILE_FP("Input File", InputFile, FilterParameter::Parameter, DxReader, "*.dx"));
parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP("Origin", Origin, FilterParameter::Parameter, DxReader));
parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP("Resolution", Resolution, FilterParameter::Parameter, DxReader));
parameters.push_back(SIMPL_NEW_STRING_FP("Data Container", VolumeDataContainerName, FilterParameter::CreatedArray, DxReader));
parameters.push_back(SeparatorFilterParameter::New("Cell Data", FilterParameter::CreatedArray));
parameters.push_back(SIMPL_NEW_STRING_FP("Cell Attribute Matrix", CellAttributeMatrixName, FilterParameter::CreatedArray, DxReader));
parameters.push_back(SIMPL_NEW_STRING_FP("Cell Feature Ids", FeatureIdsArrayName, FilterParameter::CreatedArray, DxReader));
setFilterParameters(parameters);
}
// -----------------------------------------------------------------------------
void DxReader::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
reader->openFilterGroup(this, index);
setVolumeDataContainerName(reader->readString("VolumeDataContainerName", getVolumeDataContainerName()));
setCellAttributeMatrixName(reader->readString("CellAttributeMatrixName", getCellAttributeMatrixName()));
setFeatureIdsArrayName(reader->readString("FeatureIdsArrayName", getFeatureIdsArrayName()));
setInputFile(reader->readString("InputFile", getInputFile()));
setOrigin(reader->readFloatVec3("Origin", getOrigin()));
setResolution(reader->readFloatVec3("Resolution", getResolution()));
reader->closeFilterGroup();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::updateCellInstancePointers()
{
setErrorCondition(0);
setWarningCondition(0);
if(nullptr != m_FeatureIdsPtr.lock()) /* Validate the Weak Pointer wraps a non-nullptr pointer to a DataArray<T> object */
{
m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0);
} /* Now assign the raw pointer to data from the DataArray<T> object */
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::flushCache()
{
setInputFile_Cache("");
QVector<size_t> v;
v.push_back(0);
v.push_back(0);
v.push_back(0);
setDims(v);
setLastRead(QDateTime());
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::initialize()
{
if(m_InStream.isOpen())
{
m_InStream.close();
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::dataCheck()
{
setErrorCondition(0);
setWarningCondition(0);
DataArrayPath tempPath;
DataContainer::Pointer m = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getVolumeDataContainerName());
if(getErrorCondition() < 0)
{
return;
}
ImageGeom::Pointer image = ImageGeom::CreateGeometry(SIMPL::Geometry::ImageGeometry);
m->setGeometry(image);
QFileInfo fi(getInputFile());
if(getInputFile().isEmpty())
{
QString ss = QObject::tr("The input file must be set");
setErrorCondition(-387);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
}
else if(!fi.exists())
{
QString ss = QObject::tr("The input file does not exist");
setErrorCondition(-388);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
}
if(m_InStream.isOpen())
{
m_InStream.close();
}
if(!getInputFile().isEmpty() && fi.exists())
{
QDateTime lastModified(fi.lastModified());
if(getInputFile() == getInputFile_Cache() && getLastRead().isValid() && lastModified.msecsTo(getLastRead()) >= 0)
{
// We are reading from the cache, so set the FileWasRead flag to false
m_FileWasRead = false;
QVector<size_t> v = getDims();
ImageGeom::Pointer imageGeom = m->getGeometryAs<ImageGeom>();
if(nullptr != imageGeom.get())
{
imageGeom->setDimensions(v.data());
}
}
else
{
// We are reading from the file, so set the FileWasRead flag to true
m_FileWasRead = true;
// We need to read the header of the input file to get the dimensions
m_InStream.setFileName(getInputFile());
if(!m_InStream.open(QIODevice::ReadOnly | QIODevice::Text))
{
QString ss = QObject::tr("Error opening input file: %1").arg(getInputFile());
setErrorCondition(-100);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
return;
}
int32_t error = readHeader();
m_InStream.close();
if(error < 0)
{
setErrorCondition(error);
QString ss = QObject::tr("Error occurred trying to parse the dimensions from the input file. Is the input file a Dx file?");
notifyErrorMessage(getHumanLabel(), ss, -11000);
}
// Set the file path and time stamp into the cache
setLastRead(QDateTime::currentDateTime());
setInputFile_Cache(getInputFile());
}
}
QVector<size_t> tDims = getDims();
m->createNonPrereqAttributeMatrix(this, getCellAttributeMatrixName(), tDims, AttributeMatrix::Type::Cell);
if(getErrorCondition() < 0)
{
return;
}
QVector<size_t> cDims(1, 1);
tempPath.update(getVolumeDataContainerName(), getCellAttributeMatrixName(), getFeatureIdsArrayName());
m_FeatureIdsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter, int32_t>(this, tempPath, 0, cDims);
if(nullptr != m_FeatureIdsPtr.lock())
{
m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0);
}
m->getGeometryAs<ImageGeom>()->setResolution(std::make_tuple(m_Resolution.x, m_Resolution.y, m_Resolution.z));
m->getGeometryAs<ImageGeom>()->setOrigin(std::make_tuple(m_Origin.x, m_Origin.y, m_Origin.z));
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::preflight()
{
setInPreflight(true);
emit preflightAboutToExecute();
emit updateFilterParameters(this);
dataCheck();
emit preflightExecuted();
setInPreflight(false);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DxReader::execute()
{
int32_t err = 0;
setErrorCondition(err);
dataCheck();
if(getErrorCondition() < 0)
{
return;
}
m_InStream.setFileName(getInputFile());
if(!m_InStream.open(QIODevice::ReadOnly | QIODevice::Text))
{
QString ss = QObject::tr("Error opening input file '%1'").arg(getInputFile());
setErrorCondition(-100);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
return;
}
err = readHeader();
if(err < 0)
{
m_InStream.close();
return;
}
err = readFile();
m_InStream.close();
if(err < 0)
{
return;
}
}
//-----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int32_t DxReader::readHeader()
{
QString ss;
DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVolumeDataContainerName());
int32_t error = 0;
QByteArray buf;
QList<QByteArray> tokens; /* vector to store the split data */
bool ok = false;
// Process the header information and look for the QString "counts"
// Then read the data size after that
size_t nx = 0;
size_t ny = 0;
size_t nz = 0;
bool done = false;
while(!m_InStream.atEnd() && !done)
{
buf = m_InStream.readLine();
buf = buf.trimmed();
tokens = buf.split(' ');
// continue until we find the keyword
for(qint32 i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "counts")
{
nz = tokens[i + 1].toInt(&ok, 10);
ny = tokens[i + 2].toInt(&ok, 10);
nx = tokens[i + 3].toInt(&ok, 10);
done = true;
break;
}
}
}
// qDebug() << "INFO: DX data dimensions: " ;
// qDebug() << "nz= " << nz ;
// qDebug() << "ny= " << ny ;
// qDebug() << "nx= " << nx ;
// The DX file has a unique format of 20 entries on each line. I have
// no idea who initiated this insanity but I am about to perpetuate
// it.
//
// The most simple thing to do is to read the entire dataset into one
// long vector and then read that vector to assign values to the grid
// ADR: 6 Sep 08; time to make the input much more general!
// equivalent to list-direcvted input in Fortran, actually !!
qint32 pos1 = 0;
while(pos1 == 0 && !m_InStream.atEnd())
{
// continue until we find the keyword
buf = m_InStream.readLine();
buf = buf.simplified();
tokens = buf.split(' ');
for(qint32 i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "items")
{
pos1 = i;
}
}
// Read the next line of the header if we did not find the keyword
// in the line
if(pos1 == 0)
{
if(tokens.size() == 20)
{
ss = QObject::tr("Unable to locate the last header line");
setErrorCondition(-8);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
m_InStream.close();
return getErrorCondition();
}
}
} // when we get here, we are looking at data
if(pos1 != 0)
{
error = 0;
}
// Set the values into the cache, so that they can be used later
QVector<size_t> v;
v.push_back(nx);
v.push_back(ny);
v.push_back(nz);
setDims(v);
if(nullptr != m.get())
{
ImageGeom::Pointer imageGeom = m->getGeometryAs<ImageGeom>();
if(nullptr != imageGeom.get())
{
imageGeom->setDimensions(v.data());
}
}
return error;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int32_t DxReader::readFile()
{
DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getVolumeDataContainerName());
bool finished_header = true;
bool finished_data = false;
size_t index = 0;
// Resize the Cell Attribute Matrix based on the number of points about to be read.
QVector<size_t> tDims(3, 0);
tDims[0] = m->getGeometryAs<ImageGeom>()->getXPoints();
tDims[1] = m->getGeometryAs<ImageGeom>()->getYPoints();
tDims[2] = m->getGeometryAs<ImageGeom>()->getZPoints();
m->getAttributeMatrix(getCellAttributeMatrixName())->resizeAttributeArrays(tDims);
updateCellInstancePointers();
if(getErrorCondition() < 0)
{
m_InStream.close();
return -1;
}
bool ok = false;
QByteArray buf = m_InStream.readLine();
size_t xIdx = 0, yIdx = 0, zIdx = 0;
size_t count = 0;
while(buf.size() > 0 && !m_InStream.atEnd())
{
// Get the remaining lines of the header and ignore
buf = buf.simplified();
QList<QByteArray> tokens = buf.split(' ');
size_t total = m->getGeometryAs<ImageGeom>()->getNumberOfElements();
if(count == total || (finished_header && !tokens.empty() && tokens[0] == "attribute"))
{
finished_data = true;
}
if(finished_header && !finished_data)
{
qint32 size = tokens.size();
for(qint32 in_spins = 0; in_spins < size; in_spins++)
{
int32_t fId = tokens[in_spins].toInt(&ok, 10);
count++;
index = (zIdx * tDims[0] * tDims[1]) + (tDims[0] * yIdx) + xIdx;
m_FeatureIds[index] = fId;
zIdx++; // Increment zIdx and then check all the indices and wrap back to zero if needed.
if(zIdx == tDims[2])
{
zIdx = 0;
yIdx++;
}
if(yIdx == tDims[1])
{
yIdx = 0;
xIdx++;
}
if(xIdx == tDims[0])
{
xIdx = 0;
Q_ASSERT(count == total);
}
}
}
buf = m_InStream.readLine();
}
if(count != static_cast<size_t>(m->getGeometryAs<ImageGeom>()->getNumberOfElements()))
{
QString ss = QObject::tr("Data size does not match header dimensions\t%1\t%2").arg(index).arg(m->getGeometryAs<ImageGeom>()->getNumberOfElements());
setErrorCondition(-495);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
m_InStream.close();
return getErrorCondition();
}
m_InStream.close();
return 0;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
AbstractFilter::Pointer DxReader::newFilterInstance(bool copyFilterParameters) const
{
DxReader::Pointer filter = DxReader::New();
if(copyFilterParameters)
{
copyFilterParameterInstanceVariables(filter.get());
}
return filter;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getCompiledLibraryName() const
{
return ImportExportConstants::ImportExportBaseName;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getBrandingString() const
{
return "IO";
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getFilterVersion() const
{
QString version;
QTextStream vStream(&version);
vStream << ImportExport::Version::Major() << "." << ImportExport::Version::Minor() << "." << ImportExport::Version::Patch();
return version;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getGroupName() const
{
return SIMPL::FilterGroups::IOFilters;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QUuid DxReader::getUuid()
{
return QUuid("{ba2238f8-a20f-5f2f-ac9f-43ed458460f7}");
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getSubGroupName() const
{
return SIMPL::FilterSubGroups::InputFilters;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString DxReader::getHumanLabel() const
{
return "Import Dx File (Feature Ids)";
}