-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoctproengine_bindings.cpp
More file actions
1437 lines (1230 loc) · 60.9 KB
/
octproengine_bindings.cpp
File metadata and controls
1437 lines (1230 loc) · 60.9 KB
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
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
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
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
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <pybind11/numpy.h>
#include "processor.h"
#include "processorconfiguration.h"
#include "backendconfig.h"
#include "iobuffer.h"
#include "types.h"
#include "version.h"
#include "cudautils.h"
#include "tools/recorder.h"
namespace py = pybind11;
// ============================================
// EXCEPTION DEFINITIONS
// ============================================
class InitializationError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class ConfigurationError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class BufferError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class ProcessingError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
class BackendError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
// ============================================
// NUMPY DTYPE HELPERS
// ============================================
ope::DataType numpy_dtype_to_ope(py::dtype dtype) {
if (dtype.is(py::dtype::of<uint8_t>())) {
return ope::DataType::UINT8;
} else if (dtype.is(py::dtype::of<uint16_t>())) {
return ope::DataType::UINT16;
} else if (dtype.is(py::dtype::of<uint32_t>())) {
return ope::DataType::UINT32;
} else if (dtype.is(py::dtype::of<float>())) {
return ope::DataType::FLOAT32;
} else if (dtype.is(py::dtype::of<double>())) {
return ope::DataType::FLOAT64;
} else {
throw BufferError("Unsupported NumPy dtype. Supported types: uint8, uint16, uint32, float32, float64");
}
}
std::string ope_dtype_to_string(ope::DataType dtype) {
switch (dtype) {
case ope::DataType::UINT8: return "uint8";
case ope::DataType::UINT16: return "uint16";
case ope::DataType::UINT32: return "uint32";
case ope::DataType::FLOAT32: return "float32";
case ope::DataType::FLOAT64: return "float64";
default: return "unknown";
}
}
// ============================================
// BUFFER <-> NUMPY CONVERSION
// ============================================
// Return NumPy array view of IOBuffer (zero-copy)
// config: optional processor configuration for proper 3D shape
py::array buffer_to_numpy(ope::IOBuffer& buffer, const ope::ProcessorConfiguration* config = nullptr) {
void* ptr = buffer.getDataPointer();
size_t size_bytes = buffer.getSizeInBytes();
ope::DataType dtype = buffer.getDataType();
// Determine NumPy dtype and element count
py::dtype np_dtype;
size_t num_elements;
switch (dtype) {
case ope::DataType::UINT8:
np_dtype = py::dtype::of<uint8_t>();
num_elements = size_bytes;
break;
case ope::DataType::UINT16:
np_dtype = py::dtype::of<uint16_t>();
num_elements = size_bytes / 2;
break;
case ope::DataType::UINT32:
np_dtype = py::dtype::of<uint32_t>();
num_elements = size_bytes / 4;
break;
case ope::DataType::FLOAT32:
np_dtype = py::dtype::of<float>();
num_elements = size_bytes / 4;
break;
case ope::DataType::FLOAT64:
np_dtype = py::dtype::of<double>();
num_elements = size_bytes / 8;
break;
default:
throw BufferError("Unsupported IOBuffer data type");
}
// Create properly shaped 3D array if configuration is available
if (config) {
int bscans = config->dataParams.bscansPerBuffer;
int ascans = config->dataParams.ascansPerBscan;
// Calculate signal length from actual buffer size
int signal = num_elements / (bscans * ascans);
// Shape: (bscans, ascans, signal_length)
// Strides: in bytes for each dimension (row-major C order)
size_t stride_signal = np_dtype.itemsize();
size_t stride_ascan = stride_signal * signal;
size_t stride_bscan = stride_ascan * ascans;
return py::array(np_dtype,
{bscans, ascans, signal}, // shape
{stride_bscan, stride_ascan, stride_signal}, // strides
ptr,
py::cast(&buffer));
} else {
// Fallback to 1D array if no config available
return py::array(np_dtype, {num_elements}, {np_dtype.itemsize()}, ptr, py::cast(&buffer));
}
}
// ============================================
// PROCESSOR WRAPPER WITH CALLBACK SUPPORT
// ============================================
class ProcessorWrapper {
public:
ope::Processor processor;
py::function callback;
py::function error_callback;
std::map<ope::Processor::CallbackId, py::function> pyCallbacks;
std::mutex callbacksMutex;
ProcessorWrapper(ope::Backend backend) : processor(backend) {}
void set_callback(py::function cb, py::object error_cb = py::none()) {
callback = cb;
if (!error_cb.is_none()) {
error_callback = error_cb.cast<py::function>();
}
// Set C++ callback that will call Python callback
processor.setOutputCallback([this](const ope::IOBuffer& output) {
// Capture buffer ID immediately before buffer can be recycled
uint64_t bufferId = output.getBufferId();
// Re-acquire GIL to call Python code
py::gil_scoped_acquire acquire;
try {
// Create NumPy view of output buffer (cast away const for view)
ope::IOBuffer& output_ref = const_cast<ope::IOBuffer&>(output);
py::array output_array = buffer_to_numpy(output_ref, &processor.getConfig());
// Call Python callback with captured buffer ID
callback(output_array, bufferId);
} catch (const std::exception& e) {
// Handle errors in callback
if (!error_callback.is_none()) {
try {
error_callback(py::str(e.what()));
} catch (...) {
py::print("Error in error_callback:", py::str(e.what()));
}
} else {
py::print("Error in callback:", py::str(e.what()));
}
}
});
}
ope::Processor::CallbackId add_output_callback(py::function cb) {
// Create C++ wrapper callback that handles GIL
auto wrappedCallback = [this, cb](const ope::IOBuffer& buffer) {
// Capture buffer ID immediately before buffer can be recycled
uint64_t bufferId = buffer.getBufferId();
// Re-acquire GIL before calling Python code
// We're in a C++ callback thread, need GIL to call Python
py::gil_scoped_acquire acquire;
try {
// Create NumPy view of buffer (zero-copy)
ope::IOBuffer& buffer_ref = const_cast<ope::IOBuffer&>(buffer);
py::array output_array = buffer_to_numpy(buffer_ref, &processor.getConfig());
// Call Python callback with captured buffer ID
cb(output_array, bufferId);
} catch (const py::error_already_set& e) {
// Python exception
py::print("Python error in callback:", e.what());
} catch (const std::exception& e) {
// C++ exception
py::print("C++ error in callback:", e.what());
}
};
// Register with C++ processor
ope::Processor::CallbackId id;
{
// Release GIL for C++ operation
py::gil_scoped_release release;
id = processor.addOutputCallback(wrappedCallback);
}
// Store Python function to prevent garbage collection
{
std::lock_guard<std::mutex> lock(callbacksMutex);
pyCallbacks[id] = cb;
}
return id;
}
bool remove_output_callback(ope::Processor::CallbackId id) {
bool removed;
{
py::gil_scoped_release release;
removed = processor.removeOutputCallback(id);
}
if (removed) {
std::lock_guard<std::mutex> lock(callbacksMutex);
pyCallbacks.erase(id);
}
return removed;
}
void clear_output_callbacks() {
{
py::gil_scoped_release release;
processor.clearOutputCallbacks();
}
std::lock_guard<std::mutex> lock(callbacksMutex);
pyCallbacks.clear();
}
size_t get_output_callback_count() const {
return processor.getOutputCallbackCount();
}
// Input callback methods (for raw data before processing)
ope::Processor::CallbackId add_input_callback(py::function cb) {
// Create C++ wrapper callback that handles GIL
auto wrappedCallback = [this, cb](const ope::IOBuffer& buffer) {
// Capture buffer ID immediately before buffer can be recycled
uint64_t bufferId = buffer.getBufferId();
// Re-acquire GIL before calling Python code
py::gil_scoped_acquire acquire;
try {
// Create NumPy view of buffer (zero-copy)
ope::IOBuffer& buffer_ref = const_cast<ope::IOBuffer&>(buffer);
py::array input_array = buffer_to_numpy(buffer_ref, &processor.getConfig());
// Call Python callback with captured buffer ID
cb(input_array, bufferId);
} catch (const py::error_already_set& e) {
// Python exception
py::print("Python error in input callback:", e.what());
} catch (const std::exception& e) {
// C++ exception
py::print("C++ error in input callback:", e.what());
}
};
// Register with C++ processor
ope::Processor::CallbackId id;
{
// Release GIL for C++ operation
py::gil_scoped_release release;
id = processor.addInputCallback(wrappedCallback);
}
// Store Python function to prevent garbage collection
{
std::lock_guard<std::mutex> lock(callbacksMutex);
pyCallbacks[id] = cb;
}
return id;
}
bool remove_input_callback(ope::Processor::CallbackId id) {
bool removed;
{
py::gil_scoped_release release;
removed = processor.removeInputCallback(id);
}
if (removed) {
std::lock_guard<std::mutex> lock(callbacksMutex);
pyCallbacks.erase(id);
}
return removed;
}
void clear_input_callbacks() {
{
py::gil_scoped_release release;
processor.clearInputCallbacks();
}
// Note: We don't clear pyCallbacks here as they might contain output callbacks too
// They'll be cleaned up when individual callbacks are removed
}
size_t get_input_callback_count() const {
return processor.getInputCallbackCount();
}
void process(py::array buffer_array) {
// Get buffer from the array's base object (if it's a view of IOBuffer)
py::object base = buffer_array.attr("base");
if (base.is_none()) {
throw BufferError("Buffer array is not a view of an IOBuffer. Use get_next_available_buffer() first.");
}
// Extract IOBuffer reference
ope::IOBuffer* buffer_ptr = base.cast<ope::IOBuffer*>();
// Release GIL during processing
{
py::gil_scoped_release release;
processor.process(*buffer_ptr);
}
}
py::array get_next_available_buffer() {
ope::IOBuffer* buffer;
// Release GIL while waiting for buffer
{
py::gil_scoped_release release;
buffer = &processor.getNextAvailableInputBuffer();
}
return buffer_to_numpy(*buffer, &processor.getConfig());
}
// Wrapper methods that release GIL
void initialize() {
try {
py::gil_scoped_release release;
processor.initialize();
} catch (const std::exception& e) {
throw InitializationError(std::string("Initialization failed: ") + e.what());
}
}
void stop() { // todo: rename to cleanup?
py::gil_scoped_release release;
processor.cleanup();
}
void load_config(const std::string& filepath) {
try {
processor.loadConfigurationFromFile(filepath);
} catch (const std::exception& e) {
throw ConfigurationError(std::string("Failed to load config: ") + e.what());
}
}
void save_config(const std::string& filepath) const {
try {
processor.saveConfigurationToFile(filepath);
} catch (const std::exception& e) {
throw ConfigurationError(std::string("Failed to save config: ") + e.what());
}
}
// Context manager support
ProcessorWrapper& enter() {
return *this;
}
void exit(py::object exc_type, py::object exc_value, py::object traceback) {
stop();
}
};
// ============================================
// PYBIND11 MODULE DEFINITION
// ============================================
PYBIND11_MODULE(octproengine, m) {
m.doc() = "OCTproEngine - High-performance OCT processing library";
// ============================================
// EXCEPTIONS
// ============================================
py::register_exception<InitializationError>(m, "InitializationError");
py::register_exception<ConfigurationError>(m, "ConfigurationError");
py::register_exception<BufferError>(m, "BufferError");
py::register_exception<ProcessingError>(m, "ProcessingError");
py::register_exception<BackendError>(m, "BackendError");
py::register_exception<ope::tools::RecordingException>(m, "RecordingException");
// ============================================
// IOBUFFER
// ============================================
py::class_<ope::IOBuffer>(m, "IOBuffer", py::module_local())
.def("get_size", &ope::IOBuffer::getSizeInBytes, "Get buffer size in bytes")
.def("get_data_type", &ope::IOBuffer::getDataType, "Get buffer data type");
// ============================================
// ENUMS
// ============================================
py::enum_<ope::Backend>(m, "Backend")
.value("CUDA", ope::Backend::CUDA, "NVIDIA CUDA GPU backend")
.value("CPU", ope::Backend::CPU, "CPU backend")
.value("OPENCL", ope::Backend::OPENCL, "OpenCL GPU backend")
.value("VULKAN", ope::Backend::VULKAN, "Vulkan GPU backend")
.export_values();
py::enum_<ope::DataType>(m, "DataType")
.value("UINT8", ope::DataType::UINT8)
.value("UINT16", ope::DataType::UINT16)
.value("UINT32", ope::DataType::UINT32)
.value("UINT64", ope::DataType::UINT64)
.value("INT8", ope::DataType::INT8)
.value("INT16", ope::DataType::INT16)
.value("INT32", ope::DataType::INT32)
.value("INT64", ope::DataType::INT64)
.value("FLOAT32", ope::DataType::FLOAT32)
.value("FLOAT64", ope::DataType::FLOAT64)
.value("COMPLEX_FLOAT32", ope::DataType::COMPLEX_FLOAT32)
.value("COMPLEX_FLOAT64", ope::DataType::COMPLEX_FLOAT64)
.export_values();
py::enum_<ope::InterpolationMethod>(m, "InterpolationMethod")
.value("LINEAR", ope::InterpolationMethod::LINEAR, "Linear interpolation")
.value("CUBIC", ope::InterpolationMethod::CUBIC, "Cubic interpolation")
.value("LANCZOS", ope::InterpolationMethod::LANCZOS, "Lanczos interpolation")
.export_values();
py::enum_<ope::WindowType>(m, "WindowType")
.value("HANN", ope::WindowType::HANN, "Hann window")
.value("GAUSS", ope::WindowType::GAUSS, "Gaussian window")
.value("SINE", ope::WindowType::SINE, "Sine window")
.value("LANCZOS", ope::WindowType::LANCZOS, "Lanczos window")
.value("RECTANGULAR", ope::WindowType::RECTANGULAR, "Rectangular window")
.value("FLAT_TOP", ope::WindowType::FLAT_TOP, "Flat-top window")
.export_values();
py::enum_<ope::tools::Recorder::Mode>(m, "RecorderMode")
.value("RAW_ONLY", ope::tools::Recorder::Mode::RAW_ONLY, "Record only raw (input) data")
.value("PROCESSED_ONLY", ope::tools::Recorder::Mode::PROCESSED_ONLY, "Record only processed (output) data")
.value("BOTH", ope::tools::Recorder::Mode::BOTH, "Record both raw and processed data")
.export_values();
py::enum_<ope::tools::Recorder::Format>(m, "RecorderFormat")
.value("RAW_BINARY", ope::tools::Recorder::Format::RAW_BINARY, "Raw binary format")
.export_values();
py::enum_<ope::tools::Recorder::Status>(m, "RecorderStatus")
.value("IDLE", ope::tools::Recorder::Status::IDLE, "Newly created or last recording aborted")
.value("RECORDING", ope::tools::Recorder::Status::RECORDING, "Currently collecting buffers")
.value("WRITING", ope::tools::Recorder::Status::WRITING, "Recording complete, writing to disk")
.value("COMPLETE", ope::tools::Recorder::Status::COMPLETE, "Last recording succeeded")
.value("ERROR_STATUS", ope::tools::Recorder::Status::ERROR, "Last recording failed")
.export_values();
// ============================================
// BACKEND CONFIGURATION
// ============================================
// DeviceInfo structure
py::class_<ope::DeviceInfo>(m, "DeviceInfo")
.def(py::init<>())
.def_readonly("id", &ope::DeviceInfo::id)
.def_readonly("name", &ope::DeviceInfo::name)
.def_readonly("total_memory", &ope::DeviceInfo::totalMemory)
.def_readonly("available_memory", &ope::DeviceInfo::availableMemory)
.def_readonly("compute_capability_major", &ope::DeviceInfo::computeCapabilityMajor)
.def_readonly("compute_capability_minor", &ope::DeviceInfo::computeCapabilityMinor)
.def_readonly("vendor_name", &ope::DeviceInfo::vendorName)
.def_readonly("device_version", &ope::DeviceInfo::deviceVersion)
.def("__repr__", [](const ope::DeviceInfo& info) {
return "<DeviceInfo(id=" + std::to_string(info.id) +
", name='" + info.name + "')>";
});
// Base BackendConfig class
py::class_<ope::BackendConfig>(m, "BackendConfig")
.def("get_backend_type", &ope::BackendConfig::getBackendType,
"Get the backend type for this configuration")
.def("is_valid", &ope::BackendConfig::isValid,
"Check if the configuration is valid")
.def("to_string", &ope::BackendConfig::toString,
"Get human-readable string representation")
.def("__repr__", [](const ope::BackendConfig& config) {
return "<BackendConfig(" + config.toString() + ")>";
});
// CudaConfig derived class
py::class_<ope::CudaConfig, ope::BackendConfig>(m, "CudaConfig")
.def(py::init<>())
.def_readwrite("device_id", &ope::CudaConfig::deviceId,
"CUDA device ID (default: 0)")
.def_readwrite("enable_zero_copy", &ope::CudaConfig::enableZeroCopy,
"Enable zero-copy mode for Jetson devices (default: False)")
.def("__repr__", [](const ope::CudaConfig& config) {
return "<CudaConfig(device_id=" + std::to_string(config.deviceId) +
", enable_zero_copy=" + (config.enableZeroCopy ? "True" : "False") + ")>";
});
// OpenCLConfig derived class
py::class_<ope::OpenCLConfig, ope::BackendConfig>(m, "OpenCLConfig")
.def(py::init<>())
.def_readwrite("platform_id", &ope::OpenCLConfig::platformId,
"OpenCL platform ID (default: 0)")
.def_readwrite("device_id", &ope::OpenCLConfig::deviceId,
"OpenCL device ID (default: 0)")
.def_readwrite("prefer_gpu", &ope::OpenCLConfig::preferGpu,
"Prefer GPU devices (default: True)")
.def("__repr__", [](const ope::OpenCLConfig& config) {
return "<OpenCLConfig(platform_id=" + std::to_string(config.platformId) +
", device_id=" + std::to_string(config.deviceId) +
", prefer_gpu=" + (config.preferGpu ? "True" : "False") + ")>";
});
// VulkanConfig derived class
py::class_<ope::VulkanConfig, ope::BackendConfig>(m, "VulkanConfig")
.def(py::init<>())
.def_readwrite("device_id", &ope::VulkanConfig::deviceId,
"Vulkan physical device ID (default: 0)")
.def("__repr__", [](const ope::VulkanConfig& config) {
return "<VulkanConfig(device_id=" + std::to_string(config.deviceId) + ")>";
});
// CpuConfig derived class
py::class_<ope::CpuConfig, ope::BackendConfig>(m, "CpuConfig")
.def(py::init<>())
.def_readwrite("num_threads", &ope::CpuConfig::numThreads,
"Number of threads (0 = auto-detect, default: 0)")
.def_readwrite("enable_simd", &ope::CpuConfig::enableSimd,
"Enable SIMD optimizations (default: True)")
.def("__repr__", [](const ope::CpuConfig& config) {
return "<CpuConfig(num_threads=" + std::to_string(config.numThreads) +
", enable_simd=" + (config.enableSimd ? "True" : "False") + ")>";
});
// BackendUtils class
py::class_<ope::BackendUtils>(m, "BackendUtils")
.def_static("get_cuda_devices", &ope::BackendUtils::getCudaDevices,
"Get list of available CUDA devices")
.def_static("get_opencl_devices", &ope::BackendUtils::getOpenCLDevices,
"Get list of available OpenCL devices")
.def_static("get_vulkan_devices", &ope::BackendUtils::getVulkanDevices,
"Get list of available Vulkan devices")
.def_static("get_cpu_info", &ope::BackendUtils::getCpuInfo,
"Get CPU information")
.def_static("is_cuda_available", &ope::BackendUtils::isCudaAvailable,
"Check if CUDA is available")
.def_static("is_opencl_available", &ope::BackendUtils::isOpenCLAvailable,
"Check if OpenCL is available")
.def_static("is_vulkan_available", &ope::BackendUtils::isVulkanAvailable,
"Check if Vulkan is available")
.def_static("is_cpu_available", &ope::BackendUtils::isCpuAvailable,
"Check if CPU backend is available")
.def_static("create_default_config", &ope::BackendUtils::createDefaultConfig,
py::arg("backend"),
"Create default configuration for a backend")
.def_static("parse_config", &ope::BackendUtils::parseConfig,
py::arg("config_string"),
"Parse configuration from string")
.def_static("serialize_config", &ope::BackendUtils::serializeConfig,
py::arg("config"),
"Serialize configuration to string");
// ============================================
// CUDA UTILITIES
// ============================================
py::class_<ope::CudaDeviceInfo>(m, "CudaDeviceInfo")
.def(py::init<>())
.def_readonly("device_id", &ope::CudaDeviceInfo::deviceId)
.def_readonly("name", &ope::CudaDeviceInfo::name)
.def_readonly("total_memory", &ope::CudaDeviceInfo::totalMemory)
.def_readonly("free_memory", &ope::CudaDeviceInfo::freeMemory)
.def_readonly("compute_capability_major", &ope::CudaDeviceInfo::computeCapabilityMajor)
.def_readonly("compute_capability_minor", &ope::CudaDeviceInfo::computeCapabilityMinor)
.def_readonly("max_threads_per_block", &ope::CudaDeviceInfo::maxThreadsPerBlock)
.def_readonly("multiprocessor_count", &ope::CudaDeviceInfo::multiProcessorCount)
.def_readonly("is_available", &ope::CudaDeviceInfo::isAvailable)
.def("get_compute_capability", &ope::CudaDeviceInfo::getComputeCapability,
"Get compute capability as string (e.g., '8.6')")
.def("__repr__", [](const ope::CudaDeviceInfo& info) {
return "<CudaDeviceInfo(id=" + std::to_string(info.deviceId) +
", name='" + info.name + "', compute=" + info.getComputeCapability() + ")>";
});
// CudaUtils - pure static utility class (no instances)
// Use module-level bindings instead of py::class_ to avoid instantiation issues
auto cuda_utils = m.def_submodule("CudaUtils", "CUDA utility functions");
cuda_utils.def("get_available_devices", &ope::CudaUtils::getAvailableDevices,
"Get list of available CUDA devices\n\n"
"Returns:\n"
" List[CudaDeviceInfo]: List of available GPUs (empty if no CUDA support)");
cuda_utils.def("get_device_info", &ope::CudaUtils::getDeviceInfo,
py::arg("device_id"),
"Get detailed information about specific GPU\n\n"
"Args:\n"
" device_id: GPU device ID (0-based)\n\n"
"Returns:\n"
" CudaDeviceInfo: Device information\n\n"
"Raises:\n"
" RuntimeError: If CUDA not available or device doesn't exist");
cuda_utils.def("is_device_available", &ope::CudaUtils::isDeviceAvailable,
py::arg("device_id"),
"Check if specific GPU device is available\n\n"
"Args:\n"
" device_id: GPU device ID (0-based)\n\n"
"Returns:\n"
" bool: True if device exists and is available");
cuda_utils.def("get_device_count", &ope::CudaUtils::getDeviceCount,
"Get number of available GPU devices\n\n"
"Returns:\n"
" int: Number of GPUs (0 if no CUDA support)");
cuda_utils.def("is_available", &ope::CudaUtils::isAvailable,
"Check if CUDA is available in this build\n\n"
"Returns:\n"
" bool: True if CUDA compiled and devices available");
cuda_utils.def("get_current_device", &ope::CudaUtils::getCurrentDevice,
"Get current CUDA device ID\n\n"
"Returns:\n"
" int: Current device ID, or -1 if no CUDA");
// ============================================
// CONFIGURATION STRUCTS AND ENUMS
// ============================================
// Enums for ProcessorConfiguration
py::enum_<ope::ProcessorConfiguration::LoadMode>(m, "LoadMode")
.value("OVERWRITE_ALL", ope::ProcessorConfiguration::LoadMode::OVERWRITE_ALL)
.value("PARAMETERS_ONLY", ope::ProcessorConfiguration::LoadMode::PARAMETERS_ONLY)
.value("MERGE_IF_MISSING", ope::ProcessorConfiguration::LoadMode::MERGE_IF_MISSING);
py::enum_<ope::ProcessorConfiguration::SaveMode>(m, "SaveMode")
.value("PARAMETERS_ONLY", ope::ProcessorConfiguration::SaveMode::PARAMETERS_ONLY)
.value("COMPLETE", ope::ProcessorConfiguration::SaveMode::COMPLETE);
// DataParameters
py::class_<ope::ProcessorConfiguration::DataParameters>(m, "DataParameters")
.def(py::init<>())
.def_readwrite("signalLength", &ope::ProcessorConfiguration::DataParameters::signalLength)
.def_readwrite("ascansPerBscan", &ope::ProcessorConfiguration::DataParameters::ascansPerBscan)
.def_readwrite("bscansPerBuffer", &ope::ProcessorConfiguration::DataParameters::bscansPerBuffer)
.def_readwrite("buffersPerVolume", &ope::ProcessorConfiguration::DataParameters::buffersPerVolume)
.def_readwrite("inputDataType", &ope::ProcessorConfiguration::DataParameters::inputDataType)
.def_readwrite("outputDataType", &ope::ProcessorConfiguration::DataParameters::outputDataType)
.def("samplesPerBuffer", &ope::ProcessorConfiguration::DataParameters::samplesPerBuffer)
.def("outputSignalLength", &ope::ProcessorConfiguration::DataParameters::outputSignalLength)
.def("getBitDepth", &ope::ProcessorConfiguration::DataParameters::getBitDepth)
.def("getBytesPerSample", &ope::ProcessorConfiguration::DataParameters::getBytesPerSample)
.def("getOutputBytesPerSample", &ope::ProcessorConfiguration::DataParameters::getOutputBytesPerSample);
// ProcessingParameters sub-structs
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Input>(m, "ProcessingInput")
.def(py::init<>())
.def_readwrite("bitshift", &ope::ProcessorConfiguration::ProcessingParameters::Input::bitshift);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::DCRemoval>(m, "ProcessingDCRemoval")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::DCRemoval::enabled)
.def_readwrite("windowSize", &ope::ProcessorConfiguration::ProcessingParameters::DCRemoval::windowSize);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Resampling>(m, "ProcessingResampling")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::Resampling::enabled)
.def_readwrite("method", &ope::ProcessorConfiguration::ProcessingParameters::Resampling::method)
.def_property("coefficients",
[](const ope::ProcessorConfiguration::ProcessingParameters::Resampling& self) {
return std::vector<float>(self.coefficients, self.coefficients + 4);
},
[](ope::ProcessorConfiguration::ProcessingParameters::Resampling& self, const std::vector<float>& coeffs) {
if (coeffs.size() != 4) throw std::runtime_error("Coefficients must have exactly 4 elements");
std::copy(coeffs.begin(), coeffs.end(), self.coefficients);
})
.def_readwrite("useCustomLut", &ope::ProcessorConfiguration::ProcessingParameters::Resampling::useCustomLut);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Windowing>(m, "ProcessingWindowing")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::Windowing::enabled)
.def_readwrite("type", &ope::ProcessorConfiguration::ProcessingParameters::Windowing::type)
.def_readwrite("centerPosition", &ope::ProcessorConfiguration::ProcessingParameters::Windowing::centerPosition)
.def_readwrite("fillFactor", &ope::ProcessorConfiguration::ProcessingParameters::Windowing::fillFactor)
.def_readwrite("useCustomFunction", &ope::ProcessorConfiguration::ProcessingParameters::Windowing::useCustomFunction);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Dispersion>(m, "ProcessingDispersion")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::Dispersion::enabled)
.def_property("coefficients",
[](const ope::ProcessorConfiguration::ProcessingParameters::Dispersion& self) {
return std::vector<float>(self.coefficients, self.coefficients + 4);
},
[](ope::ProcessorConfiguration::ProcessingParameters::Dispersion& self, const std::vector<float>& coeffs) {
if (coeffs.size() != 4) throw std::runtime_error("Coefficients must have exactly 4 elements");
std::copy(coeffs.begin(), coeffs.end(), self.coefficients);
})
.def_readwrite("factor", &ope::ProcessorConfiguration::ProcessingParameters::Dispersion::factor)
.def_readwrite("useCustomPhase", &ope::ProcessorConfiguration::ProcessingParameters::Dispersion::useCustomPhase);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::FixedPatternNoise>(m, "ProcessingFixedPatternNoise")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::FixedPatternNoise::enabled)
.def_readwrite("bscanAverageCount", &ope::ProcessorConfiguration::ProcessingParameters::FixedPatternNoise::bscanAverageCount)
.def_readwrite("continuous", &ope::ProcessorConfiguration::ProcessingParameters::FixedPatternNoise::continuous)
.def_readwrite("useCustomProfile", &ope::ProcessorConfiguration::ProcessingParameters::FixedPatternNoise::useCustomProfile);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Background>(m, "ProcessingBackground")
.def(py::init<>())
.def_readwrite("enabled", &ope::ProcessorConfiguration::ProcessingParameters::Background::enabled)
.def_readwrite("weight", &ope::ProcessorConfiguration::ProcessingParameters::Background::weight)
.def_readwrite("offset", &ope::ProcessorConfiguration::ProcessingParameters::Background::offset)
.def_readwrite("useCustomProfile", &ope::ProcessorConfiguration::ProcessingParameters::Background::useCustomProfile);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Intensity>(m, "ProcessingIntensity")
.def(py::init<>())
.def_readwrite("logScale", &ope::ProcessorConfiguration::ProcessingParameters::Intensity::logScale)
.def_readwrite("rangeMin", &ope::ProcessorConfiguration::ProcessingParameters::Intensity::rangeMin)
.def_readwrite("rangeMax", &ope::ProcessorConfiguration::ProcessingParameters::Intensity::rangeMax)
.def_readwrite("preScale", &ope::ProcessorConfiguration::ProcessingParameters::Intensity::preScale)
.def_readwrite("postOffset", &ope::ProcessorConfiguration::ProcessingParameters::Intensity::postOffset);
py::class_<ope::ProcessorConfiguration::ProcessingParameters::Geometry>(m, "ProcessingGeometry")
.def(py::init<>())
.def_readwrite("alternatingBscanFlip", &ope::ProcessorConfiguration::ProcessingParameters::Geometry::alternatingBscanFlip)
.def_readwrite("sinusoidalCorrection", &ope::ProcessorConfiguration::ProcessingParameters::Geometry::sinusoidalCorrection);
// ProcessingParameters main struct
py::class_<ope::ProcessorConfiguration::ProcessingParameters>(m, "ProcessingParameters")
.def(py::init<>())
.def_readwrite("input", &ope::ProcessorConfiguration::ProcessingParameters::input)
.def_readwrite("dcRemoval", &ope::ProcessorConfiguration::ProcessingParameters::dcRemoval)
.def_readwrite("resampling", &ope::ProcessorConfiguration::ProcessingParameters::resampling)
.def_readwrite("windowing", &ope::ProcessorConfiguration::ProcessingParameters::windowing)
.def_readwrite("dispersion", &ope::ProcessorConfiguration::ProcessingParameters::dispersion)
.def_readwrite("fixedPatternNoise", &ope::ProcessorConfiguration::ProcessingParameters::fixedPatternNoise)
.def_readwrite("background", &ope::ProcessorConfiguration::ProcessingParameters::background)
.def_readwrite("intensity", &ope::ProcessorConfiguration::ProcessingParameters::intensity)
.def_readwrite("geometry", &ope::ProcessorConfiguration::ProcessingParameters::geometry);
// ============================================
// CONFIGURATION CLASS
// ============================================
py::class_<ope::ProcessorConfiguration>(m, "ProcessorConfiguration")
.def(py::init<>())
// Nested structure API
.def_readwrite("dataParams", &ope::ProcessorConfiguration::dataParams)
.def_readwrite("processingParams", &ope::ProcessorConfiguration::processingParams)
// Vector-based curve methods
.def("setResamplingLut", [](ope::ProcessorConfiguration& self, const std::vector<float>& data) {
self.setResamplingLut(data);
})
.def("setWindowFunction", [](ope::ProcessorConfiguration& self, const std::vector<float>& data) {
self.setWindowFunction(data);
})
.def("setDispersionPhase", [](ope::ProcessorConfiguration& self, const std::vector<float>& data) {
self.setDispersionPhase(data);
})
.def("setBackgroundProfile", [](ope::ProcessorConfiguration& self, const std::vector<float>& data) {
self.setBackgroundProfile(data);
})
.def("setFixedPatternNoiseProfile", [](ope::ProcessorConfiguration& self, const std::vector<float>& data) {
self.setFixedPatternNoiseProfile(data);
})
.def("getResamplingLut", &ope::ProcessorConfiguration::getResamplingLut)
.def("getWindowFunction", &ope::ProcessorConfiguration::getWindowFunction)
.def("getDispersionPhase", &ope::ProcessorConfiguration::getDispersionPhase)
.def("getBackgroundProfile", &ope::ProcessorConfiguration::getBackgroundProfile)
.def("getFixedPatternNoiseProfile", &ope::ProcessorConfiguration::getFixedPatternNoiseProfile)
// Generate curves
.def("generateResamplingLut", &ope::ProcessorConfiguration::generateResamplingLut)
.def("generateWindowFunction", &ope::ProcessorConfiguration::generateWindowFunction)
.def("generateDispersionPhase", &ope::ProcessorConfiguration::generateDispersionPhase)
// Clear curves
.def("clearResamplingLut", &ope::ProcessorConfiguration::clearResamplingLut)
.def("clearWindowFunction", &ope::ProcessorConfiguration::clearWindowFunction)
.def("clearDispersionPhase", &ope::ProcessorConfiguration::clearDispersionPhase)
.def("clearBackgroundProfile", &ope::ProcessorConfiguration::clearBackgroundProfile)
.def("clearFixedPatternNoiseProfile", &ope::ProcessorConfiguration::clearFixedPatternNoiseProfile)
// Adjust curves when dimensions change
.def("adjustAllCustomCurves", &ope::ProcessorConfiguration::adjustAllCustomCurves)
// Check if custom curves are set
.def("hasCustomResamplingCurve", &ope::ProcessorConfiguration::hasCustomResamplingCurve)
.def("hasCustomWindowCurve", &ope::ProcessorConfiguration::hasCustomWindowCurve)
.def("hasCustomDispersionCurve", &ope::ProcessorConfiguration::hasCustomDispersionCurve)
.def("hasCustomPostProcessBackgroundProfile", &ope::ProcessorConfiguration::hasCustomPostProcessBackgroundProfile)
.def("hasCustomFixedPatternNoiseProfile", &ope::ProcessorConfiguration::hasCustomFixedPatternNoiseProfile)
// File I/O with modes
.def("saveToFile", &ope::ProcessorConfiguration::saveToFile,
py::arg("filepath"),
py::arg("mode") = ope::ProcessorConfiguration::SaveMode::COMPLETE)
.def("loadFromFile", &ope::ProcessorConfiguration::loadFromFile,
py::arg("filepath"),
py::arg("mode") = ope::ProcessorConfiguration::LoadMode::OVERWRITE_ALL)
// CSV export/import for curves
.def("saveResamplingLutToFile", &ope::ProcessorConfiguration::saveResamplingLutToFile)
.def("loadResamplingLutFromFile", &ope::ProcessorConfiguration::loadResamplingLutFromFile)
.def("saveWindowFunctionToFile", &ope::ProcessorConfiguration::saveWindowFunctionToFile)
.def("loadWindowFunctionFromFile", &ope::ProcessorConfiguration::loadWindowFunctionFromFile)
.def("saveDispersionPhaseToFile", &ope::ProcessorConfiguration::saveDispersionPhaseToFile)
.def("loadDispersionPhaseFromFile", &ope::ProcessorConfiguration::loadDispersionPhaseFromFile)
.def("saveBackgroundProfileToFile", &ope::ProcessorConfiguration::saveBackgroundProfileToFile)
.def("loadBackgroundProfileFromFile", &ope::ProcessorConfiguration::loadBackgroundProfileFromFile)
.def("saveFixedPatternNoiseProfileToFile", &ope::ProcessorConfiguration::saveFixedPatternNoiseProfileToFile)
.def("loadFixedPatternNoiseProfileFromFile", &ope::ProcessorConfiguration::loadFixedPatternNoiseProfileFromFile)
// Validation
.def("validate", &ope::ProcessorConfiguration::validate);
// ============================================
// PROCESSOR CLASS
// ============================================
py::class_<ProcessorWrapper>(m, "Processor")
.def(py::init<ope::Backend>(), py::arg("backend") = ope::Backend::CPU,
"Create a new Processor instance\n\n"
"Args:\n"
" backend: Backend to use (Backend.VULKAN, Backend.CUDA, Backend.CPU, or Backend.OPENCL)")
// Lifecycle
.def("initialize", &ProcessorWrapper::initialize,
"Initialize the processor and allocate buffers.\n"
"Must be called before processing data.")
.def("stop", &ProcessorWrapper::stop,
"Stop the processor and free all resources.")
// Configuration
.def("load_config", &ProcessorWrapper::load_config, py::arg("filepath"),
"Load configuration from INI file\n\n"
"Args:\n"
" filepath: Path to configuration file")
.def("save_config", &ProcessorWrapper::save_config, py::arg("filepath"),
"Save current configuration to INI file\n\n"
"Args:\n"
" filepath: Path to save configuration")
.def_property_readonly("config",
[](ProcessorWrapper& self) -> ope::ProcessorConfiguration& {
return const_cast<ope::ProcessorConfiguration&>(self.processor.getConfig());
},
py::return_value_policy::reference_internal,
"Access to configuration object (read/write)")
.def("set_config", [](ProcessorWrapper& self, const ope::ProcessorConfiguration& config) {
self.processor.setConfig(config);
}, py::arg("config"), "Set entire configuration at once")
// Input parameters
.def("set_input_parameters",
[](ProcessorWrapper& self, int signal_length, int ascans_per_bscan, int bscans_per_buffer, ope::DataType dtype) {
py::gil_scoped_release release;
self.processor.setInputParameters(signal_length, ascans_per_bscan, bscans_per_buffer, dtype);
},
py::arg("signal_length"),
py::arg("ascans_per_bscan"),
py::arg("bscans_per_buffer"),
py::arg("data_type"),
"Set input buffer parameters (requires reinitialization)")
// Backend management
.def("set_backend", [](ProcessorWrapper& self, ope::Backend backend) {
py::gil_scoped_release release;
self.processor.setBackend(backend);
}, py::arg("backend"), "Switch backend (VULKAN <-> CUDA <-> CPU <-> OpenCL)")
.def("get_backend", [](const ProcessorWrapper& self) {
return self.processor.getBackend();
}, "Get current backend")
// Unified backend configuration API
.def("set_backend_config", [](ProcessorWrapper& self, const ope::BackendConfig& config) {
py::gil_scoped_release release;
self.processor.setBackendConfig(config);
}, py::arg("config"),
"Set backend configuration\n\n"
"Automatically switches backend if type differs from current.\n"
"Preserves all processing configuration.\n\n"
"Args:\n"
" config: Backend-specific configuration (CudaConfig, OpenCLConfig, or CpuConfig)\n\n"
"Example:\n"
" >>> cuda_config = CudaConfig()\n"
" >>> cuda_config.device_id = 1\n"
" >>> processor.set_backend_config(cuda_config)")
.def("get_backend_config", [](const ProcessorWrapper& self) -> std::unique_ptr<ope::BackendConfig> {
return self.processor.getBackendConfig();
}, "Get current backend configuration")
.def("save_backend_config_to_file", [](const ProcessorWrapper& self, const std::string& filepath) {
self.processor.saveBackendConfigToFile(filepath);
}, py::arg("filepath"),
"Save backend configuration to file\n\n"
"Args:\n"
" filepath: Path to save configuration")
.def("load_backend_config_from_file", [](ProcessorWrapper& self, const std::string& filepath) {
py::gil_scoped_release release;
self.processor.loadBackendConfigFromFile(filepath);
}, py::arg("filepath"),
"Load backend configuration from file\n\n"
"Automatically switches backend if type differs from current.\n\n"
"Args:\n"
" filepath: Path to load configuration from")
// Processing
.def("set_callback", &ProcessorWrapper::set_callback,
py::arg("callback"),
py::arg("error_callback") = py::none(),
"Set callback function to receive processed output (legacy method)\n\n"
"Note: Consider using add_output_callback() for new code.\n\n"
"Args:\n"
" callback: Function that takes (NumPy array, buffer_id) as arguments\n"
" error_callback: Optional function to handle callback errors")
.def("add_output_callback", &ProcessorWrapper::add_output_callback,
py::arg("callback"),
"Add output callback for multi-consumer support\n\n"
"Allows multiple callbacks to receive processed data in parallel.\n"
"Each callback runs in its own thread.\n\n"
"Args:\n"
" callback: Function that takes (NumPy array, buffer_id) as arguments\n\n"
"Returns:\n"
" int: Callback ID for later removal\n\n"
"Example:\n"
" >>> def display(data, buffer_id):\n"
" ... print(f'Displaying buffer {buffer_id}')\n"
" ... cv2.imshow('OCT', data.copy())\n"
" >>> callback_id = processor.add_output_callback(display)\n"
" >>> processor.remove_output_callback(callback_id)")
.def("remove_output_callback", &ProcessorWrapper::remove_output_callback,
py::arg("callback_id"),
"Remove a specific callback by ID\n\n"
"Args:\n"
" callback_id: ID returned from add_output_callback()\n\n"
"Returns:\n"
" bool: True if callback was found and removed")
.def("clear_output_callbacks", &ProcessorWrapper::clear_output_callbacks,
"Remove all output callbacks\n\n"
"Stops all consumer threads and clears all registered callbacks.")
.def("get_output_callback_count", &ProcessorWrapper::get_output_callback_count,
"Get number of registered output callbacks\n\n"
"Returns:\n"
" int: Number of active output callbacks")
// Input callback methods (raw data before processing)
.def("add_input_callback", &ProcessorWrapper::add_input_callback,
py::arg("callback"),
"Add input callback for raw data before processing\n\n"
"Allows multiple callbacks to receive input data before processing.\n"
"Each callback runs in its own thread.\n"
"WARNING: Buffer is still in use by backend, copy data if needed beyond callback.\n\n"
"Args:\n"
" callback: Function that takes (NumPy array, buffer_id) as arguments\n\n"
"Returns:\n"
" int: Callback ID for later removal\n\n"
"Example:\n"
" >>> def record_raw(data, buffer_id):\n"