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 alias numpy_ndarray_Type = get_type!("numpy", "ndarray");
37 
38 template NumpyFormatType(T) {
39     static if(is(Unqual!T == Complex!F, F)) {
40         alias Float = F;
41         enum supportedComplex = F.sizeof == 4 || F.sizeof == 8;
42     }else{
43         enum supportedComplex = false;
44     }
45     enum supported = SimpleFormatType!T.supported || isBoolean!T || supportedComplex;
46 
47     static if(SimpleFormatType!T.supported) {
48         alias pyType = SimpleFormatType!T.pyType;
49     }else{
50         PyObject* pyType() {
51             assert(supported);
52 
53             PyObject* numpy = PyImport_ImportModule("numpy");
54             static if(is(Unqual!T == Complex!Float, Float)) {
55                 static if(Float.sizeof == 4) {
56                     return PyObject_GetAttrString(numpy, "complex64");
57                 }else static if(Float.sizeof == 8) {
58                     return PyObject_GetAttrString(numpy, "complex128");
59                 }else assert(0);
60             }else static if(isBoolean!T) {
61                 return PyObject_GetAttrString(numpy, "bool_");
62             }
63         }
64     }
65 }
66 static assert(NumpyFormatType!(Complex!float).supported);
67 
68 /**
69   Convert a D array to numpy.ndarray.
70   */
71 PyObject* d_to_python_numpy_ndarray(T)(T t)
72 if((isArray!T || IsStaticArrayPointer!T) &&
73         NumpyFormatType!(MatrixInfo!T.MatrixElementType).supported) {
74     import std.exception: enforce;
75     enforce(numpy_ndarray_Type(), "numpy is not available");
76     alias MatrixInfo!T.MatrixElementType ME;
77     Py_ssize_t[] shape = MatrixInfo!T.build_shape(t);
78     PyObject* pyshape = d_to_python(shape);
79     PyObject* pyformat = NumpyFormatType!ME.pyType();
80     PyObject* args = PyTuple_FromItems(pyshape, pyformat);
81     scope(exit) Py_DECREF(args);
82     PyObject* ndarray = numpy_ndarray_Type.tp_new(numpy_ndarray_Type, args, null);
83     if(!ndarray) handle_exception();
84     enforce(ndarray, "numpy.ndarray.__new__ returned null (and didn't set an exception)");
85     PydObject array = new PydObject(ndarray);
86     auto buf = array.buffer_view(PyBUF_STRIDES|PyBUF_C_CONTIGUOUS);
87     // this really should be optimized, but I am so lazy right now
88     enum xx = (MatrixInfo!T.matrixIter(
89                 "t", "shape", "_indices",
90                 MatrixInfo!T.ndim, q{
91                 static if(is(typeof($array_ixn) == ME)) {
92                     buf.set_item!ME($array_ixn, cast(Py_ssize_t[]) _indices);
93                 }
94                 },""));
95     mixin(xx);
96     // that PydObject stole ownership
97     Py_INCREF(ndarray);
98     return ndarray;
99 }
100 
101 PyObject* d_to_numpy_datetime64(T)(T t) {
102     PyObject* datetime = d_to_python(t);
103     scope(exit) Py_DECREF(datetime);
104     PyObject* args = PyTuple_FromItems(datetime);
105     scope(exit) Py_DECREF(args);
106     PyObject* datetime64 = numpy_datetime64.tp_new(numpy_datetime64, args, null);
107     return datetime64;
108 }
109