spectrumpcfstream.i.hh 18.8 KB
Newer Older
1
2
3
4
5
#ifndef RADIX_RADIXIO_SPECTRUMPCFSTREAM_HH_
#define RADIX_RADIXIO_SPECTRUMPCFSTREAM_HH_

#include <string>

Purves, Murray's avatar
Purves, Murray committed
6
7
#include "radixbug/bug.hh"
#include "radixcore/stringfunctions.hh"
8
#include "radixcore/visibility.hh"
Purves, Murray's avatar
Purves, Murray committed
9
#include "radixio/eafstream.hh"
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "radixio/spectrum.hh"

namespace radix
{
template <typename data_type>
SpectrumPCFStream<data_type>::SpectrumPCFStream(data_type container)
{
  mData = container;
}

template <typename data_type>
bool SpectrumPCFStream<data_type>::read_from(const std::string &file)
{
  bool result = false;

Purves, Murray's avatar
Purves, Murray committed
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
  radix_line("Reading data from PCF file: " << file);

  // Open a stream of the file
  eafstream stream(file.c_str(), std::ios::in | std::ios::binary);
  if (stream.is_open() == false)
  {
    return result;
  }

  // File should be little endian
  stream.setReverseBytes(false);

  // Read the header
  radix_line("  Reading header...");
  // Number of records per spectrum (NRPS)
  short nrps = stream.readShort();
  radix_line("    nrps: " << nrps);
  // Version (3-character string)
  std::string version = stream.readString(3);
  radix_line("    version: " << version);
  if (version.compare("DHS") == 0)
  {
    radix_line("    File has DHS-type header");
    mData->setDhsVersion(true);
    // Read in the DHS type header data
    std::string lastModifiedHash = stream.readString(7);
    mData->setLastModifiedHash(lastModifiedHash);
    std::string uuid = stream.readString(36);
    mData->setUuid(uuid);
    std::string inspection = stream.readString(16);
    mData->setInspection(inspection);
    short laneNumber = stream.readShort();
    mData->setLaneNumber(laneNumber);
    std::string measurementRemark = stream.readString(26);
    mData->setMeasurementRemark(measurementRemark);
    std::string instrumentType = stream.readString(28);
    mData->setInstrumentType(instrumentType);
    std::string manufacturer = stream.readString(28);
    mData->setManufacturer(manufacturer);
    std::string instrumentModel = stream.readString(18);
    mData->setInstrumentModel(instrumentModel);
    std::string instrumentID = stream.readString(18);
    mData->setInstrumentID(instrumentID);
    std::string itemDescription = stream.readString(20);
    mData->setItemDescription(itemDescription);
    std::string measurementLocationName = stream.readString(16);
    mData->setMeasurementLocationName(measurementLocationName);
    std::string measurementLocationCoords = stream.readString(16);
    mData->setMeasurementLocationCoords(measurementLocationCoords);
    short itemDetectorDistance = stream.readShort();
    mData->setItemDetectorDistance(itemDetectorDistance);
    short occupancyNumber = stream.readShort();
    mData->setOccupancyNumber(occupancyNumber);
    std::string cargoType = stream.readString(16);
    mData->setCargoType(cargoType);
  }
  else
  {
    radix_line("    File has non-DHS-type header");
    mData->setDhsVersion(false);
    // Read in the non-DHS type header data
    std::string mEnergyCalibrationLabel = stream.readString(4);
    mData->setEnergyCalibrationLabel(mEnergyCalibrationLabel);
    float mEnergyCalibrationOffset = stream.readFloat();
    mData->setEnergyCalibrationOffset(mEnergyCalibrationOffset);
    float mEnergyCalibrationGain = stream.readFloat();
    mData->setEnergyCalibrationGain(mEnergyCalibrationGain);
    float mEnergyCalibrationQuadraticTerm = stream.readFloat();
    mData->setEnergyCalibrationQuadraticTerm(mEnergyCalibrationQuadraticTerm);
    float mEnergyCalibrationCubicTerm = stream.readFloat();
    mData->setEnergyCalibrationCubicTerm(mEnergyCalibrationCubicTerm);
    float mEnergyCalibrationLowEnergy = stream.readFloat();
    mData->setEnergyCalibrationLowEnergy(mEnergyCalibrationLowEnergy);
    // Skip to end of header section (at 256 bytes)
    radix_line("    Skipping " << 256 - stream.bytesRead()
                               << " bytes to end of header (@256 bytes)");
    stream.skipBytes(256 - stream.bytesRead());
  }
  radix_line("  Header read complete; looking for deviation pairs...");

  // Read the deviation pairs (if present)
  std::array<std::array<std::array<std::array<float, 4>, 8>, 8>, 20>
      deviationPairEnergies = {0};
  std::array<std::array<std::array<std::array<float, 4>, 8>, 8>, 20>
      deviationPairOffsets          = {0};
  std::string deviationPairPresence = radix::trim_string(stream.readString(30));
  if (deviationPairPresence.compare("DeviationPairsInFile") == 0)
  {
Purves, Murray's avatar
Purves, Murray committed
113
    mData->setDeviationPairPresence(deviationPairPresence);
Purves, Murray's avatar
Purves, Murray committed
114
115
116
117
118
119
120
121
    radix_line("    Deviation pairs present; reading...");

    // Read uncompressed deviation pairs
    // Move to beginning of pairs (at 512 bytes)
    radix_line("    Skipping " << 512 - stream.bytesRead()
                               << " bytes to beginning of pairs (@512 bytes)");
    stream.skipBytes(512 - stream.bytesRead());

122
    for (size_t column = 0; column < 20; ++column)
Purves, Murray's avatar
Purves, Murray committed
123
124
125
126
127
128
    {
      radix("      ");
      for (size_t panel = 0; panel < 8; ++panel)
      {
        for (size_t mca = 0; mca < 8; ++mca)
        {
129
          for (size_t pair = 0; pair < 2; ++pair)
Purves, Murray's avatar
Purves, Murray committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
          {
            float energy = stream.readFloat();
            float offset = stream.readFloat();
            deviationPairEnergies[column][panel][mca][pair] = energy;
            deviationPairOffsets[column][panel][mca][pair]  = offset;
          }
          radix(".");
        }
        radix("-");
      }
      radix_line("|");
    }
  }
  else if (deviationPairPresence.compare("DeviationPairsInFileCompressed") == 0)
  {
Purves, Murray's avatar
Purves, Murray committed
145
    mData->setDeviationPairPresence(deviationPairPresence);
Purves, Murray's avatar
Purves, Murray committed
146
147
148
149
150
    radix_line("    Compressed deviation pairs present; reading...");

    // Read compressed  deviation pairs
    // Move to beginning of pairs
    stream.skipBytes(226);
151
    for (size_t column = 0; column < 20; ++column)
Purves, Murray's avatar
Purves, Murray committed
152
153
154
155
156
157
    {
      radix("      ");
      for (size_t panel = 0; panel < 8; ++panel)
      {
        for (size_t mca = 0; mca < 8; ++mca)
        {
158
          for (size_t pair = 0; pair < 4; ++pair)
Purves, Murray's avatar
Purves, Murray committed
159
160
          {
            float energy = float(stream.readShort()) / 10.f;
Purves, Murray's avatar
Purves, Murray committed
161
            float offset = float(stream.readShort()) / 10.f;
Purves, Murray's avatar
Purves, Murray committed
162
163
164
165
166
167
168
169
170
171
172
173
            deviationPairEnergies[column][panel][mca][pair] = energy;
            deviationPairOffsets[column][panel][mca][pair]  = offset;
          }
          radix(".");
        }
        radix("-");
      }
      radix_line("|");
    }
  }
  else
  {
Purves, Murray's avatar
Purves, Murray committed
174
    mData->setDeviationPairPresence("");
Purves, Murray's avatar
Purves, Murray committed
175
    radix_line("    No deviation pairs present");
176
177
178

    // Need to rewind to 256 bytes (start of spectrum header data)
    stream.skipBytes(-30);
Purves, Murray's avatar
Purves, Murray committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  }
  // Set deviation pairs
  mData->setDeviationPairEnergies(deviationPairEnergies);
  mData->setDeviationPairOffsets(deviationPairOffsets);

  radix_line("  Read deviation pairs; reading spectral data...");
  // Read spectral header
  // Make sure we only read till EOF
  stream.peek();
  while (stream.good())
  {
    // Read spectral header
    radix_line("    Reading spectral header...");

    // Buffer
    std::string buffer = stream.readString(180);
    radix_line("      buffer: " << buffer);
196
197
198
199
200
201
202
203
    // Split buffer into title/desc/source
    char delim        = 255;
    std::string title = "", description = "", source = "";
    if (buffer[0] == delim)
    {
      // Using a delimiter character
      radix_line("      Splitting using delimiter (" << delim << ")...");
      std::vector<std::string> bufferItems =
204
          split_string(std::string(1, delim), trim_string(buffer), true);
205
206
      if (bufferItems.size() > 0)
      {
207
        title = trim_string(bufferItems[0]);
208
209
210
      }
      if (bufferItems.size() > 1)
      {
211
        description = trim_string(bufferItems[1]);
212
213
214
      }
      if (bufferItems.size() > 2)
      {
215
        source = trim_string(bufferItems[2]);
216
217
218
219
220
221
      }
    }
    else
    {
      // Splitting evenly (60 characters each)
      radix_line("      Splitting evenly (60 chars per item)...");
222
223
224
      title       = trim_string(buffer.substr(0, 59));
      description = trim_string(buffer.substr(60, 119));
      source      = trim_string(buffer.substr(120, 179));
225
226
227
228
    }
    radix_line("      title: " << title);
    radix_line("      description: " << description);
    radix_line("      source: " << source);
Purves, Murray's avatar
Purves, Murray committed
229
    // Date/time
230
    std::string dateTime = trim_string(stream.readString(23));
Purves, Murray's avatar
Purves, Murray committed
231
232
    radix_line("      date/time: " << dateTime);
    // Tag
Purves, Murray's avatar
Purves, Murray committed
233
    std::string tag = trim_string(stream.readString(1));
Purves, Murray's avatar
Purves, Murray committed
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
    radix_line("      tag: " << tag);
    // Live time
    float liveTime = stream.readFloat();
    radix_line("      live time: " << liveTime);
    // Total time
    float totalTime = stream.readFloat();
    radix_line("      total time: " << totalTime);
    // Three unused values
    stream.readFloat();
    stream.readFloat();
    stream.readFloat();
    // Energy calibration offset
    float energyCalOffset = stream.readFloat();
    radix_line("      energy calibration offset:" << energyCalOffset);
    // Energy calibration gain
    float energyCalGain = stream.readFloat();
    radix_line("      energy calibration gain:" << energyCalGain);
    // Energy calibration quadratic term
    float energyCalQuadraticTerm = stream.readFloat();
    radix_line(
        "      energy calibration quadratic term:" << energyCalQuadraticTerm);
    // Energy calibration cubic term
    float energyCalCubicTerm = stream.readFloat();
    radix_line("      energy calibration cubic term:" << energyCalCubicTerm);
    // Energy calibration quadratic term
    float energyCalLowEnergyTerm = stream.readFloat();
    radix_line(
        "      energy calibration quadratic term:" << energyCalLowEnergyTerm);
    // Occupancy flag
    float occupancyFlag = stream.readFloat();
    radix_line("      occupancy flag:" << occupancyFlag);
    // Total neutron count
    float totalNeutronCount = stream.readFloat();
    radix_line("      total neutron count:" << totalNeutronCount);
    // Number of channels in spectrum
    int numberOfChannels = stream.readInt();
    radix_line("      number of channels in spectrum:" << numberOfChannels);
    // Read channel data
    radix_line("    Read spectral record header; reading data from "
               << numberOfChannels << " channels...");
    std::vector<float> countsByChannel;
    for (size_t channel = 0; channel < numberOfChannels; ++channel)
    {
      float counts = stream.readFloat();
      countsByChannel.push_back(counts);
    }
280
    radix_line("    " << countsByChannel.size() << " channels read");
Purves, Murray's avatar
Purves, Murray committed
281
282
283
284
285
286
287
288
289
290
291
    // Get the max number of channels available and skip to the end
    // (the rest after numberOfChannels will be junk)
    int cMaxBytes = 64 * (nrps - 1) * 4;
    radix_line("    Read to end of spectrum; skipping "
               << cMaxBytes - (numberOfChannels * 4)
               << " bytes to end of assigned memory");
    stream.skipBytes(cMaxBytes - (numberOfChannels * 4));

    // Build a SpectrumData object with this data and add it to the list
    radix_line("    Adding spectrum...");
    mData->addSpectrumData(
292
293
294
295
        title, source, description, dateTime, tag, liveTime, totalTime,
        energyCalOffset, energyCalGain, energyCalQuadraticTerm,
        energyCalCubicTerm, energyCalLowEnergyTerm, occupancyFlag,
        totalNeutronCount, numberOfChannels, countsByChannel);
Purves, Murray's avatar
Purves, Murray committed
296
297
298
299

    // Peek into next bit to check EOF
    stream.peek();
  }
300
  radix_line("  All spectral data read");
Purves, Murray's avatar
Purves, Murray committed
301

302
303
  radix_line("PCF file read complete and successful. "
             << mData->spectrumDataCount() << " spectra read");
304
305
  stream.close();

Purves, Murray's avatar
Purves, Murray committed
306
  result = true;
307
308
309
310
311
312
313
314
  return result;
}

template <typename data_type>
bool SpectrumPCFStream<data_type>::write_to(const std::string &file) const
{
  bool result = false;

Purves, Murray's avatar
Purves, Murray committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  radix_line("Writing data to PCF file: " << file);

  // Open a stream of the file
  eafstream stream(file.c_str(), std::ios::out | std::ios::binary);
  if (stream.is_open() == false)
  {
    return result;
  }

  // File should be little endian
  stream.setReverseBytes(false);

  // Write the header
  radix_line("  Writing header...");
  // Number of records per spectrum (NRPS)
  stream.writeShort(mData->nrps());
  // Rest of header depends on version type
  if (mData->dhsVersion())
  {
    radix_line("    File has DHS-type header");
335
336
337
338
    stream.writeString("DHS");
    stream.writeString(mData->lastModifiedHash(), 7);
    stream.writeString(mData->uuid(), 36);
    stream.writeString(mData->inspection(), 16);
Purves, Murray's avatar
Purves, Murray committed
339
    stream.writeShort(mData->laneNumber());
340
341
342
343
344
345
346
347
    stream.writeString(mData->measurementRemark(), 26);
    stream.writeString(mData->instrumentType(), 28);
    stream.writeString(mData->manufacturer(), 28);
    stream.writeString(mData->instrumentModel(), 18);
    stream.writeString(mData->instrumentID(), 18);
    stream.writeString(mData->itemDescription(), 20);
    stream.writeString(mData->measurementLocationName(), 16);
    stream.writeString(mData->measurementLocationCoords(), 16);
Purves, Murray's avatar
Purves, Murray committed
348
349
    stream.writeShort(mData->itemDetectorDistance());
    stream.writeShort(mData->occupancyNumber());
350
    stream.writeString(mData->cargoType(), 16);
Purves, Murray's avatar
Purves, Murray committed
351
352
353
354
  }
  else
  {
    radix_line("    File has non-DHS-type header");
355
356
    stream.writeString("   ");
    stream.writeString(mData->energyCalibrationLabel(), 4);
Purves, Murray's avatar
Purves, Murray committed
357
358
359
360
361
362
    stream.writeFloat(mData->energyCalibrationOffset());
    stream.writeFloat(mData->energyCalibrationGain());
    stream.writeFloat(mData->energyCalibrationQuadraticTerm());
    stream.writeFloat(mData->energyCalibrationCubicTerm());
    stream.writeFloat(mData->energyCalibrationLowEnergy());
    // Skip to 256 bytes (end of header)
363
    stream.writeString(" ", 256 - stream.bytesWritten());
Purves, Murray's avatar
Purves, Murray committed
364
365
366
367
368
369
370
371
372
373
  }
  radix_line("  End of header: " << stream.bytesWritten()
                                 << " bytes written so far");

  // Write deviation pairs
  radix_line("  Writing deviation pairs...");
  if (mData->deviationPairPresence().compare("DeviationPairsInFile") == 0)
  {
    radix_line("    Regular deviation pairs found:");
    // Write regular deviation pairs
374
375
    stream.writeString(mData->deviationPairPresence(), 20);
    stream.writeString(" ", 512 - stream.bytesWritten());
Purves, Murray's avatar
Purves, Murray committed
376
377

    // Write the pairs themselves
Norby, Tom's avatar
Norby, Tom committed
378
    for (size_t column = 0; column < 20; ++column)
Purves, Murray's avatar
Purves, Murray committed
379
380
381
382
383
384
    {
      radix("      ");
      for (size_t panel = 0; panel < 8; ++panel)
      {
        for (size_t mca = 0; mca < 8; ++mca)
        {
Norby, Tom's avatar
Norby, Tom committed
385
          for (size_t pair = 0; pair < 2; ++pair)
Purves, Murray's avatar
Purves, Murray committed
386
387
388
389
390
391
392
393
394
395
396
397
          {
            stream.writeFloat(
                mData->deviationPairEnergies()[column][panel][mca][pair]);
            stream.writeFloat(
                mData->deviationPairOffsets()[column][panel][mca][pair]);
          }
          radix(".");
        }
        radix("-");
      }
      radix_line("|");
    }
398

399
400
    // Skip to 256*82 bytes (start of spectral data)
    radix_line("Skipping " << (256 * 82) - stream.bytesWritten()
401
                           << " bytes to start of spectra data (256*82 = "
402
                           << 256 * 82 << " bytes)");
403
    stream.writeString(" ", (256 * 82) - stream.bytesWritten());
Purves, Murray's avatar
Purves, Murray committed
404
405
406
407
408
409
  }
  else if (mData->deviationPairPresence().compare(
               "DeviationPairsInFileCompressed") == 0)
  {
    radix_line("    Compressed deviation pairs found:");
    // Write compressed deviation pairs
410
    stream.writeString(mData->deviationPairPresence(), 30);
Purves, Murray's avatar
Purves, Murray committed
411
    // Skip to 512 bytes (start of pairs)
412
    stream.writeString(" ", 512 - stream.bytesWritten());
Purves, Murray's avatar
Purves, Murray committed
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

    // Write the pairs themselves
    for (size_t column = 0; column < 4; ++column)
    {
      radix("      ");
      for (size_t panel = 0; panel < 8; ++panel)
      {
        for (size_t mca = 0; mca < 8; ++mca)
        {
          for (size_t pair = 0; pair < 20; ++pair)
          {
            // Calculate the pair values
            short energy =
                short(mData->deviationPairEnergies()[column][panel][mca][pair] *
                      10.f);
            short offset = short(
                mData->deviationPairOffsets()[column][panel][mca][pair] * 10.f);
            stream.writeShort(energy);
            stream.writeShort(offset);
          }
          radix(".");
        }
        radix("-");
      }
      radix_line("|");
    }
439

440
441
    // Skip to 256*82 bytes (start of spectral data)
    radix_line("Skipping " << (256 * 82) - stream.bytesWritten()
442
                           << " bytes to start of spectra data (256*82 = "
443
                           << 256 * 82 << " bytes)");
444
    stream.writeString(" ", (256 * 82) - stream.bytesWritten());
Purves, Murray's avatar
Purves, Murray committed
445
446
447
448
449
  }
  else
  {
    // Don't write deviation pairs
    radix_line("    No deviation pairs found:");
450
    // Don't need to skip anything - spectrum header data starts at 256 bytes
Purves, Murray's avatar
Purves, Murray committed
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
  }

  // Write spectrum data
  // Spectrum data values
  std::string title, source, description, dateTime, tag;
  float liveTime, totalTime, energyCalOffset, energyCalGain,
      energyCalQuadraticTerm, energyCalCubicTerm, energyCalLowEnergyTerm,
      occupancyFlag, totalNeutronCount;
  int numberOfChannels;
  std::vector<float> countsByChannel;
  for (size_t i = 0; i < mData->spectrumDataCount(); ++i)
  {
    radix_line("  Writing spectrum data for spectrum "
               << i + 1 << " of " << mData->spectrumDataCount());

    // Get the spectrum
    mData->spectrumData(i, title, source, description, dateTime, tag, liveTime,
                        totalTime, energyCalOffset, energyCalGain,
                        energyCalQuadraticTerm, energyCalCubicTerm,
                        energyCalLowEnergyTerm, occupancyFlag,
                        totalNeutronCount, numberOfChannels, countsByChannel);

    // Write spectrum header
    radix_line("    Writing spectrum header:");
    std::stringstream ss;
    char delim = 255;
    ss << delim << trim_string(title) << delim << trim_string(description)
       << delim << trim_string(source);
479
480
481
    stream.writeString(ss.str(), 180);
    stream.writeString(dateTime, 23);
    stream.writeString(tag, 1);
Purves, Murray's avatar
Purves, Murray committed
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
    stream.writeFloat(liveTime);
    stream.writeFloat(totalTime);
    // Three unused floats in data structure
    stream.writeFloat(0.f);
    stream.writeFloat(0.f);
    stream.writeFloat(0.f);
    stream.writeFloat(energyCalOffset);
    stream.writeFloat(energyCalGain);
    stream.writeFloat(energyCalQuadraticTerm);
    stream.writeFloat(energyCalCubicTerm);
    stream.writeFloat(energyCalLowEnergyTerm);
    stream.writeFloat(occupancyFlag);
    stream.writeFloat(totalNeutronCount);
    stream.writeInt(numberOfChannels);

    // Write spectrum data
    radix_line("    Writing spectrum data:");
    for (size_t channel = 0; channel < countsByChannel.size(); ++channel)
    {
      stream.writeFloat(countsByChannel[channel]);
    }
    int maxChannels = 64 * (mData->nrps() - 1);
    radix_line("      Written " << countsByChannel.size()
                                << " data points; max size is " << maxChannels);
    if (countsByChannel.size() < maxChannels)
    {
      radix_line("      Writing " << maxChannels - countsByChannel.size()
                                  << " zeroes to pad to max");
      for (int i = countsByChannel.size(); i < maxChannels; ++i)
      {
        stream.writeFloat(0.f);
      }
    }

    radix_line("  Spectrum write complete");
  }

519
520
  stream.close();

Purves, Murray's avatar
Purves, Murray committed
521
  result = true;
522
523
524
525
526
527
  return result;
}

}  // namespace radix

#endif  // RADIX_RADIXIO_SPECTRUMPCFSTREAM_HH_