openzgycppmodule.cpp 85.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// 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.

#ifdef _WIN32
#pragma warning(disable: 4251) // Needs dll-interface
#endif

#define PY_SSIZE_T_CLEAN
#undef NDEBUG
#include <Python.h>
#include <structmember.h>

#include <api.h>
#include <iocontext.h>
#include <exception.h>
#include <impl/logger.h>

#include <atomic>
#include <memory>
#include <omp.h>
#include <iostream>
#include <assert.h>
#include <functional>

#ifdef _WIN32
#include <process.h> // getpid()
#endif

using namespace OpenZGY;
using namespace OpenZGY::Errors;
using InternalZGY::LoggerBase;

// The code that tries to MT-fetch one brick at a time has been removed.
// TODO-Low: converters should have a round=False argument.
// TODO-Low: convert arrays instead of just single values.

static PyObject* _zgy_error = nullptr;
static PyObject* _zgy_error_FormatError = nullptr;
static PyObject* _zgy_error_CorruptedFile = nullptr;
static PyObject* _zgy_error_UserError = nullptr;
static PyObject* _zgy_error_InternalError = nullptr;
static PyObject* _zgy_error_EndOfFile = nullptr;
static PyObject* _zgy_error_SegmentIsClosed = nullptr;
static PyObject* _zgy_error_Aborted = nullptr;
static PyObject* _zgy_error_MissingFeature = nullptr;
static PyObject* _zgy_error_IoError = nullptr;
static PyObject* _enum_SampleDataType = nullptr;
static PyObject* _enum_UnitDimension = nullptr;
static PyObject* _enum_DecimationType = nullptr;
static PyObject* _namedtuple_Statistics = nullptr;
static PyObject* _namedtuple_Histogram = nullptr;

static PyObject*
_raise_simple_error(PyObject* type, const char *message)
{
  PyErr_SetString(type==NULL ? _zgy_error : type,
                  message ? message : "error");
  return NULL;
}

static PyObject*
_raise_simple_error(PyObject* type, const std::string& message)
{
  return _raise_simple_error(type, message.c_str());
}

static PyObject*
_raise_ex()
{
  try {
    throw;
  }
  catch (const ZgyFormatError& ex)     { return _raise_simple_error(_zgy_error_FormatError,     ex.what()); }
  catch (const ZgyCorruptedFile& ex)   { return _raise_simple_error(_zgy_error_CorruptedFile,   ex.what()); }
  catch (const ZgyUserError& ex)       { return _raise_simple_error(_zgy_error_UserError,       ex.what()); }
  catch (const ZgyInternalError& ex)   { return _raise_simple_error(_zgy_error_InternalError,   ex.what()); }
  catch (const ZgyEndOfFile& ex)       { return _raise_simple_error(_zgy_error_EndOfFile,       ex.what()); }
  catch (const ZgySegmentIsClosed& ex) { return _raise_simple_error(_zgy_error_SegmentIsClosed, ex.what()); }
  catch (const ZgyAborted& ex)         { return _raise_simple_error(_zgy_error_Aborted,         ex.what()); }
  catch (const ZgyMissingFeature& ex)  { return _raise_simple_error(_zgy_error_MissingFeature,  ex.what()); }
  catch (const ZgyIoError& ex)         { return _raise_simple_error(_zgy_error_IoError,         ex.what()); }
  catch (const ZgyError& ex)           { return _raise_simple_error(_zgy_error,                 ex.what()); }
  catch (const std::exception& ex)     { return _raise_simple_error(_zgy_error,                 ex.what()); }
  catch (...)                          { return _raise_simple_error(_zgy_error, "(unknown exception"); }
}

static std::string
_toString(PyObject* obj)
{
  if (!obj)
    return "(null)";
  else if (obj == Py_None)
    return "None";
  PyObject* strobj = PyObject_Str(obj);
  if (!strobj) {
    PyErr_Clear();
    return "(error)";
  }
  const char *cstring = PyUnicode_AsUTF8(strobj);
  if (!cstring) {
    PyErr_Clear();
    return "(error)";
  }
  Py_XDECREF(strobj);
  return std::string(cstring);
}

/**
 * Return (long)obj.value.
 * On error set an exception and return -1.
 * A "value" < 0 is also flagged as an error.
 */
static long
_decodeEnum(PyObject *obj, PyObject* typeobj)
{
  if (!PyObject_TypeCheck(obj, (PyTypeObject*)typeobj)) {
    _raise_simple_error(PyExc_TypeError, "Expected " + _toString(typeobj));
    return -1;
  }
  PyObject *enum_value = PyObject_GetAttrString(obj, "value");
  if (!enum_value)
    return -1;
  long result = PyLong_AsLong(enum_value);
  Py_XDECREF(enum_value);
  if (result < 0) {
    _raise_simple_error(_zgy_error_InternalError, "Cannot get enum tag");
    return -1;
  }
  return result;
}

/////////////////////////////////////////////////////////////////////////////
///   ZgyReader class   /////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/**
 * Using the pimpl pattern, among other things because some of the members
 * are complex C++ types which don't play well with tp_init, tp_dealloc
 */
struct ZgyClassImpl
{
  typedef std::function<bool(int, const std::string&)> LoggerFn;
  std::string filename;
  int numthreads;

  // The logger verbosity is captured in the lambda assigned to logger_.
  // The logger_verbose_ member is only there so the current "verbose"
  // level can be read from application code.
  int logger_verbose_;
  LoggerFn logger_;

  //MyMetaData meta;
  //ZgyApi::ReaderPtr read_accessor;
  //ZgyApi::WriterPtr write_accessor;
  std::shared_ptr<IZgyReader> reader_;
  std::shared_ptr<IZgyWriter> writer_;
  std::shared_ptr<IZgyTools> meta_;
  std::shared_ptr<IZgyUtils> utils_;

  PyObject *debug_trace_;

  ZgyClassImpl()
    : numthreads(1)
    , logger_verbose_(-1)
    , logger_(LoggerBase::emptyCallback())
    , debug_trace_(nullptr)
  {
  }
  ~ZgyClassImpl()
  {
    Py_XDECREF(debug_trace_);
    debug_trace_ = nullptr;
  }
};

struct ZgyClass
{
  PyObject_HEAD
  ZgyClassImpl *pimpl_;
};

static bool pimplcheck(ZgyClass* self)
{
  if (!self || !self->pimpl_ || !self->pimpl_->meta_) {
    _raise_simple_error(_zgy_error_InternalError,
      "Trying to access a closed ZgyReader or ZgyWriter");
    return false;
  }
  return true;
}

static PyObject * ZgyReader_open(ZgyClass* self, PyObject* args, PyObject* keywds);
static PyObject * ZgyWriter_create(ZgyClass* self, PyObject* args, PyObject* keywds);
static PyObject * ZgyWriter_clone(ZgyClass* self, PyObject* args, PyObject* keywds);
static PyObject * ZgyUtils_open(ZgyClass* self, PyObject* args, PyObject* keywds);

static void
ZgyReader_dealloc(ZgyClass *self)
{
  ZgyClassImpl *pimpl = self->pimpl_;
  self->pimpl_ = NULL;
  pimpl->logger_(1, "Destructed a ZgyReader\n");
  delete pimpl;
  Py_TYPE(self)->tp_free((PyObject*)self);
}

static PyObject *
ZgyReader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  ZgyClass *self = reinterpret_cast<ZgyClass*>(type->tp_alloc(type, 0));
  self->pimpl_ = new ZgyClassImpl();
  self->pimpl_->logger_verbose_ = LoggerBase::getVerboseFromEnv("OPENZGY_VERBOSE");
  self->pimpl_->logger_ = LoggerBase::standardCallback(self->pimpl_->logger_verbose_, "openzgy-pyreader: ", "");
  self->pimpl_->logger_(1, "Created a new ZgyReader\n");
  return (PyObject *)self;
}

static int
ZgyReader_init(ZgyClass *self, PyObject *args, PyObject *kwds)
{
  // TODO-Low should I call the base class init now? But the base is just Object.
  PyObject* dummy = ZgyReader_open(self, args, kwds);
  int ret = dummy == NULL ? -1 : 0;
  Py_XDECREF(dummy);
  self->pimpl_->logger_(1, "Initialized a new ZgyReader\n");
  return ret;
}

static void
ZgyWriter_dealloc(ZgyClass *self)
{
  ZgyClassImpl *pimpl = self->pimpl_;
  self->pimpl_ = NULL;
  pimpl->logger_(1, "Destructed a ZgyWriter\n");
  delete pimpl;
  Py_TYPE(self)->tp_free((PyObject*)self);
}

static PyObject *
ZgyWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  ZgyClass *self = reinterpret_cast<ZgyClass*>(type->tp_alloc(type, 0));
  self->pimpl_ = new ZgyClassImpl();

  self->pimpl_->logger_verbose_ = LoggerBase::getVerboseFromEnv("OPENZGY_VERBOSE");
  self->pimpl_->logger_ = LoggerBase::standardCallback(self->pimpl_->logger_verbose_, "openzgy-pywriter: ", "");
  self->pimpl_->logger_(1, "Created a new ZgyWriter\n");
  return (PyObject *)self;
}

/**
 * Check if the arguments to the ZgyWriter constructor looks like
 * the "clone" version. If not, we will assume it is the regular create.
 * This should be unambiguous: A clone requires either the "template"
 * keyword argument or a string as the second arg. A regular create
 * cannot have the "template" keyword and the second arg should be a
 * tuple.
 */
static bool
callerWantsClone(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  static char *kwlist[] = {
    const_cast<char*>("filename"),
    const_cast<char*>("templatename"),
    const_cast<char*>("datatype"),
    const_cast<char*>("datarange"),
    const_cast<char*>("iocontext"),
    const_cast<char*>("compressor"),
    const_cast<char*>("lodcompressor"),
281
282
    const_cast<char*>("zfp_compressor"),
    const_cast<char*>("zfp_lodcompressor"),
283
284
285
286
287
288
289
290
    NULL
  };
  char *arg1 = 0, *arg2 = 0;
  PyObject* datatype_obj{nullptr};
  float dmin = 0, dmax = 0;
  PyObject* iocontext_obj{nullptr};
  PyObject* compressor_obj{nullptr};
  PyObject* lodcompressor_obj{nullptr};
291
292
  float zfp_snr = 0, zfp_lodsnr = 0;
  if (!PyArg_ParseTupleAndKeywords(args, keywds, "ss|O(ff)OOOff", kwlist,
293
294
295
                                   &arg1, &arg2, &datatype_obj, &dmin, &dmax,
                                   &iocontext_obj,
                                   &compressor_obj, &lodcompressor_obj,
296
                                   &zfp_snr, &zfp_lodsnr,
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
                                   NULL)) {
    PyErr_Clear();
    return false;
  }
  return true;
}

static int
ZgyWriter_init(ZgyClass *self, PyObject *args, PyObject *kwds)
{
  // TODO-Low should I call the base class init now? But the base is just Object.
  PyObject* dummy = 0;
  if (!callerWantsClone(self, args, kwds))
    dummy = ZgyWriter_create(self, args, kwds);
  else
    dummy = ZgyWriter_clone(self, args, kwds);

  int ret = dummy == NULL ? -1 : 0;
  Py_XDECREF(dummy);
  self->pimpl_->logger_(1, "Initialized a new ZgyWriter\n");
  return ret;
}

static void
ZgyUtils_dealloc(ZgyClass *self)
{
  ZgyClassImpl *pimpl = self->pimpl_;
  self->pimpl_ = NULL;
  pimpl->logger_(1, "Destructed a ZgyUtils\n");
  delete pimpl;
  Py_TYPE(self)->tp_free((PyObject*)self);
}

static PyObject *
ZgyUtils_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  ZgyClass *self = reinterpret_cast<ZgyClass*>(type->tp_alloc(type, 0));
  self->pimpl_ = new ZgyClassImpl();
  self->pimpl_->logger_verbose_ = LoggerBase::getVerboseFromEnv("OPENZGY_VERBOSE");
  self->pimpl_->logger_ = LoggerBase::standardCallback(self->pimpl_->logger_verbose_, "openzgy-pyutils: ", "");
  self->pimpl_->logger_(1, "Created a new ZgyUtils\n");
  return (PyObject *)self;
}

static int
ZgyUtils_init(ZgyClass *self, PyObject *args, PyObject *kwds)
{
  PyObject* dummy = ZgyUtils_open(self, args, kwds);
  int ret = dummy == NULL ? -1 : 0;
  Py_XDECREF(dummy);
  self->pimpl_->logger_(1, "Initialized a new ZgyUtils\n");
  return ret;
}

/////////////////////////////////////////////////////////////////////////////
///   ZgyReader methods   ///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

static PyObject *
ZgyCommon_enter(ZgyClass* self, PyObject* args)
{
  Py_INCREF(self);
  return (PyObject*)self;
}

static bool
ZgyCommon_close_all(ZgyClass *self)
{
  if (self->pimpl_->writer_) {
    self->pimpl_->logger_(1, "Closing and finalizing \"" + self->pimpl_->filename + "\"\n");
    try {
      // Default decimation and no progress bar.
      // Application should call finalize() directly for better control.
      self->pimpl_->writer_->finalize
        (std::vector<DecimationType>{DecimationType::LowPass,
                                     DecimationType::WeightedAverage},
         [](std::int64_t,std::int64_t){ return true; },
         /*force=*/false);
      self->pimpl_->writer_->close();
      self->pimpl_->writer_.reset();
    }
    catch (...) {
      _raise_ex();
      return false;
    }
  }

  try {
    if (self->pimpl_->reader_) {
      self->pimpl_->logger_(1, "Closing read-only file \"" + self->pimpl_->filename + "\"\n");
      self->pimpl_->reader_->close();
      self->pimpl_->reader_.reset();
    }
  }
  catch (...) {
    _raise_ex();
    return false;
  }

  // It is not really a good idea to allow reading metadata from a closed
  // accessor. This can cause other instances to be held on to too long.
  // Reasons to do so anyway: (1) there might be applicatoin code that
  // depends on this behavior, and (2) resetting meta_ here means I need
  // a null pointer check every place meta_ is used. I might have missed some.
  self->pimpl_->meta_.reset();
  self->pimpl_->filename = "";

  self->pimpl_->utils_.reset();

  return true;
}

static PyObject *
ZgyCommon_exit(ZgyClass* self, PyObject* args)
{
  if (!ZgyCommon_close_all(self))
    return NULL;
  Py_INCREF(Py_False);
  return Py_False; // If exiting due to an exception, do not swallow it.
}

/**
 * Get something that is either an attribute or a dict-like entry, i.e.
 * o["attrname"] or o.attrname. Reurns nullptr WITHOUT an exception set
 * if not found. Returns a new reference otherwise.
 */
static PyObject*
getOneAttr(PyObject* obj, const char *attrname)
{
  if (!obj || obj == Py_None || !attrname || !*attrname)
    return nullptr;
  PyObject* attr = PyUnicode_FromString(attrname);
  if (attr == NULL) {
    PyErr_Clear();
    return nullptr;
  }
  PyObject* val = PyObject_GetItem(obj, attr);
  //if (val) printf("Found o[\"%s\"]\n", attrname);
  if (val == NULL) {
    PyErr_Clear();
    val = PyObject_GetAttr(obj, attr);
    //if (val) printf("Found o.%s\n", attrname);
  }
  Py_DECREF(attr);
  if (val == NULL) {
    PyErr_Clear();
    return nullptr;
  }
  return val;
}

static std::string
getStringValuedAttr(PyObject* obj, const char *attrname)
{
  if (!obj || obj == Py_None || !attrname || !*attrname)
    return std::string();
  PyObject* val = getOneAttr(obj, attrname);
  if (val == NULL) {
    // attribute missing, I default it to the empty string.
    PyErr_Clear();
    return std::string();
  }
  const char *str = PyUnicode_AsUTF8(val);
  if (!str) {
    // Attribute might have been the wrong type?
    // Ideally I should propagate this error.
    PyErr_Clear();
    Py_DECREF(val);
    return std::string();
  }
  std::string result(str);
  Py_DECREF(val);
  //printf("Found %s = \"%s\"\n", attrname, result.c_str());
  return result;
}

static std::int64_t
getLongValuedAttr(PyObject* obj, const char *attrname, std::int64_t dflt)
{
  if (!obj || obj == Py_None || !attrname || !*attrname)
    return dflt;
  PyObject* val = getOneAttr(obj, attrname);
  if (val == NULL) {
    // Probably the attribute did not exist.
    PyErr_Clear();
    return dflt;
  }
  long long result = PyLong_AsLongLong(val);
  Py_DECREF(val);
  if (result == -1 && PyErr_Occurred()) {
    // Actually an error; should I raise it?
    PyErr_Clear();
    return dflt;
  }
  return static_cast<std::int64_t>(result);
}

static std::shared_ptr<IOContext>
ZgyCommon_getIOContext(ZgyClass *self, const char *filename, PyObject* obj)
{
  // TODO-High: iocontext is now expected to be a dict.
  // TODO-Low: Warning if unrecognized attributes are present.
  if (filename && strncmp(filename, "sd://", 5) == 0) {
    auto result = std::make_shared<SeismicStoreIOContext>();
    std::string value;
    std::int64_t ivalue;
    if (!(value = getStringValuedAttr(obj, "sdurl")).empty())
      result->sdurl(value);
    if (!(value = getStringValuedAttr(obj, "sdapikey")).empty())
      result->sdapikey(value);
    if (!(value = getStringValuedAttr(obj, "sdtoken")).empty())
      result->sdtoken(value, std::string());
509
510
511
512
513
514
    if ((ivalue = getLongValuedAttr(obj, "maxsize", -1)) != -1)
      result->maxsize((int)ivalue);
    if ((ivalue = getLongValuedAttr(obj, "maxhole", -1)) != -1)
      result->maxhole((int)ivalue);
    if ((ivalue = getLongValuedAttr(obj, "aligned", -1)) != -1)
      result->aligned((int)ivalue);
515
516
    if ((ivalue = getLongValuedAttr(obj, "segsize", -1)) != -1)
      result->segsize((int)ivalue);
517
518
    if ((ivalue = getLongValuedAttr(obj, "segsplit", -1)) != -1)
      result->segsplit((int)ivalue);
519
520
521
522
523
524
525
526
527
    if ((ivalue = getLongValuedAttr(obj, "threads", -1)) != -1)
      result->threads((int)ivalue);
    if (!(value = getStringValuedAttr(obj, "legaltag")).empty())
      result->legaltag(value);
    if (!(value = getStringValuedAttr(obj, "writeid")).empty())
      result->writeid(value);
    if (!(value = getStringValuedAttr(obj, "seismicmeta")).empty())
      result->seismicmeta(value);
    // TODO-Low: The pure Python api has seismicmeta as a dict. Do likewise.
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    if (obj) {
      PyObject *callback = getOneAttr(obj, "_debug_trace");
      // TODO-Low: The callback will be leaked because I am not storing
      // it in the pimpl struct. No big deal since this is only for
      // debugging.
      if (!callback) {
        self->pimpl_->logger_(9, "debug_trace callback was not provided.\n");
        PyErr_Clear();
      }
      else {
        self->pimpl_->logger_(2, "debug_trace callback is being registered.\n");
        // Note that the saved self->pimpl_->debug_trace_ is only used
        // to make sure the python callable is released when the file
        // is closed. The function captures the callable itself.
        // TODO-Worry: Consider leaking the callable just in case
        // I messed up and end up calling it after going out of scope,
        PyObject* old_callback = self->pimpl_->debug_trace_;
        self->pimpl_->debug_trace_ = callback;
        Py_XDECREF(old_callback);
        auto logger = self->pimpl_->logger_;
        result->debug_trace
          ([callback, logger]
           (const std::string& operation,
            std::int64_t need,
            std::int64_t want,
            std::int64_t parts,
            const std::vector<std::int64_t>& sizes)
           {
             logger(2, "debug_trace callback is being invoked.\n");
             // Ignore errors creating and populating the tuple and
             // working with numbers. How could those fail?
             // Note that SetItem steals the reference it is given.
             PyObject* sizes_obj = PyTuple_New(sizes.size());
             for (std::size_t ii = 0; ii < sizes.size(); ++ii)
               PyTuple_SetItem(sizes_obj, ii,
                               PyLong_FromLongLong((long long)sizes[ii]));
             PyObject* rc = PyObject_CallFunction
               (callback, "sLLLN", operation.c_str(),
                (long long)need, (long long)want, (long long)parts, sizes_obj);
             if (!rc) {
               logger(0, "Warning: debug_trace callback raised an error.\n");
               PyErr_Clear(); // ignore errors raised by callback.
             }
             else {
               Py_DECREF(rc);
             }
           });
      }
    }
    return result;
  }
  return nullptr;
}

static PyObject *
ZgyReader_open(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  static char *kwlist[] = {
    const_cast<char*>("filename"),
    const_cast<char*>("iocontext"),
    NULL
  };

  char *filename{nullptr};
  PyObject *iocontext_obj{nullptr};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|O", kwlist,
                                   &filename, &iocontext_obj,
                                   NULL))
    return NULL;

  try {
    std::shared_ptr<IOContext> iocontext =
      ZgyCommon_getIOContext(self, filename, iocontext_obj);

    self->pimpl_->logger_(1, "Open \"" + std::string(filename) + "\"\n");
    if (iocontext)
      self->pimpl_->logger_(1, iocontext->toString());

    self->pimpl_->reader_ = IZgyReader::open(std::string(filename), iocontext.get());
    self->pimpl_->meta_ = self->pimpl_->reader_;
    self->pimpl_->filename = filename;
    self->pimpl_->numthreads = 1;
  }
  catch (...) {
    return _raise_ex();
  }
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyUtils_open(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  static char *kwlist[] = {
    const_cast<char*>("prefix"),
    const_cast<char*>("iocontext"),
    NULL
  };

  char *prefix{nullptr};
  PyObject *iocontext_obj{nullptr};

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|O", kwlist,
                                   &prefix, &iocontext_obj,
                                   NULL))
    return NULL;

  try {
    std::shared_ptr<IOContext> iocontext =
      ZgyCommon_getIOContext(self, prefix, iocontext_obj);

    self->pimpl_->logger_(1, "Utils \"" + std::string(prefix) + "\"\n");
    if (iocontext)
      self->pimpl_->logger_(1, iocontext->toString());

    self->pimpl_->utils_ = IZgyUtils::utils(prefix, iocontext.get());
    self->pimpl_->filename = prefix;
    self->pimpl_->numthreads = 1;
  }
  catch (...) {
    return _raise_ex();
  }
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyReader_close(ZgyClass* self, PyObject* args)
{
  if (!ZgyCommon_close_all(self))
    return NULL;
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyWriter_close(ZgyClass* self, PyObject* args)
{
  if (!ZgyCommon_close_all(self))
    return NULL;
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyUtils_close(ZgyClass* self, PyObject* args)
{
  if (!ZgyCommon_close_all(self))
    return NULL;
  Py_INCREF(Py_None);
  return Py_None;
}

static void dumpBuffer(const Py_buffer& buf)
{
#if 0
  // https://docs.python.org/3/c-api/buffer.html
  const char *ro =
    buf.readonly == 0 ? "writable" :
    buf.readonly == 1 ? "readonly" : "unknown";
  printf("Python %s buffer ", ro);
  //printf("at 0x%llx ", (long long)buf.buf);
  //printf("obj 0x%llx ", (long long)buf.obj);
  printf("length = %lld * %lld ",
         (long long)buf.itemsize,
         (long long)(buf.len / buf.itemsize));
  if (buf.shape) {
    switch (buf.ndim) {
    case 0: printf("scalar "); break;
    case 1: printf("size = [%d] ", (int)buf.shape[0]); break;
    case 2: printf("size = [%d,%d] ", (int)buf.shape[0], (int)buf.shape[1]); break;
    case 3: printf("size = [%d,%d,%d] ", (int)buf.shape[0], (int)buf.shape[1], (int)buf.shape[2]); break;
    default: printf("ndim = %d ", buf.ndim); break;
    }
  }
  else {
    printf("ndim = %d. shape = (null) ", buf.ndim);
  }
  printf("format = %s\n", buf.format ? buf.format : "(null)");
#endif
}

static PyObject *
ZgyReader_read(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  int i0=0, j0=0, k0=0;
  Py_buffer bulk = {0};
  PyObject* bulkobj = NULL;
  int lod=0;
  PyObject* verbose_obj{nullptr};

  if (!self->pimpl_->reader_) {
    return _raise_simple_error(_zgy_error_UserError, "Not open for read");
  }

  static char *kwlist[] = {
#if PY_VERSION_HEX >= 0x03060000
    const_cast<char*>(""), // positional-only
    const_cast<char*>(""), // introduced in Python 3.6
#else
    const_cast<char*>("start"),
    const_cast<char*>("data"),
#endif
    const_cast<char*>("lod"),
    const_cast<char*>("verbose"), // ignored
    NULL
  };

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "(iii)O|i$O", kwlist,
                                   &i0, &j0, &k0, &bulkobj, &lod, &verbose_obj,
                                   NULL))
    return NULL;

  if (PyObject_GetBuffer(bulkobj, &bulk, PyBUF_FORMAT|PyBUF_ND|PyBUF_WRITABLE) < 0)
    return NULL;

  dumpBuffer(bulk);

  if (bulk.ndim != 3 || bulk.shape == NULL || bulk.readonly) {
    PyBuffer_Release(&bulk);
    return _raise_simple_error(PyExc_TypeError, "Expected a 3-dimensional writable array");
  }

  const IZgyWriter::size3i_t start{i0, j0, k0};
  const IZgyWriter::size3i_t count{bulk.shape[0], bulk.shape[1], bulk.shape[2]};
  const char format =
    bulk.format == NULL || bulk.format[0] == '\0' || bulk.format[1] != '\0' ?
    '?' : bulk.format[0];
  std::shared_ptr<IZgyReader> reader = self->pimpl_->reader_;

  try {
    if (count[0]==0 || count[1] == 0 || count[2]==0) {
      // nothing to be done.
    }
    else if (bulk.itemsize == sizeof(float) && format == 'f') {
      reader->read(start, count, (float*)bulk.buf, lod);
    }
    else if (bulk.itemsize == sizeof(signed short) && format == 'h') {
      reader->read(start, count, (signed short*)bulk.buf, lod);
    }
    else if (bulk.itemsize == sizeof(signed char) && format == 'b') {
      reader->read(start, count, (signed char*)bulk.buf, lod);
    }
    else {
      PyBuffer_Release(&bulk);
      return _raise_simple_error(PyExc_TypeError, "Expected array of float, short, or byte");
    }
  }
  catch (...) {
    PyBuffer_Release(&bulk);
    return _raise_ex();
  }

  PyBuffer_Release(&bulk);
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyReader_readconst(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  int i0{0}, j0{0}, k0{0};
  int ni{0}, nj{0}, nk{0};
  int lod{0};
  int as_float{1}; // PyArg_Parse.. returns bools as "int".
  PyObject* verbose_obj{nullptr};

  if (!self->pimpl_->reader_) {
    return _raise_simple_error(_zgy_error_UserError, "Not open for read");
  }

  //def readconst(self, start, count, *, lod=0, as_float=True, verbose=None)

  static char *kwlist[] = {
    const_cast<char*>("start"),
    const_cast<char*>("size"),
    const_cast<char*>("lod"),
    const_cast<char*>("as_float"),
    const_cast<char*>("verbose"), // ignored
    NULL
  };

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "(iii)(iii)|ip$O", kwlist,
                                   &i0, &j0, &k0,
                                   &ni, &nj, &nk,
                                   &lod, &as_float, &verbose_obj,
                                   NULL))
    return NULL;

  try {
    const IZgyWriter::size3i_t start{i0, j0, k0};
    const IZgyWriter::size3i_t count{ni, nj, nk};
    std::shared_ptr<IZgyReader> reader = self->pimpl_->reader_;
    const std::pair<bool,double> constant =
      reader->readconst(start, count, lod, as_float!=0);
    if (!constant.first) {
      Py_INCREF(Py_None);
      return Py_None;
    }
    else {
      // TODO-Low should I convert to int if file is integral and !as_float?
      return Py_BuildValue("d", constant.second);
    }
  }
  catch (...) {
    return _raise_ex();
  }
}

static PyObject *
ZgyWriter_write(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  int i0=0, j0=0, k0=0;
  Py_buffer bulk = {0};
  PyObject* bulkobj = NULL;
  if (!self->pimpl_->writer_) {
    return _raise_simple_error(_zgy_error_UserError, "Not open for write");
  }

  static char *kwlist[] = {
#if PY_VERSION_HEX >= 0x03060000
    const_cast<char*>(""), // positional-only
    const_cast<char*>(""), // introduced in Python 3.6
#else
    const_cast<char*>("start"),
    const_cast<char*>("data"),
#endif
    const_cast<char*>("verbose"), // ignored
    NULL
  };

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "(iii)O|$O", kwlist,
                                   &i0, &j0, &k0, &bulkobj))
    return NULL;

  if (PyObject_GetBuffer(bulkobj, &bulk, PyBUF_FORMAT|PyBUF_ND) < 0)
    return NULL;

  dumpBuffer(bulk);

  if (bulk.ndim != 3 || bulk.shape == NULL) {
    PyBuffer_Release(&bulk);
    return _raise_simple_error(PyExc_TypeError, "Expected a 3-dimensional array");
  }

  const IZgyWriter::size3i_t start{i0, j0, k0};
  const IZgyWriter::size3i_t count{bulk.shape[0], bulk.shape[1], bulk.shape[2]};
  const char format =
    bulk.format == NULL || bulk.format[0] == '\0' || bulk.format[1] != '\0' ?
    '?' : bulk.format[0];
  std::shared_ptr<IZgyWriter> writer = self->pimpl_->writer_;

  try {
    if (bulk.itemsize == sizeof(float) && format == 'f') {
      writer->write(start, count, (const float*)bulk.buf);
    }
    else if (bulk.itemsize == sizeof(signed short) && format == 'h') {
      writer->write(start, count, (const signed short*)bulk.buf);
    }
    else if (bulk.itemsize == sizeof(signed char) && format == 'b') {
      writer->write(start, count, (const signed char*)bulk.buf);
    }
    else {
      PyBuffer_Release(&bulk);
      return _raise_simple_error(PyExc_TypeError, "Expected array of float, short, or byte");
    }
  }
  catch (...) {
    PyBuffer_Release(&bulk);
    return _raise_ex();
  }
  PyBuffer_Release(&bulk);
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyWriter_writeconst(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  int i0=0, j0=0, k0=0;
  int ni=0, nj=0, nk=0;
  double value{0};
  int is_storage{0};
  int verbose{0};
  if (!self->pimpl_->writer_) {
    return _raise_simple_error(_zgy_error_UserError, "Not open for write");
  }

  // def writeconst(self, start, value, size, is_storage, *, verbose = None):

  static char *kwlist[] = {
    const_cast<char*>("start"),
    const_cast<char*>("value"),
    const_cast<char*>("size"),
    const_cast<char*>("is_storage"),
    const_cast<char*>("verbose"), // ignored
    NULL
  };

  if (!PyArg_ParseTupleAndKeywords(args, keywds, "(iii)d(iii)p|$p", kwlist,
                                   &i0, &j0, &k0,
                                   &value,
                                   &ni, &nj, &nk,
                                   &is_storage,
                                   &verbose))
    return NULL;

  const IZgyWriter::size3i_t start{i0, j0, k0};
  const IZgyWriter::size3i_t count{ni, nj, nk};
  const SampleDataType dt = is_storage ?
    self->pimpl_->meta_->datatype() : SampleDataType::float32;
  std::shared_ptr<IZgyWriter> writer = self->pimpl_->writer_;

  // The Python API writes "float" (converting as needed) or "storage"
  // (always matching the type on file, might be "float").
  // The C++ API decides what to write based on the type of the
  // value that is passed in. Which may cause a runtime error
  // if trying to use the int8 overload to write to an int16 file
  // or vice versa.
  // TODO-Low throw if outside integer range.
  try {
    switch (dt) {
    case SampleDataType::float32: {
      const float typed_value{(float)value};
      writer->writeconst(start, count, &typed_value);
      break;
    }
    case SampleDataType::int16: {
      const std::int16_t typed_value{(std::int16_t)value};
      writer->writeconst(start, count, &typed_value);
      break;
    }
    case SampleDataType::int8: {
      const std::int8_t typed_value{(std::int8_t)value};
      writer->writeconst(start, count, &typed_value);
      break;
    }
    default: {
      return _raise_simple_error(_zgy_error_InternalError,
                                 "Unsupported data type on file");
    }
    }
  }
  catch (...) {
    return _raise_ex();
  }
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
ZgyWriter_finalize(ZgyClass* self, PyObject* args, PyObject* keywds)
{
  if (!self->pimpl_->writer_) {
    return _raise_simple_error(_zgy_error_UserError, "Not open for write");
  }

  static char *kwlist[] = {
    const_cast<char*>("decimation"),
    const_cast<char*>("progress"),
    const_cast<char*>("force"),
    const_cast<char*>("verbose"),
    NULL
  };

  PyObject *decimation_obj{nullptr};
  PyObject *progress_obj{nullptr};
  int force{0}; // PyArg_Parse.. returns bools as "int".
  PyObject *verbose_obj{nullptr}; // currently ignored.
  if (!PyArg_ParseTupleAndKeywords(args, keywds, "|$OOpO", kwlist,
                                   &decimation_obj,
                                   &progress_obj,
For faster browsing, not all history is shown. View entire blame