test_api.cpp 49.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Copyright 2017-2020, Schlumberger
//
// 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.

#include "test_all.h"
#include "test_utils.h"
#include "../api.h"
18
#include "../iocontext.h"
19
20
21
22
23
24
25
26
27
28
#include "../exception.h"
#include "../impl/environment.h"

#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
#include <cstdint>
#include <cmath>
#include <numeric>
29
#include <limits>
30
31
#include <thread>
#include <chrono>
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

using namespace OpenZGY;
using namespace OpenZGY::Formatters;
using Test_Utils::LocalFileAutoDelete;

namespace {
  template<typename T, std::size_t  N>
  std::ostream& operator<<(std::ostream& os, const std::array<T,N>& a)
  {
    os << "[";
    for (std::size_t ii=0; ii<N; ++ii)
      os << a[ii] << (ii == N-1 ? "" : ", ");
    os << "]";
    return os;
  }

  std::ostream& operator<<(std::ostream& os, const SampleStatistics& in)
  {
    os << "cnt: " << in.cnt
       << " sum: " << in.sum
       << " ssq: " << in.ssq
       << " min: " << in.min
       << " max: " << in.max;
    return os;
  }

  std::ostream& operator<<(std::ostream& os, const SampleHistogram& in)
  {
    os << "cnt: " << in.samplecount
       << " min: " << in.minvalue
       << " max: " << in.maxvalue
       << " bincount: " << in.bins.size();
    return os;
  }
}

namespace Test_API {
#if 0
}
#endif

static std::string
get_testdata(const std::string& name)
{
  using InternalZGY::Environment;
#ifdef _WIN32
  std::string result = Environment::getStringEnv("OPENZGY_TESTDATA", "..\\..\\build\\testdata");
  if (result.back() != '\\')
    result += "\\";
  result += name;
  return result;
#else
  return
    Environment::getStringEnv("OPENZGY_TESTDATA", "../../build/testdata")
    + "/" + name;
#endif
}

static bool similar(double a, double b, double eps)
{
  return std::abs(a - b)  <= eps * 0.5 * (std::abs(a) + std::abs(b));
}

static void dump_api(std::shared_ptr<OpenZGY::IZgyReader> rr, std::ostream& out)
{
  const OpenZGY::IZgyReader& r = *rr.get();
  std::streamsize oldprec = std::cout.precision();
  std::ios_base::fmtflags oldflags = std::cout.flags();

  out << "File format                    = " << r.datatype() << "\n";
  out << "Size I,J,K                     = " << r.size() << "\n";
  out << "Brick size I,J,K               = " << r.bricksize() << "\n";
  out << "Number of bricks I,J,K         = " << r.brickcount()[0] << "\n";
  out << "Number of LODs                 = " << r.nlods() << "\n";
  out << "Coding range min/max           = " << r.datarange() << "\n";
  out << "Statistical min/max/count      = " << r.statistics() << "\n";
  out << "Histogram range min/max/count  = " << r.histogram() << "\n";
  out << "Inline start/increment/count   = "
      << r.annotstart()[0] << " "
      << r.annotinc()[0] << " "
      << r.size()[0] << "\n";
  out << "Xline  start/increment/count   = "
      << r.annotstart()[1] << " "
      << r.annotinc()[1] << " "
      << r.size()[1] << "\n";
  out << "Sample start/increment/count   = "
      << r.zstart() << " "
      << r.zinc() << " "
      << r.size()[2] << "\n";
  out << "Horizontal dim/factor/name     = "
      << r.hunitdim() << " "
      << r.hunitfactor() << " '"
      << r.hunitname() << "'\n";
  out << "Vertical dim/factor/name       = "
      << r.zunitdim() << " "
      << r.zunitfactor() << " '"
      << r.zunitname() << "'\n";
  out << "Ordered Corner Points Legend   = [  <i>,   <j>] { <inline>,   <xline>} (  <easting>,  <northing>)" << "\n";
  for (int ii=0; ii<4; ++ii)
    out << "Ordered Corner Point " << ii << "         = ["
        << std::fixed << std::setprecision(0)
        << std::setw(5) << r.indexcorners()[ii][0] << ", "
        << std::setw(5) << r.indexcorners()[ii][1] << "] {"
        << std::scientific << std::setprecision(6)
        << std::setw(9) << r.annotcorners()[ii][0] << ", "
        << std::setw(9) << r.annotcorners()[ii][1] << "} ("
        << std::fixed << std::setprecision(2)
        << std::setw(11) << r.corners()[ii][0] << ", "
        << std::setw(11) << r.corners()[ii][1] << ")\n"
        << std::scientific << std::setprecision(oldprec);
  // Note, I'd like defaultfloat instead of scientific
  // but the former is not supported on all compilers.
  // This is also why I need to reset the flags.
  std::cout.flags(oldflags);
}

static void must_throw(const char *expect, const std::function<void()>& fn)
{
  try {
    fn();
    if (verbose()) {
      std::cout << "Did not get expected exception \"" << expect << "\"\n";
    }
    TEST_CHECK(false && "Did not get expected exception");
  }
  catch (const OpenZGY::Errors::ZgyError& ex) {
    if (verbose()) {
      if (strstr(ex.what(), expect) != nullptr)
        std::cout << "Got expected exception: " << ex.what() << std::endl;
      else
        std::cout << "Got exception, expected \"" << expect << "\""
                  << ", got \"" << ex.what()<< "\"\n";
    }
    TEST_CHECK(strstr(ex.what(), expect) != nullptr);
  }
}

void test_readmeta()
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  if (verbose()) {
    std::cout << "\n";
    dump_api(reader, std::cout);
    //reader->dump(std::cout);
  }

  const OpenZGY::IZgyReader& r(*reader);

  TEST_CHECK(r.datatype() == SampleDataType::int8);
  TEST_CHECK(r.size()[0] == 181);
  TEST_CHECK(r.size()[1] == 241);
  TEST_CHECK(r.size()[2] == 169);
  TEST_CHECK(r.bricksize()[0] == 64);
  TEST_CHECK(r.bricksize()[1] == 64);
  TEST_CHECK(r.bricksize()[2] == 64);
  TEST_CHECK(r.brickcount()[0][0] == 3);
  TEST_CHECK(r.brickcount()[0][1] == 4);
  TEST_CHECK(r.brickcount()[0][2] == 3);
  TEST_CHECK(r.nlods() == 3);
  TEST_CHECK(std::abs(r.datarange()[0] - (-10038.5)) < 0.5);
  TEST_CHECK(std::abs(r.datarange()[1] - (+9761.62)) < 0.5);
  TEST_CHECK(std::abs(r.statistics().min - (-10038.5)) < 0.5);
  TEST_CHECK(std::abs(r.statistics().max - (+9761.62)) < 0.5);
  TEST_CHECK(std::abs(r.histogram().minvalue - (-10038.5)) < 0.5);
  TEST_CHECK(std::abs(r.histogram().maxvalue - (+9761.62)) < 0.5);
  TEST_CHECK(r.statistics().cnt == 7371949);
  TEST_CHECK(r.histogram().samplecount == 7371949);
  TEST_CHECK(r.annotstart()[0] == 640);
  TEST_CHECK(r.annotstart()[1] == 920);
  TEST_CHECK(r.annotinc()[0] == 2);
  TEST_CHECK(r.annotinc()[1] == 2);
  TEST_CHECK(r.zstart() == 648);
  TEST_CHECK(r.zinc() == 6);
  TEST_CHECK(r.hunitdim() == UnitDimension::unknown);
  TEST_CHECK(r.hunitfactor() == 1.0);
  TEST_CHECK(r.hunitname() == "");
  TEST_CHECK(r.zunitdim() == UnitDimension::unknown);
  TEST_CHECK(r.zunitfactor() == 1.0);
  TEST_CHECK(r.zunitname() == "");

  // actual
  const IZgyReader::corners_t& index = r.indexcorners();
  const IZgyReader::corners_t& annot = r.annotcorners();
  const IZgyReader::corners_t& world = r.corners();

  // expect
  double ibeg[2] { 0, 0 };
  double iend[2] { (double)r.size()[0] - 1, (double)r.size()[1] - 1 };
  double abeg[2] { r.annotstart()[0], r.annotstart()[1] };
  double aend[2] { abeg[0] + r.annotinc()[0] * (r.size()[0] - 1),
                   abeg[1] + r.annotinc()[1] * (r.size()[1] - 1)};

  TEST_CHECK(index[0][0] == ibeg[0] && index[0][1] == ibeg[1]);
  TEST_CHECK(index[1][0] == iend[0] && index[1][1] == ibeg[1]);
  TEST_CHECK(index[2][0] == ibeg[0] && index[2][1] == iend[1]);
  TEST_CHECK(index[3][0] == iend[0] && index[3][1] == iend[1]);

  TEST_CHECK(annot[0][0] == abeg[0] && annot[0][1] == abeg[1]);
  TEST_CHECK(annot[1][0] == aend[0] && annot[1][1] == abeg[1]);
  TEST_CHECK(annot[2][0] == abeg[0] && annot[2][1] == aend[1]);
  TEST_CHECK(annot[3][0] == aend[0] && annot[3][1] == aend[1]);

  TEST_CHECK(std::abs(world[0][0] -  564344.97) < 0.1);
  TEST_CHECK(std::abs(world[0][1] - 5917369.23) < 0.1);
  TEST_CHECK(std::abs(world[1][0] -  568209.86) < 0.1);
  TEST_CHECK(std::abs(world[1][1] - 5915035.21) < 0.1);
  TEST_CHECK(std::abs(world[2][0] -  567457.07) < 0.1);
  TEST_CHECK(std::abs(world[2][1] - 5922522.52) < 0.1);
  TEST_CHECK(std::abs(world[3][0] -  571321.95) < 0.1);
  TEST_CHECK(std::abs(world[3][1] - 5920188.49) < 0.1);
  reader->close();
}

void test_readconst()
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  std::pair<bool,double> c = reader->readconst(std::array<std::int64_t,3>{0,0,0}, reader->size(), 0, true);
  //std::cout << "constant? " << std::boolalpha << c.first << std::noboolalpha << " value " << c.second << "\n";
  TEST_CHECK(!c.first);
  reader->close();
}

void test_readbulk()
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size = reader->size();
  std::unique_ptr<float[]>buf(new float[size[0] * size[1] * size[2]]);
  reader->read(orig, size, buf.get(), 0);
  TEST_CHECK(std::abs(buf[0]+99.6137) < 0.001);
  reader->close();
}

void test_readbadvt()
{
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{16,16,16};
  std::unique_ptr<std::int16_t[]>buf(new std::int16_t[size[0] * size[1] * size[2]]);
  must_throw("storage cannot be null", [&](){
    reader->read(orig, size, (std::int8_t*)nullptr, 0);});
  must_throw("data type not supported", [&](){
    reader->read(orig, size, buf.get(), 0);});
  reader->close();
}

void test_readbadpos()
{
  typedef OpenZGY::IZgyWriter::size3i_t size3i_t;
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(get_testdata("Empty-v3.zgy"));
  std::unique_ptr<std::int8_t[]>buf(new std::int8_t[1024]);
  // Negative size is caught when ZgyReader::read() wraps our raw buffer into
  // a DataBuffer, so the check in ZgyInternalBulk::readToExistingBuffer()
  // is not used.
  must_throw("Size cannot be negative", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,-1,1}, buf.get(), 0);});
  must_throw("Size cannot be 0", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{0,0,0}, buf.get(), 0);});
  must_throw("outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1000}, buf.get(), 0);});
  must_throw("lod -1 is outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1}, buf.get(), -1);});
  must_throw("lod 3 is outside the valid range", [&](){
    reader->read(size3i_t{0,0,0}, size3i_t{1,1,1}, buf.get(), 3);});
  // Repeat the tests using readconst.
  must_throw("outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,-1,1}, 0, true);});
  must_throw("empty or outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{0,0,0}, 0, true);});
  must_throw("outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1000}, 0, true);});
  must_throw("lod -1 is outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1}, -1, true);});
  must_throw("lod 3 is outside the valid range", [&](){
    reader->readconst(size3i_t{0,0,0}, size3i_t{1,1,1}, 3, true);});
  reader->close();
}

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
#if HAVE_SD

/**
 * Meant to be wrapped in a functor and uses as the token callback
 * in a IOContext.
 */
class SDTokenUpdater
{
  bool alive_;
  int count_;
  std::string token_;
  mutable std::mutex mutex_;
public:
  explicit SDTokenUpdater(const std::string& token)
    : alive_(true)
    , count_(0)
    , token_(token)
    , mutex_()
  {
  }
  SDTokenUpdater(const SDTokenUpdater&) = delete;
  SDTokenUpdater& operator=(const SDTokenUpdater&) = delete;
  std::string operator()() {
    std::lock_guard<std::mutex> lk(mutex_);
    //if (verbose())
    //  std::cout << "Fetching token, alive " << alive_ << std::endl;
    if (!alive_) {
      // Possibly invoked from a static destructor, so use a fairly
      // basic way of logging the message.
      const char *msg = "FATAL ERROR: Token callback invoked after destruction\n";
      fwrite(msg, 1, strlen(msg), stderr);
      abort();
    }
    ++count_;
    return token_;
  }
  int clearcount() {
    std::lock_guard<std::mutex> lk(mutex_);
    int result = count_;
    count_ = 0;
    return result;
  }
  void update(const std::string& token) {
    std::lock_guard<std::mutex> lk(mutex_);
    token_ = token;
  }
  void die() {
    std::lock_guard<std::mutex> lk(mutex_);
    alive_ = false;
  }
};

bool
read_first_sample(const std::shared_ptr<OpenZGY::IZgyReader>& reader,
                  bool expect_ok,
                  const std::string& message)
{
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size{1,1,1};
  float bulk[1]{0};
  bool ok = false;

  if (verbose())
    std::cout << message << " is being tested." << std::endl;
  try {
    reader->read(orig, size, &bulk[0], 0);
    if (!expect_ok)
      std::cout << message << " ERROR, should not have worked."
                << std::endl;
    else if (std::abs(bulk[0]-0.0039) > 0.001)
      std::cout << message << " FAILED with wrong sample value "
                << bulk[0] << std::endl;
    else
      ok = true;
  }
  catch (const std::exception& ex) {
    if (expect_ok) {
      std::cout << message << " FAILED with: " << ex.what() << std::endl;
      ok = false;
    }
    else {
      ok = true;
      if (verbose())
        std::cout << "Got expected: " << ex.what() << std::endl;
    }
  }
  return ok;
}

std::string
cloud_synt2_name()
{
  std::string testfolder = InternalZGY::Environment::getStringEnv("OPENZGY_SDTESTDATA", "sd://sntc/testdata");
  if (testfolder.back() != '/')
    testfolder += "/";
  return testfolder + "Synt2.zgy";
}

/**
 * When using a token refresh callback, make sure it isn't invoked
 * at a point where we cannot be sure it is still valid.
 *
 * We might decide that the application is required to provide a
 * callback that stays valid. In that case this test is N/A.
 */
void
test_tokencb_destroy()
{
  using InternalZGY::Environment;
  std::string token = Environment::getStringEnv("OPENZGY_TOKEN");
  auto callback = std::make_shared<SDTokenUpdater>(token);
  std::function<std::string()> functor = [callback]() {return (*callback)();};
  auto context = SeismicStoreIOContext()
    .sdurl(Environment::getStringEnv("OPENZGY_SDURL"))
    .sdapikey(Environment::getStringEnv("OPENZGY_SDAPIKEY"))
    .sdtokencb(functor, "");
  std::shared_ptr<IZgyReader> reader =
    IZgyReader::open(cloud_synt2_name(), &context);

  // If the reader is destructed while still open then it is attempted
  // closed but it is forbidden to try to refresh the token because we
  // cannot know whether the callback is still valid. Especially if
  // triggered from a static destructor, although that might have its
  // own problems.
  (void)callback->clearcount();
  reader.reset();
  TEST_CHECK(callback->clearcount() == 0);

  // Also try to test the unlikely case that the callback is invoked
  // even later. The callback instance remains valid because the
  // functor captures a smart pointer reference to it. It is too late
  // to report that this particular test failed. Instead the call to
  // die() will make the test suite abort if the callback gets invoked
  // when it shouldn't have been.
  callback->die();
}

/**
 * \brief Check that the access token may be replaced on an open file.
 *
 * This is tricky. Manual steps are needed to run the full test.
 *
 * For example, even if the SAuth token expires in just a few minutes
 * it can be used to obtain a GCS token with a lifetime of (currently)
 * one hour. That token is cached which means the system won't even
 * try to use the new SAuth token for reading bulk until an hour has
 * elapsed. At least I think this is what is going on.
 *
 * There may be other places where a token is used past its expiry
 * date bacause it is too expensive to validate the token too often.
 *
 * So here is a possible test scenario:
 *
 *   \li Obtain a 24-hour token with $(echo $(sdutil auth idtoken))
 *   \li Open a file with that token and read a few bytes fron it.
 *   \li Sleep for 24 hours waiting for the token to expire.
 *   \li Sleep for 60 minutes to let GCS tokens expire.
 *   \li Sleep for 30 minutes or more to hopefully expire whatever is left.
 *   \li Continue reading from the file, verify you get an error.
 *   \li Obtain a new token with $(echo $(sdutil auth idtoken))
 *   \li (You may need to login if sdutil's 7-day(?) refresh token has expired).
 *   \li Store the new token in the SDManager.
 *   \li Continue reading and verify that it now works.
 *
 * Yes I realize it might be sufficient with max(24h,1h)+30min instead
 * of adding the numbers so I might shave off one hour. But if the
 * test fails it will take another day to run it again.
 *
 * If running a test for 26 hours is impractical then you can obtain
 * two sdutil tokens with 23 hours between them. You can then pass
 * both tokens to the test program and you will only need to sleep for
 * 2.5 hours. Or even less if you cut it fine with the interval
 * between tokens. This is what this test does; with the two tokens
 * in $OPENZGY_TOKEN (about to expire) and $OPENZGY_NEWTOKEN (fresh).
 */
void
test_tokencb_normal()
{
  using InternalZGY::Environment;
  if (verbose())
    std::cout << std::endl;

  std::string oldtoken = Environment::getStringEnv("OPENZGY_TOKEN");
  auto callback = std::make_shared<SDTokenUpdater>("BOGUS.INVALID.TOKEN");
  std::function<std::string()> functor = [callback]() {return (*callback)();};
  auto context = SeismicStoreIOContext()
    .sdurl(Environment::getStringEnv("OPENZGY_SDURL"))
    .sdapikey(Environment::getStringEnv("OPENZGY_SDAPIKEY"))
    .sdtokencb(functor, "");
  callback->update(oldtoken);

  // Reading from a file should work just as normal;
  // the only difference is that the token is picked up
  // via the callback.
  std::shared_ptr<IZgyReader> reader =
    IZgyReader::open(cloud_synt2_name(), &context);

  TEST_CHECK(read_first_sample(reader, true, "Normal read"));
  TEST_CHECK(callback->clearcount() > 0);

  int sleeptime = Environment::getNumericEnv("OPENZGY_TEST_TOKENCB_SLEEP", -1);
  std::string newtoken = Environment::getStringEnv("OPENZGY_NEWTOKEN", "");
  if (sleeptime >= 0 && !newtoken.empty()) {
    // This test can literally take hours to run, so it can only be
    // run manually. Read some data, wait for token to expire, read
    // some more, get a new token. This check verifies that that both
    // OpenZGY and SDAPI can properly recover from an expired token. A
    // variant of this test could pre-emptively replace the expired
    // token before trying to read from it.
    std::cout << "Sleeping " << sleeptime
              << " minutes waiting for token to expire."
              << std::endl;
    std::this_thread::sleep_for (std::chrono::minutes(sleeptime));
    std::cout << "Awake!" << std::endl;
    TEST_CHECK(read_first_sample(reader, false, "Expired token"));
    callback->update(newtoken);
    TEST_CHECK(read_first_sample(reader, true, "Restored token"));
  }
  else if (sleeptime >= 0 && !oldtoken.empty()) {
    // Run a simpler version of the above that doesn't match a real
    // scenario and I can't really complain if it fails.
    // Caveat: SDManager might choose to keep its existing token if it
    // realizes that its existing token is still valid, or the new
    // token is bogus, or both. That is a completely reasonable
    // behavior. The test will set an expired or otherwise bad token
    // and make sure the read fails. Then set back the original and it
    // should work again. $OPENZGY_BADTOKEN should preferably be a
    // real token that has expired so it is closer to reality.
    // Experiments show that the test still needs to wait 60 minutes for
    // any cached GCS tokens to expire. See comment at start of function.
    if (verbose())
      std::cout << "Running the simplified tokencallback test." << std::endl;
    std::string badtoken = Environment::getStringEnv("OPENZGY_BADTOKEN", "BOGUS");
    callback->update(badtoken);
    if (sleeptime > 0) {
      std::cout << "Sleeping " << sleeptime
                << " minutes waiting for token to expire."
                << std::endl;
      std::this_thread::sleep_for (std::chrono::minutes(sleeptime));
      std::cout << "Awake!" << std::endl;
    }
    TEST_CHECK(read_first_sample(reader, false, "Bogus token"));
    TEST_CHECK(callback->clearcount() > 0);
    callback->update(oldtoken);
    TEST_CHECK(read_first_sample(reader, true, "Restored token"));
    TEST_CHECK(callback->clearcount() > 0);
  }

  // If there is something wrong with the token now then the close might
  // also throw. The actual message from this secondary error is not important.
  try {
    reader->close();
    TEST_CHECK(callback->clearcount() > 0);
  }
  catch (const std::exception& ex)
  {
    std::cout << "Exception closing the dataset: " << ex.what() << std::endl;
    TEST_CHECK(false && "failed in close");
  }

  // Repeat the test in test_tokencb_destroy(). The situation is
  // different because the reader is (or was attempted) closed.
  (void)callback->clearcount();
  reader.reset();
  TEST_CHECK(callback->clearcount() == 0);
  callback->die();
}

#endif

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
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
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
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
void test_ZgyWriterArgs()
{
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename("testfile")
    .size(33, 28, 92)
    .datatype(SampleDataType::int16)
    .zunit(UnitDimension::time, "ms", 1000);
  std::stringstream ss;
  args.dump(ss);
  if (verbose())
    std::cout << ss.str() << std::flush;
  TEST_CHECK(ss.str().find("filename:    \"testfile\"") != std::string::npos);
  TEST_CHECK(ss.str().find("size:        (33,28,92)") != std::string::npos);
  TEST_CHECK(ss.str().find("bricksize:   (64,64,64)") != std::string::npos);
  TEST_CHECK(ss.str().find("\"ms\"") != std::string::npos);
}

void test_write()
{
  LocalFileAutoDelete lad("testfile.zgy");
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(33, 28, 92)
    .datatype(SampleDataType::int16)
    .datarange(-32768,+32767)
    .ilstart(1).ilinc(2)
    .xlstart(500).xlinc(5)
    .zstart(100).zinc(4)
    .zunit(UnitDimension::time, "ms", 1000);
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  std::vector<float> data(2*3*4, -1000);
  const OpenZGY::IZgyWriter::size3i_t origin{0,0,0};
  const OpenZGY::IZgyWriter::size3i_t bsize{64,64,64};
  const OpenZGY::IZgyWriter::size3i_t count{2,3,4};
  float fortytwo{42};
  writer->writeconst(origin, bsize, &fortytwo);
  writer->write(origin, count, data.data());
  writer->finalize(std::vector<OpenZGY::DecimationType>{}, nullptr);
  writer->close();

  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(lad.name());
  if (verbose()) {
    std::cout << "\n";
    dump_api(reader, std::cout);
    //reader->dump(std::cout);
  }
  std::unique_ptr<float[]> checkdata(new float[64*64*64]);
  reader->read(origin, bsize, checkdata.get(), 0);
  TEST_CHECK(checkdata[0] == -1000);
  TEST_CHECK(checkdata[63] == 42);
  const SampleHistogram h = reader->histogram();
  TEST_CHECK(similar(h.minvalue, -32768, 1e-5));
  TEST_CHECK(similar(h.maxvalue, +32767, 1e-5));
  TEST_CHECK(h.samplecount == 33*28*92);
  TEST_CHECK(h.bins[124] == 2*3*4);
  TEST_CHECK(h.bins[128] == 33*28*92 - 2*3*4);
  reader->close();
}

void test_historange()
{
  LocalFileAutoDelete lad("testhisto.zgy");
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(33, 28, 92)
    .datatype(SampleDataType::float32);
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  std::vector<float> data(2*3*4, 0);
  const OpenZGY::IZgyWriter::size3i_t origin{0,0,0};
  const OpenZGY::IZgyWriter::size3i_t bottom{0,0,0};
  const OpenZGY::IZgyWriter::size3i_t bsize{64,64,64};
  const OpenZGY::IZgyWriter::size3i_t count{2,3,4};
  float fortytwo{42};
  writer->writeconst(origin, bsize, &fortytwo);
  data[0] = -1000;
  writer->write(bottom, count, data.data());
  data[0] = -500;
  writer->write(bottom, count, data.data());
  writer->finalize(std::vector<OpenZGY::DecimationType>{OpenZGY::DecimationType::Decimate}, nullptr);
  writer->close();

  // The writer has seen "42" (as a constant brick), "0", "-500", and "-1000".
  // The latter was overwritten so the true value range is now -500..+42
  // but by design and for implementation reasons the histogram range will be
  // large enough to also hold the "-1000". A narrower range than -500..+42
  // (e.g. because I forgot to include the writeconst) would be a bug.
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(lad.name());
  const SampleHistogram h = reader->histogram();
  TEST_CHECK(similar(h.minvalue, -1000, 1e-5));
  TEST_CHECK(similar(h.maxvalue, +42, 1e-5));
  TEST_CHECK(h.samplecount == 33*28*92);
  reader->close();
}

void test_lod(OpenZGY::DecimationType decimation)
{
  LocalFileAutoDelete lad("testlods.zgy");
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(3, 2, 101)
    .datatype(SampleDataType::float32);
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  std::vector<float> data(3*2*101, 100);
  const OpenZGY::IZgyWriter::size3i_t origin{0,0,0};
  const OpenZGY::IZgyWriter::size3i_t ssize{3,2,101};
  const OpenZGY::IZgyWriter::size3i_t lod1size{2,1,51};
  data[16] = 50; // cube[0,0,16]
  data[2*(101*2)+0*(101)+32] = 200; // cube[2,0,32]
  writer->write(origin, ssize, data.data());
  writer->finalize(std::vector<OpenZGY::DecimationType>{decimation}, nullptr);
  writer->close();

  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(lad.name());
  std::unique_ptr<float[]> lowres(new float[2*1*51]);
  reader->read(origin, lod1size, lowres.get(), 1);

  // The only input samples that differ from 100 are [0,0,16] and [2,0,32]
  // corresponding to [0,0,8] and [1,0,16] in LOD 1. So the asserts
  // check those two and (for the first value) some samples above and below.

  if (verbose()) {
    std::cout << "LOD 1, algorithm " << int(decimation) << "\n";
    for (int ii=0; ii<16; ++ii)
      std::cout << "  " << lowres[ii] << "\n";
  }

  // Expected result around [0,0,8].
  // The first "expect" is based on a previous run but you can see
  // that this looks like a lowpass filter. Ditto for the second which
  // should be like average, just one sample != 100, but lower because
  // the single "50" input carries more weight. The last one is computed
  // trivially by hand.
  static double expect_zero[16]{0};
  static double expect_lowpass[16]
    {100.0,  100.0, 100.0, 100.0, 100.0, 100.0, 103.62, 93.39,
     76.64, 105.51, 95.84, 100.0, 100.0, 100.0,  100.0, 100.0};
  static double expect_weighted[16]
    {100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0,
     50.57, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0};
  static double expect_average[16]
    {100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0,
     93.75, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0};

  const double* expect = expect_zero;
  switch (decimation) {
  case OpenZGY::DecimationType::LowPass:         expect = expect_lowpass; break;
  case OpenZGY::DecimationType::WeightedAverage: expect = expect_weighted; break;
  case OpenZGY::DecimationType::Average:         expect = expect_average; break;
  default: break;
  }

  for (int ii=0; ii<16; ++ii)
    TEST_CHECK(similar(lowres[ii], expect[ii], 0.02));

  // Expected result around [1,0,16].
  // Currently if the size is odd then the last slice will be all zero.
  // Except for lowpass. This might change later.
  const double value = lowres[1*(1*51)+0*(51)+16]; // [1,0,16]
  if (verbose())
    std::cout << "  " << value << "\n";
  switch (decimation) {
  case OpenZGY::DecimationType::LowPass:
    TEST_CHECK(similar(value, 146.73, 0.02));
    break;
  default:
    TEST_CHECK(similar(value, 0, 0.02));
    break;
  }

  reader->close();
}

void test_lod_lowpass()
{
  test_lod(OpenZGY::DecimationType::LowPass);
}

void test_lod_weighted()
{
  test_lod(OpenZGY::DecimationType::WeightedAverage);
}

void test_lod_average()
{
  test_lod(OpenZGY::DecimationType::Average);
}

void compare_stats(const SampleStatistics& a, const SampleStatistics& b, double eps)
{
  TEST_CHECK(a.cnt == b.cnt);
  TEST_CHECK(similar(a.sum, b.sum, eps));
  TEST_CHECK(similar(a.ssq, b.ssq, eps));
  TEST_CHECK(similar(a.min, b.min, eps));
  TEST_CHECK(similar(a.max, b.max, eps));
}

void compare_histo(const SampleHistogram& a, const SampleHistogram& b, double eps)
{
  // Consistency checks done on both histograms in turn.
  // The histogram on file stores sample_count. If there are no NaN, Inf,
  // or outside-range this should match the sum of all bins.
  const std::int64_t acount =
    std::accumulate(a.bins.begin(), a.bins.end(), std::int64_t(0));
  const std::int64_t bcount =
    std::accumulate(b.bins.begin(), b.bins.end(), std::int64_t(0));
  TEST_CHECK(a.samplecount == acount);
  TEST_CHECK(b.samplecount == bcount);
  // Now compare the two histograms.
  TEST_CHECK(a.bins.size() == b.bins.size());
  TEST_CHECK(a.samplecount == b.samplecount);
  TEST_CHECK(similar(a.minvalue, b.minvalue, eps));
  TEST_CHECK(similar(a.maxvalue, b.maxvalue, eps));
  for (std::size_t ii = 0; ii < std::min(a.bins.size(), b.bins.size()); ++ii) {
    TEST_CHECK(a.bins[ii] == b.bins[ii]);
    if (verbose())
      std::cout << "[" << ii << "] "
                << std::setw(8) << a.bins[ii] << " "
                << std::setw(8) << b.bins[ii] << " "
                << std::setw(8) << (a.bins[ii] - b.bins[ii]) << "\n";
  }
}

void compare_files(const std::string& fa, const std::string& fb)
{
  std::shared_ptr<OpenZGY::IZgyReader> a = OpenZGY::IZgyReader::open(fa);
  std::shared_ptr<OpenZGY::IZgyReader> b = OpenZGY::IZgyReader::open(fb);
  if (verbose()) {
    std::cout << "Statistics\n"
              << "a: " << a->statistics() << "\nb: " << b->statistics() << "\n";
    std::cout << "Histogram\n"
              << "a: " << a->histogram() << "\nb: " << b->histogram() << "\n";
  }
  compare_stats(a->statistics(), b->statistics(), 1.0e-5);
  compare_histo(a->histogram(), b->histogram(), 1.0e-5);
  // Files with an integral type normally have histogram range set to
  // codingrange. I.e. we assume both the extreme minimum and the
  // extreme maximum are in use instead of checking. This might change
  // in the future for int16 files, so a failure here might not mean
  // there is anything wrong.
  if (a->datatype() != OpenZGY::SampleDataType::float32) {
    TEST_CHECK(similar(a->datarange()[0], a->histogram().minvalue, 1.0e-5));
    TEST_CHECK(similar(a->datarange()[1], a->histogram().maxvalue, 1.0e-5));
  }
  if (b->datatype() != OpenZGY::SampleDataType::float32) {
    TEST_CHECK(similar(b->datarange()[0], b->histogram().minvalue, 1.0e-5));
    TEST_CHECK(similar(b->datarange()[1], b->histogram().maxvalue, 1.0e-5));
  }
}

void test_copy()
{
  std::string fname = get_testdata("Fancy-int8.zgy");
  LocalFileAutoDelete lad("testcopy.zgy");
  std::string oname = lad.name();

  // read
  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(fname);
  const std::array<std::int64_t,3> orig{0,0,0};
  const std::array<std::int64_t,3> size = reader->size();
  std::unique_ptr<float[]>buf(new float[size[0] * size[1] * size[2]]);
  reader->read(orig, size, buf.get(), 0);

  // write
  ZgyWriterArgs args = ZgyWriterArgs()
    .metafrom(reader)
    //.datatype(SampleDataType::float32)
    .filename(oname);
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  const OpenZGY::IZgyWriter::size3i_t origin{0,0,0};
  writer->write(origin, size, buf.get());
  writer->finalize(std::vector<OpenZGY::DecimationType>{OpenZGY::DecimationType::Decimate}, nullptr);
  reader->close();
  writer->close();

  // check
  compare_files(fname, oname);
}

void test_enums()
{
  std::stringstream ss;
  ss << SampleDataType::int8 << ", "
     << UnitDimension::length << ", "
     << DecimationType::Median;
  TEST_CHECK(ss.str() == "SampleDataType::int8, UnitDimension::length, DecimationType::Median");
}

namespace {
  /**
   * Compressor function that always returns "cannot compress", so the
   * file remains uncompressed. The instance keeps track of how many
   * times the low level code attempted a compression. So the unit
   * tests can check that the code did in fact try.
   *
   * The instance itself is noncopyable; otherwise it would be
   * pointless to keep state. This means that although the signature
   * is correct it will need to be wrapped in a lambda that can be
   * copied while still pointing to the same DummyCompressor instance.
   * get() will return a suitable lambda.
   */
  class DummyCompressor
  {
  public:
    int called;
    DummyCompressor(const DummyCompressor&) = delete;
    const DummyCompressor& operator=(const DummyCompressor&) = delete;
    DummyCompressor() : called(0)
    {
    }
    IZgyWriter::rawdata_t operator()(const IZgyWriter::rawdata_t&, const IZgyWriter::size3i_t&) {
      ++called;
      return IZgyWriter::rawdata_t{nullptr, 0};
    }
    IZgyWriter::compressor_t get()
    {
      return [this](const IZgyWriter::rawdata_t& data, const IZgyWriter::size3i_t& shape) {return (*this)(data, shape);};
    }
  };
} // namespace

void test_dummy_compress()
{
  LocalFileAutoDelete lad("dummycompress.zgy");
  DummyCompressor compressor, lodcompressor;
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(33, 28, 92)
    .datatype(SampleDataType::float32)
    .compressor(compressor.get())
    .lodcompressor(lodcompressor.get());
  std::shared_ptr<IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  std::vector<float> data = Test_Utils::random_vector(33*28*92LL);
  const IZgyWriter::size3i_t origin{0,0,0};
  const IZgyWriter::size3i_t size = writer->size();
  writer->write(origin, size, data.data());
  TEST_CHECK(compressor.called == 2);
  writer->finalize();
  TEST_CHECK(lodcompressor.called == 1);
  writer->close();
}

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
struct onevalue_t
{
  double range_lo, range_hi;
  double stats_lo, stats_hi;
  double histo_lo, histo_hi;
  std::int64_t stats_count;
  std::int64_t histo_count;
  std::vector<std::int64_t> bins;

  onevalue_t(const std::array<float,2>& range,
             const SampleStatistics& stats,
             const SampleHistogram& histo)
    : range_lo(range[0]), range_hi(range[1])
    , stats_lo(stats.min), stats_hi(stats.max)
    , histo_lo(histo.minvalue), histo_hi(histo.maxvalue)
    , stats_count(stats.cnt)
    , histo_count(histo.samplecount)
    , bins(histo.bins)
  {
  }
};

943
onevalue_t test_histo_onevalue(SampleDataType dtype, float value, bool fill, const std::array<float,2>& datarange)
944
945
946
947
948
949
950
951
952
953
954
955
{
  if (verbose())
    std::cout << "\nTest dtype " << (int)dtype
              << " value " << value
              << (fill ? " only" : " and unwritten bricks")
              << "\n";
  typedef OpenZGY::IZgyWriter::size3i_t size3i_t;
  LocalFileAutoDelete lad("testhisto.zgy");
  ZgyWriterArgs args = ZgyWriterArgs()
    .filename(lad.name())
    .size(64,64,3*64)
    .datatype(dtype) // if float, datarange will be ignored.
956
    .datarange(datarange[0], datarange[1]);
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
  std::shared_ptr<OpenZGY::IZgyWriter> writer = OpenZGY::IZgyWriter::open(args);
  if (std::isfinite(value)) {
    std::vector<float> buf(64*64*64, value);
    writer->write(size3i_t{0,0,0}, size3i_t{64,64,64}, buf.data());
  }
  if (fill && std::isfinite(value)) {
    std::vector<float> buf(64*64*128, value);
    writer->write(size3i_t{0,0,64}, size3i_t{64,64,128}, buf.data());
  }
  writer->finalize(std::vector<OpenZGY::DecimationType>{OpenZGY::DecimationType::Decimate}, nullptr, /*force=*/true);
  writer->close();

  std::shared_ptr<OpenZGY::IZgyReader> reader = OpenZGY::IZgyReader::open(lad.name());

  if (verbose()) {
    std::cout << "Data range " << reader->datarange()[0]
              << " " << reader->datarange()[1] << "\n";
    std::cout << "Statistics " << reader->statistics() << "\n";
    std::cout << "Histogram  " << reader->histogram() << "\n";
    std::cout << std::flush;
  }
  return onevalue_t(reader->datarange(),
                    reader->statistics(),
                    reader->histogram());
}

983
984
985
986
987
988
989
onevalue_t test_histo_onevalue(SampleDataType dtype, float value, bool fill)
{
  float center = std::isfinite(value) ? value : -0.25;
  return test_histo_onevalue(dtype, value, fill,
                             std::array<float,2>{center-1, center+1});
}

990
991
992
993
994
995
996
997
998
999
1000
void test_histo_cornercase_float()
{
  const float nan = std::numeric_limits<float>::quiet_NaN();
  const std::int64_t BRICK = 64*64*64;

  // Float: datarange with zero size is valid on input,
  // in fact the data range isn't specified by the user.
  // Reading back data gives the statistical range
  // which for float may include defaultvalue.
  // The histogram will use the fuzzy algorithm.

For faster browsing, not all history is shown. View entire blame