SEGYImport.cpp 136 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/****************************************************************************
** Copyright 2019 The Open Group
** Copyright 2019 Bluware, Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**   http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
****************************************************************************/

Jørgen Lind's avatar
Jørgen Lind committed
18
#define _CRT_SECURE_NO_WARNINGS 1
19
#include <SEGYUtils/SEGYFileInfo.h>
20
#include "IO/File.h"
21
#include "VDS/Hash.h"
22
#include <SEGYUtils/DataProvider.h>
23
#include <SEGYUtils/TraceDataManager.h>
24
#include "TraceInfo2DManager.h"
25
26

#include <OpenVDS/OpenVDS.h>
27
#include <OpenVDS/MetadataContainer.h>
28
29
30
31
32
33
#include <OpenVDS/VolumeDataLayoutDescriptor.h>
#include <OpenVDS/VolumeDataAxisDescriptor.h>
#include <OpenVDS/VolumeDataChannelDescriptor.h>
#include <OpenVDS/VolumeDataAccess.h>
#include <OpenVDS/Range.h>
#include <OpenVDS/VolumeDataLayout.h>
34
#include <OpenVDS/KnownMetadata.h>
Morten Ofstad's avatar
Morten Ofstad committed
35
#include <OpenVDS/GlobalMetadataCommon.h>
36

37
38
#include "IO/IOManager.h"

39
40
41
42
43
44
#include <mutex>
#include <cstdlib>
#include <climits>
#include <cassert>
#include <algorithm>

Jim King's avatar
Jim King committed
45
46
47
#define _USE_MATH_DEFINES
#include <math.h>

Jørgen Lind's avatar
Jørgen Lind committed
48
#include <cxxopts/cxxopts.hpp>
49
50
51
#include <json/json.h>
#include <fmt/format.h>

52
#include "SplitUrl.h"
53
#include <PrintHelpers.h>
54
#include <HelpConnection.h>
55

56
#include <chrono>
57
#include <numeric>
58
#include <set>
59

Jørgen Lind's avatar
Jørgen Lind committed
60
61
62
63
64
65
#if defined(WIN32)
#undef WIN32_LEAN_AND_MEAN // avoid warnings if defined on command line
#define WIN32_LEAN_AND_MEAN 1
#define NOMINMAX 1
#include <io.h>
#include <windows.h>
66

67
68
constexpr double METERS_PER_FOOT = 0.3048;

69
70
71
72
73
74
75
76
int64_t GetTotalSystemMemory()
{
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    return int64_t(status.ullTotalPhys);
}

Jørgen Lind's avatar
Jørgen Lind committed
77
78
#else
#include <unistd.h>
79
80
81
82
83
84
85

int64_t GetTotalSystemMemory()
{
    long pages = sysconf(_SC_PHYS_PAGES);
    long page_size = sysconf(_SC_PAGE_SIZE);
    return int64_t(pages) * int64_t(page_size);
}
Jørgen Lind's avatar
Jørgen Lind committed
86
87
#endif

88
89
90
91
92
93
inline char asciitolower(char in) {
  if (in <= 'Z' && in >= 'A')
    return in - ('Z' - 'z');
  return in;
}

94
static DataProvider CreateDataProviderFromFile(const std::string &filename, OpenVDS::Error &error)
Jørgen Lind's avatar
Jørgen Lind committed
95
96
97
98
99
100
101
{
  std::unique_ptr<OpenVDS::File> file(new OpenVDS::File());
  if (!file->Open(filename, false, false, false, error))
    return DataProvider((OpenVDS::File *)nullptr);
  return DataProvider(file.release());
}

102
static DataProvider CreateDataProviderFromOpenOptions(const std::string &url, const std::string &connectionString, OpenVDS::Error &error)
Jørgen Lind's avatar
Jørgen Lind committed
103
{
Jørgen Lind's avatar
Jørgen Lind committed
104
  std::unique_ptr<OpenVDS::IOManager> ioManager(OpenVDS::IOManager::CreateIOManager(url, connectionString, OpenVDS::IOManager::AccessPattern::ReadOnly, error));
Jørgen Lind's avatar
Jørgen Lind committed
105
  if (error.code)
106
107
    return DataProvider("", (OpenVDS::IOManager*)nullptr, error);
  return DataProvider(url, ioManager.release(), error);
Jørgen Lind's avatar
Jørgen Lind committed
108
109
}

110
DataProvider CreateDataProvider(const std::string& url, const std::string& connection, OpenVDS::Error& error)
111
{
112
  if (OpenVDS::IsSupportedProtocol(url))
113
  {
114
    return CreateDataProviderFromOpenOptions(url, connection, error);
115
116
117
  }
  else
  {
118
    return CreateDataProviderFromFile(url, error);
119
120
121
122
  }
  return DataProvider(nullptr);
}

Jørgen Lind's avatar
Jørgen Lind committed
123
static std::vector<DataProvider> CreateDataProviders(const std::vector<std::string> &fileNames, const std::string &connection, OpenVDS::Error &error, std::string &errorFileName)
124
125
126
127
128
129
130
131
132
133
{
  std::vector<DataProvider>
    dataProviders;

  for (const auto& fileName : fileNames)
  {
    dataProviders.push_back(CreateDataProvider(fileName, connection, error));

    if (error.code != 0)
    {
Jørgen Lind's avatar
Jørgen Lind committed
134
      errorFileName = fileName;
135
136
137
138
139
140
141
      dataProviders.clear();
      break;
    }
  }
  return dataProviders;
}

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
Json::Value
SerializeSEGYBinInfo(SEGYBinInfo const& binInfo)
{
  Json::Value
    jsonBinInfo;

  jsonBinInfo["inlineNumber"] = binInfo.m_inlineNumber;
  jsonBinInfo["crosslineNumber"] = binInfo.m_crosslineNumber;

  jsonBinInfo["ensembleXCoordinate"] = binInfo.m_ensembleXCoordinate;
  jsonBinInfo["ensembleYCoordinate"] = binInfo.m_ensembleYCoordinate;

  return jsonBinInfo;
}

Json::Value
SerializeSEGYSegmentInfo(SEGYSegmentInfo const& segmentInfo)
{
  Json::Value
    jsonSegmentInfo;

  jsonSegmentInfo["primaryKey"] = segmentInfo.m_primaryKey;
  jsonSegmentInfo["traceStart"] = segmentInfo.m_traceStart;
  jsonSegmentInfo["traceStop"] = segmentInfo.m_traceStop;

  jsonSegmentInfo["binInfoStart"] = SerializeSEGYBinInfo(segmentInfo.m_binInfoStart);
  jsonSegmentInfo["binInfoStop"] = SerializeSEGYBinInfo(segmentInfo.m_binInfoStop);

  return jsonSegmentInfo;
}

std::string
ToString(SEGY::Endianness endiannness)
{
  switch (endiannness)
  {
  case SEGY::Endianness::BigEndian:  return "BigEndian";
  case SEGY::Endianness::LittleEndian: return "LittleEndian";
  default:
    assert(0); return "";
  }
}

std::string
ToString(SEGY::FieldWidth fieldWidth)
{
  switch (fieldWidth)
  {
  case SEGY::FieldWidth::TwoByte:  return "TwoByte";
  case SEGY::FieldWidth::FourByte: return "FourByte";
  default:
    assert(0); return "";
  }
}

Json::Value
SerializeSEGYHeaderField(SEGY::HeaderField const& headerField)
{
  Json::Value
    jsonHeaderField(Json::ValueType::arrayValue);

  jsonHeaderField.append(headerField.byteLocation);
  jsonHeaderField.append(ToString(headerField.fieldWidth));

  return jsonHeaderField;
}

Json::Value
Jim King's avatar
Jim King committed
210
SerializeSEGYFileInfo(SEGYFileInfo const& fileInfo, const int fileIndex)
211
212
213
214
215
216
217
218
{
  Json::Value
    jsonFileInfo;

  jsonFileInfo["persistentID"] = fmt::format("{:X}", fileInfo.m_persistentID);
  jsonFileInfo["headerEndianness"] = ToString(fileInfo.m_headerEndianness);
  jsonFileInfo["dataSampleFormatCode"] = (int)fileInfo.m_dataSampleFormatCode;
  jsonFileInfo["sampleCount"] = fileInfo.m_sampleCount;
219
  jsonFileInfo["startTime"] = fileInfo.m_startTimeMilliseconds;
220
  jsonFileInfo["sampleInterval"] = fileInfo.m_sampleIntervalMilliseconds;
Jim King's avatar
Jim King committed
221
  jsonFileInfo["traceCount"] = fileInfo.m_traceCounts[fileIndex];
222
223
224
  jsonFileInfo["primaryKey"] = SerializeSEGYHeaderField(fileInfo.m_primaryKey);
  jsonFileInfo["secondaryKey"] = SerializeSEGYHeaderField(fileInfo.m_secondaryKey);

225
  if (fileInfo.m_segyType == SEGY::SEGYType::PrestackOffsetSorted)
226
  {
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    Json::Value
      jsonOffsetMap;

    for (const auto& entry : fileInfo.m_segmentInfoListsByOffset[fileIndex])
    {
      Json::Value
        jsonSegmentInfoArray(Json::ValueType::arrayValue);

      for (auto const& segmentInfo : entry.second)
      {
        jsonSegmentInfoArray.append(SerializeSEGYSegmentInfo(segmentInfo));
      }

      jsonOffsetMap[std::to_string(entry.first)] = jsonSegmentInfoArray;
    }

    jsonFileInfo["segmentInfo"] = jsonOffsetMap;
244
  }
245
246
247
248
249
250
251
252
253
  else
  {
    Json::Value
      jsonSegmentInfoArray(Json::ValueType::arrayValue);

    for (auto const& segmentInfo : fileInfo.m_segmentInfoLists[fileIndex])
    {
      jsonSegmentInfoArray.append(SerializeSEGYSegmentInfo(segmentInfo));
    }
254

255
256
    jsonFileInfo["segmentInfo"] = jsonSegmentInfoArray;
  }
257
258
259
260
261
262
263

  return jsonFileInfo;
}

std::map<std::string, SEGY::HeaderField>
g_traceHeaderFields =
{
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
 { "tracesequencenumber",           SEGY::TraceHeader::TraceSequenceNumberHeaderField },
 { "tracesequencenumberwithinfile", SEGY::TraceHeader::TraceSequenceNumberWithinFileHeaderField },
 { "energysourcepointnumber",       SEGY::TraceHeader::EnergySourcePointNumberHeaderField },
 { "ensemblenumber",                SEGY::TraceHeader::EnsembleNumberHeaderField },
 { "tracenumberwithinensemble",     SEGY::TraceHeader::TraceNumberWithinEnsembleHeaderField },
 { "traceidentificationcode",       SEGY::TraceHeader::TraceIdentificationCodeHeaderField },
 { "coordinatescale",               SEGY::TraceHeader::CoordinateScaleHeaderField },
 { "sourcexcoordinate",             SEGY::TraceHeader::SourceXCoordinateHeaderField },
 { "sourceycoordinate",             SEGY::TraceHeader::SourceYCoordinateHeaderField },
 { "groupxcoordinate",              SEGY::TraceHeader::GroupXCoordinateHeaderField },
 { "groupycoordinate",              SEGY::TraceHeader::GroupYCoordinateHeaderField },
 { "coordinateunits",               SEGY::TraceHeader::CoordinateUnitsHeaderField },
 { "starttime",                     SEGY::TraceHeader::StartTimeHeaderField },
 { "numsamples",                    SEGY::TraceHeader::NumSamplesHeaderField },
 { "sampleinterval",                SEGY::TraceHeader::SampleIntervalHeaderField },
 { "ensemblexcoordinate",           SEGY::TraceHeader::EnsembleXCoordinateHeaderField },
 { "ensembleycoordinate",           SEGY::TraceHeader::EnsembleYCoordinateHeaderField },
 { "inlinenumber",                  SEGY::TraceHeader::InlineNumberHeaderField },
 { "crosslinenumber",               SEGY::TraceHeader::CrosslineNumberHeaderField },
 { "receiver",                      SEGY::TraceHeader::ReceiverHeaderField },
284
285
286
287
288
289
 { "offset",                        SEGY::TraceHeader::OffsetHeaderField },
 { "offsetx",                       SEGY::TraceHeader::OffsetXHeaderField },
 { "offsety",                       SEGY::TraceHeader::OffsetYHeaderField },
 { "azimuth",                       SEGY::TraceHeader::Azimuth },
 { "mutestarttime",                 SEGY::TraceHeader::MuteStartTime },
 { "muteendtime",                   SEGY::TraceHeader::MuteEndTime },
290
291
292
293
294
};

std::map<std::string, std::string>
g_aliases =
{
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
 { "inline",              "inlinenumber" },
 { "crossline",           "crosslinenumber" },
 { "shot",                "energysourcepointnumber" },
 { "sp",                  "energysourcepointnumber" },
 { "cdp",                 "ensemblenumber" },
 { "cmp",                 "ensemblenumber" },
 { "easting",             "ensemblexcoordinate" },
 { "northing",            "ensembleycoordinate" },
 { "cdpxcoordinate",      "ensemblexcoordinate" },
 { "cdpycoordinate",      "ensembleycoordinate" },
 { "cdp-x",               "ensemblexcoordinate" },
 { "cdp-y",               "ensembleycoordinate" },
 { "source-x",            "sourcexcoordinate" },
 { "source-y",            "sourceycoordinate" },
 { "group-x",             "groupxcoordinate" },
 { "group-y",             "groupycoordinate" },
 { "receiverxcoordinate", "groupxcoordinate" },
 { "receiverycoordinate", "groupycoordinate" },
 { "receiver-x",          "groupxcoordinate" },
 { "receiver-y",          "groupycoordinate" },
 { "scalar",              "coordinatescale" }
316
317
318
319
320
};

void
ResolveAlias(std::string& fieldName)
{
321
322

  std::transform(fieldName.begin(), fieldName.end(), fieldName.begin(), asciitolower);
323
324
325
326
327
328
329
330
331
332
333
334
  if (g_aliases.find(fieldName) != g_aliases.end())
  {
    fieldName = g_aliases[fieldName];
  }
}

SEGY::Endianness
EndiannessFromJson(Json::Value const& jsonEndianness)
{
  std::string
    endiannessString = jsonEndianness.asString();

335
336
  std::transform(endiannessString.begin(), endiannessString.end(), endiannessString.begin(), asciitolower);
  if (endiannessString == "bigendian")
337
338
339
  {
    return SEGY::Endianness::BigEndian;
  }
340
  else if (endiannessString == "littleendian")
341
342
343
344
345
346
347
348
349
350
351
352
  {
    return SEGY::Endianness::LittleEndian;
  }

  throw Json::Exception("Illegal endianness");
}

SEGY::FieldWidth
FieldWidthFromJson(Json::Value const& jsonFieldWidth)
{
  std::string
    fieldWidthString = jsonFieldWidth.asString();
353
  std::transform(fieldWidthString.begin(), fieldWidthString.end(), fieldWidthString.begin(), asciitolower);
354

355
  if (fieldWidthString == "twobyte")
356
357
358
  {
    return SEGY::FieldWidth::TwoByte;
  }
359
  else if (fieldWidthString == "fourbyte")
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
  {
    return SEGY::FieldWidth::FourByte;
  }

  throw Json::Exception("Illegal field width");
}

SEGY::HeaderField
HeaderFieldFromJson(Json::Value const& jsonHeaderField)
{
  int
    bytePosition = jsonHeaderField[0].asInt();

  SEGY::FieldWidth
    fieldWidth = FieldWidthFromJson(jsonHeaderField[1]);

  if (bytePosition < 1 || bytePosition > SEGY::TraceHeaderSize - ((fieldWidth == SEGY::FieldWidth::TwoByte) ? 2 : 4))
  {
    throw Json::Exception(std::string("Illegal field definition: ") + jsonHeaderField.toStyledString());
  }

  return SEGY::HeaderField(bytePosition, fieldWidth);
}

bool
385
ParseHeaderFormatFile(DataProvider &dataProvider, std::map<std::string, SEGY::HeaderField>& traceHeaderFields, SEGY::Endianness& headerEndianness, OpenVDS::Error &error)
386
{
387
  int64_t dataSize = dataProvider.Size(error);
388
389
390
391
392
393

  if (error.code != 0)
  {
    return false;
  }

394
  if (dataSize > INT_MAX)
395
396
397
398
399
  {
    return false;
  }

  std::unique_ptr<char[]>
400
    buffer(new char[dataSize]);
401

402
  dataProvider.Read(buffer.get(), 0, (int32_t)dataSize, error);
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

  if (error.code != 0)
  {
    return false;
  }

  try
  {
    Json::CharReaderBuilder
      rbuilder;

    rbuilder["collectComments"] = false;

    std::string
      errs;

    std::unique_ptr<Json::CharReader>
      reader(rbuilder.newCharReader());

    Json::Value
      root;

    bool
426
      success = reader->parse(buffer.get(), buffer.get() + dataSize, &root, &errs);
427
428
429
430
431
432
433
434
435
436
437

    if (!success)
    {
      throw Json::Exception(errs);
    }

    for (std::string const& fieldName : root.getMemberNames())
    {
      std::string canonicalFieldName = fieldName;
      ResolveAlias(canonicalFieldName);

438
      if (canonicalFieldName == "endianness")
439
440
441
442
443
444
445
446
447
      {
        headerEndianness = EndiannessFromJson(root[fieldName]);
      }
      else
      {
        traceHeaderFields[canonicalFieldName] = HeaderFieldFromJson(root[fieldName]);
      }
    }
  }
Jørgen Lind's avatar
Jørgen Lind committed
448
  catch (Json::Exception &e)
449
  {
450
451
    error.code = -1;
    error.string = e.what();
452
453
454
455
456
457
    return false;
  }

  return true;
}

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
bool OnlyDigits(const std::string& str)
{
  for (auto a : str)
  {
    if (a < '0' || a > '9')
      return false;
  }
  return true;
}

bool
ParseHeaderFieldArgs(const std::vector<std::string> &header_fields_args, std::map<std::string, SEGY::HeaderField>& traceHeaderFields, SEGY::Endianness& headerEndianness, OpenVDS::Error& error)
{
  for (auto& header_field : header_fields_args)
  {
    if (header_field.empty())
    {
      error.code = -1;
      error.string = "Cannot parse empty header-field";
      return false;
    }
    auto it = std::find(header_field.begin(), header_field.end(), '=');
    if (it == header_field.end())
    {
      error.code = -1;
      error.string = fmt::format("Failed to parse header-field {}.", header_field);
      return false;
    }
    std::string header_name(header_field.begin(), it);
    if (it + 1 == header_field.end())
    {
      error.code = -1;
      error.string = fmt::format("Can not find value for header-field {}.", header_name);
      return false;
    }
    std::string header_value(it + 1, header_field.end());
    auto min_delimiter = std::find(header_value.begin(), header_value.end(), '-');
    int field_width = -1;
    int offset = -1;
    if (min_delimiter != header_value.end())
    {
      if (min_delimiter + 1 == header_value.end())
      {
        error.code = -1;
        error.string = fmt::format("unable to parse value for header-field {} with value {}.", header_name, header_value);
        return false;
      }
      std::string value_start(header_value.begin(), min_delimiter);
      std::string value_end(min_delimiter + 1, header_value.end());
      if (!OnlyDigits(value_start) || !OnlyDigits(value_end))
      {
        error.code = -1;
        error.string = fmt::format("unable to parse header-field {} value range {}.", header_name, header_value);
        return false;
      }
      int value_start_value = atoi(value_start.c_str());
      int value_end_value = atoi(value_end.c_str());
      offset = value_start_value;
      field_width = value_end_value - value_start_value;
    }
    else
    {
      auto colon_delimiter = std::find(header_value.begin(), header_value.end(), ':');
      std::string offset_str(header_value.begin(), colon_delimiter);
      if (!OnlyDigits(offset_str))
      {
        error.code = -1;
        error.string = fmt::format("unable to parse offset for header-field {}: {}.", header_name, header_value);
        return false;
      }
      offset = atoi(offset_str.c_str());
      if (colon_delimiter < header_value.end() && colon_delimiter + 1 < header_value.end())
      {
        std::string width_str(colon_delimiter + 1, header_value.end());
        if (!OnlyDigits(width_str))
        {
          error.code = -1;
          error.string = fmt::format("unable to parse width specifier for header-field {}: {}.", header_name, width_str);
          return false;
        }
        field_width = atoi(width_str.c_str());
      }
    }
    if (offset < 0)
    {
      error.code = -1;
      error.string = fmt::format("unable to find offset for header-field {}: {}.", header_name, header_value);
      return false;
    }
    ResolveAlias(header_name);
    auto& traceHeaderField = traceHeaderFields[header_name];
    traceHeaderField.byteLocation = offset;
    if (field_width != -1)
    {
      if (field_width == 2)
      {
        traceHeaderField.fieldWidth = SEGY::FieldWidth::TwoByte;
      }
      else if (field_width == 4)
      {
        traceHeaderField.fieldWidth = SEGY::FieldWidth::FourByte;
      }
      else
      {
        error.code = -1;
        error.string = fmt::format("header-field {} has illegal field width of {}. Only widths of 2 or 4 are accepted.", header_name, field_width);
        return false;
      }
    }
  }
  return true;
}

571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
SEGYBinInfo
binInfoFromJson(Json::Value const& jsonBinInfo)
{
  int inlineNumber = jsonBinInfo["inlineNumber"].asInt();
  int crosslineNumber = jsonBinInfo["crosslineNumber"].asInt();
  double ensembleXCoordinate = jsonBinInfo["ensembleXCoordinate"].asDouble();
  double ensembleYCoordinate = jsonBinInfo["ensembleYCoordinate"].asDouble();

  return SEGYBinInfo(inlineNumber, crosslineNumber, ensembleXCoordinate, ensembleYCoordinate);
}

SEGYSegmentInfo
segmentInfoFromJson(Json::Value const& jsonSegmentInfo)
{
  int primaryKey = jsonSegmentInfo["primaryKey"].asInt();
  int traceStart = jsonSegmentInfo["traceStart"].asInt();
  int traceStop = jsonSegmentInfo["traceStop"].asInt();
  SEGYBinInfo binInfoStart = binInfoFromJson(jsonSegmentInfo["binInfoStart"]);
  SEGYBinInfo binInfoStop = binInfoFromJson(jsonSegmentInfo["binInfoStop"]);

  return SEGYSegmentInfo(primaryKey, traceStart, traceStop, binInfoStart, binInfoStop);
}

594
595
596
597
598
599
600
601
602
std::vector<int>
getOrderedSegmentListIndices(SEGYFileInfo const& fileInfo, size_t& globalTotalSegments)
{
  // Generate a list of indices that will traverse m_segyFileInfo.m_segmentInfoLists in primary key order, which
  // may be different from the order that the files were given.

  std::vector<int>
    orderedListIndices;
  globalTotalSegments = 0;
603
604

  if (fileInfo.IsOffsetSorted())
605
  {
606
    for (int i = 0; i < fileInfo.m_segmentInfoListsByOffset.size(); ++i)
607
    {
608
609
610
611
612
      orderedListIndices.push_back(i);
      for (const auto& entry : fileInfo.m_segmentInfoListsByOffset[i])
      {
        globalTotalSegments += entry.second.size();
      }
613
    }
614
615
616
617
618
619
620
621
622
623
624
625

    // don't need to check for ascending/descending primary key because the map will have offsets (keys) sorted in ascending order

    auto
      comparator = [&](int i1, int i2)
    {
      const auto
        & v1 = fileInfo.m_segmentInfoListsByOffset[i1],
        & v2 = fileInfo.m_segmentInfoListsByOffset[i2];
      return (*v1.begin()).first < (*v2.begin()).first;
    };
    std::sort(orderedListIndices.begin(), orderedListIndices.end(), comparator);
626
  }
627
  else
628
  {
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    size_t
      longestList = 0;
    for (size_t i = 0; i < fileInfo.m_segmentInfoLists.size(); ++i)
    {
      orderedListIndices.push_back(static_cast<int>(i));
      globalTotalSegments += fileInfo.m_segmentInfoLists[i].size();
      if (fileInfo.m_segmentInfoLists[i].size() > fileInfo.m_segmentInfoLists[longestList].size())
      {
        longestList = i;
      }
    }
    const bool
      isAscending = fileInfo.m_segmentInfoLists[longestList].front().m_binInfoStart.m_inlineNumber <= fileInfo.m_segmentInfoLists[longestList].back().m_binInfoStart.m_inlineNumber;
    auto
      comparator = [&](int i1, int i2)
    {
      const auto
        & v1 = fileInfo.m_segmentInfoLists[i1],
        & v2 = fileInfo.m_segmentInfoLists[i2];
      return isAscending ? v1.front().m_binInfoStart.m_inlineNumber < v2.front().m_binInfoStart.m_inlineNumber : v2.front().m_binInfoStart.m_inlineNumber < v1.front().m_binInfoStart.m_inlineNumber;
    };
    std::sort(orderedListIndices.begin(), orderedListIndices.end(), comparator);
  }
652
653
654
655

  return orderedListIndices;
}

656
SEGYSegmentInfo const&
657
findRepresentativeSegment(SEGYFileInfo const& fileInfo, int& primaryStep, int& bestListIndex)
658
{
659
660
  assert(!fileInfo.IsOffsetSorted());

661
662
663
664
665
666
667
  // Since we give more weight to segments near the center of the data we need a sorted index of segment lists so that we can
  // traverse the lists in data order, instead of the arbitrary order given by the filename ordering.
  size_t
    globalTotalSegments = 0;
  auto
    orderedListIndices = getOrderedSegmentListIndices(fileInfo, globalTotalSegments);

668
  primaryStep = 0;
669
  bestListIndex = 0;
670

671
  float bestScore = 0.0f;
Jim King's avatar
Jim King committed
672
  size_t bestIndex = 0;
673
674

  int segmentPrimaryStep = 0;
675

676
677
678
679
  size_t
    globalOffset = 0;

  for (const auto listIndex : orderedListIndices)
680
  {
681
682
    const auto&
      segmentInfoList = fileInfo.m_segmentInfoLists[listIndex];
683

Jim King's avatar
Jim King committed
684
    for (size_t i = 0; i < segmentInfoList.size(); i++)
685
686
687
    {
      int64_t
        numTraces = (segmentInfoList[i].m_traceStop - segmentInfoList[i].m_traceStart + 1);
688

689
690
691
      // index of this segment within the entirety of segments from all input files
      const auto
        globalIndex = globalOffset + i;
692

693
694
      float
        multiplier = 1.5f - abs(globalIndex - (float)globalTotalSegments / 2) / (float)globalTotalSegments; // give 50% more importance to a segment in the middle of the dataset
695

696
697
      float
        score = float(numTraces) * multiplier;
698

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
      if (score > bestScore)
      {
        bestScore = score;
        bestListIndex = listIndex;
        bestIndex = i;
      }

      // Updating the primary step with the step for the previous segment intentionally ignores the step of the last segment since it can be anomalous
      if (segmentPrimaryStep && (!primaryStep || std::abs(segmentPrimaryStep) < std::abs(primaryStep)))
      {
        primaryStep = segmentPrimaryStep;
      }

      if (i > 0)
      {
        segmentPrimaryStep = segmentInfoList[i].m_primaryKey - segmentInfoList[i - 1].m_primaryKey;
      }
716
    }
717
718

    globalOffset += segmentInfoList.size();
719
720
  }

721
722
723
  // If the primary step couldn't be determined, set it to the last step or 1
  primaryStep = primaryStep ? primaryStep : std::max(segmentPrimaryStep, 1);

724
  return fileInfo.m_segmentInfoLists[bestListIndex][bestIndex];
725
726
}

727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// Analog of findRepresentativeSegment for offset-sorted prestack
int
findRepresentativePrimaryKey(SEGYFileInfo const& fileInfo, int& primaryStep)
{
  // If primary keys are reverse-sorted in the file the structures we build below will hide that.
  // For the computations we're doing in this method it's OK that we're not preserving the original order.

  // scan segment infos to get primary key values and total trace count per primary key
  std::map<int, int64_t>
    primaryKeyLengths;
  for (const auto& offsetMap : fileInfo.m_segmentInfoListsByOffset)
  {
    for (const auto& entry : offsetMap)
    {
      for (const auto& segmentInfo : entry.second)
      {
        const auto
          segmentLength = segmentInfo.m_traceStop - segmentInfo.m_traceStart + 1;
        const auto
          newSum = segmentLength + primaryKeyLengths[segmentInfo.m_primaryKey];
        primaryKeyLengths[segmentInfo.m_primaryKey] = newSum;
      }
    }
  }

  // determine primary step
  primaryStep = 0;
  int
    segmentPrimaryStep = 0,
    previousPrimaryKey = 0,
    firstPrimaryKey = 0,
    lastPrimaryKey = 0;
  bool
    firstSegment = true;
  for (const auto& entry : primaryKeyLengths)
  {
    if (firstSegment)
    {
      firstSegment = false;
      previousPrimaryKey = entry.first;
      firstPrimaryKey = entry.first;
      lastPrimaryKey = entry.first;
    }
    else
    {
      lastPrimaryKey = entry.first;

      // Updating the primary step with the step for the previous segment intentionally ignores the step of the last segment since it can be anomalous
      if (segmentPrimaryStep && (!primaryStep || std::abs(segmentPrimaryStep) < std::abs(primaryStep)))
      {
        primaryStep = segmentPrimaryStep;
      }

      segmentPrimaryStep = entry.first - previousPrimaryKey;
      previousPrimaryKey = entry.first;
    }
  }

  // If the primary step couldn't be determined, set it to the last step or 1
  primaryStep = primaryStep ? primaryStep : std::max(segmentPrimaryStep, 1);

  float
    bestScore = 0.0f;
  int
    bestPrimaryKey = 0;

  for (const auto& entry : primaryKeyLengths)
  {
    const auto&
      numTraces = entry.second;

    // index of this segment within the entirety of segments from all input files
    const auto
      factor = abs(static_cast<float>(entry.first - firstPrimaryKey) / static_cast<float>(lastPrimaryKey - firstPrimaryKey));

    const auto
      multiplier = 1.5f - abs(factor - 0.5f); // give 50% more importance to a segment in the middle of the dataset

    const auto
      score = static_cast<float>(numTraces) * multiplier;

    if (score > bestScore)
    {
      bestScore = score;
      bestPrimaryKey = entry.first;
    }
  }

  return bestPrimaryKey;
}

818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
void
copySamples(const void* data, SEGY::BinaryHeader::DataSampleFormatCode dataSampleFormatCode, SEGY::Endianness endianness, float* target, int sampleStart, int sampleCount)
{
  if (dataSampleFormatCode == SEGY::BinaryHeader::DataSampleFormatCode::IBMFloat)
  {
    if(endianness == SEGY::Endianness::LittleEndian)
    {
      // Reverse endianness since Ibm2ieee expects big endian data
      const char * source = reinterpret_cast<const char*>((intptr_t)data + (size_t)sampleStart * 4);
      std::unique_ptr<char[]> temp(new char[sampleCount * 4]);
      for(int sample = 0; sample < sampleCount; sample++)
      {
        temp[sample * 4 + 0] = source[sample * 4 + 3];
        temp[sample * 4 + 1] = source[sample * 4 + 2];
        temp[sample * 4 + 2] = source[sample * 4 + 1];
        temp[sample * 4 + 3] = source[sample * 4 + 0];
      }
      SEGY::Ibm2ieee(target, temp.get(), sampleCount);
    }
    else
    {
      assert(endianness == SEGY::Endianness::BigEndian);
      SEGY::Ibm2ieee(target, reinterpret_cast<const uint32_t*>((intptr_t)data + (size_t)sampleStart * 4), sampleCount);
    }
  }
  else
  {
    assert(dataSampleFormatCode == SEGY::BinaryHeader::DataSampleFormatCode::IEEEFloat);
    if(endianness == SEGY::Endianness::LittleEndian)
    {
      SEGY::ConvertFromEndianness<SEGY::Endianness::LittleEndian>(target, reinterpret_cast<const char*>((intptr_t)data + (size_t)sampleStart * 4), sampleCount);
    }
    else
    {
      assert(endianness == SEGY::Endianness::BigEndian);
      SEGY::ConvertFromEndianness<SEGY::Endianness::BigEndian>(target, reinterpret_cast<const char*>((intptr_t)data + (size_t)sampleStart * 4), sampleCount);
    }
  }
}

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
void
updateValueRangeHeaps(const SEGYFileInfo& fileInfo, const int heapSizeMax, std::vector<float>& minHeap, std::vector<float>& maxHeap, const void * data, std::vector<float>& sampleBuffer)
{
  if (fileInfo.m_dataSampleFormatCode == SEGY::BinaryHeader::DataSampleFormatCode::IBMFloat || fileInfo.m_dataSampleFormatCode == SEGY::BinaryHeader::DataSampleFormatCode::IEEEFloat)
  {
    sampleBuffer.resize(fileInfo.m_sampleCount);
    copySamples(data, fileInfo.m_dataSampleFormatCode, fileInfo.m_headerEndianness, sampleBuffer.data(), 0, fileInfo.m_sampleCount);

    for (int sample = 0; sample < fileInfo.m_sampleCount; sample++)
    {
      if (int(minHeap.size()) < heapSizeMax)
      {
        minHeap.push_back(sampleBuffer[sample]);
        std::push_heap(minHeap.begin(), minHeap.end(), std::less<float>());
      }
      else if (sampleBuffer[sample] < minHeap[0])
      {
        std::pop_heap(minHeap.begin(), minHeap.end(), std::less<float>());
        minHeap.back() = sampleBuffer[sample];
        std::push_heap(minHeap.begin(), minHeap.end(), std::less<float>());
      }

      if (int(maxHeap.size()) < heapSizeMax)
      {
        maxHeap.push_back(sampleBuffer[sample]);
        std::push_heap(maxHeap.begin(), maxHeap.end(), std::greater<float>());
      }
      else if (sampleBuffer[sample] > maxHeap[0])
      {
        std::pop_heap(maxHeap.begin(), maxHeap.end(), std::greater<float>());
        maxHeap.back() = sampleBuffer[sample];
        std::push_heap(maxHeap.begin(), maxHeap.end(), std::greater<float>());
      }
    }
  }
}

895
bool
Jim King's avatar
Jim King committed
896
analyzeSegment(DataProvider &dataProvider, SEGYFileInfo const& fileInfo, SEGYSegmentInfo const& segmentInfo, float valueRangePercentile, OpenVDS::FloatRange& valueRange, int& fold, int& secondaryStep, const SEGY::SEGYType segyType, int& offsetStart, int& offsetEnd, int& offsetStep, TraceInfo2DManager * pTraceInfo2DManager, bool isTraceOrderByOffset, bool jsonOutput, OpenVDS::Error& error)
897
{
898
  assert(segmentInfo.m_traceStop >= segmentInfo.m_traceStart && "A valid segment info should always have a stop trace greater or equal to the start trace");
899
900
901
  assert(pTraceInfo2DManager != nullptr);

  pTraceInfo2DManager->Clear();
902

903
  bool success = true;
904

905
906
907
  valueRange = OpenVDS::FloatRange(0.0f, 1.0f);
  secondaryStep = 0;
  fold = 1;
908
909
910
  offsetStart = 0;
  offsetEnd = 0;
  offsetStep = 0;
911

912
  const int traceByteSize = fileInfo.TraceByteSize();
913

914
915
916
  int64_t traceBufferStart = 0;
  int traceBufferSize = 0;
  std::unique_ptr<char[]> buffer;
917

918
  // Create min/max heaps for determining value range
919
  int heapSizeMax = int(((100.0f - valueRangePercentile) / 100.0f) * (segmentInfo.m_traceStop - segmentInfo.m_traceStart + 1) * fileInfo.m_sampleCount / 2) + 1;
920

921
922
923
924
925
926
  std::vector<float> minHeap, maxHeap;

  minHeap.reserve(heapSizeMax);
  maxHeap.reserve(heapSizeMax);

  // Allocate sample buffer for converting samples to float
927
  std::vector<float> sampleBuffer(fileInfo.m_sampleCount);
928
929
930
931

  // Determine fold and secondary step
  int gatherSecondaryKey = 0, gatherFold = 0, gatherSecondaryStep = 0;

932
933
  std::set<int>
    offsetValues;
934

935
  for (int64_t trace = segmentInfo.m_traceStart; trace <= segmentInfo.m_traceStop; trace++)
936
  {
937
938
939
    if(trace - traceBufferStart >= traceBufferSize)
    {
      traceBufferStart = trace;
940
      traceBufferSize = (segmentInfo.m_traceStop - trace + 1) < 1000 ? int(segmentInfo.m_traceStop - trace + 1) : 1000;
941

942
      buffer.reset(new char[static_cast<size_t>(traceByteSize) * traceBufferSize]);
943
944
      int64_t offset = SEGY::TextualFileHeaderSize + SEGY::BinaryFileHeaderSize + traceByteSize * traceBufferStart;
      success = dataProvider.Read(buffer.get(), offset, traceByteSize * traceBufferSize, error);
945

946
947
948
949
950
      if (!success)
      {
        break;
      }
    }
951

952
953
    const void *header = buffer.get() + traceByteSize * (trace - traceBufferStart);
    const void *data   = buffer.get() + traceByteSize * (trace - traceBufferStart) + SEGY::TraceHeaderSize;
954

955
    int tracePrimaryKey = fileInfo.Is2D() ? 0 : SEGY::ReadFieldFromHeader(header, fileInfo.m_primaryKey, fileInfo.m_headerEndianness);
956
    int traceSecondaryKey = fileInfo.IsUnbinned() ? static_cast<int>(trace - segmentInfo.m_traceStart + 1) : SEGY::ReadFieldFromHeader(header, fileInfo.m_secondaryKey, fileInfo.m_headerEndianness);
957

958
    if(tracePrimaryKey != segmentInfo.m_primaryKey)
959
    {
960
      OpenVDS::printWarning(jsonOutput, "SEGY", fmt::format("trace {} has a primary key that doesn't match with the segment. This trace will be ignored.", segmentInfo.m_traceStart + trace));
961
962
963
      continue;
    }

964
965
    pTraceInfo2DManager->AddTraceInfo(static_cast<const char *>(header));

966
967
968
969
970
971
972
973
974
975
976
977
    if(gatherFold > 0 && traceSecondaryKey == gatherSecondaryKey)
    {
      gatherFold++;
      fold = std::max(fold, gatherFold);
    }
    else
    {
      // Updating the secondary step with the step for the previous gather intentionally ignores the step of the last gather since it can be anomalous
      if(gatherSecondaryStep && (!secondaryStep || std::abs(gatherSecondaryStep) < std::abs(secondaryStep)))
      {
        secondaryStep = gatherSecondaryStep;
      }
978

979
      if(gatherFold > 0)
980
      {
981
        gatherSecondaryStep = traceSecondaryKey - gatherSecondaryKey;
982
      }
983
984
985
986
      gatherSecondaryKey = traceSecondaryKey;
      gatherFold = 1;
    }

987
    if (fileInfo.HasGatherOffset())
988
    {
989
      const auto
990
        thisOffset = SEGY::ReadFieldFromHeader(header, g_traceHeaderFields["offset"], fileInfo.m_headerEndianness);
991
      offsetValues.insert(thisOffset);
992
993
    }

994
    // Update value range
995
    updateValueRangeHeaps(fileInfo, heapSizeMax, minHeap, maxHeap, data, sampleBuffer);
996
997
  }

998
  if (fileInfo.HasGatherOffset() && !fileInfo.IsUnbinned())
999
  {
1000
    offsetStart = *offsetValues.begin();
For faster browsing, not all history is shown. View entire blame