1 /*
2 Copyright (c) 2012 Ellery Newcomer
3 
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10 
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13 
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22 
23 /**
24   Various utilities operating on non-standard python objects.
25 */
26 module pyd.extra;
27 
28 import std.traits;
29 import std.complex;
30 
31 import pyd.pydobject;
32 import pyd.exception;
33 import pyd.make_object;
34 import deimos.python.Python;
35 
36 @property PyTypeObject* numpy_ndarray_Type() {
37     static PyTypeObject* m_type;
38     static bool inited = false;
39     if(!inited) {
40         inited = true;
41         PyObject* numpy = PyImport_ImportModule("numpy");
42         if(numpy) {
43             scope(exit) Py_XDECREF(numpy);
44             m_type = cast(PyTypeObject*) PyObject_GetAttrString(numpy, "ndarray");
45         }else{
46             PyErr_Clear();
47         }
48     }
49     return m_type;
50 }
51 
52 template NumpyFormatType(T) {
53     static if(is(Unqual!T == Complex!F, F)) {
54         alias Float = F;
55         enum supportedComplex = F.sizeof == 4 || F.sizeof == 8;
56     }else{
57         enum supportedComplex = false;
58     }
59     enum supported = SimpleFormatType!T.supported || isBoolean!T || supportedComplex;
60 
61     static if(SimpleFormatType!T.supported) {
62         alias pyType = SimpleFormatType!T.pyType;
63     }else{
64         PyObject* pyType() {
65             assert(supported);
66 
67             PyObject* numpy = PyImport_ImportModule("numpy");
68             static if(is(Unqual!T == Complex!Float, Float)) {
69                 static if(Float.sizeof == 4) {
70                     return PyObject_GetAttrString(numpy, "complex64");
71                 }else static if(Float.sizeof == 8) {
72                     return PyObject_GetAttrString(numpy, "complex128");
73                 }else assert(0);
74             }else static if(isBoolean!T) {
75                 return PyObject_GetAttrString(numpy, "bool_");
76             }
77         }
78     }
79 }
80 static assert(NumpyFormatType!(Complex!float).supported);
81 
82 /**
83   Convert a D array to numpy.ndarray.
84   */
85 PyObject* d_to_python_numpy_ndarray(T)(T t) 
86 if((isArray!T || IsStaticArrayPointer!T) &&
87         NumpyFormatType!(MatrixInfo!T.MatrixElementType).supported) {
88     enforce(numpy_ndarray_Type, "numpy is not available"); 
89     alias MatrixInfo!T.MatrixElementType ME;
90     Py_ssize_t[] shape = MatrixInfo!T.build_shape(t);
91     PyObject* pyshape = d_to_python(shape);
92     PyObject* pyformat = NumpyFormatType!ME.pyType();
93     PyObject* args = PyTuple_New(2);
94     scope(exit) Py_DECREF(args);
95     PyTuple_SetItem(args, 0, pyshape);
96     PyTuple_SetItem(args, 1, pyformat);
97     PyObject* ndarray = numpy_ndarray_Type.tp_new(numpy_ndarray_Type, args, null);
98     if(!ndarray) handle_exception();
99     enforce(ndarray, "numpy.ndarray.__new__ returned null (and didn't set an exception)");
100     PydObject array = new PydObject(ndarray);
101     auto buf = array.buffer_view(PyBUF_STRIDES|PyBUF_C_CONTIGUOUS);
102     // this really should be optimized, but I am so lazy right now
103     enum xx = (MatrixInfo!T.matrixIter(
104                 "t", "shape", "_indeces",
105                 MatrixInfo!T.ndim, q{
106                 static if(is(typeof($array_ixn) == ME)) {
107                     buf.set_item!ME($array_ixn, cast(Py_ssize_t[]) _indeces);
108                 }
109                 },""));
110     mixin(xx);
111     // that PydObject stole ownership
112     Py_INCREF(ndarray);
113     return ndarray;
114 }