Nektar++
Loading...
Searching...
No Matches
Public Member Functions | Private Member Functions | Private Attributes | Static Private Attributes | List of all members
Nektar::LibUtilities::PtsIOHdf5 Class Reference

Writes a time series of point data to a HDF5 file. More...

#include <PtsIOHdf5.h>

Public Member Functions

 PtsIOHdf5 (LibUtilities::CommSharedPtr pComm, const std::string &fileName, const NekDouble time, const PtsFieldSharedPtr &ptsField, const size_t expectedRows=0)
 Opens fileName and prepares it to receive the fields described by ptsField, discarding any data at or after time. expectedRows is an optional hint at how many times will be written, used only to choose a chunk size; zero means it is not known.
 
 ~PtsIOHdf5 ()
 
void Write (const PtsFieldSharedPtr &ptsField, const NekDouble time)
 Appends the field values held by ptsField at time time.
 
void Close ()
 Flushes and closes the file. Called by the destructor.
 

Private Member Functions

size_t ChunkRows (const size_t rowLength, const size_t expectedRows) const
 Number of time rows in a single chunk.
 
NekDouble ReadTime (const H5::DataSetSharedPtr &dataSet, const hsize_t row) const
 Reads the time stored in the first column of row row.
 
hsize_t FindRestartRow (const H5::DataSetSharedPtr &dataSet, const hsize_t nRows, const NekDouble time) const
 Index of the first row whose time is at or after time.
 

Private Attributes

LibUtilities::CommSharedPtr m_comm
 
const std::string m_fileName
 Name of file.
 
bool m_isRoot = false
 True on the process that owns the file.
 
size_t m_nPts = 0
 Number of points, fixed when the file is opened.
 
hsize_t m_row = 0
 Index of the next row to be written.
 
H5::FileSharedPtr m_file
 
H5::GroupSharedPtr m_timeGroup
 
std::vector< H5::DataSetSharedPtr > m_fieldData
 
std::vector< NekDouble > m_rowBuffer
 Scratch space for one row: time followed by one value per point.
 

Static Private Attributes

static constexpr size_t TargetChunkBytes = 64 * 1024
 Target size of a single HDF5 chunk, in bytes. Chunks much smaller than this make the chunk index dominate the file; chunks much larger risk exceeding the default chunk cache.
 
static constexpr size_t MinChunkRows = 64
 Fewest time rows in a chunk. A chunk holding only a handful of rows costs more in index entries than it saves in allocated space.
 

Detailed Description

Writes a time series of point data to a HDF5 file.

The file is laid out as

NEKTAR/
  COORDINATES/
    x          - dataset, [npoints]
    y          - dataset, [npoints]
    z          - dataset, [npoints]
  TIME-DATA/
    <field1>   - dataset, [ntimes x (npoints + 1)]
    ...
    <fieldN>   - dataset, [ntimes x (npoints + 1)]

The coordinates are fixed for the lifetime of the file and are written once. Each field is a single two-dimensional dataset, extensible along the time dimension, whose first column holds the time and whose remaining columns hold that field's value at each point. Storing the time in the datasets themselves means a row is self-describing and the whole time history of a field can be read with a single call.

Definition at line 74 of file PtsIOHdf5.h.

Constructor & Destructor Documentation

◆ PtsIOHdf5()

Nektar::LibUtilities::PtsIOHdf5::PtsIOHdf5 ( LibUtilities::CommSharedPtr  pComm,
const std::string &  fileName,
const NekDouble  time,
const PtsFieldSharedPtr &  ptsField,
const size_t  expectedRows = 0 
)

Opens fileName and prepares it to receive the fields described by ptsField, discarding any data at or after time. expectedRows is an optional hint at how many times will be written, used only to choose a chunk size; zero means it is not known.

Opens the file and prepares it to receive data.

If fileName does not exist it is created. If it does exist, the coordinates it holds are checked against ptsField and any rows at or after time are discarded, so that a simulation restarted from an earlier time overwrites the history it is about to recompute rather than appending to it.

Only the root process touches the file; see Write().

Parameters
pCommCommunicator
fileNameName of file
timePhysical time at which output will start
ptsFieldSupplies the point coordinates and the field names. The field values it holds are not used.
expectedRowsHint at the number of times that will be written, or zero if unknown. Only affects the chunk size.

Definition at line 64 of file PtsIOHdf5.cpp.

68 : m_comm(pComm), m_fileName(fileName)
69{
70 m_isRoot = m_comm->TreatAsRankZero();
71
72 if (!m_isRoot)
73 {
74 return;
75 }
76
77 m_nPts = ptsField->GetNpoints();
78 const size_t nFields = ptsField->GetNFields();
79 const size_t nDim = ptsField->GetDim();
80 const hsize_t rowLen = m_nPts + 1;
81 const hsize_t chunkLen = ChunkRows(rowLen, expectedRows);
82
83 m_rowBuffer.resize(rowLen, 0.0);
84
85 // Open an existing file, or create a new one
86 if (fs::exists(fs::path(m_fileName)))
87 {
88 m_file = H5::File::Open(m_fileName, H5F_ACC_RDWR);
89 }
90 else
91 {
92 m_file = H5::File::Create(m_fileName, H5F_ACC_TRUNC);
93 }
94
95 // ContainsDataSet tests for a link of this name, so it answers for a
96 // group just as well as for a dataset
97 H5::GroupSharedPtr root = m_file->ContainsDataSet("NEKTAR")
98 ? m_file->OpenGroup("NEKTAR")
99 : m_file->CreateGroup("NEKTAR");
100
101 // Coordinates are fixed for the lifetime of the file, so write them on
102 // the first visit and check them for consistency on any later one
103 const std::vector<std::string> dimName{"x", "y", "z"};
104 H5::GroupSharedPtr coordGroup = root->ContainsDataSet("COORDINATES")
105 ? root->OpenGroup("COORDINATES")
106 : root->CreateGroup("COORDINATES");
107
108 for (size_t i = 0; i < nDim; ++i)
109 {
110 if (coordGroup->ContainsDataSet(dimName[i]))
111 {
112 H5::DataSetSharedPtr coordData =
113 coordGroup->OpenDataSet(dimName[i]);
114 ASSERTL0(coordData->GetSpace()->GetSize() == m_nPts,
115 "The number of points in dataset '" + dimName[i] +
116 "' of file '" + m_fileName +
117 "' does not match the number of history points.");
118 continue;
119 }
120
122 H5::DataSetSharedPtr coordData = coordGroup->CreateDataSet(
123 dimName[i], H5::DataType::OfObject(NekDouble{0.}), space);
124
125 std::vector<NekDouble> coords(m_nPts, 0.0);
126 for (size_t j = 0; j < m_nPts; ++j)
127 {
128 coords[j] = ptsField->GetPointVal(i, j);
129 }
130 space->SelectRange(0, m_nPts);
131 coordData->Write(coords, space);
132 }
133
134 m_timeGroup = root->ContainsDataSet("TIME-DATA")
135 ? root->OpenGroup("TIME-DATA")
136 : root->CreateGroup("TIME-DATA");
137
138 // Open or create one extensible dataset per field. The number of rows
139 // already present is taken from the first field that exists; a field that
140 // has only just been added to the session starts empty and is grown to
141 // match, with HDF5 filling the rows it missed with zeros.
142 bool haveRows = false;
143 hsize_t nRowsFile = 0;
144
145 for (size_t i = 0; i < nFields; ++i)
146 {
147 const std::string fieldName = ptsField->GetFieldName(i);
148
149 if (m_timeGroup->ContainsDataSet(fieldName))
150 {
151 H5::DataSetSharedPtr fieldData =
152 m_timeGroup->OpenDataSet(fieldName);
153 std::vector<hsize_t> dims = fieldData->GetSpace()->GetDims();
154
155 ASSERTL0(dims.size() == 2 && dims[1] == rowLen,
156 "Dataset '" + fieldName + "' of file '" + m_fileName +
157 "' does not hold the expected number of history "
158 "points.");
159
160 if (!haveRows)
161 {
162 nRowsFile = dims[0];
163 haveRows = true;
164 }
165
166 m_fieldData.push_back(fieldData);
167 continue;
168 }
169
170 // Unlimited along time, fixed along the row
171 std::vector<hsize_t> dims{0, rowLen};
172 std::vector<hsize_t> maxDims{H5S_UNLIMITED, rowLen};
173 std::vector<hsize_t> chunk{chunkLen, rowLen};
174
176 createPL->SetChunk(chunk);
177
178 m_fieldData.push_back(m_timeGroup->CreateDataSet(
179 fieldName, H5::DataType::OfObject(NekDouble{0.}),
180 std::make_shared<H5::DataSpace>(dims, maxDims), createPL));
181 }
182
183 // Drop any rows at or after the restart time
184 m_row = haveRows ? FindRestartRow(m_fieldData[0], nRowsFile, time) : 0;
185
186 for (auto &fieldData : m_fieldData)
187 {
188 fieldData->SetExtent(std::vector<hsize_t>{m_row, rowLen});
189 }
190
191 m_file->Flush();
192}
#define ASSERTL0(condition, msg)
static DataSpaceSharedPtr OneD(hsize_t size)
Definition H5.cpp:406
static DataTypeSharedPtr OfObject(const T &obj)
Definition H5.h:407
static FileSharedPtr Open(const std::string &filename, unsigned mode, PListSharedPtr accessPL=PList::Default())
Definition H5.cpp:642
static FileSharedPtr Create(const std::string &filename, unsigned mode, PListSharedPtr createPL=PList::Default(), PListSharedPtr accessPL=PList::Default())
Definition H5.cpp:633
static PListSharedPtr DatasetCreate()
Properties for dataset creation.
Definition H5.cpp:97
bool m_isRoot
True on the process that owns the file.
Definition PtsIOHdf5.h:118
std::vector< H5::DataSetSharedPtr > m_fieldData
Definition PtsIOHdf5.h:128
LibUtilities::CommSharedPtr m_comm
Definition PtsIOHdf5.h:112
hsize_t FindRestartRow(const H5::DataSetSharedPtr &dataSet, const hsize_t nRows, const NekDouble time) const
Index of the first row whose time is at or after time.
hsize_t m_row
Index of the next row to be written.
Definition PtsIOHdf5.h:124
const std::string m_fileName
Name of file.
Definition PtsIOHdf5.h:115
std::vector< NekDouble > m_rowBuffer
Scratch space for one row: time followed by one value per point.
Definition PtsIOHdf5.h:131
size_t ChunkRows(const size_t rowLength, const size_t expectedRows) const
Number of time rows in a single chunk.
size_t m_nPts
Number of points, fixed when the file is opened.
Definition PtsIOHdf5.h:121
H5::GroupSharedPtr m_timeGroup
Definition PtsIOHdf5.h:127
std::shared_ptr< DataSpace > DataSpaceSharedPtr
Definition H5.h:78
std::shared_ptr< PList > PListSharedPtr
Definition H5.h:92
std::shared_ptr< Group > GroupSharedPtr
Definition FieldIOHdf5.h:48
std::shared_ptr< DataSet > DataSetSharedPtr
Definition H5.h:90

References ASSERTL0, ChunkRows(), Nektar::LibUtilities::H5::File::Create(), Nektar::LibUtilities::H5::PList::DatasetCreate(), FindRestartRow(), m_comm, m_fieldData, m_file, m_fileName, m_isRoot, m_nPts, m_row, m_rowBuffer, m_timeGroup, Nektar::LibUtilities::H5::DataType::OfObject(), Nektar::LibUtilities::H5::DataSpace::OneD(), and Nektar::LibUtilities::H5::File::Open().

◆ ~PtsIOHdf5()

Nektar::LibUtilities::PtsIOHdf5::~PtsIOHdf5 ( )

Definition at line 197 of file PtsIOHdf5.cpp.

198{
199 Close();
200}
void Close()
Flushes and closes the file. Called by the destructor.

References Close().

Member Function Documentation

◆ ChunkRows()

size_t Nektar::LibUtilities::PtsIOHdf5::ChunkRows ( const size_t  rowLength,
const size_t  expectedRows 
) const
private

Number of time rows in a single chunk.

HDF5 allocates a chunk as soon as any part of it is written, so a chunk sized for a long run would be mostly empty after a short one. The chunk is therefore capped at PtsIOHdf5::TargetChunkBytes, which keeps the chunk index small, and then reduced to expectedRows where that is known to be smaller, subject to a floor of PtsIOHdf5::MinChunkRows.

Definition at line 211 of file PtsIOHdf5.cpp.

213{
214 const size_t maxRows =
215 std::max<size_t>(1, TargetChunkBytes / (rowLength * sizeof(NekDouble)));
216
217 if (expectedRows == 0 || expectedRows >= maxRows)
218 {
219 return maxRows;
220 }
221
222 return std::min(maxRows, std::max(expectedRows, MinChunkRows));
223}
static constexpr size_t TargetChunkBytes
Target size of a single HDF5 chunk, in bytes. Chunks much smaller than this make the chunk index domi...
Definition PtsIOHdf5.h:100
static constexpr size_t MinChunkRows
Fewest time rows in a chunk. A chunk holding only a handful of rows costs more in index entries than ...
Definition PtsIOHdf5.h:104

References MinChunkRows, and TargetChunkBytes.

Referenced by PtsIOHdf5().

◆ Close()

void Nektar::LibUtilities::PtsIOHdf5::Close ( )

Flushes and closes the file. Called by the destructor.

Definition at line 333 of file PtsIOHdf5.cpp.

334{
335 m_fieldData.clear();
336 m_timeGroup.reset();
337 m_file.reset();
338}

References m_fieldData, m_file, and m_timeGroup.

Referenced by ~PtsIOHdf5().

◆ FindRestartRow()

hsize_t Nektar::LibUtilities::PtsIOHdf5::FindRestartRow ( const H5::DataSetSharedPtr &  dataSet,
const hsize_t  nRows,
const NekDouble  time 
) const
private

Index of the first row whose time is at or after time.

Times increase down the dataset, so this is a binary search; only the rows it visits are read, rather than the whole time column.

Definition at line 247 of file PtsIOHdf5.cpp.

250{
251 hsize_t lo = 0, hi = nRows;
252
253 while (lo < hi)
254 {
255 const hsize_t mid = lo + (hi - lo) / 2;
256 const NekDouble tTest = ReadTime(dataSet, mid);
257
258 // A relative comparison, so that the row written at exactly the
259 // restart time is recognised whatever the magnitude of the time
260 if (tTest > time || IsRealEqual(tTest, time))
261 {
262 hi = mid;
263 }
264 else
265 {
266 lo = mid + 1;
267 }
268 }
269
270 return lo;
271}
static void mid(int m, int a, int b)
NekDouble ReadTime(const H5::DataSetSharedPtr &dataSet, const hsize_t row) const
Reads the time stored in the first column of row row.
bool IsRealEqual(T1 &&lhs, T2 &&rhs, const unsigned int factor=NekConstants::kNekFloatCompFact)
compare reals of same type with relative tolerance

References hi, Nektar::LibUtilities::IsRealEqual(), lo, mid(), and ReadTime().

Referenced by PtsIOHdf5().

◆ ReadTime()

NekDouble Nektar::LibUtilities::PtsIOHdf5::ReadTime ( const H5::DataSetSharedPtr &  dataSet,
const hsize_t  row 
) const
private

Reads the time stored in the first column of row row.

Definition at line 228 of file PtsIOHdf5.cpp.

230{
231 H5::DataSpaceSharedPtr space = dataSet->GetSpace();
232 space->SelectRange(std::vector<hsize_t>{row, 0},
233 std::vector<hsize_t>{1, 1});
234
235 std::vector<NekDouble> value;
236 dataSet->Read(value, space);
237
238 return value[0];
239}

Referenced by FindRestartRow().

◆ Write()

void Nektar::LibUtilities::PtsIOHdf5::Write ( const PtsFieldSharedPtr &  ptsField,
const NekDouble  time 
)

Appends the field values held by ptsField at time time.

Appends one row of field values.

Each field's dataset is extended by a single row, which is then filled with time followed by that field's value at each point.

Note that the file is written by the root process, so distributed data must be communicated to it before calling this function. This limitation might be relaxed in the future: because each field is one dataset, each process could write the points it owns directly as a collective operation.

Parameters
ptsFieldPtsField holding the values for this time
timePhysical time

Definition at line 287 of file PtsIOHdf5.cpp.

288{
289 if (!m_isRoot)
290 {
291 return;
292 }
293
294 ASSERTL1(m_file, "PtsIOHdf5 has been closed.");
295 ASSERTL0(ptsField->GetNpoints() == m_nPts &&
296 ptsField->GetNFields() == m_fieldData.size(),
297 "PtsField does not match the file opened by PtsIOHdf5.");
298
299 const hsize_t rowLen = m_nPts + 1;
300 const size_t nDim = ptsField->GetDim();
301
302 const std::vector<hsize_t> dims{m_row + 1, rowLen};
303 const std::vector<hsize_t> start{m_row, 0};
304 const std::vector<hsize_t> count{1, rowLen};
305
306 m_rowBuffer[0] = time;
307
308 for (size_t i = 0; i < m_fieldData.size(); ++i)
309 {
310 const Array<OneD, NekDouble> field = ptsField->GetPts(i + nDim);
311 for (size_t j = 0; j < m_nPts; ++j)
312 {
313 m_rowBuffer[j + 1] = field[j];
314 }
315
316 m_fieldData[i]->SetExtent(dims);
317
318 // The dataspace must be re-read after the extent changes
319 H5::DataSpaceSharedPtr space = m_fieldData[i]->GetSpace();
320 space->SelectRange(start, count);
321 m_fieldData[i]->Write(m_rowBuffer, space);
322 }
323
324 ++m_row;
325
326 // Keep the file usable, and the data safe, if the run is interrupted
327 m_file->Flush();
328}
#define ASSERTL1(condition, msg)
Assert Level 1 – Debugging which is used whether in FULLDEBUG or DEBUG compilation mode....

References ASSERTL0, ASSERTL1, m_fieldData, m_file, m_isRoot, m_nPts, m_row, and m_rowBuffer.

Member Data Documentation

◆ m_comm

LibUtilities::CommSharedPtr Nektar::LibUtilities::PtsIOHdf5::m_comm
private

Definition at line 112 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5().

◆ m_fieldData

std::vector<H5::DataSetSharedPtr> Nektar::LibUtilities::PtsIOHdf5::m_fieldData
private

Definition at line 128 of file PtsIOHdf5.h.

Referenced by Close(), PtsIOHdf5(), and Write().

◆ m_file

H5::FileSharedPtr Nektar::LibUtilities::PtsIOHdf5::m_file
private

Definition at line 126 of file PtsIOHdf5.h.

Referenced by Close(), PtsIOHdf5(), and Write().

◆ m_fileName

const std::string Nektar::LibUtilities::PtsIOHdf5::m_fileName
private

Name of file.

Definition at line 115 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5().

◆ m_isRoot

bool Nektar::LibUtilities::PtsIOHdf5::m_isRoot = false
private

True on the process that owns the file.

Definition at line 118 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5(), and Write().

◆ m_nPts

size_t Nektar::LibUtilities::PtsIOHdf5::m_nPts = 0
private

Number of points, fixed when the file is opened.

Definition at line 121 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5(), and Write().

◆ m_row

hsize_t Nektar::LibUtilities::PtsIOHdf5::m_row = 0
private

Index of the next row to be written.

Definition at line 124 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5(), and Write().

◆ m_rowBuffer

std::vector<NekDouble> Nektar::LibUtilities::PtsIOHdf5::m_rowBuffer
private

Scratch space for one row: time followed by one value per point.

Definition at line 131 of file PtsIOHdf5.h.

Referenced by PtsIOHdf5(), and Write().

◆ m_timeGroup

H5::GroupSharedPtr Nektar::LibUtilities::PtsIOHdf5::m_timeGroup
private

Definition at line 127 of file PtsIOHdf5.h.

Referenced by Close(), and PtsIOHdf5().

◆ MinChunkRows

constexpr size_t Nektar::LibUtilities::PtsIOHdf5::MinChunkRows = 64
staticconstexprprivate

Fewest time rows in a chunk. A chunk holding only a handful of rows costs more in index entries than it saves in allocated space.

Definition at line 104 of file PtsIOHdf5.h.

Referenced by ChunkRows().

◆ TargetChunkBytes

constexpr size_t Nektar::LibUtilities::PtsIOHdf5::TargetChunkBytes = 64 * 1024
staticconstexprprivate

Target size of a single HDF5 chunk, in bytes. Chunks much smaller than this make the chunk index dominate the file; chunks much larger risk exceeding the default chunk cache.

Definition at line 100 of file PtsIOHdf5.h.

Referenced by ChunkRows().