File: data_array_from_py.h

package info (click to toggle)
pytango 10.1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,304 kB
  • sloc: python: 27,795; cpp: 16,150; sql: 252; sh: 152; makefile: 43
file content (326 lines) | stat: -rw-r--r-- 14,044 bytes parent folder | download
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
/*
 * SPDX-FileCopyrightText: All Contributors to the PyTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

// This header file is just some template functions moved apart from
// attribute.cpp, and should only be included there.

#pragma once

#include "types_structs_macros.h"
#include "convertors/generic_from_py.h"

// cppTango "feature": commands expect, that we allocate memory with "allocbuf", while attributes - new[].
// So.....

enum MemoryAllocation {
    ALLOC,
    NEW
};

#define MEMORY_ALLOCATOR(TangoScalarType, TangoArrayType, len, allocation)  \
    TangoScalarType *tg_data;                                               \
    switch(allocation) {                                                    \
    case MemoryAllocation::ALLOC:                                           \
        tg_data = TangoArrayType::allocbuf(static_cast<_CORBA_ULong>(len)); \
        break;                                                              \
    case MemoryAllocation::NEW:                                             \
        tg_data = new TangoScalarType[len];                                 \
        break;                                                              \
    default:                                                                \
        throw std::invalid_argument("Unknown allocation method");           \
    }

template <int tangoArrayTypeConst>
inline void buffer_deleter__(typename TANGO_const2scalartype(tangoArrayTypeConst) * tg_data,
                             MemoryAllocation allocation,
                             [[maybe_unused]] py::size_t processed_elements) {
    using TangoArrayType = typename TANGO_const2type(tangoArrayTypeConst);

    switch(allocation) {
    case MemoryAllocation::ALLOC:
        TangoArrayType::freebuf(tg_data);
        break;
    case MemoryAllocation::NEW:
        delete[] tg_data;
        break;
    default:
        throw std::invalid_argument("Unknown allocation method");
    }
}

template <>
inline void buffer_deleter__<Tango::DEVVAR_STRINGARRAY>(Tango::DevString *tg_data,
                                                        MemoryAllocation allocation,
                                                        py::size_t processed_elements) {
    switch(allocation) {
    case MemoryAllocation::ALLOC:
        Tango::DevVarStringArray::freebuf(tg_data);
        break;
    case MemoryAllocation::NEW: {
        for(py::size_t i = 0; i < processed_elements; ++i) {
            delete[] tg_data[i];
        }
        delete[] tg_data;
        break;
    }
    default:
        throw std::invalid_argument("Unknown allocation method");
    }
}

template <int tangoArrayTypeConst>
    inline typename TANGO_const2scalartype(tangoArrayTypeConst) * python_to_cpp_buffer_generic(py::object &py_val,
                                                                                               MemoryAllocation allocation,
                                                                                               const std::string &fname,
                                                                                               bool isImage,
                                                                                               py::size_t &res_dim_x,
                                                                                               py::size_t &res_dim_y) {
    using TangoScalarType = typename TANGO_const2scalartype(tangoArrayTypeConst);
    using TangoArrayType = typename TANGO_const2type(tangoArrayTypeConst);

    std::string err_msg = isImage
                              ? "Expecting a sequence of sequences (IMAGE attribute)."
                              : "Expecting a sequence (SPECTRUM attribute).";

    if(py::isinstance<py::str>(py_val) || !py::isinstance<py::sequence>(py_val)) {
        Tango::Except::throw_exception("PyDs_WrongParameters",
                                       err_msg,
                                       fname + "()");
    }

    py::list py_list = py::cast<py::list>(py_val);
    py::size_t len = py::len(py_val);

    if(len > 0 && isImage) {
        py::object py_row0 = py_list[0];
        if(!py::isinstance<py::sequence>(py_row0)) {
            Tango::Except::throw_exception("PyDs_WrongParameters",
                                           err_msg,
                                           fname + "()");
        }

        res_dim_y = len;
        res_dim_x = py::len(py_row0);
        len = res_dim_x * res_dim_y;
    } else {
        res_dim_y = 0;
        res_dim_x = len;
    }

    /// @bug Why not TangoArrayType::allocbuf(len)? Because
    /// I will use it in set_value(tg_ptr,...,release=true).
    /// Tango API makes delete[] tg_ptr instead of freebuf(tg_ptr).
    /// This is usually the same, but for Tango::DevStringArray the
    /// behaviour seems different and causes weird troubles..

    MEMORY_ALLOCATOR(TangoScalarType, TangoArrayType, len, allocation);

    TangoScalarType tg_scalar;
    py::size_t idx = 0;
    try {
        if(isImage) {
            for(py::size_t y = 0; y < res_dim_y; y++) {
                py::list py_row = py_list[y];
                for(py::size_t x = 0; x < res_dim_x; x++) {
                    array_element_from_py<tangoArrayTypeConst>::convert(py_row[x], tg_scalar);
                    tg_data[idx] = tg_scalar;
                    idx++;
                }
            }
        } else {
            for(py::size_t x = 0; x < res_dim_x; x++) {
                array_element_from_py<tangoArrayTypeConst>::convert(py_list[x], tg_scalar);
                tg_data[idx] = tg_scalar;
                idx++;
            }
        }
    } catch(...) {
        buffer_deleter__<tangoArrayTypeConst>(tg_data, allocation, idx);
        throw;
    }
    return tg_data;
}

template <int tangoArrayTypeConst>
    inline typename TANGO_const2scalartype(tangoArrayTypeConst) * python_to_cpp_buffer(py::object &py_val,
                                                                                       MemoryAllocation allocation,
                                                                                       const std::string &fname,
                                                                                       bool isImage,
                                                                                       py::size_t &res_dim_x,
                                                                                       py::size_t &res_dim_y) {
    using TangoArrayType = typename TANGO_const2type(tangoArrayTypeConst);
    using TangoScalarType = typename TANGO_const2scalartype(tangoArrayTypeConst);

    if(!py::isinstance<py::array>(py_val)) {
        return python_to_cpp_buffer_generic<tangoArrayTypeConst>(py_val,
                                                                 allocation,
                                                                 fname,
                                                                 isImage,
                                                                 res_dim_x,
                                                                 res_dim_y);
    }

    py::array arr = py_val.cast<py::array>();
    long nd = arr.ndim();
    const py::ssize_t *signed_dims = arr.shape();
    std::vector<py::size_t> dims;
    for(long i = 0; i < nd; ++i) {
        dims.push_back(static_cast<py::size_t>(signed_dims[i]));
    }
    py::size_t len = 0;

    // Retrieve the NumPy array flags
    int flags = arr.flags();

    // Check if the array is exactly what we need: contiguous, aligned, and correct data type
    const bool exact_array = ((flags & NPY_ARRAY_C_CONTIGUOUS) != 0) &&
                             ((flags & NPY_ARRAY_ALIGNED) != 0) &&
                             arr.dtype().is(pybind11::dtype::of<TangoScalarType>());

    // Handle empty arrays first - set dimensions to 0 regardless of actual dimensions
    bool is_empty = false;
    if(isImage) {
        if(nd == 2 && dims[0] == 0) {
            // Empty 2D array
            is_empty = true;
        } else if(nd == 1 && dims[0] == 0) {
            // Empty 1D array passed as image - treat as empty 2D
            is_empty = true;
        } else if(nd != 2) {
            Tango::Except::throw_exception("PyDs_WrongNumpyArrayDimensions",
                                           "Expecting a sequence of sequences (IMAGE attribute).",
                                           fname + "()");
        }
    } else {
        if(nd == 1 && dims[0] == 0) {
            // Empty 1D array
            is_empty = true;
        } else if(nd != 1) {
            Tango::Except::throw_exception("PyDs_WrongNumpyArrayDimensions",
                                           "Expecting a sequence (SPECTRUM attribute).",
                                           fname + "()");
        }
    }

    if(is_empty) {
        len = 0;
        res_dim_x = 0;
        res_dim_y = 0;
    } else if(isImage) {
        len = dims[0] * dims[1];
        res_dim_x = dims[1];
        res_dim_y = dims[0];
    } else {
        len = dims[0];
        res_dim_x = dims[0];
    }

    MEMORY_ALLOCATOR(TangoScalarType, TangoArrayType, len, allocation);

    if(exact_array) {
        memcpy(tg_data, arr.data(), len * sizeof(TangoScalarType));
    } else {
        try {
            py::array_t<TangoScalarType, py::array::c_style | py::array::forcecast> arr_casted(arr);

            py::size_t processed_elements = static_cast<py::size_t>(arr_casted.size());
            if(processed_elements < len) {
                buffer_deleter__<tangoArrayTypeConst>(tg_data, allocation, processed_elements);
                throw py::value_error("Array size is smaller than expected.");
            }

            memcpy(tg_data, arr_casted.data(), len * sizeof(TangoScalarType));
        } catch(const py::error_already_set &) {
            buffer_deleter__<tangoArrayTypeConst>(tg_data, allocation, 0);
            throw;
        }
    }

    return tg_data;
}

template <>
    inline TANGO_const2scalartype(Tango::DEVVAR_STRINGARRAY) *
    python_to_cpp_buffer<Tango::DEVVAR_STRINGARRAY>(py::object &py_val,
                                                    MemoryAllocation allocation,
                                                    const std::string &fname,
                                                    bool isImage,
                                                    py::size_t &res_dim_x,
                                                    py::size_t &res_dim_y) {
    return python_to_cpp_buffer_generic<Tango::DEVVAR_STRINGARRAY>(py_val,
                                                                   allocation,
                                                                   fname,
                                                                   isImage,
                                                                   res_dim_x,
                                                                   res_dim_y);
}

template <int tangoArrayTypeConst>
    inline typename TANGO_const2type(tangoArrayTypeConst) * fast_convert2array(py::object py_value) {
    using TangoScalarType = typename TANGO_const2scalartype(tangoArrayTypeConst);
    using TangoArrayType = typename TANGO_const2type(tangoArrayTypeConst);

    py::size_t res_dim_x, res_dim_y;

    TangoScalarType *array = python_to_cpp_buffer<tangoArrayTypeConst>(py_value,
                                                                       MemoryAllocation ::ALLOC,
                                                                       "array_python_data_to_cpp",
                                                                       false,
                                                                       res_dim_x,
                                                                       res_dim_y);

    try {
        // not a bug: res_dim_y means nothing to us, we are unidimensional
        // here we have max_len and current_len = res_dim_x
        return new TangoArrayType(static_cast<_CORBA_ULong>(res_dim_x),
                                  static_cast<_CORBA_ULong>(res_dim_x),
                                  array,
                                  true);
    } catch(...) {
        TangoArrayType::freebuf(array);
        throw;
    }
}

template <>
    inline TANGO_const2type(Tango::DEVVAR_LONGSTRINGARRAY) * fast_convert2array<Tango::DEVVAR_LONGSTRINGARRAY>(py::object py_value) {
    py::object py_long, py_str;

    __long_double_string_array_helper(py_value,
                                      DevVarNumericStringArray::LONG_STRING,
                                      "fast_convert2array()",
                                      py_long,
                                      py_str);

    std::unique_ptr<Tango::DevVarLongArray> a_long(fast_convert2array<Tango::DEVVAR_LONGARRAY>(py_long));
    std::unique_ptr<Tango::DevVarStringArray> a_str(fast_convert2array<Tango::DEVVAR_STRINGARRAY>(py_str));
    std::unique_ptr<Tango::DevVarLongStringArray> result(new Tango::DevVarLongStringArray());

    result->lvalue = *a_long;
    result->svalue = *a_str;

    return result.release();
}

template <>
    inline TANGO_const2type(Tango::DEVVAR_DOUBLESTRINGARRAY) * fast_convert2array<Tango::DEVVAR_DOUBLESTRINGARRAY>(py::object py_value) {
    py::object py_double, py_str;

    __long_double_string_array_helper(py_value,
                                      DevVarNumericStringArray::LONG_STRING,
                                      "fast_convert2array()",
                                      py_double,
                                      py_str);

    std::unique_ptr<Tango::DevVarDoubleArray> a_double(fast_convert2array<Tango::DEVVAR_DOUBLEARRAY>(py_double));
    std::unique_ptr<Tango::DevVarStringArray> a_str(fast_convert2array<Tango::DEVVAR_STRINGARRAY>(py_str));
    std::unique_ptr<Tango::DevVarDoubleStringArray> result(new Tango::DevVarDoubleStringArray());

    result->dvalue = *a_double;
    result->svalue = *a_str;

    return result.release();
}