Merge lp:~xnox/ubuntu/quantal/libvigraimpex/boost1.49 into lp:ubuntu/quantal/libvigraimpex
- Quantal (12.10)
- boost1.49
- Merge into quantal
Status: | Merged |
---|---|
Merge reported by: | Micah Gersten |
Merged at revision: | not available |
Proposed branch: | lp:~xnox/ubuntu/quantal/libvigraimpex/boost1.49 |
Merge into: | lp:ubuntu/quantal/libvigraimpex |
Diff against target: |
6794 lines (+2317/-4327) 15 files modified
.pc/applied-patches (+1/-1) .pc/debian-changes-1.7.1+dfsg1-2ubuntu1/include/vigra/numpy_array.hxx (+0/-1922) .pc/fix-ftbfs-gcc4.7.diff/include/vigra/box.hxx (+545/-0) .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_ridge_split.hxx (+449/-0) .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_split.hxx (+1199/-0) .pc/sizeof_ldbl_not_sizeof_dbl.diff/include/vigra/numpy_array.hxx (+0/-1918) debian/changelog (+30/-0) debian/control (+1/-1) debian/patches/debian-changes-1.7.1+dfsg1-2ubuntu1 (+17/-265) debian/patches/fix-ftbfs-gcc4.7.diff (+66/-0) debian/patches/series (+3/-1) include/vigra/box.hxx (+2/-2) include/vigra/random_forest/rf_ridge_split.hxx (+2/-2) include/vigra/random_forest/rf_split.hxx (+2/-2) vigranumpy/docsrc/conf.py.THIS (+0/-213) |
To merge this branch: | bzr merge lp:~xnox/ubuntu/quantal/libvigraimpex/boost1.49 |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Ubuntu branches | Pending | ||
Barry Warsaw | Pending | ||
Review via email: mp+110409@code.launchpad.net |
Commit message
Description of the change
This merges libvigraimpex from debian.
Barry, can you please review this package as it has interesting history and you were the last one to merge it.
Barry Warsaw (barry) wrote : | # |
Dimitri John Ledkov (xnox) wrote : | # |
On 14/06/12 21:49, Barry Warsaw wrote:
> On Jun 14, 2012, at 08:30 PM, Dmitrijs Ledkovs wrote:
>
>> Barry, can you please review this package as it has interesting history and
>> you were the last one to merge it.
>
> What a mess! Sigh. Just one thing stands out.
>
>
> === modified file 'include/
> === modified file 'include/
>
> Why are these being modified in the source tree? Is this just quilt/bzr
> artifacts? Does it actually build with these changes? Are they in a quilt
> patch?
>
That is the new fix-ftbfs-
That's the reason why I'm merging this =)
Because it's a new patch you get: .pc/ & in tree modifications & an
extra patch in debian/patches/.
=/
--
Regards,
Dmitrijs.
Barry Warsaw (barry) wrote : | # |
On Jun 14, 2012, at 09:55 PM, Dmitrijs Ledkovs wrote:
>Because it's a new patch you get: .pc/ & in tree modifications & an
>extra patch in debian/patches/.
:(
Dimitri John Ledkov (xnox) wrote : | # |
On 14/06/12 22:02, Barry Warsaw wrote:
> On Jun 14, 2012, at 09:55 PM, Dmitrijs Ledkovs wrote:
>
>> Because it's a new patch you get: .pc/ & in tree modifications & an
>> extra patch in debian/patches/.
>
> :(
>
Will you sponsor this? =)
--
Regards,
Dmitrijs.
Barry Warsaw (barry) wrote : | # |
On Jun 14, 2012, at 09:25 PM, Dmitrijs Ledkovs wrote:
>On 14/06/12 22:02, Barry Warsaw wrote:
>> On Jun 14, 2012, at 09:55 PM, Dmitrijs Ledkovs wrote:
>>
>>> Because it's a new patch you get: .pc/ & in tree modifications & an
>>> extra patch in debian/patches/.
>>
>> :(
>>
>
>Will you sponsor this? =)
Sure, if it builds locally for me. :)
Dimitri John Ledkov (xnox) wrote : | # |
On 14/06/12 23:05, Barry Warsaw wrote:
> On Jun 14, 2012, at 09:25 PM, Dmitrijs Ledkovs wrote:
>
>> On 14/06/12 22:02, Barry Warsaw wrote:
>>> On Jun 14, 2012, at 09:55 PM, Dmitrijs Ledkovs wrote:
>>>
>>>> Because it's a new patch you get: .pc/ & in tree modifications & an
>>>> extra patch in debian/patches/.
>>>
>>> :(
>>>
>>
>> Will you sponsor this? =)
>
> Sure, if it builds locally for me. :)
>
I take it, it's still building ;-)
--
Regards,
Dmitrijs.
Barry Warsaw (barry) wrote : | # |
On Jun 14, 2012, at 11:08 PM, Dmitrijs Ledkovs wrote:
>I take it, it's still building ;-)
chugga chugga :)
Preview Diff
1 | === modified file '.pc/applied-patches' |
2 | --- .pc/applied-patches 2011-11-08 19:31:51 +0000 |
3 | +++ .pc/applied-patches 2012-06-14 20:29:21 +0000 |
4 | @@ -8,6 +8,6 @@ |
5 | fix-ftbfs-gcc4.6.diff |
6 | fix-convolutiontest.diff |
7 | libpng15 |
8 | +fix-ftbfs-gcc4.7.diff |
9 | no-hdf5.diff |
10 | debian-changes-1.7.1+dfsg1-2ubuntu1 |
11 | -sizeof_ldbl_not_sizeof_dbl.diff |
12 | |
13 | === removed file '.pc/debian-changes-1.7.1+dfsg1-2ubuntu1/include/vigra/numpy_array.hxx' |
14 | --- .pc/debian-changes-1.7.1+dfsg1-2ubuntu1/include/vigra/numpy_array.hxx 2011-10-20 09:30:45 +0000 |
15 | +++ .pc/debian-changes-1.7.1+dfsg1-2ubuntu1/include/vigra/numpy_array.hxx 1970-01-01 00:00:00 +0000 |
16 | @@ -1,1922 +0,0 @@ |
17 | -/************************************************************************/ |
18 | -/* */ |
19 | -/* Copyright 2009 by Ullrich Koethe and Hans Meine */ |
20 | -/* */ |
21 | -/* This file is part of the VIGRA computer vision library. */ |
22 | -/* The VIGRA Website is */ |
23 | -/* http://hci.iwr.uni-heidelberg.de/vigra/ */ |
24 | -/* Please direct questions, bug reports, and contributions to */ |
25 | -/* ullrich.koethe@iwr.uni-heidelberg.de or */ |
26 | -/* vigra@informatik.uni-hamburg.de */ |
27 | -/* */ |
28 | -/* Permission is hereby granted, free of charge, to any person */ |
29 | -/* obtaining a copy of this software and associated documentation */ |
30 | -/* files (the "Software"), to deal in the Software without */ |
31 | -/* restriction, including without limitation the rights to use, */ |
32 | -/* copy, modify, merge, publish, distribute, sublicense, and/or */ |
33 | -/* sell copies of the Software, and to permit persons to whom the */ |
34 | -/* Software is furnished to do so, subject to the following */ |
35 | -/* conditions: */ |
36 | -/* */ |
37 | -/* The above copyright notice and this permission notice shall be */ |
38 | -/* included in all copies or substantial portions of the */ |
39 | -/* Software. */ |
40 | -/* */ |
41 | -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ |
42 | -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ |
43 | -/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ |
44 | -/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ |
45 | -/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ |
46 | -/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ |
47 | -/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ |
48 | -/* OTHER DEALINGS IN THE SOFTWARE. */ |
49 | -/* */ |
50 | -/************************************************************************/ |
51 | - |
52 | -#ifndef VIGRA_NUMPY_ARRAY_HXX |
53 | -#define VIGRA_NUMPY_ARRAY_HXX |
54 | - |
55 | -#include <Python.h> |
56 | -#include <iostream> |
57 | -#include <algorithm> |
58 | -#include <complex> |
59 | -#include <string> |
60 | -#include <sstream> |
61 | -#include <map> |
62 | -#include <vigra/multi_array.hxx> |
63 | -#include <vigra/array_vector.hxx> |
64 | -#include <vigra/sized_int.hxx> |
65 | -#include <vigra/python_utility.hxx> |
66 | -#include <numpy/arrayobject.h> |
67 | - |
68 | -int _import_array(); |
69 | - |
70 | -namespace vigra { |
71 | - |
72 | -/********************************************************/ |
73 | -/* */ |
74 | -/* Singleband and Multiband */ |
75 | -/* */ |
76 | -/********************************************************/ |
77 | - |
78 | -typedef float NumpyValueType; |
79 | - |
80 | -template <class T> |
81 | -struct Singleband // the last array dimension is not to be interpreted as a channel dimension |
82 | -{ |
83 | - typedef T value_type; |
84 | -}; |
85 | - |
86 | -template <class T> |
87 | -struct Multiband // the last array dimension is a channel dimension |
88 | -{ |
89 | - typedef T value_type; |
90 | -}; |
91 | - |
92 | -template<class T> |
93 | -struct NumericTraits<Singleband<T> > |
94 | -: public NumericTraits<T> |
95 | -{}; |
96 | - |
97 | -template<class T> |
98 | -struct NumericTraits<Multiband<T> > |
99 | -{ |
100 | - typedef Multiband<T> Type; |
101 | -/* |
102 | - typedef int Promote; |
103 | - typedef unsigned int UnsignedPromote; |
104 | - typedef double RealPromote; |
105 | - typedef std::complex<RealPromote> ComplexPromote; |
106 | -*/ |
107 | - typedef Type ValueType; |
108 | - |
109 | - typedef typename NumericTraits<T>::isIntegral isIntegral; |
110 | - typedef VigraFalseType isScalar; |
111 | - typedef typename NumericTraits<T>::isSigned isSigned; |
112 | - typedef typename NumericTraits<T>::isSigned isOrdered; |
113 | - typedef typename NumericTraits<T>::isSigned isComplex; |
114 | -/* |
115 | - static signed char zero() { return 0; } |
116 | - static signed char one() { return 1; } |
117 | - static signed char nonZero() { return 1; } |
118 | - static signed char min() { return SCHAR_MIN; } |
119 | - static signed char max() { return SCHAR_MAX; } |
120 | - |
121 | -#ifdef NO_INLINE_STATIC_CONST_DEFINITION |
122 | - enum { minConst = SCHAR_MIN, maxConst = SCHAR_MIN }; |
123 | -#else |
124 | - static const signed char minConst = SCHAR_MIN; |
125 | - static const signed char maxConst = SCHAR_MIN; |
126 | -#endif |
127 | - |
128 | - static Promote toPromote(signed char v) { return v; } |
129 | - static RealPromote toRealPromote(signed char v) { return v; } |
130 | - static signed char fromPromote(Promote v) { |
131 | - return ((v < SCHAR_MIN) ? SCHAR_MIN : (v > SCHAR_MAX) ? SCHAR_MAX : v); |
132 | - } |
133 | - static signed char fromRealPromote(RealPromote v) { |
134 | - return ((v < 0.0) |
135 | - ? ((v < (RealPromote)SCHAR_MIN) |
136 | - ? SCHAR_MIN |
137 | - : static_cast<signed char>(v - 0.5)) |
138 | - : (v > (RealPromote)SCHAR_MAX) |
139 | - ? SCHAR_MAX |
140 | - : static_cast<signed char>(v + 0.5)); |
141 | - } |
142 | -*/ |
143 | -}; |
144 | - |
145 | -template <class T> |
146 | -class MultibandVectorAccessor |
147 | -{ |
148 | - MultiArrayIndex size_, stride_; |
149 | - |
150 | - public: |
151 | - MultibandVectorAccessor(MultiArrayIndex size, MultiArrayIndex stride) |
152 | - : size_(size), |
153 | - stride_(stride) |
154 | - {} |
155 | - |
156 | - |
157 | - typedef Multiband<T> value_type; |
158 | - |
159 | - /** the vector's value_type |
160 | - */ |
161 | - typedef T component_type; |
162 | - |
163 | - typedef VectorElementAccessor<MultibandVectorAccessor<T> > ElementAccessor; |
164 | - |
165 | - /** Read the component data at given vector index |
166 | - at given iterator position |
167 | - */ |
168 | - template <class ITERATOR> |
169 | - component_type const & getComponent(ITERATOR const & i, int idx) const |
170 | - { |
171 | - return *(&*i+idx*stride_); |
172 | - } |
173 | - |
174 | - /** Set the component data at given vector index |
175 | - at given iterator position. The type <TT>V</TT> of the passed |
176 | - in <TT>value</TT> is automatically converted to <TT>component_type</TT>. |
177 | - In case of a conversion floating point -> intergral this includes rounding and clipping. |
178 | - */ |
179 | - template <class V, class ITERATOR> |
180 | - void setComponent(V const & value, ITERATOR const & i, int idx) const |
181 | - { |
182 | - *(&*i+idx*stride_) = detail::RequiresExplicitCast<component_type>::cast(value); |
183 | - } |
184 | - |
185 | - /** Read the component data at given vector index |
186 | - at an offset of given iterator position |
187 | - */ |
188 | - template <class ITERATOR, class DIFFERENCE> |
189 | - component_type const & getComponent(ITERATOR const & i, DIFFERENCE const & diff, int idx) const |
190 | - { |
191 | - return *(&i[diff]+idx*stride_); |
192 | - } |
193 | - |
194 | - /** Set the component data at given vector index |
195 | - at an offset of given iterator position. The type <TT>V</TT> of the passed |
196 | - in <TT>value</TT> is automatically converted to <TT>component_type</TT>. |
197 | - In case of a conversion floating point -> intergral this includes rounding and clipping. |
198 | - */ |
199 | - template <class V, class ITERATOR, class DIFFERENCE> |
200 | - void |
201 | - setComponent(V const & value, ITERATOR const & i, DIFFERENCE const & diff, int idx) const |
202 | - { |
203 | - *(&i[diff]+idx*stride_) = detail::RequiresExplicitCast<component_type>::cast(value); |
204 | - } |
205 | - |
206 | - template <class U> |
207 | - MultiArrayIndex size(U) const |
208 | - { |
209 | - return size_; |
210 | - } |
211 | -}; |
212 | - |
213 | -/********************************************************/ |
214 | -/* */ |
215 | -/* a few Python utilities */ |
216 | -/* */ |
217 | -/********************************************************/ |
218 | - |
219 | -namespace detail { |
220 | - |
221 | -inline long spatialDimensions(PyObject * obj) |
222 | -{ |
223 | - static python_ptr key(PyString_FromString("spatialDimensions"), python_ptr::keep_count); |
224 | - python_ptr pres(PyObject_GetAttr(obj, key), python_ptr::keep_count); |
225 | - long res = pres && PyInt_Check(pres) |
226 | - ? PyInt_AsLong(pres) |
227 | - : -1; |
228 | - return res; |
229 | -} |
230 | - |
231 | -/* |
232 | - * The registry is used to optionally map specific C++ types to |
233 | - * specific python sub-classes of numpy.ndarray (for example, |
234 | - * MultiArray<2, Singleband<int> > to a user-defined Python class 'ScalarImage'). |
235 | - * |
236 | - * One needs to use NUMPY_ARRAY_INITIALIZE_REGISTRY once in a python |
237 | - * extension module using this technique, in order to actually provide |
238 | - * the registry (this is done by vigranumpycmodule and will then be |
239 | - * available for other modules, too). Alternatively, |
240 | - * NUMPY_ARRAY_DUMMY_REGISTRY may be used to disable this feature |
241 | - * completely. In both cases, the macro must not be enclosed by any |
242 | - * namespace, so it is best put right at the beginning of the file |
243 | - * (e.g. below the #includes). |
244 | - */ |
245 | - |
246 | -typedef std::map<std::string, std::pair<python_ptr, python_ptr> > ArrayTypeMap; |
247 | - |
248 | -VIGRA_EXPORT ArrayTypeMap * getArrayTypeMap(); |
249 | - |
250 | -#define NUMPY_ARRAY_INITIALIZE_REGISTRY \ |
251 | - namespace vigra { namespace detail { \ |
252 | - ArrayTypeMap * getArrayTypeMap() \ |
253 | - { \ |
254 | - static ArrayTypeMap arrayTypeMap; \ |
255 | - return &arrayTypeMap; \ |
256 | - } \ |
257 | - }} // namespace vigra::detail |
258 | - |
259 | -#define NUMPY_ARRAY_DUMMY_REGISTRY \ |
260 | - namespace vigra { namespace detail { \ |
261 | - ArrayTypeMap * getArrayTypeMap() \ |
262 | - { \ |
263 | - return NULL; \ |
264 | - } \ |
265 | - }} // namespace vigra::detail |
266 | - |
267 | -inline |
268 | -void registerPythonArrayType(std::string const & name, PyObject * obj, PyObject * typecheck) |
269 | -{ |
270 | - ArrayTypeMap *types = getArrayTypeMap(); |
271 | - vigra_precondition( |
272 | - types != NULL, |
273 | - "registerPythonArrayType(): module was compiled without array type registry."); |
274 | - vigra_precondition( |
275 | - obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), |
276 | - "registerPythonArrayType(obj): obj is not a subtype of numpy.ndarray."); |
277 | - if(typecheck && PyCallable_Check(typecheck)) |
278 | - (*types)[name] = std::make_pair(python_ptr(obj), python_ptr(typecheck)); |
279 | - else |
280 | - (*types)[name] = std::make_pair(python_ptr(obj), python_ptr()); |
281 | -// std::cerr << "Registering " << ((PyTypeObject *)obj)->tp_name << " for " << name << "\n"; |
282 | -} |
283 | - |
284 | -inline |
285 | -python_ptr getArrayTypeObject(std::string const & name, PyTypeObject * def = 0) |
286 | -{ |
287 | - ArrayTypeMap *types = getArrayTypeMap(); |
288 | - if(!types) |
289 | - // dummy registry -> handle like empty registry |
290 | - return python_ptr((PyObject *)def); |
291 | - |
292 | - python_ptr res; |
293 | - ArrayTypeMap::iterator i = types->find(name); |
294 | - if(i != types->end()) |
295 | - res = i->second.first; |
296 | - else |
297 | - res = python_ptr((PyObject *)def); |
298 | -// std::cerr << "Requested " << name << ", got " << ((PyTypeObject *)res.get())->tp_name << "\n"; |
299 | - return res; |
300 | -} |
301 | - |
302 | -// there are two cases for the return: |
303 | -// * if a typecheck function was registered, it is returned |
304 | -// * a null pointer is returned if nothing was registered for either key, or if |
305 | -// a type was registered without typecheck function |
306 | -inline python_ptr |
307 | -getArrayTypecheckFunction(std::string const & keyFull, std::string const & key) |
308 | -{ |
309 | - python_ptr res; |
310 | - ArrayTypeMap *types = getArrayTypeMap(); |
311 | - if(types) |
312 | - { |
313 | - ArrayTypeMap::iterator i = types->find(keyFull); |
314 | - if(i == types->end()) |
315 | - i = types->find(key); |
316 | - if(i != types->end()) |
317 | - res = i->second.second; |
318 | - } |
319 | - return res; |
320 | -} |
321 | - |
322 | -inline bool |
323 | -performCustomizedArrayTypecheck(PyObject * obj, std::string const & keyFull, std::string const & key) |
324 | -{ |
325 | - if(obj == 0 || !PyArray_Check(obj)) |
326 | - return false; |
327 | - python_ptr typecheck = getArrayTypecheckFunction(keyFull, key); |
328 | - if(typecheck == 0) |
329 | - return true; // no custom test registered |
330 | - python_ptr args(PyTuple_Pack(1, obj), python_ptr::keep_count); |
331 | - pythonToCppException(args); |
332 | - python_ptr res(PyObject_Call(typecheck.get(), args.get(), 0), python_ptr::keep_count); |
333 | - pythonToCppException(res); |
334 | - vigra_precondition(PyBool_Check(res), |
335 | - "NumpyArray conversion: registered typecheck function did not return a boolean."); |
336 | - return (void*)res.get() == (void*)Py_True; |
337 | -} |
338 | - |
339 | -inline |
340 | -python_ptr constructNumpyArrayImpl( |
341 | - PyTypeObject * type, |
342 | - ArrayVector<npy_intp> const & shape, npy_intp *strides, |
343 | - NPY_TYPES typeCode, bool init) |
344 | -{ |
345 | - python_ptr array; |
346 | - |
347 | - if(strides == 0) |
348 | - { |
349 | - array = python_ptr(PyArray_New(type, shape.size(), (npy_intp *)shape.begin(), typeCode, 0, 0, 0, 1 /* Fortran order */, 0), |
350 | - python_ptr::keep_count); |
351 | - } |
352 | - else |
353 | - { |
354 | - int N = shape.size(); |
355 | - ArrayVector<npy_intp> pshape(N); |
356 | - for(int k=0; k<N; ++k) |
357 | - pshape[strides[k]] = shape[k]; |
358 | - |
359 | - array = python_ptr(PyArray_New(type, N, pshape.begin(), typeCode, 0, 0, 0, 1 /* Fortran order */, 0), |
360 | - python_ptr::keep_count); |
361 | - pythonToCppException(array); |
362 | - |
363 | - PyArray_Dims permute = { strides, N }; |
364 | - array = python_ptr(PyArray_Transpose((PyArrayObject*)array.get(), &permute), python_ptr::keep_count); |
365 | - } |
366 | - pythonToCppException(array); |
367 | - |
368 | - if(init) |
369 | - PyArray_FILLWBYTE((PyArrayObject *)array.get(), 0); |
370 | - |
371 | - return array; |
372 | -} |
373 | - |
374 | -// strideOrdering will be ignored unless order == "A" |
375 | -// TODO: this function should receive some refactoring in order to make |
376 | -// the rules clear from the code rather than from comments |
377 | -inline python_ptr |
378 | -constructNumpyArrayImpl(PyTypeObject * type, ArrayVector<npy_intp> const & shape, |
379 | - unsigned int spatialDimensions, unsigned int channels, |
380 | - NPY_TYPES typeCode, std::string order, bool init, |
381 | - ArrayVector<npy_intp> strideOrdering = ArrayVector<npy_intp>()) |
382 | -{ |
383 | - // shape must have at least length spatialDimensions, but can also have a channel dimension |
384 | - vigra_precondition(shape.size() == spatialDimensions || shape.size() == spatialDimensions + 1, |
385 | - "constructNumpyArray(type, shape, ...): shape has wrong length."); |
386 | - |
387 | - // if strideOrdering is given, it must have at least length spatialDimensions, |
388 | - // but can also have a channel dimension |
389 | - vigra_precondition(strideOrdering.size() == 0 || strideOrdering.size() == spatialDimensions || |
390 | - strideOrdering.size() == spatialDimensions + 1, |
391 | - "constructNumpyArray(type, ..., strideOrdering): strideOrdering has wrong length."); |
392 | - |
393 | - if(channels == 0) // if the requested number of channels is not given ... |
394 | - { |
395 | - // ... deduce it |
396 | - if(shape.size() == spatialDimensions) |
397 | - channels = 1; |
398 | - else |
399 | - channels = shape.back(); |
400 | - } |
401 | - else |
402 | - { |
403 | - // otherwise, if the shape object also contains a channel dimension, they must be consistent |
404 | - if(shape.size() > spatialDimensions) |
405 | - vigra_precondition(channels == (unsigned int)shape[spatialDimensions], |
406 | - "constructNumpyArray(type, ...): shape contradicts requested number of channels."); |
407 | - } |
408 | - |
409 | - // if we have only one channel, no explicit channel dimension should be in the shape |
410 | - unsigned int shapeSize = channels == 1 |
411 | - ? spatialDimensions |
412 | - : spatialDimensions + 1; |
413 | - |
414 | - // create the shape object with optional channel dimension |
415 | - ArrayVector<npy_intp> pshape(shapeSize); |
416 | - std::copy(shape.begin(), shape.begin()+std::min(shape.size(), pshape.size()), pshape.begin()); |
417 | - if(shapeSize > spatialDimensions) |
418 | - pshape[spatialDimensions] = channels; |
419 | - |
420 | - // order "A" means "preserve order" when an array is copied, and |
421 | - // defaults to "V" when a new array is created without explicit strideOrdering |
422 | - // |
423 | - if(order == "A") |
424 | - { |
425 | - if(strideOrdering.size() == 0) |
426 | - { |
427 | - order = "V"; |
428 | - } |
429 | - else if(strideOrdering.size() > shapeSize) |
430 | - { |
431 | - // make sure that strideOrdering length matches shape length |
432 | - ArrayVector<npy_intp> pstride(strideOrdering.begin(), strideOrdering.begin()+shapeSize); |
433 | - |
434 | - // adjust the ordering when the channel dimension has been dropped because channel == 1 |
435 | - if(strideOrdering[shapeSize] == 0) |
436 | - for(unsigned int k=0; k<shapeSize; ++k) |
437 | - pstride[k] -= 1; |
438 | - pstride.swap(strideOrdering); |
439 | - } |
440 | - else if(strideOrdering.size() < shapeSize) |
441 | - { |
442 | - // make sure that strideOrdering length matches shape length |
443 | - ArrayVector<npy_intp> pstride(shapeSize); |
444 | - |
445 | - // adjust the ordering when the channel dimension has been dropped because channel == 1 |
446 | - for(unsigned int k=0; k<shapeSize-1; ++k) |
447 | - pstride[k] = strideOrdering[k] + 1; |
448 | - pstride[shapeSize-1] = 0; |
449 | - pstride.swap(strideOrdering); |
450 | - } |
451 | - } |
452 | - |
453 | - // create the appropriate strideOrdering objects for the other memory orders |
454 | - // (when strideOrdering already contained data, it is ignored because order != "A") |
455 | - if(order == "C") |
456 | - { |
457 | - strideOrdering.resize(shapeSize); |
458 | - for(unsigned int k=0; k<shapeSize; ++k) |
459 | - strideOrdering[k] = shapeSize-1-k; |
460 | - } |
461 | - else if(order == "F" || (order == "V" && channels == 1)) |
462 | - { |
463 | - strideOrdering.resize(shapeSize); |
464 | - for(unsigned int k=0; k<shapeSize; ++k) |
465 | - strideOrdering[k] = k; |
466 | - } |
467 | - else if(order == "V") |
468 | - { |
469 | - strideOrdering.resize(shapeSize); |
470 | - for(unsigned int k=0; k<shapeSize-1; ++k) |
471 | - strideOrdering[k] = k+1; |
472 | - strideOrdering[shapeSize-1] = 0; |
473 | - } |
474 | - |
475 | - return constructNumpyArrayImpl(type, pshape, strideOrdering.begin(), typeCode, init); |
476 | -} |
477 | - |
478 | -template <class TINY_VECTOR> |
479 | -inline |
480 | -python_ptr constructNumpyArrayFromData( |
481 | - std::string const & typeKeyFull, |
482 | - std::string const & typeKey, |
483 | - TINY_VECTOR const & shape, npy_intp *strides, |
484 | - NPY_TYPES typeCode, void *data) |
485 | -{ |
486 | - ArrayVector<npy_intp> pyShape(shape.begin(), shape.end()); |
487 | - |
488 | - python_ptr type = detail::getArrayTypeObject(typeKeyFull); |
489 | - if(type == 0) |
490 | - type = detail::getArrayTypeObject(typeKey, &PyArray_Type); |
491 | - |
492 | - python_ptr array(PyArray_New((PyTypeObject *)type.ptr(), shape.size(), pyShape.begin(), typeCode, strides, data, 0, NPY_WRITEABLE, 0), |
493 | - python_ptr::keep_count); |
494 | - pythonToCppException(array); |
495 | - |
496 | - return array; |
497 | -} |
498 | - |
499 | - |
500 | -} // namespace detail |
501 | - |
502 | -/********************************************************/ |
503 | -/* */ |
504 | -/* NumpyArrayValuetypeTraits */ |
505 | -/* */ |
506 | -/********************************************************/ |
507 | - |
508 | -template<class ValueType> |
509 | -struct ERROR_NumpyArrayValuetypeTraits_not_specialized_for_ { }; |
510 | - |
511 | -template<class ValueType> |
512 | -struct NumpyArrayValuetypeTraits |
513 | -{ |
514 | - static bool isValuetypeCompatible(PyArrayObject const * obj) |
515 | - { |
516 | - return ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType>(); |
517 | - } |
518 | - |
519 | - static ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType> typeCode; |
520 | - |
521 | - static std::string typeName() |
522 | - { |
523 | - return std::string("ERROR: NumpyArrayValuetypeTraits not specialized for this case"); |
524 | - } |
525 | - |
526 | - static std::string typeNameImpex() |
527 | - { |
528 | - return std::string("ERROR: NumpyArrayValuetypeTraits not specialized for this case"); |
529 | - } |
530 | - |
531 | - static PyObject * typeObject() |
532 | - { |
533 | - return (PyObject *)0; |
534 | - } |
535 | -}; |
536 | - |
537 | -template<class ValueType> |
538 | -ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType> NumpyArrayValuetypeTraits<ValueType>::typeCode; |
539 | - |
540 | -#define VIGRA_NUMPY_VALUETYPE_TRAITS(type, typeID, numpyTypeName, impexTypeName) \ |
541 | -template <> \ |
542 | -struct NumpyArrayValuetypeTraits<type > \ |
543 | -{ \ |
544 | - static bool isValuetypeCompatible(PyArrayObject const * obj) /* obj must not be NULL */ \ |
545 | - { \ |
546 | - return PyArray_EquivTypenums(typeID, PyArray_DESCR((PyObject *)obj)->type_num) && \ |
547 | - PyArray_ITEMSIZE((PyObject *)obj) == sizeof(type); \ |
548 | - } \ |
549 | - \ |
550 | - static NPY_TYPES const typeCode = typeID; \ |
551 | - \ |
552 | - static std::string typeName() \ |
553 | - { \ |
554 | - return #numpyTypeName; \ |
555 | - } \ |
556 | - \ |
557 | - static std::string typeNameImpex() \ |
558 | - { \ |
559 | - return impexTypeName; \ |
560 | - } \ |
561 | - \ |
562 | - static PyObject * typeObject() \ |
563 | - { \ |
564 | - return PyArray_TypeObjectFromType(typeID); \ |
565 | - } \ |
566 | -}; |
567 | - |
568 | -VIGRA_NUMPY_VALUETYPE_TRAITS(bool, NPY_BOOL, bool, "UINT8") |
569 | -VIGRA_NUMPY_VALUETYPE_TRAITS(signed char, NPY_INT8, int8, "INT16") |
570 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned char, NPY_UINT8, uint8, "UINT8") |
571 | -VIGRA_NUMPY_VALUETYPE_TRAITS(short, NPY_INT16, int16, "INT16") |
572 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned short, NPY_UINT16, uint16, "UINT16") |
573 | - |
574 | -#if VIGRA_BITSOF_LONG == 32 |
575 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long, NPY_INT32, int32, "INT32") |
576 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long, NPY_UINT32, uint32, "UINT32") |
577 | -#elif VIGRA_BITSOF_LONG == 64 |
578 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long, NPY_INT64, int64, "DOUBLE") |
579 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long, NPY_UINT64, uint64, "DOUBLE") |
580 | -#endif |
581 | - |
582 | -#if VIGRA_BITSOF_INT == 32 |
583 | -VIGRA_NUMPY_VALUETYPE_TRAITS(int, NPY_INT32, int32, "INT32") |
584 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned int, NPY_UINT32, uint32, "UINT32") |
585 | -#elif VIGRA_BITSOF_INT == 64 |
586 | -VIGRA_NUMPY_VALUETYPE_TRAITS(int, NPY_INT64, int64, "DOUBLE") |
587 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned int, NPY_UINT64, uint64, "DOUBLE") |
588 | -#endif |
589 | - |
590 | -#ifdef PY_LONG_LONG |
591 | -# if VIGRA_BITSOF_LONG_LONG == 32 |
592 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long long, NPY_INT32, int32, "INT32") |
593 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long long, NPY_UINT32, uint32, "UINT32") |
594 | -# elif VIGRA_BITSOF_LONG_LONG == 64 |
595 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long long, NPY_INT64, int64, "DOUBLE") |
596 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long long, NPY_UINT64, uint64, "DOUBLE") |
597 | -# endif |
598 | -#endif |
599 | - |
600 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_float32, NPY_FLOAT32, float32, "FLOAT") |
601 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_float64, NPY_FLOAT64, float64, "DOUBLE") |
602 | -#if NPY_SIZEOF_LONGDOUBLE != NPY_SIZEOF_DOUBLE |
603 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_longdouble, NPY_LONGDOUBLE, longdouble, "") |
604 | -#endif |
605 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_cfloat, NPY_CFLOAT, complex64, "") |
606 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_float>, NPY_CFLOAT, complex64, "") |
607 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_cdouble, NPY_CDOUBLE, complex128, "") |
608 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_double>, NPY_CDOUBLE, complex128, "") |
609 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_clongdouble, NPY_CLONGDOUBLE, clongdouble, "") |
610 | -#if NPY_SIZEOF_LONGDOUBLE != NPY_SIZEOF_DOUBLE |
611 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_longdouble>, NPY_CLONGDOUBLE, clongdouble, "") |
612 | -#endif |
613 | - |
614 | -#undef VIGRA_NUMPY_VALUETYPE_TRAITS |
615 | - |
616 | -/********************************************************/ |
617 | -/* */ |
618 | -/* NumpyArrayTraits */ |
619 | -/* */ |
620 | -/********************************************************/ |
621 | - |
622 | -template <class U, int N> |
623 | -bool stridesAreAscending(TinyVector<U, N> const & strides) |
624 | -{ |
625 | - for(int k=1; k<N; ++k) |
626 | - if(strides[k] < strides[k-1]) |
627 | - return false; |
628 | - return true; |
629 | -} |
630 | - |
631 | -template<unsigned int N, class T, class Stride> |
632 | -struct NumpyArrayTraits; |
633 | - |
634 | -template<unsigned int N, class T> |
635 | -struct NumpyArrayTraits<N, T, StridedArrayTag> |
636 | -{ |
637 | - typedef T dtype; |
638 | - typedef T value_type; |
639 | - typedef NumpyArrayValuetypeTraits<T> ValuetypeTraits; |
640 | - static NPY_TYPES const typeCode = ValuetypeTraits::typeCode; |
641 | - |
642 | - enum { spatialDimensions = N, channels = 1 }; |
643 | - |
644 | - static bool isArray(PyObject * obj) |
645 | - { |
646 | - return obj && PyArray_Check(obj); |
647 | - } |
648 | - |
649 | - static bool isClassCompatible(PyObject * obj) |
650 | - { |
651 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
652 | - } |
653 | - |
654 | - static bool isValuetypeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
655 | - { |
656 | - return ValuetypeTraits::isValuetypeCompatible(obj); |
657 | - } |
658 | - |
659 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
660 | - { |
661 | - return PyArray_NDIM((PyObject *)obj) == N-1 || |
662 | - PyArray_NDIM((PyObject *)obj) == N || |
663 | - (PyArray_NDIM((PyObject *)obj) == N+1 && PyArray_DIM((PyObject *)obj, N) == 1); |
664 | - } |
665 | - |
666 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
667 | - { |
668 | - return ValuetypeTraits::isValuetypeCompatible(obj) && |
669 | - isShapeCompatible(obj); |
670 | - } |
671 | - |
672 | - template <class U> |
673 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
674 | - T *data, TinyVector<U, N> const & stride) |
675 | - { |
676 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
677 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
678 | - } |
679 | - |
680 | - static std::string typeKey() |
681 | - { |
682 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", *>"; |
683 | - return key; |
684 | - } |
685 | - |
686 | - static std::string typeKeyFull() |
687 | - { |
688 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", " + |
689 | - ValuetypeTraits::typeName() + ", StridedArrayTag>"; |
690 | - return key; |
691 | - } |
692 | -}; |
693 | - |
694 | -/********************************************************/ |
695 | - |
696 | -template<unsigned int N, class T> |
697 | -struct NumpyArrayTraits<N, T, UnstridedArrayTag> |
698 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
699 | -{ |
700 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
701 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
702 | - |
703 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
704 | - { |
705 | - return BaseType::isShapeCompatible(obj) && |
706 | - PyArray_STRIDES((PyObject *)obj)[0] == PyArray_ITEMSIZE((PyObject *)obj); |
707 | - } |
708 | - |
709 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
710 | - { |
711 | - return BaseType::isValuetypeCompatible(obj) && |
712 | - isShapeCompatible(obj); |
713 | - } |
714 | - |
715 | - template <class U> |
716 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
717 | - T *data, TinyVector<U, N> const & stride) |
718 | - { |
719 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
720 | - return detail::constructNumpyArrayFromData(typeKeyFull(), BaseType::typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
721 | - } |
722 | - |
723 | - static std::string typeKeyFull() |
724 | - { |
725 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", " + |
726 | - ValuetypeTraits::typeName() + ", UnstridedArrayTag>"; |
727 | - return key; |
728 | - } |
729 | -}; |
730 | - |
731 | -/********************************************************/ |
732 | - |
733 | -template<unsigned int N, class T> |
734 | -struct NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> |
735 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
736 | -{ |
737 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
738 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
739 | - |
740 | - static bool isClassCompatible(PyObject * obj) |
741 | - { |
742 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
743 | - } |
744 | - |
745 | - template <class U> |
746 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
747 | - T *data, TinyVector<U, N> const & stride) |
748 | - { |
749 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
750 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
751 | - } |
752 | - |
753 | - static std::string typeKey() |
754 | - { |
755 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<*> >"; |
756 | - return key; |
757 | - } |
758 | - |
759 | - static std::string typeKeyFull() |
760 | - { |
761 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<" + |
762 | - ValuetypeTraits::typeName() + ">, StridedArrayTag>"; |
763 | - return key; |
764 | - } |
765 | -}; |
766 | - |
767 | -/********************************************************/ |
768 | - |
769 | -template<unsigned int N, class T> |
770 | -struct NumpyArrayTraits<N, Singleband<T>, UnstridedArrayTag> |
771 | -: public NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> |
772 | -{ |
773 | - typedef NumpyArrayTraits<N, T, UnstridedArrayTag> UnstridedTraits; |
774 | - typedef NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> BaseType; |
775 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
776 | - |
777 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
778 | - { |
779 | - return UnstridedTraits::isShapeCompatible(obj); |
780 | - } |
781 | - |
782 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
783 | - { |
784 | - return UnstridedTraits::isPropertyCompatible(obj); |
785 | - } |
786 | - |
787 | - template <class U> |
788 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
789 | - T *data, TinyVector<U, N> const & stride) |
790 | - { |
791 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
792 | - return detail::constructNumpyArrayFromData(typeKeyFull(), BaseType::typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
793 | - } |
794 | - |
795 | - static std::string typeKeyFull() |
796 | - { |
797 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<" + |
798 | - ValuetypeTraits::typeName() + ">, UnstridedArrayTag>"; |
799 | - return key; |
800 | - } |
801 | -}; |
802 | - |
803 | -/********************************************************/ |
804 | - |
805 | -template<unsigned int N, class T> |
806 | -struct NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> |
807 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
808 | -{ |
809 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
810 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
811 | - |
812 | - enum { spatialDimensions = N-1, channels = 0 }; |
813 | - |
814 | - static bool isClassCompatible(PyObject * obj) |
815 | - { |
816 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
817 | - } |
818 | - |
819 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
820 | - { |
821 | - return PyArray_NDIM(obj) == N || PyArray_NDIM(obj) == N-1; |
822 | - } |
823 | - |
824 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
825 | - { |
826 | - return ValuetypeTraits::isValuetypeCompatible(obj) && |
827 | - isShapeCompatible(obj); |
828 | - } |
829 | - |
830 | - template <class U> |
831 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
832 | - T *data, TinyVector<U, N> const & stride) |
833 | - { |
834 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
835 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
836 | - } |
837 | - |
838 | - static std::string typeKey() |
839 | - { |
840 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Multiband<*> >"; |
841 | - return key; |
842 | - } |
843 | - |
844 | - static std::string typeKeyFull() |
845 | - { |
846 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Multiband<" + |
847 | - ValuetypeTraits::typeName() + ">, StridedArrayTag>"; |
848 | - return key; |
849 | - } |
850 | -}; |
851 | - |
852 | -/********************************************************/ |
853 | - |
854 | -template<unsigned int N, class T> |
855 | -struct NumpyArrayTraits<N, Multiband<T>, UnstridedArrayTag> |
856 | -: public NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> |
857 | -{ |
858 | - typedef NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> BaseType; |
859 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
860 | - |
861 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
862 | - { |
863 | - return BaseType::isShapeCompatible(obj) && |
864 | - PyArray_STRIDES((PyObject *)obj)[0] == PyArray_ITEMSIZE((PyObject *)obj); |
865 | - } |
866 | - |
867 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
868 | - { |
869 | - return BaseType::isValuetypeCompatible(obj) && |
870 | - isShapeCompatible(obj); |
871 | - } |
872 | - |
873 | - template <class U> |
874 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
875 | - T *data, TinyVector<U, N> const & stride) |
876 | - { |
877 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
878 | - return detail::constructNumpyArrayFromData(typeKeyFull(), BaseType::typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
879 | - } |
880 | - |
881 | - static std::string typeKeyFull() |
882 | - { |
883 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Multiband<" + |
884 | - ValuetypeTraits::typeName() + ">, UnstridedArrayTag>"; |
885 | - return key; |
886 | - } |
887 | -}; |
888 | - |
889 | -/********************************************************/ |
890 | - |
891 | -template<unsigned int N, int M, class T> |
892 | -struct NumpyArrayTraits<N, TinyVector<T, M>, StridedArrayTag> |
893 | -{ |
894 | - typedef T dtype; |
895 | - typedef TinyVector<T, M> value_type; |
896 | - typedef NumpyArrayValuetypeTraits<T> ValuetypeTraits; |
897 | - static NPY_TYPES const typeCode = ValuetypeTraits::typeCode; |
898 | - |
899 | - enum { spatialDimensions = N, channels = M }; |
900 | - |
901 | - static bool isArray(PyObject * obj) |
902 | - { |
903 | - return obj && PyArray_Check(obj); |
904 | - } |
905 | - |
906 | - static bool isClassCompatible(PyObject * obj) |
907 | - { |
908 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
909 | - } |
910 | - |
911 | - static bool isValuetypeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
912 | - { |
913 | - return ValuetypeTraits::isValuetypeCompatible(obj); |
914 | - } |
915 | - |
916 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
917 | - { |
918 | - return PyArray_NDIM((PyObject *)obj) == N+1 && |
919 | - PyArray_DIM((PyObject *)obj, N) == M && |
920 | - PyArray_STRIDES((PyObject *)obj)[N] == PyArray_ITEMSIZE((PyObject *)obj); |
921 | - } |
922 | - |
923 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
924 | - { |
925 | - return ValuetypeTraits::isValuetypeCompatible(obj) && |
926 | - isShapeCompatible(obj); |
927 | - } |
928 | - |
929 | - template <class U> |
930 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
931 | - T *data, TinyVector<U, N> const & stride) |
932 | - { |
933 | - TinyVector<npy_intp, N+1> npyShape; |
934 | - std::copy(shape.begin(), shape.end(), npyShape.begin()); |
935 | - npyShape[N] = M; |
936 | - |
937 | - TinyVector<npy_intp, N+1> npyStride; |
938 | - std::transform( |
939 | - stride.begin(), stride.end(), npyStride.begin(), |
940 | - std::bind2nd(std::multiplies<npy_intp>(), sizeof(value_type))); |
941 | - npyStride[N] = sizeof(T); |
942 | - |
943 | - return detail::constructNumpyArrayFromData( |
944 | - typeKeyFull(), typeKey(), npyShape, |
945 | - npyStride.begin(), ValuetypeTraits::typeCode, data); |
946 | - } |
947 | - |
948 | - static std::string typeKey() |
949 | - { |
950 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", TinyVector<*, " + asString(M) + "> >"; |
951 | - return key; |
952 | - } |
953 | - |
954 | - static std::string typeKeyFull() |
955 | - { |
956 | - static std::string key = std::string("NumpyArray<") + asString(N) + |
957 | - ", TinyVector<" + ValuetypeTraits::typeName() + ", " + asString(M) + ">, StridedArrayTag>"; |
958 | - return key; |
959 | - } |
960 | -}; |
961 | - |
962 | -/********************************************************/ |
963 | - |
964 | -template<unsigned int N, int M, class T> |
965 | -struct NumpyArrayTraits<N, TinyVector<T, M>, UnstridedArrayTag> |
966 | -: public NumpyArrayTraits<N, TinyVector<T, M>, StridedArrayTag> |
967 | -{ |
968 | - typedef NumpyArrayTraits<N, TinyVector<T, M>, StridedArrayTag> BaseType; |
969 | - typedef typename BaseType::value_type value_type; |
970 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
971 | - |
972 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
973 | - { |
974 | - return BaseType::isShapeCompatible(obj) && |
975 | - PyArray_STRIDES((PyObject *)obj)[0] == sizeof(TinyVector<T, M>); |
976 | - } |
977 | - |
978 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
979 | - { |
980 | - return BaseType::isValuetypeCompatible(obj) && |
981 | - isShapeCompatible(obj); |
982 | - } |
983 | - |
984 | - template <class U> |
985 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
986 | - T *data, TinyVector<U, N> const & stride) |
987 | - { |
988 | - TinyVector<npy_intp, N+1> npyShape; |
989 | - std::copy(shape.begin(), shape.end(), npyShape.begin()); |
990 | - npyShape[N] = M; |
991 | - |
992 | - TinyVector<npy_intp, N+1> npyStride; |
993 | - std::transform( |
994 | - stride.begin(), stride.end(), npyStride.begin(), |
995 | - std::bind2nd(std::multiplies<npy_intp>(), sizeof(value_type))); |
996 | - npyStride[N] = sizeof(T); |
997 | - |
998 | - return detail::constructNumpyArrayFromData( |
999 | - typeKeyFull(), BaseType::typeKey(), npyShape, |
1000 | - npyStride.begin(), ValuetypeTraits::typeCode, data); |
1001 | - } |
1002 | - |
1003 | - static std::string typeKeyFull() |
1004 | - { |
1005 | - static std::string key = std::string("NumpyArray<") + asString(N) + |
1006 | - ", TinyVector<" + ValuetypeTraits::typeName() + ", " + asString(M) + ">, UnstridedArrayTag>"; |
1007 | - return key; |
1008 | - } |
1009 | -}; |
1010 | - |
1011 | -/********************************************************/ |
1012 | - |
1013 | -template<unsigned int N, class T> |
1014 | -struct NumpyArrayTraits<N, RGBValue<T>, StridedArrayTag> |
1015 | -: public NumpyArrayTraits<N, TinyVector<T, 3>, StridedArrayTag> |
1016 | -{ |
1017 | - typedef T dtype; |
1018 | - typedef RGBValue<T> value_type; |
1019 | - typedef NumpyArrayValuetypeTraits<T> ValuetypeTraits; |
1020 | - |
1021 | - static bool isClassCompatible(PyObject * obj) |
1022 | - { |
1023 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
1024 | - } |
1025 | - |
1026 | - template <class U> |
1027 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
1028 | - T *data, TinyVector<U, N> const & stride) |
1029 | - { |
1030 | - TinyVector<npy_intp, N+1> npyShape; |
1031 | - std::copy(shape.begin(), shape.end(), npyShape.begin()); |
1032 | - npyShape[N] = 3; |
1033 | - |
1034 | - TinyVector<npy_intp, N+1> npyStride; |
1035 | - std::transform( |
1036 | - stride.begin(), stride.end(), npyStride.begin(), |
1037 | - std::bind2nd(std::multiplies<npy_intp>(), sizeof(value_type))); |
1038 | - npyStride[N] = sizeof(T); |
1039 | - |
1040 | - return detail::constructNumpyArrayFromData( |
1041 | - typeKeyFull(), typeKey(), npyShape, |
1042 | - npyStride.begin(), ValuetypeTraits::typeCode, data); |
1043 | - } |
1044 | - |
1045 | - static std::string typeKey() |
1046 | - { |
1047 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", RGBValue<*> >"; |
1048 | - return key; |
1049 | - } |
1050 | - |
1051 | - static std::string typeKeyFull() |
1052 | - { |
1053 | - static std::string key = std::string("NumpyArray<") + asString(N) + |
1054 | - ", RGBValue<" + ValuetypeTraits::typeName() + ">, StridedArrayTag>"; |
1055 | - return key; |
1056 | - } |
1057 | -}; |
1058 | - |
1059 | -/********************************************************/ |
1060 | - |
1061 | -template<unsigned int N, class T> |
1062 | -struct NumpyArrayTraits<N, RGBValue<T>, UnstridedArrayTag> |
1063 | -: public NumpyArrayTraits<N, RGBValue<T>, StridedArrayTag> |
1064 | -{ |
1065 | - typedef NumpyArrayTraits<N, TinyVector<T, 3>, UnstridedArrayTag> UnstridedTraits; |
1066 | - typedef NumpyArrayTraits<N, RGBValue<T>, StridedArrayTag> BaseType; |
1067 | - typedef typename BaseType::value_type value_type; |
1068 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
1069 | - |
1070 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
1071 | - { |
1072 | - return UnstridedTraits::isShapeCompatible(obj); |
1073 | - } |
1074 | - |
1075 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
1076 | - { |
1077 | - return UnstridedTraits::isPropertyCompatible(obj); |
1078 | - } |
1079 | - |
1080 | - template <class U> |
1081 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
1082 | - T *data, TinyVector<U, N> const & stride) |
1083 | - { |
1084 | - TinyVector<npy_intp, N+1> npyShape; |
1085 | - std::copy(shape.begin(), shape.end(), npyShape.begin()); |
1086 | - npyShape[N] = 3; |
1087 | - |
1088 | - TinyVector<npy_intp, N+1> npyStride; |
1089 | - std::transform( |
1090 | - stride.begin(), stride.end(), npyStride.begin(), |
1091 | - std::bind2nd(std::multiplies<npy_intp>(), sizeof(value_type))); |
1092 | - npyStride[N] = sizeof(T); |
1093 | - |
1094 | - return detail::constructNumpyArrayFromData( |
1095 | - typeKeyFull(), BaseType::typeKey(), npyShape, |
1096 | - npyStride.begin(), ValuetypeTraits::typeCode, data); |
1097 | - } |
1098 | - |
1099 | - static std::string typeKeyFull() |
1100 | - { |
1101 | - static std::string key = std::string("NumpyArray<") + asString(N) + |
1102 | - ", RGBValue<" + ValuetypeTraits::typeName() + ">, UnstridedArrayTag>"; |
1103 | - return key; |
1104 | - } |
1105 | -}; |
1106 | - |
1107 | -/********************************************************/ |
1108 | -/* */ |
1109 | -/* NumpyAnyArray */ |
1110 | -/* */ |
1111 | -/********************************************************/ |
1112 | - |
1113 | -/** Wrapper class for a Python array. |
1114 | - |
1115 | - This class stores a reference-counted pointer to an Python numpy array object, |
1116 | - i.e. an object where <tt>PyArray_Check(object)</tt> returns true (in Python, the |
1117 | - object is then a subclass of <tt>numpy.ndarray</tt>). This class is mainly used |
1118 | - as a smart pointer to these arrays, but some basic access and conversion functions |
1119 | - are also provided. |
1120 | - |
1121 | - <b>\#include</b> \<<a href="numpy__array_8hxx-source.html">vigra/numpy_array.hxx</a>\><br> |
1122 | - Namespace: vigra |
1123 | -*/ |
1124 | -class NumpyAnyArray |
1125 | -{ |
1126 | - protected: |
1127 | - python_ptr pyArray_; |
1128 | - |
1129 | - // We want to apply broadcasting to the channel dimension. |
1130 | - // Since only leading dimensions can be added during numpy |
1131 | - // broadcasting, we permute the array accordingly. |
1132 | - NumpyAnyArray permuteChannelsToFront() const |
1133 | - { |
1134 | - MultiArrayIndex M = ndim(); |
1135 | - ArrayVector<npy_intp> permutation(M); |
1136 | - for(int k=0; k<M; ++k) |
1137 | - permutation[k] = M-1-k; |
1138 | - // explicit cast to int is neede here to avoid gcc c++0x compilation |
1139 | - // error: narrowing conversion of ‘M’ from ‘vigra::MultiArrayIndex’ |
1140 | - // to ‘int’ inside { } |
1141 | - // int overflow should not occur here because PyArray_NDIM returns |
1142 | - // an integer which is converted to long in NumpyAnyArray::ndim() |
1143 | - PyArray_Dims permute = { permutation.begin(), (int) M }; |
1144 | - python_ptr array(PyArray_Transpose(pyArray(), &permute), python_ptr::keep_count); |
1145 | - pythonToCppException(array); |
1146 | - return NumpyAnyArray(array.ptr()); |
1147 | - } |
1148 | - |
1149 | - public: |
1150 | - |
1151 | - /// difference type |
1152 | - typedef ArrayVector<npy_intp> difference_type; |
1153 | - |
1154 | - /** |
1155 | - Construct from a Python object. If \a obj is NULL, or is not a subclass |
1156 | - of numpy.ndarray, the resulting NumpyAnyArray will have no data (i.e. |
1157 | - hasData() returns false). Otherwise, it creates a new reference to the array |
1158 | - \a obj, unless \a createCopy is true, where a new array is created by calling |
1159 | - the C-equivalent of obj->copy(). |
1160 | - */ |
1161 | - explicit NumpyAnyArray(PyObject * obj = 0, bool createCopy = false, PyTypeObject * type = 0) |
1162 | - { |
1163 | - if(obj == 0) |
1164 | - return; |
1165 | - vigra_precondition(type == 0 || PyType_IsSubtype(type, &PyArray_Type), |
1166 | - "NumpyAnyArray(obj, createCopy, type): type must be numpy.ndarray or a subclass thereof."); |
1167 | - if(createCopy) |
1168 | - makeCopy(obj, type); |
1169 | - else |
1170 | - vigra_precondition(makeReference(obj, type), "NumpyAnyArray(obj): obj isn't a numpy array."); |
1171 | - } |
1172 | - |
1173 | - /** |
1174 | - Copy constructor. By default, it creates a new reference to the array |
1175 | - \a other. When \a createCopy is true, a new array is created by calling |
1176 | - the C-equivalent of other.copy(). |
1177 | - */ |
1178 | - NumpyAnyArray(NumpyAnyArray const & other, bool createCopy = false, PyTypeObject * type = 0) |
1179 | - { |
1180 | - if(!other.hasData()) |
1181 | - return; |
1182 | - vigra_precondition(type == 0 || PyType_IsSubtype(type, &PyArray_Type), |
1183 | - "NumpyAnyArray(obj, createCopy, type): type must be numpy.ndarray or a subclass thereof."); |
1184 | - if(createCopy) |
1185 | - makeCopy(other.pyObject(), type); |
1186 | - else |
1187 | - makeReference(other.pyObject(), type); |
1188 | - } |
1189 | - |
1190 | - // auto-generated destructor is ok |
1191 | - |
1192 | - /** |
1193 | - * Assignment operator. If this is already a view with data |
1194 | - * (i.e. hasData() is true) and the shapes match, the RHS |
1195 | - * array contents are copied via the C-equivalent of |
1196 | - * 'self[...] = other[...]'. If the shapes don't matched, |
1197 | - * broadcasting is tried on the trailing (i.e. channel) |
1198 | - * dimension. |
1199 | - * If the LHS is an empty view, assignment is identical to |
1200 | - * makeReference(other.pyObject()). |
1201 | - */ |
1202 | - NumpyAnyArray & operator=(NumpyAnyArray const & other) |
1203 | - { |
1204 | - if(hasData()) |
1205 | - { |
1206 | - vigra_precondition(other.hasData(), |
1207 | - "NumpyArray::operator=(): Cannot assign from empty array."); |
1208 | - if(PyArray_CopyInto(permuteChannelsToFront().pyArray(), other.permuteChannelsToFront().pyArray()) == -1) |
1209 | - pythonToCppException(0); |
1210 | - } |
1211 | - else |
1212 | - { |
1213 | - pyArray_ = other.pyArray_; |
1214 | - } |
1215 | - return *this; |
1216 | - } |
1217 | - |
1218 | - /** |
1219 | - Returns the number of dimensions of this array, or 0 if |
1220 | - hasData() is false. |
1221 | - */ |
1222 | - MultiArrayIndex ndim() const |
1223 | - { |
1224 | - if(hasData()) |
1225 | - return PyArray_NDIM(pyObject()); |
1226 | - return 0; |
1227 | - } |
1228 | - |
1229 | - /** |
1230 | - Returns the number of spatial dimensions of this array, or 0 if |
1231 | - hasData() is false. If the enclosed Python array does not define |
1232 | - the attribute spatialDimensions, ndim() is returned. |
1233 | - */ |
1234 | - MultiArrayIndex spatialDimensions() const |
1235 | - { |
1236 | - if(!hasData()) |
1237 | - return 0; |
1238 | - MultiArrayIndex s = detail::spatialDimensions(pyObject()); |
1239 | - if(s == -1) |
1240 | - s = ndim(); |
1241 | - return s; |
1242 | - } |
1243 | - |
1244 | - /** |
1245 | - Returns the shape of this array. The size of |
1246 | - the returned shape equals ndim(). |
1247 | - */ |
1248 | - difference_type shape() const |
1249 | - { |
1250 | - if(hasData()) |
1251 | - return difference_type(PyArray_DIMS(pyObject()), PyArray_DIMS(pyObject()) + ndim()); |
1252 | - return difference_type(); |
1253 | - } |
1254 | - |
1255 | - /** Compute the ordering of the strides of this array. |
1256 | - The result is describes the current permutation of the axes relative |
1257 | - to an ascending stride order. |
1258 | - */ |
1259 | - difference_type strideOrdering() const |
1260 | - { |
1261 | - if(!hasData()) |
1262 | - return difference_type(); |
1263 | - MultiArrayIndex N = ndim(); |
1264 | - difference_type stride(PyArray_STRIDES(pyObject()), PyArray_STRIDES(pyObject()) + N), |
1265 | - permutation(N); |
1266 | - for(MultiArrayIndex k=0; k<N; ++k) |
1267 | - permutation[k] = k; |
1268 | - for(MultiArrayIndex k=0; k<N-1; ++k) |
1269 | - { |
1270 | - MultiArrayIndex smallest = k; |
1271 | - for(MultiArrayIndex j=k+1; j<N; ++j) |
1272 | - { |
1273 | - if(stride[j] < stride[smallest]) |
1274 | - smallest = j; |
1275 | - } |
1276 | - if(smallest != k) |
1277 | - { |
1278 | - std::swap(stride[k], stride[smallest]); |
1279 | - std::swap(permutation[k], permutation[smallest]); |
1280 | - } |
1281 | - } |
1282 | - difference_type ordering(N); |
1283 | - for(MultiArrayIndex k=0; k<N; ++k) |
1284 | - ordering[permutation[k]] = k; |
1285 | - return ordering; |
1286 | - } |
1287 | - |
1288 | - /** |
1289 | - Returns the value type of the elements in this array, or -1 |
1290 | - when hasData() is false. |
1291 | - */ |
1292 | - int dtype() const |
1293 | - { |
1294 | - if(hasData()) |
1295 | - return PyArray_DESCR(pyObject())->type_num; |
1296 | - return -1; |
1297 | - } |
1298 | - |
1299 | - /** |
1300 | - * Return a borrowed reference to the internal PyArrayObject. |
1301 | - */ |
1302 | - PyArrayObject * pyArray() const |
1303 | - { |
1304 | - return (PyArrayObject *)pyArray_.get(); |
1305 | - } |
1306 | - |
1307 | - /** |
1308 | - * Return a borrowed reference to the internal PyArrayObject |
1309 | - * (see pyArray()), cast to PyObject for your convenience. |
1310 | - */ |
1311 | - PyObject * pyObject() const |
1312 | - { |
1313 | - return pyArray_.get(); |
1314 | - } |
1315 | - |
1316 | - /** |
1317 | - Reset the NumpyAnyArray to the given object. If \a obj is a numpy array object, |
1318 | - a new reference to that array is created, and the function returns |
1319 | - true. Otherwise, it returns false and the NumpyAnyArray remains unchanged. |
1320 | - If \a type is given, the new reference will be a view with that type, provided |
1321 | - that \a type is a numpy ndarray or a subclass thereof. Otherwise, an |
1322 | - exception is thrown. |
1323 | - */ |
1324 | - bool makeReference(PyObject * obj, PyTypeObject * type = 0) |
1325 | - { |
1326 | - if(obj == 0 || !PyArray_Check(obj)) |
1327 | - return false; |
1328 | - if(type != 0) |
1329 | - { |
1330 | - vigra_precondition(PyType_IsSubtype(type, &PyArray_Type) != 0, |
1331 | - "NumpyAnyArray::makeReference(obj, type): type must be numpy.ndarray or a subclass thereof."); |
1332 | - obj = PyArray_View((PyArrayObject*)obj, 0, type); |
1333 | - pythonToCppException(obj); |
1334 | - } |
1335 | - pyArray_.reset(obj); |
1336 | - return true; |
1337 | - } |
1338 | - |
1339 | - /** |
1340 | - Create a copy of the given array object. If \a obj is a numpy array object, |
1341 | - a copy is created via the C-equivalent of 'obj->copy()'. If |
1342 | - this call fails, or obj was not an array, an exception is thrown |
1343 | - and the NumpyAnyArray remains unchanged. |
1344 | - */ |
1345 | - void makeCopy(PyObject * obj, PyTypeObject * type = 0) |
1346 | - { |
1347 | - vigra_precondition(obj && PyArray_Check(obj), |
1348 | - "NumpyAnyArray::makeCopy(obj): obj is not an array."); |
1349 | - vigra_precondition(type == 0 || PyType_IsSubtype(type, &PyArray_Type), |
1350 | - "NumpyAnyArray::makeCopy(obj, type): type must be numpy.ndarray or a subclass thereof."); |
1351 | - python_ptr array(PyArray_NewCopy((PyArrayObject*)obj, NPY_ANYORDER), python_ptr::keep_count); |
1352 | - pythonToCppException(array); |
1353 | - makeReference(array, type); |
1354 | - } |
1355 | - |
1356 | - /** |
1357 | - Check whether this NumpyAnyArray actually points to a Python array. |
1358 | - */ |
1359 | - bool hasData() const |
1360 | - { |
1361 | - return pyArray_ != 0; |
1362 | - } |
1363 | -}; |
1364 | - |
1365 | -/********************************************************/ |
1366 | -/* */ |
1367 | -/* NumpyArray */ |
1368 | -/* */ |
1369 | -/********************************************************/ |
1370 | - |
1371 | -/** Provide the MultiArrayView interface for a Python array. |
1372 | - |
1373 | - This class inherits from both \ref vigra::MultiArrayView and \ref vigra::NumpyAnyArray |
1374 | - in order to support easy and save application of VIGRA functions to Python arrays. |
1375 | - |
1376 | - <b>\#include</b> \<<a href="numpy__array_8hxx-source.html">vigra/numpy_array.hxx</a>\><br> |
1377 | - Namespace: vigra |
1378 | -*/ |
1379 | -template <unsigned int N, class T, class Stride = StridedArrayTag> |
1380 | -class NumpyArray |
1381 | -: public MultiArrayView<N, typename NumpyArrayTraits<N, T, Stride>::value_type, Stride>, |
1382 | - public NumpyAnyArray |
1383 | -{ |
1384 | - public: |
1385 | - typedef NumpyArrayTraits<N, T, Stride> ArrayTraits; |
1386 | - typedef typename ArrayTraits::dtype dtype; |
1387 | - typedef T pseudo_value_type; |
1388 | - |
1389 | - static NPY_TYPES const typeCode = ArrayTraits::typeCode; |
1390 | - |
1391 | - /** the view type associated with this array. |
1392 | - */ |
1393 | - typedef MultiArrayView<N, typename ArrayTraits::value_type, Stride> view_type; |
1394 | - |
1395 | - enum { actual_dimension = view_type::actual_dimension }; |
1396 | - |
1397 | - /** the array's value type |
1398 | - */ |
1399 | - typedef typename view_type::value_type value_type; |
1400 | - |
1401 | - /** pointer type |
1402 | - */ |
1403 | - typedef typename view_type::pointer pointer; |
1404 | - |
1405 | - /** const pointer type |
1406 | - */ |
1407 | - typedef typename view_type::const_pointer const_pointer; |
1408 | - |
1409 | - /** reference type (result of operator[]) |
1410 | - */ |
1411 | - typedef typename view_type::reference reference; |
1412 | - |
1413 | - /** const reference type (result of operator[] const) |
1414 | - */ |
1415 | - typedef typename view_type::const_reference const_reference; |
1416 | - |
1417 | - /** size type |
1418 | - */ |
1419 | - typedef typename view_type::size_type size_type; |
1420 | - |
1421 | - /** difference type (used for multi-dimensional offsets and indices) |
1422 | - */ |
1423 | - typedef typename view_type::difference_type difference_type; |
1424 | - |
1425 | - /** difference and index type for a single dimension |
1426 | - */ |
1427 | - typedef typename view_type::difference_type_1 difference_type_1; |
1428 | - |
1429 | - /** traverser type |
1430 | - */ |
1431 | - typedef typename view_type::traverser traverser; |
1432 | - |
1433 | - /** traverser type to const data |
1434 | - */ |
1435 | - typedef typename view_type::const_traverser const_traverser; |
1436 | - |
1437 | - /** sequential (random access) iterator type |
1438 | - */ |
1439 | - typedef value_type * iterator; |
1440 | - |
1441 | - /** sequential (random access) const iterator type |
1442 | - */ |
1443 | - typedef value_type * const_iterator; |
1444 | - |
1445 | - using view_type::shape; // resolve ambiguity of multiple inheritance |
1446 | - using view_type::hasData; // resolve ambiguity of multiple inheritance |
1447 | - using view_type::strideOrdering; // resolve ambiguity of multiple inheritance |
1448 | - |
1449 | - protected: |
1450 | - |
1451 | - // this function assumes that pyArray_ has already been set, and compatibility been checked |
1452 | - void setupArrayView(); |
1453 | - |
1454 | - static python_ptr getArrayTypeObject() |
1455 | - { |
1456 | - python_ptr type = detail::getArrayTypeObject(ArrayTraits::typeKeyFull()); |
1457 | - if(type == 0) |
1458 | - type = detail::getArrayTypeObject(ArrayTraits::typeKey(), &PyArray_Type); |
1459 | - return type; |
1460 | - } |
1461 | - |
1462 | - static python_ptr init(difference_type const & shape, bool init = true) |
1463 | - { |
1464 | - ArrayVector<npy_intp> pshape(shape.begin(), shape.end()); |
1465 | - return detail::constructNumpyArrayImpl((PyTypeObject *)getArrayTypeObject().ptr(), pshape, |
1466 | - ArrayTraits::spatialDimensions, ArrayTraits::channels, |
1467 | - typeCode, "V", init); |
1468 | - } |
1469 | - |
1470 | - static python_ptr init(difference_type const & shape, difference_type const & strideOrdering, bool init = true) |
1471 | - { |
1472 | - ArrayVector<npy_intp> pshape(shape.begin(), shape.end()), |
1473 | - pstrideOrdering(strideOrdering.begin(), strideOrdering.end()); |
1474 | - return detail::constructNumpyArrayImpl((PyTypeObject *)getArrayTypeObject().ptr(), pshape, |
1475 | - ArrayTraits::spatialDimensions, ArrayTraits::channels, |
1476 | - typeCode, "A", init, pstrideOrdering); |
1477 | - } |
1478 | - |
1479 | - public: |
1480 | - |
1481 | - using view_type::init; |
1482 | - |
1483 | - /** |
1484 | - * Construct from a given PyObject pointer. When the given |
1485 | - * python object is NULL, the internal python array will be |
1486 | - * NULL and hasData() will return false. |
1487 | - * |
1488 | - * Otherwise, the function attempts to create a |
1489 | - * new reference to the given Python object, unless |
1490 | - * copying is forced by setting \a createCopy to true. |
1491 | - * If either of this fails, the function throws an exception. |
1492 | - * This will not happen if isStrictlyCompatible(obj) (in case |
1493 | - * of creating a new reference) or isCopyCompatible(obj) |
1494 | - * (in case of copying) have returned true beforehand. |
1495 | - */ |
1496 | - explicit NumpyArray(PyObject *obj = 0, bool createCopy = false) |
1497 | - { |
1498 | - if(obj == 0) |
1499 | - return; |
1500 | - if(createCopy) |
1501 | - makeCopy(obj); |
1502 | - else |
1503 | - vigra_precondition(makeReference(obj), |
1504 | - "NumpyArray(obj): Cannot construct from incompatible array."); |
1505 | - } |
1506 | - |
1507 | - /** |
1508 | - * Copy constructor; does not copy the memory, but creates a |
1509 | - * new reference to the same underlying python object, unless |
1510 | - * a copy is forced by setting \a createCopy to true. |
1511 | - * (If the source object has no data, this one will have |
1512 | - * no data, too.) |
1513 | - */ |
1514 | - NumpyArray(const NumpyArray &other, bool createCopy = false) : |
1515 | - MultiArrayView<N, typename NumpyArrayTraits<N, T, Stride>::value_type, Stride>(other), |
1516 | - NumpyAnyArray(other, createCopy) |
1517 | - { |
1518 | - if(!other.hasData()) |
1519 | - return; |
1520 | - if(createCopy) |
1521 | - makeCopy(other.pyObject()); |
1522 | - else |
1523 | - makeReferenceUnchecked(other.pyObject()); |
1524 | - } |
1525 | - |
1526 | - /** |
1527 | - * Allocate new memory and copy data from a MultiArrayView. |
1528 | - */ |
1529 | - explicit NumpyArray(const view_type &other) |
1530 | - { |
1531 | - if(!other.hasData()) |
1532 | - return; |
1533 | - vigra_postcondition(makeReference(init(other.shape(), false)), |
1534 | - "NumpyArray(view_type): Python constructor did not produce a compatible array."); |
1535 | - static_cast<view_type &>(*this) = other; |
1536 | - } |
1537 | - |
1538 | - /** |
1539 | - * Construct a new array object, allocating an internal python |
1540 | - * ndarray of the given shape (in fortran order), initialized |
1541 | - * with zeros. |
1542 | - * |
1543 | - * An exception is thrown when construction fails. |
1544 | - */ |
1545 | - explicit NumpyArray(difference_type const & shape) |
1546 | - { |
1547 | - vigra_postcondition(makeReference(init(shape)), |
1548 | - "NumpyArray(shape): Python constructor did not produce a compatible array."); |
1549 | - } |
1550 | - |
1551 | - /** |
1552 | - * Construct a new array object, allocating an internal python |
1553 | - * ndarray of the given shape and given stride ordering, initialized |
1554 | - * with zeros. |
1555 | - * |
1556 | - * An exception is thrown when construction fails. |
1557 | - */ |
1558 | - NumpyArray(difference_type const & shape, difference_type const & strideOrdering) |
1559 | - { |
1560 | - vigra_postcondition(makeReference(init(shape, strideOrdering)), |
1561 | - "NumpyArray(shape): Python constructor did not produce a compatible array."); |
1562 | - } |
1563 | - |
1564 | - /** |
1565 | - * Constructor from NumpyAnyArray. |
1566 | - * Equivalent to NumpyArray(other.pyObject()) |
1567 | - */ |
1568 | - NumpyArray(const NumpyAnyArray &other, bool createCopy = false) |
1569 | - { |
1570 | - if(!other.hasData()) |
1571 | - return; |
1572 | - if(createCopy) |
1573 | - makeCopy(other.pyObject()); |
1574 | - else |
1575 | - vigra_precondition(makeReference(other.pyObject()), //, false), |
1576 | - "NumpyArray(NumpyAnyArray): Cannot construct from incompatible or empty array."); |
1577 | - } |
1578 | - |
1579 | - /** |
1580 | - * Assignment operator. If this is already a view with data |
1581 | - * (i.e. hasData() is true) and the shapes match, the RHS |
1582 | - * array contents are copied. If this is an empty view, |
1583 | - * assignment is identical to makeReferenceUnchecked(other.pyObject()). |
1584 | - * See MultiArrayView::operator= for further information on |
1585 | - * semantics. |
1586 | - */ |
1587 | - NumpyArray &operator=(const NumpyArray &other) |
1588 | - { |
1589 | - if(hasData()) |
1590 | - view_type::operator=(other); |
1591 | - else |
1592 | - makeReferenceUnchecked(other.pyObject()); |
1593 | - return *this; |
1594 | - } |
1595 | - |
1596 | - /** |
1597 | - * Assignment operator. If this is already a view with data |
1598 | - * (i.e. hasData() is true) and the shapes match, the RHS |
1599 | - * array contents are copied. |
1600 | - * If this is an empty view, assignment is identical to |
1601 | - * makeReference(other.pyObject()). |
1602 | - * Otherwise, an exception is thrown. |
1603 | - */ |
1604 | - NumpyArray &operator=(const NumpyAnyArray &other) |
1605 | - { |
1606 | - if(hasData()) |
1607 | - { |
1608 | - NumpyAnyArray::operator=(other); |
1609 | - } |
1610 | - else if(isStrictlyCompatible(other.pyObject())) |
1611 | - { |
1612 | - makeReferenceUnchecked(other.pyObject()); |
1613 | - } |
1614 | - else |
1615 | - { |
1616 | - vigra_precondition(false, |
1617 | - "NumpyArray::operator=(): Cannot assign from incompatible array."); |
1618 | - } |
1619 | - return *this; |
1620 | - } |
1621 | - |
1622 | - /** |
1623 | - * Test whether a given python object is a numpy array that can be |
1624 | - * converted (copied) into an array compatible to this NumpyArray type. |
1625 | - * This means that the array's shape conforms to the requirements of |
1626 | - * makeCopy(). |
1627 | - */ |
1628 | - static bool isCopyCompatible(PyObject *obj) |
1629 | - { |
1630 | - return ArrayTraits::isArray(obj) && |
1631 | - ArrayTraits::isShapeCompatible((PyArrayObject *)obj); |
1632 | - } |
1633 | - |
1634 | - /** |
1635 | - * Test whether a given python object is a numpy array with a |
1636 | - * compatible dtype and the correct shape and strides, so that it |
1637 | - * can be referenced as a view by this NumpyArray type (i.e. |
1638 | - * it conforms to the requirements of makeReference()). |
1639 | - */ |
1640 | - static bool isReferenceCompatible(PyObject *obj) |
1641 | - { |
1642 | - return ArrayTraits::isArray(obj) && |
1643 | - ArrayTraits::isPropertyCompatible((PyArrayObject *)obj); |
1644 | - } |
1645 | - |
1646 | - /** |
1647 | - * Like isReferenceCompatible(obj), but also executes a customized type compatibility |
1648 | - * check when such a check has been registered for this class via |
1649 | - * registerPythonArrayType(). |
1650 | - * |
1651 | - * This facilitates proper overload resolution between |
1652 | - * NumpyArray<3, Multiband<T> > (a multiband image) and NumpyArray<3, Singleband<T> > (a scalar volume). |
1653 | - */ |
1654 | - static bool isStrictlyCompatible(PyObject *obj) |
1655 | - { |
1656 | -#if VIGRA_CONVERTER_DEBUG |
1657 | - std::cerr << "class " << typeid(NumpyArray).name() << " got " << obj->ob_type->tp_name << "\n"; |
1658 | - bool isClassCompatible=ArrayTraits::isClassCompatible(obj); |
1659 | - bool isPropertyCompatible((PyArrayObject *)obj); |
1660 | - std::cerr<<"isClassCompatible: "<<isClassCompatible<<std::endl; |
1661 | - std::cerr<<"isPropertyCompatible: "<<isPropertyCompatible<<std::endl; |
1662 | -#endif |
1663 | - return ArrayTraits::isClassCompatible(obj) && |
1664 | - ArrayTraits::isPropertyCompatible((PyArrayObject *)obj); |
1665 | - } |
1666 | - |
1667 | - /** |
1668 | - * Create a vector representing the standard stride ordering of a NumpyArray. |
1669 | - * That is, we get a vector representing the range [0,...,N-1], which |
1670 | - * denotes the stride ordering for Fortran order. |
1671 | - */ |
1672 | - static difference_type standardStrideOrdering() |
1673 | - { |
1674 | - difference_type strideOrdering; |
1675 | - for(unsigned int k=0; k<N; ++k) |
1676 | - strideOrdering[k] = k; |
1677 | - return strideOrdering; |
1678 | - } |
1679 | - |
1680 | - /** |
1681 | - * Set up a view to the given object without checking compatibility. |
1682 | - * This function must not be used unless isReferenceCompatible(obj) returned |
1683 | - * true on the given object (otherwise, a crash is likely). |
1684 | - */ |
1685 | - void makeReferenceUnchecked(PyObject *obj) |
1686 | - { |
1687 | - NumpyAnyArray::makeReference(obj); |
1688 | - setupArrayView(); |
1689 | - } |
1690 | - |
1691 | - /** |
1692 | - * Try to set up a view referencing the given PyObject. |
1693 | - * Returns false if the python object is not a compatible |
1694 | - * numpy array (see isReferenceCompatible() or |
1695 | - * isStrictlyCompatible(), according to the parameter \a |
1696 | - * strict). |
1697 | - */ |
1698 | - bool makeReference(PyObject *obj, bool strict = true) |
1699 | - { |
1700 | - if(strict) |
1701 | - { |
1702 | - if(!isStrictlyCompatible(obj)) |
1703 | - return false; |
1704 | - } |
1705 | - else |
1706 | - { |
1707 | - if(!isReferenceCompatible(obj)) |
1708 | - return false; |
1709 | - } |
1710 | - makeReferenceUnchecked(obj); |
1711 | - return true; |
1712 | - } |
1713 | - |
1714 | - /** |
1715 | - * Try to set up a view referencing the same data as the given |
1716 | - * NumpyAnyArray. This overloaded variant simply calls |
1717 | - * makeReference() on array.pyObject(). |
1718 | - */ |
1719 | - bool makeReference(const NumpyAnyArray &array, bool strict = true) |
1720 | - { |
1721 | - return makeReference(array.pyObject(), strict); |
1722 | - } |
1723 | - |
1724 | - /** |
1725 | - * Set up an unsafe reference to the given MultiArrayView. |
1726 | - * ATTENTION: This creates a numpy.ndarray that points to the |
1727 | - * same data, but does not own it, so it must be ensured by |
1728 | - * other means that the memory does not get freed before the |
1729 | - * end of the ndarray's lifetime! (One elegant way would be |
1730 | - * to set the 'base' attribute of the resulting ndarray to a |
1731 | - * python object which directly or indirectly holds the memory |
1732 | - * of the given MultiArrayView.) |
1733 | - */ |
1734 | - void makeReference(const view_type &multiArrayView) |
1735 | - { |
1736 | - vigra_precondition(!hasData(), "makeReference(): cannot replace existing view with given buffer"); |
1737 | - |
1738 | - // construct an ndarray that points to our data (taking strides into account): |
1739 | - python_ptr array(ArrayTraits::constructor(multiArrayView.shape(), multiArrayView.data(), multiArrayView.stride())); |
1740 | - |
1741 | - view_type::operator=(multiArrayView); |
1742 | - pyArray_ = array; |
1743 | - } |
1744 | - |
1745 | - /** |
1746 | - Try to create a copy of the given PyObject. |
1747 | - Raises an exception when obj is not a compatible array |
1748 | - (see isCopyCompatible() or isStrictlyCompatible(), according to the |
1749 | - parameter \a strict) or the Python constructor call failed. |
1750 | - */ |
1751 | - void makeCopy(PyObject *obj, bool strict = false) |
1752 | - { |
1753 | - vigra_precondition(strict ? isStrictlyCompatible(obj) : isCopyCompatible(obj), |
1754 | - "NumpyArray::makeCopy(obj): Cannot copy an incompatible array."); |
1755 | - |
1756 | - int M = PyArray_NDIM(obj); |
1757 | - TinyVector<npy_intp, N> shape; |
1758 | - std::copy(PyArray_DIMS(obj), PyArray_DIMS(obj)+M, shape.begin()); |
1759 | - if(M == N-1) |
1760 | - shape[M] = 1; |
1761 | - vigra_postcondition(makeReference(init(shape, false)), |
1762 | - "NumpyArray::makeCopy(obj): Copy created an incompatible array."); |
1763 | - NumpyAnyArray::operator=(NumpyAnyArray(obj)); |
1764 | -// if(PyArray_CopyInto(pyArray(), (PyArrayObject*)obj) == -1) |
1765 | -// pythonToCppException(0); |
1766 | - } |
1767 | - |
1768 | - /** |
1769 | - Allocate new memory with the given shape and initialize with zeros.<br> |
1770 | - If a stride ordering is given, the resulting array will have this stride |
1771 | - ordering, when it is compatible with the array's memory layout (unstrided |
1772 | - arrays only permit the standard ascending stride ordering). |
1773 | - |
1774 | - <em>Note:</em> this operation invalidates dependent objects |
1775 | - (MultiArrayViews and iterators) |
1776 | - */ |
1777 | - void reshape(difference_type const & shape, difference_type const & strideOrdering = standardStrideOrdering()) |
1778 | - { |
1779 | - vigra_postcondition(makeReference(init(shape, strideOrdering)), |
1780 | - "NumpyArray(shape): Python constructor did not produce a compatible array."); |
1781 | - } |
1782 | - |
1783 | - /** |
1784 | - When this array has no data, allocate new memory with the given \a shape and |
1785 | - initialize with zeros. Otherwise, check if the new shape matches the old shape |
1786 | - and throw a precondition exception with the given \a message if not. |
1787 | - */ |
1788 | - void reshapeIfEmpty(difference_type const & shape, std::string message = "") |
1789 | - { |
1790 | - reshapeIfEmpty(shape, standardStrideOrdering(), message); |
1791 | - } |
1792 | - |
1793 | - /** |
1794 | - When this array has no data, allocate new memory with the given \a shape and |
1795 | - initialize with zeros. Otherwise, check if the new shape matches the old shape |
1796 | - and throw a precondition exception with the given \a message if not. If strict |
1797 | - is true, the given stride ordering must also match that of the existing data. |
1798 | - */ |
1799 | - void reshapeIfEmpty(difference_type const & shape, difference_type const & strideOrdering, |
1800 | - std::string message = "", bool strict = false) |
1801 | - { |
1802 | - if(hasData()) |
1803 | - { |
1804 | - if(strict) |
1805 | - { |
1806 | - if(message == "") |
1807 | - message = "NumpyArray::reshapeIfEmpty(shape): array was not empty, and shape or stride ordering did not match."; |
1808 | - vigra_precondition(shape == this->shape() && strideOrdering == this->strideOrdering(), message.c_str()); |
1809 | - } |
1810 | - else |
1811 | - { |
1812 | - if(message == "") |
1813 | - message = "NumpyArray::reshapeIfEmpty(shape): array was not empty, and shape did not match."; |
1814 | - vigra_precondition(shape == this->shape(), message.c_str()); |
1815 | - } |
1816 | - } |
1817 | - else |
1818 | - { |
1819 | - reshape(shape, strideOrdering); |
1820 | - } |
1821 | - } |
1822 | -}; |
1823 | - |
1824 | - // this function assumes that pyArray_ has already been set, and compatibility been checked |
1825 | -template <unsigned int N, class T, class Stride> |
1826 | -void NumpyArray<N, T, Stride>::setupArrayView() |
1827 | -{ |
1828 | - if(NumpyAnyArray::hasData()) |
1829 | - { |
1830 | - unsigned int dimension = std::min<unsigned int>(actual_dimension, pyArray()->nd); |
1831 | - std::copy(pyArray()->dimensions, pyArray()->dimensions + dimension, this->m_shape.begin()); |
1832 | - std::copy(pyArray()->strides, pyArray()->strides + dimension, this->m_stride.begin()); |
1833 | - if(pyArray()->nd < actual_dimension) |
1834 | - { |
1835 | - this->m_shape[dimension] = 1; |
1836 | - this->m_stride[dimension] = sizeof(value_type); |
1837 | - } |
1838 | - this->m_stride /= sizeof(value_type); |
1839 | - this->m_ptr = reinterpret_cast<pointer>(pyArray()->data); |
1840 | - } |
1841 | - else |
1842 | - { |
1843 | - this->m_ptr = 0; |
1844 | - } |
1845 | -} |
1846 | - |
1847 | - |
1848 | -typedef NumpyArray<2, float > NumpyFArray2; |
1849 | -typedef NumpyArray<3, float > NumpyFArray3; |
1850 | -typedef NumpyArray<4, float > NumpyFArray4; |
1851 | -typedef NumpyArray<2, Singleband<float> > NumpyFImage; |
1852 | -typedef NumpyArray<3, Singleband<float> > NumpyFVolume; |
1853 | -typedef NumpyArray<2, RGBValue<float> > NumpyFRGBImage; |
1854 | -typedef NumpyArray<3, RGBValue<float> > NumpyFRGBVolume; |
1855 | -typedef NumpyArray<3, Multiband<float> > NumpyFMultibandImage; |
1856 | -typedef NumpyArray<4, Multiband<float> > NumpyFMultibandVolume; |
1857 | - |
1858 | -inline void import_vigranumpy() |
1859 | -{ |
1860 | - if(_import_array() < 0) |
1861 | - pythonToCppException(0); |
1862 | - python_ptr module(PyImport_ImportModule("vigra.vigranumpycore"), python_ptr::keep_count); |
1863 | - pythonToCppException(module); |
1864 | -} |
1865 | - |
1866 | -/********************************************************/ |
1867 | -/* */ |
1868 | -/* NumpyArray Multiband Argument Object Factories */ |
1869 | -/* */ |
1870 | -/********************************************************/ |
1871 | - |
1872 | -template <class PixelType, class Stride> |
1873 | -inline triple<ConstStridedImageIterator<PixelType>, |
1874 | - ConstStridedImageIterator<PixelType>, |
1875 | - MultibandVectorAccessor<PixelType> > |
1876 | -srcImageRange(NumpyArray<3, Multiband<PixelType>, Stride> const & img) |
1877 | -{ |
1878 | - ConstStridedImageIterator<PixelType> |
1879 | - ul(img.data(), 1, img.stride(0), img.stride(1)); |
1880 | - return triple<ConstStridedImageIterator<PixelType>, |
1881 | - ConstStridedImageIterator<PixelType>, |
1882 | - MultibandVectorAccessor<PixelType> > |
1883 | - (ul, ul + Size2D(img.shape(0), img.shape(1)), MultibandVectorAccessor<PixelType>(img.shape(2), img.stride(2))); |
1884 | -} |
1885 | - |
1886 | -template <class PixelType, class Stride> |
1887 | -inline pair< ConstStridedImageIterator<PixelType>, |
1888 | - MultibandVectorAccessor<PixelType> > |
1889 | -srcImage(NumpyArray<3, Multiband<PixelType>, Stride> const & img) |
1890 | -{ |
1891 | - ConstStridedImageIterator<PixelType> |
1892 | - ul(img.data(), 1, img.stride(0), img.stride(1)); |
1893 | - return pair<ConstStridedImageIterator<PixelType>, MultibandVectorAccessor<PixelType> > |
1894 | - (ul, MultibandVectorAccessor<PixelType>(img.shape(2), img.stride(2))); |
1895 | -} |
1896 | - |
1897 | -template <class PixelType, class Stride> |
1898 | -inline triple< StridedImageIterator<PixelType>, |
1899 | - StridedImageIterator<PixelType>, |
1900 | - MultibandVectorAccessor<PixelType> > |
1901 | -destImageRange(NumpyArray<3, Multiband<PixelType>, Stride> & img) |
1902 | -{ |
1903 | - StridedImageIterator<PixelType> |
1904 | - ul(img.data(), 1, img.stride(0), img.stride(1)); |
1905 | - typedef typename AccessorTraits<PixelType>::default_accessor Accessor; |
1906 | - return triple<StridedImageIterator<PixelType>, |
1907 | - StridedImageIterator<PixelType>, |
1908 | - MultibandVectorAccessor<PixelType> > |
1909 | - (ul, ul + Size2D(img.shape(0), img.shape(1)), |
1910 | - MultibandVectorAccessor<PixelType>(img.shape(2), img.stride(2))); |
1911 | -} |
1912 | - |
1913 | -template <class PixelType, class Stride> |
1914 | -inline pair< StridedImageIterator<PixelType>, |
1915 | - MultibandVectorAccessor<PixelType> > |
1916 | -destImage(NumpyArray<3, Multiband<PixelType>, Stride> & img) |
1917 | -{ |
1918 | - StridedImageIterator<PixelType> |
1919 | - ul(img.data(), 1, img.stride(0), img.stride(1)); |
1920 | - return pair<StridedImageIterator<PixelType>, MultibandVectorAccessor<PixelType> > |
1921 | - (ul, MultibandVectorAccessor<PixelType>(img.shape(2), img.stride(2))); |
1922 | -} |
1923 | - |
1924 | -template <class PixelType, class Stride> |
1925 | -inline pair< ConstStridedImageIterator<PixelType>, |
1926 | - MultibandVectorAccessor<PixelType> > |
1927 | -maskImage(NumpyArray<3, Multiband<PixelType>, Stride> const & img) |
1928 | -{ |
1929 | - ConstStridedImageIterator<PixelType> |
1930 | - ul(img.data(), 1, img.stride(0), img.stride(1)); |
1931 | - typedef typename AccessorTraits<PixelType>::default_accessor Accessor; |
1932 | - return pair<ConstStridedImageIterator<PixelType>, MultibandVectorAccessor<PixelType> > |
1933 | - (ul, MultibandVectorAccessor<PixelType>(img.shape(2), img.stride(2))); |
1934 | -} |
1935 | - |
1936 | -} // namespace vigra |
1937 | - |
1938 | -#endif // VIGRA_NUMPY_ARRAY_HXX |
1939 | |
1940 | === removed directory '.pc/debian-changes-1.7.1+dfsg1-2ubuntu1/vigranumpy' |
1941 | === removed directory '.pc/debian-changes-1.7.1+dfsg1-2ubuntu1/vigranumpy/docsrc' |
1942 | === removed file '.pc/debian-changes-1.7.1+dfsg1-2ubuntu1/vigranumpy/docsrc/conf.py.THIS' |
1943 | === added directory '.pc/fix-ftbfs-gcc4.7.diff' |
1944 | === added directory '.pc/fix-ftbfs-gcc4.7.diff/include' |
1945 | === added directory '.pc/fix-ftbfs-gcc4.7.diff/include/vigra' |
1946 | === added file '.pc/fix-ftbfs-gcc4.7.diff/include/vigra/box.hxx' |
1947 | --- .pc/fix-ftbfs-gcc4.7.diff/include/vigra/box.hxx 1970-01-01 00:00:00 +0000 |
1948 | +++ .pc/fix-ftbfs-gcc4.7.diff/include/vigra/box.hxx 2012-06-14 20:29:21 +0000 |
1949 | @@ -0,0 +1,545 @@ |
1950 | +/************************************************************************/ |
1951 | +/* */ |
1952 | +/* Copyright 2009-2010 by Ullrich Koethe and Hans Meine */ |
1953 | +/* */ |
1954 | +/* This file is part of the VIGRA computer vision library. */ |
1955 | +/* The VIGRA Website is */ |
1956 | +/* http://hci.iwr.uni-heidelberg.de/vigra/ */ |
1957 | +/* Please direct questions, bug reports, and contributions to */ |
1958 | +/* ullrich.koethe@iwr.uni-heidelberg.de or */ |
1959 | +/* vigra@informatik.uni-hamburg.de */ |
1960 | +/* */ |
1961 | +/* Permission is hereby granted, free of charge, to any person */ |
1962 | +/* obtaining a copy of this software and associated documentation */ |
1963 | +/* files (the "Software"), to deal in the Software without */ |
1964 | +/* restriction, including without limitation the rights to use, */ |
1965 | +/* copy, modify, merge, publish, distribute, sublicense, and/or */ |
1966 | +/* sell copies of the Software, and to permit persons to whom the */ |
1967 | +/* Software is furnished to do so, subject to the following */ |
1968 | +/* conditions: */ |
1969 | +/* */ |
1970 | +/* The above copyright notice and this permission notice shall be */ |
1971 | +/* included in all copies or substantial portions of the */ |
1972 | +/* Software. */ |
1973 | +/* */ |
1974 | +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ |
1975 | +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ |
1976 | +/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ |
1977 | +/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ |
1978 | +/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ |
1979 | +/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ |
1980 | +/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ |
1981 | +/* OTHER DEALINGS IN THE SOFTWARE. */ |
1982 | +/* */ |
1983 | +/************************************************************************/ |
1984 | + |
1985 | +#ifndef VIGRA_BOX_HXX |
1986 | +#define VIGRA_BOX_HXX |
1987 | + |
1988 | +#include "metaprogramming.hxx" |
1989 | +#include "numerictraits.hxx" |
1990 | +#include "tinyvector.hxx" |
1991 | + |
1992 | +namespace vigra { |
1993 | + |
1994 | +namespace detail { |
1995 | + |
1996 | +// RangePolicy used for floating point coordinate types |
1997 | +template<class VALUETYPE> |
1998 | +struct EndInsidePolicy |
1999 | +{ |
2000 | + static inline bool isEmptyRange(VALUETYPE b, VALUETYPE e) |
2001 | + { |
2002 | + return e < b; // <= |
2003 | + } |
2004 | + |
2005 | + static inline VALUETYPE pointEnd(VALUETYPE p) |
2006 | + { |
2007 | + return p; // +1 |
2008 | + } |
2009 | +}; |
2010 | + |
2011 | +// RangePolicy used for integer coordinate types |
2012 | +template<class VALUETYPE> |
2013 | +struct EndOutsidePolicy |
2014 | +{ |
2015 | + static inline bool isEmptyRange(VALUETYPE b, VALUETYPE e) |
2016 | + { |
2017 | + return e <= b; |
2018 | + } |
2019 | + |
2020 | + static inline VALUETYPE pointEnd(VALUETYPE p) |
2021 | + { |
2022 | + return p+1; |
2023 | + } |
2024 | +}; |
2025 | + |
2026 | +} // namespace vigra::detail |
2027 | + |
2028 | +/** \addtogroup RangesAndPoints */ |
2029 | +//@{ |
2030 | + /** \brief Represent an n-dimensional box as a (begin, end) pair. |
2031 | + * Depending on the value type, end() is considered to be |
2032 | + * outside the box (as in the STL, for integer types), or |
2033 | + * inside (for floating point types). size() will always be |
2034 | + * end() - begin(). |
2035 | + */ |
2036 | +template<class VALUETYPE, unsigned int DIMENSION> |
2037 | +class Box |
2038 | +{ |
2039 | + public: |
2040 | + /** STL-compatible definition of coordinate valuetype |
2041 | + */ |
2042 | + typedef VALUETYPE value_type; |
2043 | + |
2044 | + /** Promoted coordinate valuetype, used for volume() |
2045 | + */ |
2046 | + typedef typename NumericTraits<VALUETYPE>::Promote VolumeType; |
2047 | + |
2048 | + /** Vector type used for begin() and end() |
2049 | + */ |
2050 | + typedef TinyVector<VALUETYPE, DIMENSION> Vector; |
2051 | + |
2052 | + enum { Dimension = DIMENSION }; |
2053 | + |
2054 | + protected: |
2055 | + Vector begin_, end_; |
2056 | + |
2057 | + /** Range policy (EndInsidePolicy/EndOutsidePolicy, depending on valuetype) |
2058 | + */ |
2059 | + typedef typename If<typename NumericTraits<VALUETYPE>::isIntegral, |
2060 | + detail::EndOutsidePolicy<VALUETYPE>, |
2061 | + detail::EndInsidePolicy<VALUETYPE> >::type RangePolicy; |
2062 | + |
2063 | + public: |
2064 | + /** Construct an empty box (isEmpty() will return true). |
2065 | + * (Internally, this will initialize all dimensions with the |
2066 | + * empty range [1..0].) |
2067 | + */ |
2068 | + Box() |
2069 | + : begin_(NumericTraits<Vector>::one()) |
2070 | + {} |
2071 | + |
2072 | + /** Construct a box representing the given range. Depending |
2073 | + * on the value type, end() is considered to be outside the |
2074 | + * box (as in the STL, for integer types), or inside (for |
2075 | + * floating point types). |
2076 | + */ |
2077 | + Box(Vector const &begin, Vector const &end) |
2078 | + : begin_(begin), end_(end) |
2079 | + {} |
2080 | + |
2081 | + /** Construct a box of given size at the origin (i.e. end() == |
2082 | + * size()). |
2083 | + */ |
2084 | + explicit Box(Vector const &size) |
2085 | + : end_(size) |
2086 | + {} |
2087 | + |
2088 | + /** Get begin vector (i.e. smallest coordinates for each |
2089 | + * dimension). This is the first point (scan-order wise) |
2090 | + * which is considered to be "in" the box. |
2091 | + */ |
2092 | + Vector const & begin() const |
2093 | + { |
2094 | + return begin_; |
2095 | + } |
2096 | + |
2097 | + /** Access begin vector (i.e. smallest coordinates for each |
2098 | + * dimension). This is the first point (scan-order wise) |
2099 | + * which is considered to be "in" the box. |
2100 | + */ |
2101 | + Vector & begin() |
2102 | + { |
2103 | + return begin_; |
2104 | + } |
2105 | + |
2106 | + /** Get end vector (i.e. coordinates higher than begin() in |
2107 | + * each dimension for non-empty boxes). This is begin() + |
2108 | + * size(), and depending on the valuetype (float/int), this is |
2109 | + * the last point within or the first point outside the box, |
2110 | + * respectively. |
2111 | + */ |
2112 | + Vector const & end() const |
2113 | + { |
2114 | + return end_; |
2115 | + } |
2116 | + |
2117 | + /** Access end vector (i.e. coordinates higher than begin() in |
2118 | + * each dimension for non-empty boxes). This is begin() + |
2119 | + * size(), and depending on the valuetype (float/int), this is |
2120 | + * the last point within or the first point outside the box, |
2121 | + * respectively. |
2122 | + */ |
2123 | + Vector & end() |
2124 | + { |
2125 | + return end_; |
2126 | + } |
2127 | + |
2128 | + /** Change begin() without changing end(), changing size() |
2129 | + * accordingly. |
2130 | + */ |
2131 | + void setBegin(Vector const &begin) |
2132 | + { |
2133 | + begin_ = begin; |
2134 | + } |
2135 | + |
2136 | + /** Change end() without changing begin(), which will change |
2137 | + * the size() most probably. |
2138 | + */ |
2139 | + void setEnd(Vector const &end) |
2140 | + { |
2141 | + end_ = end; |
2142 | + } |
2143 | + |
2144 | + /** Move the whole box so that the given point will be |
2145 | + * begin() afterwards. |
2146 | + */ |
2147 | + void moveTo(Vector const &newBegin) |
2148 | + { |
2149 | + end_ += newBegin - begin_; |
2150 | + begin_ = newBegin; |
2151 | + } |
2152 | + |
2153 | + /** Move the whole box by the given offset. |
2154 | + * (Equivalent to operator+=) |
2155 | + */ |
2156 | + void moveBy(Vector const &offset) |
2157 | + { |
2158 | + begin_ += offset; |
2159 | + end_ += offset; |
2160 | + } |
2161 | + |
2162 | + /** Determine and return the area of this box. That is, |
2163 | + * if this rect isEmpty(), returns zero, otherwise returns the |
2164 | + * product of the extents in each dimension. |
2165 | + */ |
2166 | + VolumeType volume() const |
2167 | + { |
2168 | + if(isEmpty()) |
2169 | + return 0; |
2170 | + |
2171 | + VolumeType result(end_[0] - begin_[0]); |
2172 | + for(unsigned int i = 1; i < DIMENSION; ++i) |
2173 | + result *= end_[i] - begin_[i]; |
2174 | + return result; |
2175 | + } |
2176 | + |
2177 | + /** Determine and return the size of this box. The size |
2178 | + * might be zero or even negative in one or more dimensions, |
2179 | + * and if so, isEmpty() will return true. |
2180 | + */ |
2181 | + Vector size() const |
2182 | + { |
2183 | + return end_ - begin_; |
2184 | + } |
2185 | + |
2186 | + /** Resize this box to the given extents. This will |
2187 | + * change end() only. |
2188 | + */ |
2189 | + void setSize(Vector const &size) |
2190 | + { |
2191 | + end_ = begin_ + size; |
2192 | + } |
2193 | + |
2194 | + /** Increase the size of the box by the given |
2195 | + * offset. This will move end() only. (If any of offset's |
2196 | + * components is negative, the box will get smaller |
2197 | + * accordingly.) |
2198 | + */ |
2199 | + void addSize(Vector const &offset) |
2200 | + { |
2201 | + end_ += offset; |
2202 | + } |
2203 | + |
2204 | + /** Adds a border of the given width around the box. That |
2205 | + * means, begin()'s components are moved by -borderWidth |
2206 | + * and end()'s by borderWidth. (If borderWidth is |
2207 | + * negative, the box will get smaller accordingly.) |
2208 | + */ |
2209 | + void addBorder(VALUETYPE borderWidth) |
2210 | + { |
2211 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2212 | + { |
2213 | + begin_[i] -= borderWidth; |
2214 | + end_[i] += borderWidth; |
2215 | + } |
2216 | + } |
2217 | + |
2218 | + /// equality check |
2219 | + bool operator==(Box const &r) const |
2220 | + { |
2221 | + return (begin_ == r.begin_) && (end_ == r.end_); |
2222 | + } |
2223 | + |
2224 | + /// inequality check |
2225 | + bool operator!=(Box const &r) const |
2226 | + { |
2227 | + return (begin_ != r.begin_) || (end_ != r.end_); |
2228 | + } |
2229 | + |
2230 | + /** Return whether this box is considered empty. It is |
2231 | + * non-empty if all end() coordinates are greater than (or |
2232 | + * equal, for floating point valuetypes) the corresponding |
2233 | + * begin() coordinates. Uniting an empty box with something |
2234 | + * will return the bounding box of the 'something', and |
2235 | + * intersecting any box with an empty box will again yield an |
2236 | + * empty box. |
2237 | + */ |
2238 | + bool isEmpty() const |
2239 | + { |
2240 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2241 | + if(RangePolicy::isEmptyRange(begin_[i], end_[i])) |
2242 | + return true; |
2243 | + return false; |
2244 | + } |
2245 | + |
2246 | + /** Return whether this box contains the given point. |
2247 | + * That is, if the point lies within the range [begin, end] in |
2248 | + * each dimension (excluding end() itself for integer valuetypes). |
2249 | + */ |
2250 | + bool contains(Vector const &p) const |
2251 | + { |
2252 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2253 | + if((p[i] < begin_[i]) || |
2254 | + RangePolicy::isEmptyRange(p[i], end_[i])) |
2255 | + return false; |
2256 | + return true; |
2257 | + } |
2258 | + |
2259 | + /** Return whether this box contains the given |
2260 | + * one. <tt>r1.contains(r2)</tt> returns the same as |
2261 | + * <tt>r1 == (r1|r2)</tt> (but is of course more |
2262 | + * efficient). That also means, a box (even an empty one!) |
2263 | + * contains() any empty box. |
2264 | + */ |
2265 | + bool contains(Box const &r) const |
2266 | + { |
2267 | + if(r.isEmpty()) |
2268 | + return true; |
2269 | + if(!contains(r.begin_)) |
2270 | + return false; |
2271 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2272 | + if(r.end_[i] > end_[i]) |
2273 | + return false; |
2274 | + return true; |
2275 | + } |
2276 | + |
2277 | + /** Return whether this box overlaps with the given |
2278 | + * one. <tt>r1.intersects(r2)</tt> returns the same as |
2279 | + * <tt>!(r1&r2).isEmpty()</tt> (but is of course much more |
2280 | + * efficient). |
2281 | + */ |
2282 | + bool intersects(Box const &r) const |
2283 | + { |
2284 | + if(r.isEmpty() || isEmpty()) |
2285 | + return false; |
2286 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2287 | + if(RangePolicy::isEmptyRange(r.begin_[i], end_[i]) || |
2288 | + RangePolicy::isEmptyRange(begin_[i], r.end_[i])) |
2289 | + return false; |
2290 | + return true; |
2291 | + } |
2292 | + |
2293 | + /** Modifies this box by including the given point. |
2294 | + * The result will be the bounding box of the box and the |
2295 | + * point. If isEmpty() returns true on the original box, the |
2296 | + * union will be a box containing only the given point. |
2297 | + */ |
2298 | + Box &operator|=(Vector const &p) |
2299 | + { |
2300 | + if(isEmpty()) |
2301 | + { |
2302 | + begin_ = p; |
2303 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2304 | + end_[i] = RangePolicy::pointEnd(p[i]); |
2305 | + } |
2306 | + else |
2307 | + { |
2308 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2309 | + { |
2310 | + if(p[i] < begin_[i]) |
2311 | + begin_[i] = p[i]; |
2312 | + if(RangePolicy::isEmptyRange(p[i], end_[i])) |
2313 | + end_[i] = RangePolicy::pointEnd(p[i]); |
2314 | + } |
2315 | + } |
2316 | + return *this; |
2317 | + } |
2318 | + |
2319 | + /** Returns the union of this box and the given point. |
2320 | + * The result will be the bounding box of the box and the |
2321 | + * point. If isEmpty() returns true on the original box, the |
2322 | + * union will be a box containing only the given point. |
2323 | + */ |
2324 | + Box operator|(Vector const &p) const |
2325 | + { |
2326 | + Box result(*this); |
2327 | + result |= p; |
2328 | + return result; |
2329 | + } |
2330 | + |
2331 | + /** Modifies this box by uniting it with the given one. |
2332 | + * The result will be the bounding box of both boxs. If one of |
2333 | + * the boxes isEmpty(), the union will be the other one. |
2334 | + */ |
2335 | + Box &operator|=(Box const &r) |
2336 | + { |
2337 | + if(r.isEmpty()) |
2338 | + return *this; |
2339 | + if(isEmpty()) |
2340 | + return operator=(r); |
2341 | + |
2342 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2343 | + { |
2344 | + if(r.begin_[i] < begin_[i]) |
2345 | + begin_[i] = r.begin_[i]; |
2346 | + if(end_[i] < r.end_[i]) |
2347 | + end_[i] = r.end_[i]; |
2348 | + } |
2349 | + return *this; |
2350 | + } |
2351 | + |
2352 | + /** Returns the union of this box and the given one. |
2353 | + * The result will be the bounding box of both boxs. If one of |
2354 | + * the boxes isEmpty(), the union will be the other one. |
2355 | + */ |
2356 | + Box operator|(Box const &r) const |
2357 | + { |
2358 | + Box result(*this); |
2359 | + result |= r; |
2360 | + return result; |
2361 | + } |
2362 | + |
2363 | + /** Modifies this box by intersecting it with the given one. |
2364 | + * The result will be the maximal box contained in both |
2365 | + * original ones. Intersecting with an empty box will yield |
2366 | + * again an empty box. |
2367 | + */ |
2368 | + Box &operator&=(Box const &r) |
2369 | + { |
2370 | + if(isEmpty()) |
2371 | + return *this; |
2372 | + if(r.isEmpty()) |
2373 | + return operator=(r); |
2374 | + |
2375 | + for(unsigned int i = 0; i < DIMENSION; ++i) |
2376 | + { |
2377 | + if(begin_[i] < r.begin_[i]) |
2378 | + begin_[i] = r.begin_[i]; |
2379 | + if(r.end_[i] < end_[i]) |
2380 | + end_[i] = r.end_[i]; |
2381 | + } |
2382 | + return *this; |
2383 | + } |
2384 | + |
2385 | + /** Intersects this box with the given one. |
2386 | + * The result will be the maximal box contained in both |
2387 | + * original ones. Intersecting with an empty box will yield |
2388 | + * again an empty box. |
2389 | + */ |
2390 | + Box operator&(Box const &r) const |
2391 | + { |
2392 | + Box result(*this); |
2393 | + result &= r; |
2394 | + return result; |
2395 | + } |
2396 | + |
2397 | + /** |
2398 | + * Scale box by scalar multiply-assignment. The same scalar |
2399 | + * multiply-assignment operation will be performed on both |
2400 | + * begin() and end(). |
2401 | + */ |
2402 | + Box &operator*=(double scale) |
2403 | + { |
2404 | + begin_ *= scale; |
2405 | + end_ *= scale; |
2406 | + return *this; |
2407 | + } |
2408 | + |
2409 | + /** |
2410 | + * Return box scaled by given factor. The same scalar |
2411 | + * multiplication will be performed on both begin() and end(). |
2412 | + */ |
2413 | + Box operator*(double scale) |
2414 | + { |
2415 | + Box result(*this); |
2416 | + result *= scale; |
2417 | + return result; |
2418 | + } |
2419 | + |
2420 | + /** |
2421 | + * Scale box by scalar divide-assignment. The same scalar |
2422 | + * divide-assignment operation will be performed on both |
2423 | + * begin() and end(). |
2424 | + */ |
2425 | + Box &operator/=(double scale) |
2426 | + { |
2427 | + begin_ /= scale; |
2428 | + end_ /= scale; |
2429 | + return *this; |
2430 | + } |
2431 | + |
2432 | + /** |
2433 | + * Return box scaled by inverse of given factor. The same scalar |
2434 | + * division will be performed on both begin() and end(). |
2435 | + */ |
2436 | + Box operator/(double scale) |
2437 | + { |
2438 | + Box result(*this); |
2439 | + result /= scale; |
2440 | + return result; |
2441 | + } |
2442 | + |
2443 | + /** |
2444 | + * Translate box by vector addition-assignment. The same vector |
2445 | + * addition-assignment operation will be performed on both |
2446 | + * begin() and end(). |
2447 | + */ |
2448 | + Box &operator+=(const Vector &offset) |
2449 | + { |
2450 | + begin_ += offset; |
2451 | + end_ += offset; |
2452 | + return *this; |
2453 | + } |
2454 | + |
2455 | + /** |
2456 | + * Translate box by vector addition. The same vector addition |
2457 | + * operation will be performed on both begin() and end(). |
2458 | + */ |
2459 | + Box operator+(const Vector &offset) |
2460 | + { |
2461 | + Box result(*this); |
2462 | + result += offset; |
2463 | + return result; |
2464 | + } |
2465 | + |
2466 | + /** |
2467 | + * Translate box by vector subtract-assignment. The same vector |
2468 | + * subtract-assignment operation will be performed on both |
2469 | + * begin() and end(). |
2470 | + */ |
2471 | + Box &operator-=(const Vector &offset) |
2472 | + { |
2473 | + begin_ -= offset; |
2474 | + end_ -= offset; |
2475 | + return *this; |
2476 | + } |
2477 | + |
2478 | + /** |
2479 | + * Translate box by vector subtract. The same vector subtract |
2480 | + * operation will be performed on both begin() and end(). |
2481 | + */ |
2482 | + Box operator-(const Vector &offset) |
2483 | + { |
2484 | + Box result(*this); |
2485 | + result -= offset; |
2486 | + return result; |
2487 | + } |
2488 | +}; |
2489 | + |
2490 | +//@} |
2491 | + |
2492 | +} // namespace vigra |
2493 | + |
2494 | +#endif // VIGRA_BOX_HXX |
2495 | |
2496 | === added directory '.pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest' |
2497 | === added file '.pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_ridge_split.hxx' |
2498 | --- .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_ridge_split.hxx 1970-01-01 00:00:00 +0000 |
2499 | +++ .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_ridge_split.hxx 2012-06-14 20:29:21 +0000 |
2500 | @@ -0,0 +1,449 @@ |
2501 | +// |
2502 | +// C++ Interface: rf_ridge_split |
2503 | +// |
2504 | +// Description: |
2505 | +// |
2506 | +// |
2507 | +// Author: Nico Splitthoff <splitthoff@zg00103>, (C) 2009 |
2508 | +// |
2509 | +// Copyright: See COPYING file that comes with this distribution |
2510 | +// |
2511 | +// |
2512 | +#ifndef VIGRA_RANDOM_FOREST_RIDGE_SPLIT_H |
2513 | +#define VIGRA_RANDOM_FOREST_RIDGE_SPLIT_H |
2514 | +//#include "rf_sampling.hxx" |
2515 | +#include "../sampling.hxx" |
2516 | +#include "rf_split.hxx" |
2517 | +#include "rf_nodeproxy.hxx" |
2518 | +#include "../regression.hxx" |
2519 | + |
2520 | +#define outm(v) std::cout << (#v) << ": " << (v) << std::endl; |
2521 | +#define outm2(v) std::cout << (#v) << ": " << (v) << ", "; |
2522 | + |
2523 | +namespace vigra |
2524 | +{ |
2525 | + |
2526 | +/*template<> |
2527 | +class Node<i_RegrNode> |
2528 | +: public NodeBase |
2529 | +{ |
2530 | +public: |
2531 | + typedef NodeBase BT; |
2532 | + |
2533 | + |
2534 | + Node( BT::T_Container_type & topology, |
2535 | + BT::P_Container_type & param, |
2536 | + int nNumCols) |
2537 | + : BT(5+nNumCols,2+nNumCols,topology, param) |
2538 | + { |
2539 | + BT::typeID() = i_RegrNode; |
2540 | + } |
2541 | + |
2542 | + Node( BT::T_Container_type & topology, |
2543 | + BT::P_Container_type & param, |
2544 | + INT n ) |
2545 | + : BT(5,2,topology, param, n) |
2546 | + {} |
2547 | + |
2548 | + Node( BT & node_) |
2549 | + : BT(5, 2, node_) |
2550 | + {} |
2551 | + |
2552 | + double& threshold() |
2553 | + { |
2554 | + return BT::parameters_begin()[1]; |
2555 | + } |
2556 | + |
2557 | + BT::INT& column() |
2558 | + { |
2559 | + return BT::column_data()[0]; |
2560 | + } |
2561 | + |
2562 | + template<class U, class C> |
2563 | + BT::INT& next(MultiArrayView<2,U,C> const & feature) |
2564 | + { |
2565 | + return (feature(0, column()) < threshold())? child(0):child(1); |
2566 | + } |
2567 | +};*/ |
2568 | + |
2569 | + |
2570 | +template<class ColumnDecisionFunctor, class Tag = ClassificationTag> |
2571 | +class RidgeSplit: public SplitBase<Tag> |
2572 | +{ |
2573 | + public: |
2574 | + |
2575 | + |
2576 | + typedef SplitBase<Tag> SB; |
2577 | + |
2578 | + ArrayVector<Int32> splitColumns; |
2579 | + ColumnDecisionFunctor bgfunc; |
2580 | + |
2581 | + double region_gini_; |
2582 | + ArrayVector<double> min_gini_; |
2583 | + ArrayVector<ptrdiff_t> min_indices_; |
2584 | + ArrayVector<double> min_thresholds_; |
2585 | + |
2586 | + int bestSplitIndex; |
2587 | + |
2588 | + //dns |
2589 | + bool m_bDoScalingInTraining; |
2590 | + bool m_bDoBestLambdaBasedOnGini; |
2591 | + |
2592 | + RidgeSplit() |
2593 | + :m_bDoScalingInTraining(true), |
2594 | + m_bDoBestLambdaBasedOnGini(true) |
2595 | + { |
2596 | + } |
2597 | + |
2598 | + double minGini() const |
2599 | + { |
2600 | + return min_gini_[bestSplitIndex]; |
2601 | + } |
2602 | + |
2603 | + int bestSplitColumn() const |
2604 | + { |
2605 | + return splitColumns[bestSplitIndex]; |
2606 | + } |
2607 | + |
2608 | + bool& doScalingInTraining() |
2609 | + { return m_bDoScalingInTraining; } |
2610 | + |
2611 | + bool& doBestLambdaBasedOnGini() |
2612 | + { return m_bDoBestLambdaBasedOnGini; } |
2613 | + |
2614 | + template<class T> |
2615 | + void set_external_parameters(ProblemSpec<T> const & in) |
2616 | + { |
2617 | + SB::set_external_parameters(in); |
2618 | + bgfunc.set_external_parameters(in); |
2619 | + int featureCount_ = in.column_count_; |
2620 | + splitColumns.resize(featureCount_); |
2621 | + for(int k=0; k<featureCount_; ++k) |
2622 | + splitColumns[k] = k; |
2623 | + min_gini_.resize(featureCount_); |
2624 | + min_indices_.resize(featureCount_); |
2625 | + min_thresholds_.resize(featureCount_); |
2626 | + } |
2627 | + |
2628 | + |
2629 | + template<class T, class C, class T2, class C2, class Region, class Random> |
2630 | + int findBestSplit(MultiArrayView<2, T, C> features, |
2631 | + MultiArrayView<2, T2, C2> multiClassLabels, |
2632 | + Region & region, |
2633 | + ArrayVector<Region>& childRegions, |
2634 | + Random & randint) |
2635 | + { |
2636 | + |
2637 | + //std::cerr << "Split called" << std::endl; |
2638 | + typedef typename Region::IndexIterator IndexIterator; |
2639 | + typedef typename MultiArrayView <2, T, C>::difference_type fShape; |
2640 | + typedef typename MultiArrayView <2, T2, C2>::difference_type lShape; |
2641 | + typedef typename MultiArrayView <2, double>::difference_type dShape; |
2642 | + |
2643 | + // calculate things that haven't been calculated yet. |
2644 | +// std::cout << "start" << std::endl; |
2645 | + if(std::accumulate(region.classCounts().begin(), |
2646 | + region.classCounts().end(), 0) != region.size()) |
2647 | + { |
2648 | + RandomForestClassCounter< MultiArrayView<2,T2, C2>, |
2649 | + ArrayVector<double> > |
2650 | + counter(multiClassLabels, region.classCounts()); |
2651 | + std::for_each( region.begin(), region.end(), counter); |
2652 | + region.classCountsIsValid = true; |
2653 | + } |
2654 | + |
2655 | + |
2656 | + // Is the region pure already? |
2657 | + region_gini_ = GiniCriterion::impurity(region.classCounts(), |
2658 | + region.size()); |
2659 | + if(region_gini_ == 0 || region.size() < SB::ext_param_.actual_mtry_ || region.oob_size() < 2) |
2660 | + return makeTerminalNode(features, multiClassLabels, region, randint); |
2661 | + |
2662 | + // select columns to be tried. |
2663 | + for(int ii = 0; ii < SB::ext_param_.actual_mtry_; ++ii) |
2664 | + std::swap(splitColumns[ii], |
2665 | + splitColumns[ii+ randint(features.shape(1) - ii)]); |
2666 | + |
2667 | + //do implicit binary case |
2668 | + MultiArray<2, T2> labels(lShape(multiClassLabels.shape(0),1)); |
2669 | + //number of classes should be >1, otherwise makeTerminalNode would have been called |
2670 | + int nNumClasses=0; |
2671 | + for(int n=0; n<(int)region.classCounts().size(); n++) |
2672 | + nNumClasses+=((region.classCounts()[n]>0) ? 1:0); |
2673 | + |
2674 | + //convert to binary case |
2675 | + if(nNumClasses>2) |
2676 | + { |
2677 | + int nMaxClass=0; |
2678 | + int nMaxClassCounts=0; |
2679 | + for(int n=0; n<(int)region.classCounts().size(); n++) |
2680 | + { |
2681 | + //this should occur in any case: |
2682 | + //we had more than two non-zero classes in order to get here |
2683 | + if(region.classCounts()[n]>nMaxClassCounts) |
2684 | + { |
2685 | + nMaxClassCounts=region.classCounts()[n]; |
2686 | + nMaxClass=n; |
2687 | + } |
2688 | + } |
2689 | + |
2690 | + //create binary labels |
2691 | + for(int n=0; n<multiClassLabels.shape(0); n++) |
2692 | + labels(n,0)=((multiClassLabels(n,0)==nMaxClass) ? 1:0); |
2693 | + } |
2694 | + else |
2695 | + labels=multiClassLabels; |
2696 | + |
2697 | + //_do implicit binary case |
2698 | + |
2699 | + //uncomment this for some debugging |
2700 | +/* int nNumCases=features.shape(0); |
2701 | + |
2702 | + typedef typename MultiArrayView <2, int>::difference_type nShape; |
2703 | + MultiArray<2, int> elementCounterArray(nShape(nNumCases,1),(int)0); |
2704 | + int nUniqueElements=0; |
2705 | + for(int n=0; n<region.size(); n++) |
2706 | + elementCounterArray[region[n]]++; |
2707 | + |
2708 | + for(int n=0; n<nNumCases; n++) |
2709 | + nUniqueElements+=((elementCounterArray[n]>0) ? 1:0); |
2710 | + |
2711 | + outm(nUniqueElements); |
2712 | + nUniqueElements=0; |
2713 | + MultiArray<2, int> elementCounterArray_oob(nShape(nNumCases,1),(int)0); |
2714 | + for(int n=0; n<region.oob_size(); n++) |
2715 | + elementCounterArray_oob[region.oob_begin()[n]]++; |
2716 | + for(int n=0; n<nNumCases; n++) |
2717 | + nUniqueElements+=((elementCounterArray_oob[n]>0) ? 1:0); |
2718 | + outm(nUniqueElements); |
2719 | + |
2720 | + int notUniqueElements=0; |
2721 | + for(int n=0; n<nNumCases; n++) |
2722 | + notUniqueElements+=(((elementCounterArray_oob[n]>0) && (elementCounterArray[n]>0)) ? 1:0); |
2723 | + outm(notUniqueElements);*/ |
2724 | + |
2725 | + //outm(SB::ext_param_.actual_mtry_); |
2726 | + |
2727 | + |
2728 | +//select submatrix of features for regression calculation |
2729 | + MultiArrayView<2, T, C> cVector; |
2730 | + MultiArray<2, T> xtrain(fShape(region.size(),SB::ext_param_.actual_mtry_)); |
2731 | + //we only want -1 and 1 for this |
2732 | + MultiArray<2, double> regrLabels(dShape(region.size(),1)); |
2733 | + |
2734 | + //copy data into a vigra data structure and centre and scale while doing so |
2735 | + MultiArray<2, double> meanMatrix(dShape(SB::ext_param_.actual_mtry_,1)); |
2736 | + MultiArray<2, double> stdMatrix(dShape(SB::ext_param_.actual_mtry_,1)); |
2737 | + for(int m=0; m<SB::ext_param_.actual_mtry_; m++) |
2738 | + { |
2739 | + cVector=columnVector(features, splitColumns[m]); |
2740 | + |
2741 | + //centre and scale the data |
2742 | + double dCurrFeatureColumnMean=0.0; |
2743 | + double dCurrFeatureColumnStd=1.0; //default value |
2744 | + |
2745 | + //calc mean on bootstrap data |
2746 | + for(int n=0; n<region.size(); n++) |
2747 | + dCurrFeatureColumnMean+=cVector[region[n]]; |
2748 | + dCurrFeatureColumnMean/=region.size(); |
2749 | + //calc scaling |
2750 | + if(m_bDoScalingInTraining) |
2751 | + { |
2752 | + for(int n=0; n<region.size(); n++) |
2753 | + { |
2754 | + dCurrFeatureColumnStd+= |
2755 | + (cVector[region[n]]-dCurrFeatureColumnMean)*(cVector[region[n]]-dCurrFeatureColumnMean); |
2756 | + } |
2757 | + //unbiased std estimator: |
2758 | + dCurrFeatureColumnStd=sqrt(dCurrFeatureColumnStd/(region.size()-1)); |
2759 | + } |
2760 | + //dCurrFeatureColumnStd is still 1.0 if we didn't want scaling |
2761 | + stdMatrix(m,0)=dCurrFeatureColumnStd; |
2762 | + |
2763 | + meanMatrix(m,0)=dCurrFeatureColumnMean; |
2764 | + |
2765 | + //get feature matrix, i.e. A (note that weighting is done automatically |
2766 | + //since rows can occur multiple times -> bagging) |
2767 | + for(int n=0; n<region.size(); n++) |
2768 | + xtrain(n,m)=(cVector[region[n]]-dCurrFeatureColumnMean)/dCurrFeatureColumnStd; |
2769 | + } |
2770 | + |
2771 | +// std::cout << "middle" << std::endl; |
2772 | + //get label vector (i.e. b) |
2773 | + for(int n=0; n<region.size(); n++) |
2774 | + { |
2775 | + //we checked for/built binary case further up. |
2776 | + //class labels should thus be either 0 or 1 |
2777 | + //-> convert to -1 and 1 for regression |
2778 | + regrLabels(n,0)=((labels[region[n]]==0) ? -1:1); |
2779 | + } |
2780 | + |
2781 | + MultiArray<2, double> dLambdas(dShape(11,1)); |
2782 | + int nCounter=0; |
2783 | + for(int nLambda=-5; nLambda<=5; nLambda++) |
2784 | + dLambdas[nCounter++]=pow(10.0,nLambda); |
2785 | + //destination vector for regression coefficients; use same type as for xtrain |
2786 | + MultiArray<2, double> regrCoef(dShape(SB::ext_param_.actual_mtry_,11)); |
2787 | + ridgeRegressionSeries(xtrain,regrLabels,regrCoef,dLambdas); |
2788 | + |
2789 | + double dMaxRidgeSum=NumericTraits<double>::min(); |
2790 | + double dCurrRidgeSum; |
2791 | + int nMaxRidgeSumAtLambdaInd=0; |
2792 | + |
2793 | + for(int nLambdaInd=0; nLambdaInd<11; nLambdaInd++) |
2794 | + { |
2795 | + //just sum up the correct answers |
2796 | + //(correct means >=intercept for class 1, <intercept for class 0) |
2797 | + //(intercept=0 or intercept=threshold based on gini) |
2798 | + dCurrRidgeSum=0.0; |
2799 | + |
2800 | + //assemble projection vector |
2801 | + MultiArray<2, double> dDistanceFromHyperplane(dShape(features.shape(0),1)); |
2802 | + |
2803 | + for(int n=0; n<region.oob_size(); n++) |
2804 | + { |
2805 | + dDistanceFromHyperplane(region.oob_begin()[n],0)=0.0; |
2806 | + for (int m=0; m<SB::ext_param_.actual_mtry_; m++) |
2807 | + { |
2808 | + dDistanceFromHyperplane(region.oob_begin()[n],0)+= |
2809 | + features(region.oob_begin()[n],splitColumns[m])*regrCoef(m,nLambdaInd); |
2810 | + } |
2811 | + } |
2812 | + |
2813 | + double dCurrIntercept=0.0; |
2814 | + if(m_bDoBestLambdaBasedOnGini) |
2815 | + { |
2816 | + //calculate gini index |
2817 | + bgfunc(dDistanceFromHyperplane, |
2818 | + 0, |
2819 | + labels, |
2820 | + region.oob_begin(), region.oob_end(), |
2821 | + region.classCounts()); |
2822 | + dCurrIntercept=bgfunc.min_threshold_; |
2823 | + } |
2824 | + else |
2825 | + { |
2826 | + for (int m=0; m<SB::ext_param_.actual_mtry_; m++) |
2827 | + dCurrIntercept+=meanMatrix(m,0)*regrCoef(m,nLambdaInd); |
2828 | + } |
2829 | + |
2830 | + for(int n=0; n<region.oob_size(); n++) |
2831 | + { |
2832 | + //check what lambda performs best on oob data |
2833 | + int nClassPrediction=((dDistanceFromHyperplane(region.oob_begin()[n],0) >=dCurrIntercept) ? 1:0); |
2834 | + dCurrRidgeSum+=((nClassPrediction == labels(region.oob_begin()[n],0)) ? 1:0); |
2835 | + } |
2836 | + if(dCurrRidgeSum>dMaxRidgeSum) |
2837 | + { |
2838 | + dMaxRidgeSum=dCurrRidgeSum; |
2839 | + nMaxRidgeSumAtLambdaInd=nLambdaInd; |
2840 | + } |
2841 | + } |
2842 | + |
2843 | +// std::cout << "middle2" << std::endl; |
2844 | + //create a Node for output |
2845 | + Node<i_HyperplaneNode> node(SB::ext_param_.actual_mtry_, SB::t_data, SB::p_data); |
2846 | + |
2847 | + //normalise coeffs |
2848 | + //data was scaled (by 1.0 or by std) -> take into account |
2849 | + MultiArray<2, double> dCoeffVector(dShape(SB::ext_param_.actual_mtry_,1)); |
2850 | + for(int n=0; n<SB::ext_param_.actual_mtry_; n++) |
2851 | + dCoeffVector(n,0)=regrCoef(n,nMaxRidgeSumAtLambdaInd)*stdMatrix(n,0); |
2852 | + |
2853 | + //calc norm |
2854 | + double dVnorm=columnVector(regrCoef,nMaxRidgeSumAtLambdaInd).norm(); |
2855 | + |
2856 | + for(int n=0; n<SB::ext_param_.actual_mtry_; n++) |
2857 | + node.weights()[n]=dCoeffVector(n,0)/dVnorm; |
2858 | + //_normalise coeffs |
2859 | + |
2860 | + //save the columns |
2861 | + node.column_data()[0]=SB::ext_param_.actual_mtry_; |
2862 | + for(int n=0; n<SB::ext_param_.actual_mtry_; n++) |
2863 | + node.column_data()[n+1]=splitColumns[n]; |
2864 | + |
2865 | + //assemble projection vector |
2866 | + //careful here: "region" is a pointer to indices... |
2867 | + //all the indices in "region" need to have valid data |
2868 | + //convert from "region" space to original "feature" space |
2869 | + MultiArray<2, double> dDistanceFromHyperplane(dShape(features.shape(0),1)); |
2870 | + |
2871 | + for(int n=0; n<region.size(); n++) |
2872 | + { |
2873 | + dDistanceFromHyperplane(region[n],0)=0.0; |
2874 | + for (int m=0; m<SB::ext_param_.actual_mtry_; m++) |
2875 | + { |
2876 | + dDistanceFromHyperplane(region[n],0)+= |
2877 | + features(region[n],m)*node.weights()[m]; |
2878 | + } |
2879 | + } |
2880 | + for(int n=0; n<region.oob_size(); n++) |
2881 | + { |
2882 | + dDistanceFromHyperplane(region.oob_begin()[n],0)=0.0; |
2883 | + for (int m=0; m<SB::ext_param_.actual_mtry_; m++) |
2884 | + { |
2885 | + dDistanceFromHyperplane(region.oob_begin()[n],0)+= |
2886 | + features(region.oob_begin()[n],m)*node.weights()[m]; |
2887 | + } |
2888 | + } |
2889 | + |
2890 | + //calculate gini index |
2891 | + bgfunc(dDistanceFromHyperplane, |
2892 | + 0, |
2893 | + labels, |
2894 | + region.begin(), region.end(), |
2895 | + region.classCounts()); |
2896 | + |
2897 | + // did not find any suitable split |
2898 | + if(closeAtTolerance(bgfunc.min_gini_, NumericTraits<double>::max())) |
2899 | + return makeTerminalNode(features, multiClassLabels, region, randint); |
2900 | + |
2901 | + //take gini threshold here due to scaling, normalisation, etc. of the coefficients |
2902 | + node.intercept() = bgfunc.min_threshold_; |
2903 | + SB::node_ = node; |
2904 | + |
2905 | + childRegions[0].classCounts() = bgfunc.bestCurrentCounts[0]; |
2906 | + childRegions[1].classCounts() = bgfunc.bestCurrentCounts[1]; |
2907 | + childRegions[0].classCountsIsValid = true; |
2908 | + childRegions[1].classCountsIsValid = true; |
2909 | + |
2910 | + // Save the ranges of the child stack entries. |
2911 | + childRegions[0].setRange( region.begin() , region.begin() + bgfunc.min_index_ ); |
2912 | + childRegions[0].rule = region.rule; |
2913 | + childRegions[0].rule.push_back(std::make_pair(1, 1.0)); |
2914 | + childRegions[1].setRange( region.begin() + bgfunc.min_index_ , region.end() ); |
2915 | + childRegions[1].rule = region.rule; |
2916 | + childRegions[1].rule.push_back(std::make_pair(1, 1.0)); |
2917 | + |
2918 | + //adjust oob ranges |
2919 | +// std::cout << "adjust oob" << std::endl; |
2920 | + //sort the oobs |
2921 | + std::sort(region.oob_begin(), region.oob_end(), |
2922 | + SortSamplesByDimensions< MultiArray<2, double> > (dDistanceFromHyperplane, 0)); |
2923 | + |
2924 | + //find split index |
2925 | + int nOOBindx; |
2926 | + for(nOOBindx=0; nOOBindx<region.oob_size(); nOOBindx++) |
2927 | + { |
2928 | + if(dDistanceFromHyperplane(region.oob_begin()[nOOBindx],0)>=node.intercept()) |
2929 | + break; |
2930 | + } |
2931 | + |
2932 | + childRegions[0].set_oob_range( region.oob_begin() , region.oob_begin() + nOOBindx ); |
2933 | + childRegions[1].set_oob_range( region.oob_begin() + nOOBindx , region.oob_end() ); |
2934 | + |
2935 | +// std::cout << "end" << std::endl; |
2936 | +// outm2(region.oob_begin());outm2(nOOBindx);outm(region.oob_begin() + nOOBindx); |
2937 | + //_adjust oob ranges |
2938 | + |
2939 | + return i_HyperplaneNode; |
2940 | + } |
2941 | +}; |
2942 | + |
2943 | +/** Standard ridge regression split |
2944 | + */ |
2945 | +typedef RidgeSplit<BestGiniOfColumn<GiniCriterion> > GiniRidgeSplit; |
2946 | + |
2947 | + |
2948 | +} //namespace vigra |
2949 | +#endif // VIGRA_RANDOM_FOREST_RIDGE_SPLIT_H |
2950 | |
2951 | === added file '.pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_split.hxx' |
2952 | --- .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_split.hxx 1970-01-01 00:00:00 +0000 |
2953 | +++ .pc/fix-ftbfs-gcc4.7.diff/include/vigra/random_forest/rf_split.hxx 2012-06-14 20:29:21 +0000 |
2954 | @@ -0,0 +1,1199 @@ |
2955 | +/************************************************************************/ |
2956 | +/* */ |
2957 | +/* Copyright 2008-2009 by Ullrich Koethe and Rahul Nair */ |
2958 | +/* */ |
2959 | +/* This file is part of the VIGRA computer vision library. */ |
2960 | +/* The VIGRA Website is */ |
2961 | +/* http://hci.iwr.uni-heidelberg.de/vigra/ */ |
2962 | +/* Please direct questions, bug reports, and contributions to */ |
2963 | +/* ullrich.koethe@iwr.uni-heidelberg.de or */ |
2964 | +/* vigra@informatik.uni-hamburg.de */ |
2965 | +/* */ |
2966 | +/* Permission is hereby granted, free of charge, to any person */ |
2967 | +/* obtaining a copy of this software and associated documentation */ |
2968 | +/* files (the "Software"), to deal in the Software without */ |
2969 | +/* restriction, including without limitation the rights to use, */ |
2970 | +/* copy, modify, merge, publish, distribute, sublicense, and/or */ |
2971 | +/* sell copies of the Software, and to permit persons to whom the */ |
2972 | +/* Software is furnished to do so, subject to the following */ |
2973 | +/* conditions: */ |
2974 | +/* */ |
2975 | +/* The above copyright notice and this permission notice shall be */ |
2976 | +/* included in all copies or substantial portions of the */ |
2977 | +/* Software. */ |
2978 | +/* */ |
2979 | +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ |
2980 | +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ |
2981 | +/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ |
2982 | +/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ |
2983 | +/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ |
2984 | +/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ |
2985 | +/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ |
2986 | +/* OTHER DEALINGS IN THE SOFTWARE. */ |
2987 | +/* */ |
2988 | +/************************************************************************/ |
2989 | +#ifndef VIGRA_RANDOM_FOREST_SPLIT_HXX |
2990 | +#define VIGRA_RANDOM_FOREST_SPLIT_HXX |
2991 | +#include <algorithm> |
2992 | +#include <cstddef> |
2993 | +#include <map> |
2994 | +#include <numeric> |
2995 | +#include <math.h> |
2996 | +#include "../mathutil.hxx" |
2997 | +#include "../array_vector.hxx" |
2998 | +#include "../sized_int.hxx" |
2999 | +#include "../matrix.hxx" |
3000 | +#include "../random.hxx" |
3001 | +#include "../functorexpression.hxx" |
3002 | +#include "rf_nodeproxy.hxx" |
3003 | +//#include "rf_sampling.hxx" |
3004 | +#include "rf_region.hxx" |
3005 | +//#include "../hokashyap.hxx" |
3006 | +//#include "vigra/rf_helpers.hxx" |
3007 | + |
3008 | +namespace vigra |
3009 | +{ |
3010 | + |
3011 | +// Incomplete Class to ensure that findBestSplit is always implemented in |
3012 | +// the derived classes of SplitBase |
3013 | +class CompileTimeError; |
3014 | + |
3015 | + |
3016 | +namespace detail |
3017 | +{ |
3018 | + template<class Tag> |
3019 | + class Normalise |
3020 | + { |
3021 | + public: |
3022 | + template<class Iter> |
3023 | + static void exec(Iter begin, Iter end) |
3024 | + {} |
3025 | + }; |
3026 | + |
3027 | + template<> |
3028 | + class Normalise<ClassificationTag> |
3029 | + { |
3030 | + public: |
3031 | + template<class Iter> |
3032 | + static void exec (Iter begin, Iter end) |
3033 | + { |
3034 | + double bla = std::accumulate(begin, end, 0.0); |
3035 | + for(int ii = 0; ii < end - begin; ++ii) |
3036 | + begin[ii] = begin[ii]/bla ; |
3037 | + } |
3038 | + }; |
3039 | +} |
3040 | + |
3041 | + |
3042 | +/** Base Class for all SplitFunctors used with the \ref RandomForest class |
3043 | + defines the interface used while learning a tree. |
3044 | +**/ |
3045 | +template<class Tag> |
3046 | +class SplitBase |
3047 | +{ |
3048 | + public: |
3049 | + |
3050 | + typedef Tag RF_Tag; |
3051 | + typedef DT_StackEntry<ArrayVectorView<Int32>::iterator> |
3052 | + StackEntry_t; |
3053 | + |
3054 | + ProblemSpec<> ext_param_; |
3055 | + |
3056 | + NodeBase::T_Container_type t_data; |
3057 | + NodeBase::P_Container_type p_data; |
3058 | + |
3059 | + NodeBase node_; |
3060 | + |
3061 | + /** returns the DecisionTree Node created by |
3062 | + \ref findBestSplit or \ref makeTerminalNode. |
3063 | + **/ |
3064 | + |
3065 | + template<class T> |
3066 | + void set_external_parameters(ProblemSpec<T> const & in) |
3067 | + { |
3068 | + ext_param_ = in; |
3069 | + t_data.push_back(in.column_count_); |
3070 | + t_data.push_back(in.class_count_); |
3071 | + } |
3072 | + |
3073 | + NodeBase & createNode() |
3074 | + { |
3075 | + return node_; |
3076 | + } |
3077 | + |
3078 | + int classCount() const |
3079 | + { |
3080 | + return int(t_data[1]); |
3081 | + } |
3082 | + |
3083 | + int featureCount() const |
3084 | + { |
3085 | + return int(t_data[0]); |
3086 | + } |
3087 | + |
3088 | + /** resets internal data. Should always be called before |
3089 | + calling findBestSplit or makeTerminalNode |
3090 | + **/ |
3091 | + void reset() |
3092 | + { |
3093 | + t_data.resize(2); |
3094 | + p_data.resize(0); |
3095 | + } |
3096 | + |
3097 | + |
3098 | + /** findBestSplit has to be implemented in derived split functor. |
3099 | + these functions only insures That a CompileTime error is issued |
3100 | + if no such method was defined. |
3101 | + **/ |
3102 | + |
3103 | + template<class T, class C, class T2, class C2, class Region, class Random> |
3104 | + int findBestSplit(MultiArrayView<2, T, C> features, |
3105 | + MultiArrayView<2, T2, C2> labels, |
3106 | + Region region, |
3107 | + ArrayVector<Region> childs, |
3108 | + Random randint) |
3109 | + { |
3110 | + CompileTimeError SplitFunctor__findBestSplit_member_was_not_defined; |
3111 | + return 0; |
3112 | + } |
3113 | + |
3114 | + /** default action for creating a terminal Node. |
3115 | + sets the Class probability of the remaining region according to |
3116 | + the class histogram |
3117 | + **/ |
3118 | + template<class T, class C, class T2,class C2, class Region, class Random> |
3119 | + int makeTerminalNode(MultiArrayView<2, T, C> features, |
3120 | + MultiArrayView<2, T2, C2> labels, |
3121 | + Region & region, |
3122 | + Random randint) |
3123 | + { |
3124 | + Node<e_ConstProbNode> ret(t_data, p_data); |
3125 | + node_ = ret; |
3126 | + if(ext_param_.class_weights_.size() != region.classCounts().size()) |
3127 | + { |
3128 | + std::copy( region.classCounts().begin(), |
3129 | + region.classCounts().end(), |
3130 | + ret.prob_begin()); |
3131 | + } |
3132 | + else |
3133 | + { |
3134 | + std::transform( region.classCounts().begin(), |
3135 | + region.classCounts().end(), |
3136 | + ext_param_.class_weights_.begin(), |
3137 | + ret.prob_begin(), std::multiplies<double>()); |
3138 | + } |
3139 | + detail::Normalise<RF_Tag>::exec(ret.prob_begin(), ret.prob_end()); |
3140 | + ret.weights() = region.size(); |
3141 | + return e_ConstProbNode; |
3142 | + } |
3143 | + |
3144 | + |
3145 | +}; |
3146 | + |
3147 | +/** Functor to sort the indices of a feature Matrix by a certain dimension |
3148 | +**/ |
3149 | +template<class DataMatrix> |
3150 | +class SortSamplesByDimensions |
3151 | +{ |
3152 | + DataMatrix const & data_; |
3153 | + MultiArrayIndex sortColumn_; |
3154 | + double thresVal_; |
3155 | + public: |
3156 | + |
3157 | + SortSamplesByDimensions(DataMatrix const & data, |
3158 | + MultiArrayIndex sortColumn, |
3159 | + double thresVal = 0.0) |
3160 | + : data_(data), |
3161 | + sortColumn_(sortColumn), |
3162 | + thresVal_(thresVal) |
3163 | + {} |
3164 | + |
3165 | + void setColumn(MultiArrayIndex sortColumn) |
3166 | + { |
3167 | + sortColumn_ = sortColumn; |
3168 | + } |
3169 | + void setThreshold(double value) |
3170 | + { |
3171 | + thresVal_ = value; |
3172 | + } |
3173 | + |
3174 | + bool operator()(MultiArrayIndex l, MultiArrayIndex r) const |
3175 | + { |
3176 | + return data_(l, sortColumn_) < data_(r, sortColumn_); |
3177 | + } |
3178 | + bool operator()(MultiArrayIndex l) const |
3179 | + { |
3180 | + return data_(l, sortColumn_) < thresVal_; |
3181 | + } |
3182 | +}; |
3183 | + |
3184 | +template<class DataMatrix> |
3185 | +class DimensionNotEqual |
3186 | +{ |
3187 | + DataMatrix const & data_; |
3188 | + MultiArrayIndex sortColumn_; |
3189 | + |
3190 | + public: |
3191 | + |
3192 | + DimensionNotEqual(DataMatrix const & data, |
3193 | + MultiArrayIndex sortColumn) |
3194 | + : data_(data), |
3195 | + sortColumn_(sortColumn) |
3196 | + {} |
3197 | + |
3198 | + void setColumn(MultiArrayIndex sortColumn) |
3199 | + { |
3200 | + sortColumn_ = sortColumn; |
3201 | + } |
3202 | + |
3203 | + bool operator()(MultiArrayIndex l, MultiArrayIndex r) const |
3204 | + { |
3205 | + return data_(l, sortColumn_) != data_(r, sortColumn_); |
3206 | + } |
3207 | +}; |
3208 | + |
3209 | +template<class DataMatrix> |
3210 | +class SortSamplesByHyperplane |
3211 | +{ |
3212 | + DataMatrix const & data_; |
3213 | + Node<i_HyperplaneNode> const & node_; |
3214 | + |
3215 | + public: |
3216 | + |
3217 | + SortSamplesByHyperplane(DataMatrix const & data, |
3218 | + Node<i_HyperplaneNode> const & node) |
3219 | + : |
3220 | + data_(data), |
3221 | + node_() |
3222 | + {} |
3223 | + |
3224 | + /** calculate the distance of a sample point to a hyperplane |
3225 | + */ |
3226 | + double operator[](MultiArrayIndex l) const |
3227 | + { |
3228 | + double result_l = -1 * node_.intercept(); |
3229 | + for(int ii = 0; ii < node_.columns_size(); ++ii) |
3230 | + { |
3231 | + result_l += rowVector(data_, l)[node_.columns_begin()[ii]] |
3232 | + * node_.weights()[ii]; |
3233 | + } |
3234 | + return result_l; |
3235 | + } |
3236 | + |
3237 | + bool operator()(MultiArrayIndex l, MultiArrayIndex r) const |
3238 | + { |
3239 | + return (*this)[l] < (*this)[r]; |
3240 | + } |
3241 | + |
3242 | +}; |
3243 | + |
3244 | +/** makes a Class Histogram given indices in a labels_ array |
3245 | + * usage: |
3246 | + * MultiArrayView<2, T2, C2> labels = makeSomeLabels() |
3247 | + * ArrayVector<int> hist(numberOfLabels(labels), 0); |
3248 | + * RandomForestClassCounter<T2, C2, ArrayVector> counter(labels, hist); |
3249 | + * |
3250 | + * Container<int> indices = getSomeIndices() |
3251 | + * std::for_each(indices, counter); |
3252 | + */ |
3253 | +template <class DataSource, class CountArray> |
3254 | +class RandomForestClassCounter |
3255 | +{ |
3256 | + DataSource const & labels_; |
3257 | + CountArray & counts_; |
3258 | + |
3259 | + public: |
3260 | + |
3261 | + RandomForestClassCounter(DataSource const & labels, |
3262 | + CountArray & counts) |
3263 | + : labels_(labels), |
3264 | + counts_(counts) |
3265 | + { |
3266 | + reset(); |
3267 | + } |
3268 | + |
3269 | + void reset() |
3270 | + { |
3271 | + counts_.init(0); |
3272 | + } |
3273 | + |
3274 | + void operator()(MultiArrayIndex l) const |
3275 | + { |
3276 | + counts_[labels_[l]] +=1; |
3277 | + } |
3278 | +}; |
3279 | + |
3280 | + |
3281 | +/** Functor To Calculate the Best possible Split Based on the Gini Index |
3282 | + given Labels and Features along a given Axis |
3283 | +*/ |
3284 | + |
3285 | +namespace detail |
3286 | +{ |
3287 | + template<int N> |
3288 | + class ConstArr |
3289 | + { |
3290 | + public: |
3291 | + double operator[](size_t) const |
3292 | + { |
3293 | + return (double)N; |
3294 | + } |
3295 | + }; |
3296 | + |
3297 | + |
3298 | +} |
3299 | + |
3300 | + |
3301 | + |
3302 | + |
3303 | +/** Functor to calculate the entropy based impurity |
3304 | + */ |
3305 | +class EntropyCriterion |
3306 | +{ |
3307 | +public: |
3308 | + /**caculate the weighted gini impurity based on class histogram |
3309 | + * and class weights |
3310 | + */ |
3311 | + template<class Array, class Array2> |
3312 | + double operator() (Array const & hist, |
3313 | + Array2 const & weights, |
3314 | + double total = 1.0) const |
3315 | + { |
3316 | + return impurity(hist, weights, total); |
3317 | + } |
3318 | + |
3319 | + /** calculate the gini based impurity based on class histogram |
3320 | + */ |
3321 | + template<class Array> |
3322 | + double operator()(Array const & hist, double total = 1.0) const |
3323 | + { |
3324 | + return impurity(hist, total); |
3325 | + } |
3326 | + |
3327 | + /** static version of operator(hist total) |
3328 | + */ |
3329 | + template<class Array> |
3330 | + static double impurity(Array const & hist, double total) |
3331 | + { |
3332 | + return impurity(hist, detail::ConstArr<1>(), total); |
3333 | + } |
3334 | + |
3335 | + /** static version of operator(hist, weights, total) |
3336 | + */ |
3337 | + template<class Array, class Array2> |
3338 | + static double impurity (Array const & hist, |
3339 | + Array2 const & weights, |
3340 | + double total) |
3341 | + { |
3342 | + |
3343 | + int class_count = hist.size(); |
3344 | + double entropy = 0.0; |
3345 | + if(class_count == 2) |
3346 | + { |
3347 | + double p0 = (hist[0]/total); |
3348 | + double p1 = (hist[1]/total); |
3349 | + entropy = 0 - weights[0]*p0*std::log(p0) - weights[1]*p1*std::log(p1); |
3350 | + } |
3351 | + else |
3352 | + { |
3353 | + for(int ii = 0; ii < class_count; ++ii) |
3354 | + { |
3355 | + double w = weights[ii]; |
3356 | + double pii = hist[ii]/total; |
3357 | + entropy -= w*( pii*std::log(pii)); |
3358 | + } |
3359 | + } |
3360 | + entropy = total * entropy; |
3361 | + return entropy; |
3362 | + } |
3363 | +}; |
3364 | + |
3365 | +/** Functor to calculate the gini impurity |
3366 | + */ |
3367 | +class GiniCriterion |
3368 | +{ |
3369 | +public: |
3370 | + /**caculate the weighted gini impurity based on class histogram |
3371 | + * and class weights |
3372 | + */ |
3373 | + template<class Array, class Array2> |
3374 | + double operator() (Array const & hist, |
3375 | + Array2 const & weights, |
3376 | + double total = 1.0) const |
3377 | + { |
3378 | + return impurity(hist, weights, total); |
3379 | + } |
3380 | + |
3381 | + /** calculate the gini based impurity based on class histogram |
3382 | + */ |
3383 | + template<class Array> |
3384 | + double operator()(Array const & hist, double total = 1.0) const |
3385 | + { |
3386 | + return impurity(hist, total); |
3387 | + } |
3388 | + |
3389 | + /** static version of operator(hist total) |
3390 | + */ |
3391 | + template<class Array> |
3392 | + static double impurity(Array const & hist, double total) |
3393 | + { |
3394 | + return impurity(hist, detail::ConstArr<1>(), total); |
3395 | + } |
3396 | + |
3397 | + /** static version of operator(hist, weights, total) |
3398 | + */ |
3399 | + template<class Array, class Array2> |
3400 | + static double impurity (Array const & hist, |
3401 | + Array2 const & weights, |
3402 | + double total) |
3403 | + { |
3404 | + |
3405 | + int class_count = hist.size(); |
3406 | + double gini = 0.0; |
3407 | + if(class_count == 2) |
3408 | + { |
3409 | + double w = weights[0] * weights[1]; |
3410 | + gini = w * (hist[0] * hist[1] / total); |
3411 | + } |
3412 | + else |
3413 | + { |
3414 | + for(int ii = 0; ii < class_count; ++ii) |
3415 | + { |
3416 | + double w = weights[ii]; |
3417 | + gini += w*( hist[ii]*( 1.0 - w * hist[ii]/total ) ); |
3418 | + } |
3419 | + } |
3420 | + return gini; |
3421 | + } |
3422 | +}; |
3423 | + |
3424 | + |
3425 | +template <class DataSource, class Impurity= GiniCriterion> |
3426 | +class ImpurityLoss |
3427 | +{ |
3428 | + |
3429 | + DataSource const & labels_; |
3430 | + ArrayVector<double> counts_; |
3431 | + ArrayVector<double> const class_weights_; |
3432 | + double total_counts_; |
3433 | + Impurity impurity_; |
3434 | + |
3435 | + public: |
3436 | + |
3437 | + template<class T> |
3438 | + ImpurityLoss(DataSource const & labels, |
3439 | + ProblemSpec<T> const & ext_) |
3440 | + : labels_(labels), |
3441 | + counts_(ext_.class_count_, 0.0), |
3442 | + class_weights_(ext_.class_weights_), |
3443 | + total_counts_(0.0) |
3444 | + {} |
3445 | + |
3446 | + void reset() |
3447 | + { |
3448 | + counts_.init(0); |
3449 | + total_counts_ = 0.0; |
3450 | + } |
3451 | + |
3452 | + template<class Counts> |
3453 | + double increment_histogram(Counts const & counts) |
3454 | + { |
3455 | + std::transform(counts.begin(), counts.end(), |
3456 | + counts_.begin(), counts_.begin(), |
3457 | + std::plus<double>()); |
3458 | + total_counts_ = std::accumulate( counts_.begin(), |
3459 | + counts_.end(), |
3460 | + 0.0); |
3461 | + return impurity_(counts_, class_weights_, total_counts_); |
3462 | + } |
3463 | + |
3464 | + template<class Counts> |
3465 | + double decrement_histogram(Counts const & counts) |
3466 | + { |
3467 | + std::transform(counts.begin(), counts.end(), |
3468 | + counts_.begin(), counts_.begin(), |
3469 | + std::minus<double>()); |
3470 | + total_counts_ = std::accumulate( counts_.begin(), |
3471 | + counts_.end(), |
3472 | + 0.0); |
3473 | + return impurity_(counts_, class_weights_, total_counts_); |
3474 | + } |
3475 | + |
3476 | + template<class Iter> |
3477 | + double increment(Iter begin, Iter end) |
3478 | + { |
3479 | + for(Iter iter = begin; iter != end; ++iter) |
3480 | + { |
3481 | + counts_[labels_(*iter, 0)] +=1.0; |
3482 | + total_counts_ +=1.0; |
3483 | + } |
3484 | + return impurity_(counts_, class_weights_, total_counts_); |
3485 | + } |
3486 | + |
3487 | + template<class Iter> |
3488 | + double decrement(Iter const & begin, Iter const & end) |
3489 | + { |
3490 | + for(Iter iter = begin; iter != end; ++iter) |
3491 | + { |
3492 | + counts_[labels_(*iter,0)] -=1.0; |
3493 | + total_counts_ -=1.0; |
3494 | + } |
3495 | + return impurity_(counts_, class_weights_, total_counts_); |
3496 | + } |
3497 | + |
3498 | + template<class Iter, class Resp_t> |
3499 | + double init (Iter begin, Iter end, Resp_t resp) |
3500 | + { |
3501 | + reset(); |
3502 | + std::copy(resp.begin(), resp.end(), counts_.begin()); |
3503 | + total_counts_ = std::accumulate(counts_.begin(), counts_.end(), 0.0); |
3504 | + return impurity_(counts_,class_weights_, total_counts_); |
3505 | + } |
3506 | + |
3507 | + ArrayVector<double> const & response() |
3508 | + { |
3509 | + return counts_; |
3510 | + } |
3511 | +}; |
3512 | + |
3513 | +template <class DataSource> |
3514 | +class RegressionForestCounter |
3515 | +{ |
3516 | + typedef MultiArrayShape<2>::type Shp; |
3517 | + DataSource const & labels_; |
3518 | + ArrayVector <double> mean_; |
3519 | + ArrayVector <double> variance_; |
3520 | + ArrayVector <double> tmp_; |
3521 | + size_t count_; |
3522 | + |
3523 | + template<class T> |
3524 | + RegressionForestCounter(DataSource const & labels, |
3525 | + ProblemSpec<T> const & ext_) |
3526 | + : |
3527 | + labels_(labels), |
3528 | + mean_(ext_.response_size, 0.0), |
3529 | + variance_(ext_.response_size, 0.0), |
3530 | + tmp_(ext_.response_size), |
3531 | + count_(0) |
3532 | + {} |
3533 | + |
3534 | + // west's alorithm for incremental variance |
3535 | + // calculation |
3536 | + template<class Iter> |
3537 | + double increment (Iter begin, Iter end) |
3538 | + { |
3539 | + for(Iter iter = begin; iter != end; ++iter) |
3540 | + { |
3541 | + ++count_; |
3542 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3543 | + tmp_[ii] = labels_(*iter, ii) - mean_[ii]; |
3544 | + double f = 1.0 / count_, |
3545 | + f1 = 1.0 - f; |
3546 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3547 | + mean_[ii] += f*tmp_[ii]; |
3548 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3549 | + variance_[ii] += f1*sq(tmp_[ii]); |
3550 | + } |
3551 | + return std::accumulate(variance_.begin(), |
3552 | + variance_.end(), |
3553 | + 0.0, |
3554 | + std::plus<double>()) |
3555 | + /(count_ -1); |
3556 | + } |
3557 | + |
3558 | + template<class Iter> |
3559 | + double decrement (Iter begin, Iter end) |
3560 | + { |
3561 | + for(Iter iter = begin; iter != end; ++iter) |
3562 | + { |
3563 | + --count_; |
3564 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3565 | + tmp_[ii] = labels_(*iter, ii) - mean_[ii]; |
3566 | + double f = 1.0 / count_, |
3567 | + f1 = 1.0 + f; |
3568 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3569 | + mean_[ii] -= f*tmp_[ii]; |
3570 | + for(int ii = 0; ii < mean_.size(); ++ii) |
3571 | + variance_[ii] -= f1*sq(tmp_[ii]); |
3572 | + } |
3573 | + return std::accumulate(variance_.begin(), |
3574 | + variance_.end(), |
3575 | + 0.0, |
3576 | + std::plus<double>()) |
3577 | + /(count_ -1); |
3578 | + } |
3579 | + |
3580 | + template<class Iter, class Resp_t> |
3581 | + double init (Iter begin, Iter end, Resp_t resp) |
3582 | + { |
3583 | + reset(); |
3584 | + return increment(begin, end); |
3585 | + } |
3586 | + |
3587 | + |
3588 | + ArrayVector<double> const & response() |
3589 | + { |
3590 | + return mean_; |
3591 | + } |
3592 | + |
3593 | + void reset() |
3594 | + { |
3595 | + mean_.init(0.0); |
3596 | + variance_.init(0.0); |
3597 | + count_ = 0; |
3598 | + } |
3599 | +}; |
3600 | + |
3601 | +template<class Tag, class Datatyp> |
3602 | +struct LossTraits; |
3603 | + |
3604 | +struct LSQLoss |
3605 | +{}; |
3606 | + |
3607 | +template<class Datatype> |
3608 | +struct LossTraits<GiniCriterion, Datatype> |
3609 | +{ |
3610 | + typedef ImpurityLoss<Datatype, GiniCriterion> type; |
3611 | +}; |
3612 | + |
3613 | +template<class Datatype> |
3614 | +struct LossTraits<EntropyCriterion, Datatype> |
3615 | +{ |
3616 | + typedef ImpurityLoss<Datatype, EntropyCriterion> type; |
3617 | +}; |
3618 | + |
3619 | +template<class Datatype> |
3620 | +struct LossTraits<LSQLoss, Datatype> |
3621 | +{ |
3622 | + typedef RegressionForestCounter<Datatype> type; |
3623 | +}; |
3624 | + |
3625 | +/** Given a column, choose a split that minimizes some loss |
3626 | + */ |
3627 | +template<class LineSearchLossTag> |
3628 | +class BestGiniOfColumn |
3629 | +{ |
3630 | +public: |
3631 | + ArrayVector<double> class_weights_; |
3632 | + ArrayVector<double> bestCurrentCounts[2]; |
3633 | + double min_gini_; |
3634 | + ptrdiff_t min_index_; |
3635 | + double min_threshold_; |
3636 | + ProblemSpec<> ext_param_; |
3637 | + |
3638 | + BestGiniOfColumn() |
3639 | + {} |
3640 | + |
3641 | + template<class T> |
3642 | + BestGiniOfColumn(ProblemSpec<T> const & ext) |
3643 | + : |
3644 | + class_weights_(ext.class_weights_), |
3645 | + ext_param_(ext) |
3646 | + { |
3647 | + bestCurrentCounts[0].resize(ext.class_count_); |
3648 | + bestCurrentCounts[1].resize(ext.class_count_); |
3649 | + } |
3650 | + template<class T> |
3651 | + void set_external_parameters(ProblemSpec<T> const & ext) |
3652 | + { |
3653 | + class_weights_ = ext.class_weights_; |
3654 | + ext_param_ = ext; |
3655 | + bestCurrentCounts[0].resize(ext.class_count_); |
3656 | + bestCurrentCounts[1].resize(ext.class_count_); |
3657 | + } |
3658 | + /** calculate the best gini split along a Feature Column |
3659 | + * \param column, the feature vector - has to support the [] operator |
3660 | + * \param labels, the label vector |
3661 | + * \param begin |
3662 | + * \param end (in and out) |
3663 | + * begin and end iterators to the indices of the |
3664 | + * samples in the current region. |
3665 | + * the range begin - end is sorted by the column supplied |
3666 | + * during function execution. |
3667 | + * \param class_counts |
3668 | + * class histogram of the range. |
3669 | + * |
3670 | + * precondition: begin, end valid range, |
3671 | + * class_counts positive integer valued array with the |
3672 | + * class counts in the current range. |
3673 | + * labels.size() >= max(begin, end); |
3674 | + * postcondition: |
3675 | + * begin, end sorted by column given. |
3676 | + * min_gini_ contains the minimum gini found or |
3677 | + * NumericTraits<double>::max if no split was found. |
3678 | + * min_index_ countains the splitting index in the range |
3679 | + * or invalid data if no split was found. |
3680 | + * BestCirremtcounts[0] and [1] contain the |
3681 | + * class histogram of the left and right region of |
3682 | + * the left and right regions. |
3683 | + */ |
3684 | + template< class DataSourceF_t, |
3685 | + class DataSource_t, |
3686 | + class I_Iter, |
3687 | + class Array> |
3688 | + void operator()(DataSourceF_t const & column, |
3689 | + int g, |
3690 | + DataSource_t const & labels, |
3691 | + I_Iter & begin, |
3692 | + I_Iter & end, |
3693 | + Array const & region_response) |
3694 | + { |
3695 | + std::sort(begin, end, |
3696 | + SortSamplesByDimensions<DataSourceF_t>(column, g)); |
3697 | + typedef typename |
3698 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
3699 | + LineSearchLoss left(labels, ext_param_); |
3700 | + LineSearchLoss right(labels, ext_param_); |
3701 | + |
3702 | + |
3703 | + |
3704 | + min_gini_ = right.init(begin, end, region_response); |
3705 | + min_threshold_ = *begin; |
3706 | + min_index_ = 0; |
3707 | + DimensionNotEqual<DataSourceF_t> comp(column, g); |
3708 | + |
3709 | + I_Iter iter = begin; |
3710 | + I_Iter next = std::adjacent_find(iter, end, comp); |
3711 | + while( next != end) |
3712 | + { |
3713 | + |
3714 | + double loss = right.decrement(iter, next + 1) |
3715 | + + left.increment(iter , next + 1); |
3716 | +#ifdef CLASSIFIER_TEST |
3717 | + if(loss < min_gini_ && !closeAtTolerance(loss, min_gini_)) |
3718 | +#else |
3719 | + if(loss < min_gini_ ) |
3720 | +#endif |
3721 | + { |
3722 | + bestCurrentCounts[0] = left.response(); |
3723 | + bestCurrentCounts[1] = right.response(); |
3724 | +#ifdef CLASSIFIER_TEST |
3725 | + min_gini_ = loss < min_gini_? loss : min_gini_; |
3726 | +#else |
3727 | + min_gini_ = loss; |
3728 | +#endif |
3729 | + min_index_ = next - begin +1 ; |
3730 | + min_threshold_ = (double(column(*next,g)) + double(column(*(next +1), g)))/2.0; |
3731 | + } |
3732 | + iter = next +1 ; |
3733 | + next = std::adjacent_find(iter, end, comp); |
3734 | + } |
3735 | + } |
3736 | + |
3737 | + template<class DataSource_t, class Iter, class Array> |
3738 | + double loss_of_region(DataSource_t const & labels, |
3739 | + Iter & begin, |
3740 | + Iter & end, |
3741 | + Array const & region_response) const |
3742 | + { |
3743 | + typedef typename |
3744 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
3745 | + LineSearchLoss region_loss(labels, ext_param_); |
3746 | + return |
3747 | + region_loss.init(begin, end, region_response); |
3748 | + } |
3749 | + |
3750 | +}; |
3751 | + |
3752 | + |
3753 | +/** Chooses mtry columns ad applys ColumnDecisionFunctor to each of the |
3754 | + * columns. Then Chooses the column that is best |
3755 | + */ |
3756 | +template<class ColumnDecisionFunctor, class Tag = ClassificationTag> |
3757 | +class ThresholdSplit: public SplitBase<Tag> |
3758 | +{ |
3759 | + public: |
3760 | + |
3761 | + |
3762 | + typedef SplitBase<Tag> SB; |
3763 | + |
3764 | + ArrayVector<Int32> splitColumns; |
3765 | + ColumnDecisionFunctor bgfunc; |
3766 | + |
3767 | + double region_gini_; |
3768 | + ArrayVector<double> min_gini_; |
3769 | + ArrayVector<ptrdiff_t> min_indices_; |
3770 | + ArrayVector<double> min_thresholds_; |
3771 | + |
3772 | + int bestSplitIndex; |
3773 | + |
3774 | + double minGini() const |
3775 | + { |
3776 | + return min_gini_[bestSplitIndex]; |
3777 | + } |
3778 | + int bestSplitColumn() const |
3779 | + { |
3780 | + return splitColumns[bestSplitIndex]; |
3781 | + } |
3782 | + double bestSplitThreshold() const |
3783 | + { |
3784 | + return min_thresholds_[bestSplitIndex]; |
3785 | + } |
3786 | + |
3787 | + template<class T> |
3788 | + void set_external_parameters(ProblemSpec<T> const & in) |
3789 | + { |
3790 | + SB::set_external_parameters(in); |
3791 | + bgfunc.set_external_parameters( SB::ext_param_); |
3792 | + int featureCount_ = SB::ext_param_.column_count_; |
3793 | + splitColumns.resize(featureCount_); |
3794 | + for(int k=0; k<featureCount_; ++k) |
3795 | + splitColumns[k] = k; |
3796 | + min_gini_.resize(featureCount_); |
3797 | + min_indices_.resize(featureCount_); |
3798 | + min_thresholds_.resize(featureCount_); |
3799 | + } |
3800 | + |
3801 | + |
3802 | + template<class T, class C, class T2, class C2, class Region, class Random> |
3803 | + int findBestSplit(MultiArrayView<2, T, C> features, |
3804 | + MultiArrayView<2, T2, C2> labels, |
3805 | + Region & region, |
3806 | + ArrayVector<Region>& childRegions, |
3807 | + Random & randint) |
3808 | + { |
3809 | + |
3810 | + typedef typename Region::IndexIterator IndexIterator; |
3811 | + if(region.size() == 0) |
3812 | + { |
3813 | + std::cerr << "SplitFunctor::findBestSplit(): stackentry with 0 examples encountered\n" |
3814 | + "continuing learning process...."; |
3815 | + } |
3816 | + // calculate things that haven't been calculated yet. |
3817 | + |
3818 | + if(std::accumulate(region.classCounts().begin(), |
3819 | + region.classCounts().end(), 0) != region.size()) |
3820 | + { |
3821 | + RandomForestClassCounter< MultiArrayView<2,T2, C2>, |
3822 | + ArrayVector<double> > |
3823 | + counter(labels, region.classCounts()); |
3824 | + std::for_each( region.begin(), region.end(), counter); |
3825 | + region.classCountsIsValid = true; |
3826 | + } |
3827 | + |
3828 | + // Is the region pure already? |
3829 | + region_gini_ = bgfunc.loss_of_region(labels, |
3830 | + region.begin(), |
3831 | + region.end(), |
3832 | + region.classCounts()); |
3833 | + if(region_gini_ <= SB::ext_param_.precision_) |
3834 | + return makeTerminalNode(features, labels, region, randint); |
3835 | + |
3836 | + // select columns to be tried. |
3837 | + for(int ii = 0; ii < SB::ext_param_.actual_mtry_; ++ii) |
3838 | + std::swap(splitColumns[ii], |
3839 | + splitColumns[ii+ randint(features.shape(1) - ii)]); |
3840 | + |
3841 | + // find the best gini index |
3842 | + bestSplitIndex = 0; |
3843 | + double current_min_gini = region_gini_; |
3844 | + int num2try = features.shape(1); |
3845 | + for(int k=0; k<num2try; ++k) |
3846 | + { |
3847 | + //this functor does all the work |
3848 | + bgfunc(features, |
3849 | + splitColumns[k], |
3850 | + labels, |
3851 | + region.begin(), region.end(), |
3852 | + region.classCounts()); |
3853 | + min_gini_[k] = bgfunc.min_gini_; |
3854 | + min_indices_[k] = bgfunc.min_index_; |
3855 | + min_thresholds_[k] = bgfunc.min_threshold_; |
3856 | +#ifdef CLASSIFIER_TEST |
3857 | + if( bgfunc.min_gini_ < current_min_gini |
3858 | + && !closeAtTolerance(bgfunc.min_gini_, current_min_gini)) |
3859 | +#else |
3860 | + if(bgfunc.min_gini_ < current_min_gini) |
3861 | +#endif |
3862 | + { |
3863 | + current_min_gini = bgfunc.min_gini_; |
3864 | + childRegions[0].classCounts() = bgfunc.bestCurrentCounts[0]; |
3865 | + childRegions[1].classCounts() = bgfunc.bestCurrentCounts[1]; |
3866 | + childRegions[0].classCountsIsValid = true; |
3867 | + childRegions[1].classCountsIsValid = true; |
3868 | + |
3869 | + bestSplitIndex = k; |
3870 | + num2try = SB::ext_param_.actual_mtry_; |
3871 | + } |
3872 | + } |
3873 | + |
3874 | + // did not find any suitable split |
3875 | + if(closeAtTolerance(current_min_gini, region_gini_)) |
3876 | + return makeTerminalNode(features, labels, region, randint); |
3877 | + |
3878 | + //create a Node for output |
3879 | + Node<i_ThresholdNode> node(SB::t_data, SB::p_data); |
3880 | + SB::node_ = node; |
3881 | + node.threshold() = min_thresholds_[bestSplitIndex]; |
3882 | + node.column() = splitColumns[bestSplitIndex]; |
3883 | + |
3884 | + // partition the range according to the best dimension |
3885 | + SortSamplesByDimensions<MultiArrayView<2, T, C> > |
3886 | + sorter(features, node.column(), node.threshold()); |
3887 | + IndexIterator bestSplit = |
3888 | + std::partition(region.begin(), region.end(), sorter); |
3889 | + // Save the ranges of the child stack entries. |
3890 | + childRegions[0].setRange( region.begin() , bestSplit ); |
3891 | + childRegions[0].rule = region.rule; |
3892 | + childRegions[0].rule.push_back(std::make_pair(1, 1.0)); |
3893 | + childRegions[1].setRange( bestSplit , region.end() ); |
3894 | + childRegions[1].rule = region.rule; |
3895 | + childRegions[1].rule.push_back(std::make_pair(1, 1.0)); |
3896 | + |
3897 | + return i_ThresholdNode; |
3898 | + } |
3899 | +}; |
3900 | + |
3901 | +typedef ThresholdSplit<BestGiniOfColumn<GiniCriterion> > GiniSplit; |
3902 | +typedef ThresholdSplit<BestGiniOfColumn<EntropyCriterion> > EntropySplit; |
3903 | +typedef ThresholdSplit<BestGiniOfColumn<LSQLoss>, RegressionTag> RegressionSplit; |
3904 | + |
3905 | +namespace rf |
3906 | +{ |
3907 | + |
3908 | +/** This namespace contains additional Splitfunctors. |
3909 | + * |
3910 | + * The Split functor classes are designed in a modular fashion because new split functors may |
3911 | + * share a lot of code with existing ones. |
3912 | + * |
3913 | + * ThresholdSplit implements the functionality needed for any split functor, that makes its |
3914 | + * decision via one dimensional axis-parallel cuts. The Template parameter defines how the split |
3915 | + * along one dimension is chosen. |
3916 | + * |
3917 | + * The BestGiniOfColumn class chooses a split that minimizes one of the Loss functions supplied |
3918 | + * (GiniCriterion for classification and LSQLoss for regression). Median chooses the Split in a |
3919 | + * kD tree fashion. |
3920 | + * |
3921 | + * |
3922 | + * Currently defined typedefs: |
3923 | + * \code |
3924 | + * typedef ThresholdSplit<BestGiniOfColumn<GiniCriterion> > GiniSplit; |
3925 | + * typedef ThresholdSplit<BestGiniOfColumn<LSQLoss>, RegressionTag> RegressionSplit; |
3926 | + * typedef ThresholdSplit<Median> MedianSplit; |
3927 | + * \endcode |
3928 | + */ |
3929 | +namespace split |
3930 | +{ |
3931 | + |
3932 | +/** This Functor chooses the median value of a column |
3933 | + */ |
3934 | +class Median |
3935 | +{ |
3936 | +public: |
3937 | + |
3938 | + typedef GiniCriterion LineSearchLossTag; |
3939 | + ArrayVector<double> class_weights_; |
3940 | + ArrayVector<double> bestCurrentCounts[2]; |
3941 | + double min_gini_; |
3942 | + ptrdiff_t min_index_; |
3943 | + double min_threshold_; |
3944 | + ProblemSpec<> ext_param_; |
3945 | + |
3946 | + Median() |
3947 | + {} |
3948 | + |
3949 | + template<class T> |
3950 | + Median(ProblemSpec<T> const & ext) |
3951 | + : |
3952 | + class_weights_(ext.class_weights_), |
3953 | + ext_param_(ext) |
3954 | + { |
3955 | + bestCurrentCounts[0].resize(ext.class_count_); |
3956 | + bestCurrentCounts[1].resize(ext.class_count_); |
3957 | + } |
3958 | + |
3959 | + template<class T> |
3960 | + void set_external_parameters(ProblemSpec<T> const & ext) |
3961 | + { |
3962 | + class_weights_ = ext.class_weights_; |
3963 | + ext_param_ = ext; |
3964 | + bestCurrentCounts[0].resize(ext.class_count_); |
3965 | + bestCurrentCounts[1].resize(ext.class_count_); |
3966 | + } |
3967 | + |
3968 | + template< class DataSourceF_t, |
3969 | + class DataSource_t, |
3970 | + class I_Iter, |
3971 | + class Array> |
3972 | + void operator()(DataSourceF_t const & column, |
3973 | + DataSource_t const & labels, |
3974 | + I_Iter & begin, |
3975 | + I_Iter & end, |
3976 | + Array const & region_response) |
3977 | + { |
3978 | + std::sort(begin, end, |
3979 | + SortSamplesByDimensions<DataSourceF_t>(column, 0)); |
3980 | + typedef typename |
3981 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
3982 | + LineSearchLoss left(labels, ext_param_); |
3983 | + LineSearchLoss right(labels, ext_param_); |
3984 | + right.init(begin, end, region_response); |
3985 | + |
3986 | + min_gini_ = NumericTraits<double>::max(); |
3987 | + min_index_ = floor(double(end - begin)/2.0); |
3988 | + min_threshold_ = column[*(begin + min_index_)]; |
3989 | + SortSamplesByDimensions<DataSourceF_t> |
3990 | + sorter(column, 0, min_threshold_); |
3991 | + I_Iter part = std::partition(begin, end, sorter); |
3992 | + DimensionNotEqual<DataSourceF_t> comp(column, 0); |
3993 | + if(part == begin) |
3994 | + { |
3995 | + part= std::adjacent_find(part, end, comp)+1; |
3996 | + |
3997 | + } |
3998 | + if(part >= end) |
3999 | + { |
4000 | + return; |
4001 | + } |
4002 | + else |
4003 | + { |
4004 | + min_threshold_ = column[*part]; |
4005 | + } |
4006 | + min_gini_ = right.decrement(begin, part) |
4007 | + + left.increment(begin , part); |
4008 | + |
4009 | + bestCurrentCounts[0] = left.response(); |
4010 | + bestCurrentCounts[1] = right.response(); |
4011 | + |
4012 | + min_index_ = part - begin; |
4013 | + } |
4014 | + |
4015 | + template<class DataSource_t, class Iter, class Array> |
4016 | + double loss_of_region(DataSource_t const & labels, |
4017 | + Iter & begin, |
4018 | + Iter & end, |
4019 | + Array const & region_response) const |
4020 | + { |
4021 | + typedef typename |
4022 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
4023 | + LineSearchLoss region_loss(labels, ext_param_); |
4024 | + return |
4025 | + region_loss.init(begin, end, region_response); |
4026 | + } |
4027 | + |
4028 | +}; |
4029 | + |
4030 | +typedef ThresholdSplit<Median> MedianSplit; |
4031 | + |
4032 | + |
4033 | +/** This Functor chooses a random value of a column |
4034 | + */ |
4035 | +class RandomSplitOfColumn |
4036 | +{ |
4037 | +public: |
4038 | + |
4039 | + typedef GiniCriterion LineSearchLossTag; |
4040 | + ArrayVector<double> class_weights_; |
4041 | + ArrayVector<double> bestCurrentCounts[2]; |
4042 | + double min_gini_; |
4043 | + ptrdiff_t min_index_; |
4044 | + double min_threshold_; |
4045 | + ProblemSpec<> ext_param_; |
4046 | + typedef RandomMT19937 Random_t; |
4047 | + Random_t random; |
4048 | + |
4049 | + RandomSplitOfColumn() |
4050 | + {} |
4051 | + |
4052 | + template<class T> |
4053 | + RandomSplitOfColumn(ProblemSpec<T> const & ext) |
4054 | + : |
4055 | + class_weights_(ext.class_weights_), |
4056 | + ext_param_(ext), |
4057 | + random(RandomSeed) |
4058 | + { |
4059 | + bestCurrentCounts[0].resize(ext.class_count_); |
4060 | + bestCurrentCounts[1].resize(ext.class_count_); |
4061 | + } |
4062 | + |
4063 | + template<class T> |
4064 | + RandomSplitOfColumn(ProblemSpec<T> const & ext, Random_t & random_) |
4065 | + : |
4066 | + class_weights_(ext.class_weights_), |
4067 | + ext_param_(ext), |
4068 | + random(random_) |
4069 | + { |
4070 | + bestCurrentCounts[0].resize(ext.class_count_); |
4071 | + bestCurrentCounts[1].resize(ext.class_count_); |
4072 | + } |
4073 | + |
4074 | + template<class T> |
4075 | + void set_external_parameters(ProblemSpec<T> const & ext) |
4076 | + { |
4077 | + class_weights_ = ext.class_weights_; |
4078 | + ext_param_ = ext; |
4079 | + bestCurrentCounts[0].resize(ext.class_count_); |
4080 | + bestCurrentCounts[1].resize(ext.class_count_); |
4081 | + } |
4082 | + |
4083 | + template< class DataSourceF_t, |
4084 | + class DataSource_t, |
4085 | + class I_Iter, |
4086 | + class Array> |
4087 | + void operator()(DataSourceF_t const & column, |
4088 | + DataSource_t const & labels, |
4089 | + I_Iter & begin, |
4090 | + I_Iter & end, |
4091 | + Array const & region_response) |
4092 | + { |
4093 | + std::sort(begin, end, |
4094 | + SortSamplesByDimensions<DataSourceF_t>(column, 0)); |
4095 | + typedef typename |
4096 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
4097 | + LineSearchLoss left(labels, ext_param_); |
4098 | + LineSearchLoss right(labels, ext_param_); |
4099 | + right.init(begin, end, region_response); |
4100 | + |
4101 | + |
4102 | + min_gini_ = NumericTraits<double>::max(); |
4103 | + |
4104 | + min_index_ = begin + random.uniformInt(end -begin); |
4105 | + min_threshold_ = column[*(begin + min_index_)]; |
4106 | + SortSamplesByDimensions<DataSourceF_t> |
4107 | + sorter(column, 0, min_threshold_); |
4108 | + I_Iter part = std::partition(begin, end, sorter); |
4109 | + DimensionNotEqual<DataSourceF_t> comp(column, 0); |
4110 | + if(part == begin) |
4111 | + { |
4112 | + part= std::adjacent_find(part, end, comp)+1; |
4113 | + |
4114 | + } |
4115 | + if(part >= end) |
4116 | + { |
4117 | + return; |
4118 | + } |
4119 | + else |
4120 | + { |
4121 | + min_threshold_ = column[*part]; |
4122 | + } |
4123 | + min_gini_ = right.decrement(begin, part) |
4124 | + + left.increment(begin , part); |
4125 | + |
4126 | + bestCurrentCounts[0] = left.response(); |
4127 | + bestCurrentCounts[1] = right.response(); |
4128 | + |
4129 | + min_index_ = part - begin; |
4130 | + } |
4131 | + |
4132 | + template<class DataSource_t, class Iter, class Array> |
4133 | + double loss_of_region(DataSource_t const & labels, |
4134 | + Iter & begin, |
4135 | + Iter & end, |
4136 | + Array const & region_response) const |
4137 | + { |
4138 | + typedef typename |
4139 | + LossTraits<LineSearchLossTag, DataSource_t>::type LineSearchLoss; |
4140 | + LineSearchLoss region_loss(labels, ext_param_); |
4141 | + return |
4142 | + region_loss.init(begin, end, region_response); |
4143 | + } |
4144 | + |
4145 | +}; |
4146 | + |
4147 | +typedef ThresholdSplit<RandomSplitOfColumn> RandomSplit; |
4148 | +} |
4149 | +} |
4150 | + |
4151 | + |
4152 | +} //namespace vigra |
4153 | +#endif // VIGRA_RANDOM_FOREST_SPLIT_HXX |
4154 | |
4155 | === removed directory '.pc/sizeof_ldbl_not_sizeof_dbl.diff' |
4156 | === removed directory '.pc/sizeof_ldbl_not_sizeof_dbl.diff/include' |
4157 | === removed directory '.pc/sizeof_ldbl_not_sizeof_dbl.diff/include/vigra' |
4158 | === removed file '.pc/sizeof_ldbl_not_sizeof_dbl.diff/include/vigra/numpy_array.hxx' |
4159 | --- .pc/sizeof_ldbl_not_sizeof_dbl.diff/include/vigra/numpy_array.hxx 2011-11-08 19:31:51 +0000 |
4160 | +++ .pc/sizeof_ldbl_not_sizeof_dbl.diff/include/vigra/numpy_array.hxx 1970-01-01 00:00:00 +0000 |
4161 | @@ -1,1918 +0,0 @@ |
4162 | -/************************************************************************/ |
4163 | -/* */ |
4164 | -/* Copyright 2009 by Ullrich Koethe and Hans Meine */ |
4165 | -/* */ |
4166 | -/* This file is part of the VIGRA computer vision library. */ |
4167 | -/* The VIGRA Website is */ |
4168 | -/* http://hci.iwr.uni-heidelberg.de/vigra/ */ |
4169 | -/* Please direct questions, bug reports, and contributions to */ |
4170 | -/* ullrich.koethe@iwr.uni-heidelberg.de or */ |
4171 | -/* vigra@informatik.uni-hamburg.de */ |
4172 | -/* */ |
4173 | -/* Permission is hereby granted, free of charge, to any person */ |
4174 | -/* obtaining a copy of this software and associated documentation */ |
4175 | -/* files (the "Software"), to deal in the Software without */ |
4176 | -/* restriction, including without limitation the rights to use, */ |
4177 | -/* copy, modify, merge, publish, distribute, sublicense, and/or */ |
4178 | -/* sell copies of the Software, and to permit persons to whom the */ |
4179 | -/* Software is furnished to do so, subject to the following */ |
4180 | -/* conditions: */ |
4181 | -/* */ |
4182 | -/* The above copyright notice and this permission notice shall be */ |
4183 | -/* included in all copies or substantial portions of the */ |
4184 | -/* Software. */ |
4185 | -/* */ |
4186 | -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ |
4187 | -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ |
4188 | -/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ |
4189 | -/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ |
4190 | -/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ |
4191 | -/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ |
4192 | -/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ |
4193 | -/* OTHER DEALINGS IN THE SOFTWARE. */ |
4194 | -/* */ |
4195 | -/************************************************************************/ |
4196 | - |
4197 | -#ifndef VIGRA_NUMPY_ARRAY_HXX |
4198 | -#define VIGRA_NUMPY_ARRAY_HXX |
4199 | - |
4200 | -#include <Python.h> |
4201 | -#include <iostream> |
4202 | -#include <algorithm> |
4203 | -#include <complex> |
4204 | -#include <string> |
4205 | -#include <sstream> |
4206 | -#include <map> |
4207 | -#include <vigra/multi_array.hxx> |
4208 | -#include <vigra/array_vector.hxx> |
4209 | -#include <vigra/sized_int.hxx> |
4210 | -#include <vigra/python_utility.hxx> |
4211 | -#include <numpy/arrayobject.h> |
4212 | - |
4213 | -int _import_array(); |
4214 | - |
4215 | -namespace vigra { |
4216 | - |
4217 | -/********************************************************/ |
4218 | -/* */ |
4219 | -/* Singleband and Multiband */ |
4220 | -/* */ |
4221 | -/********************************************************/ |
4222 | - |
4223 | -typedef float NumpyValueType; |
4224 | - |
4225 | -template <class T> |
4226 | -struct Singleband // the last array dimension is not to be interpreted as a channel dimension |
4227 | -{ |
4228 | - typedef T value_type; |
4229 | -}; |
4230 | - |
4231 | -template <class T> |
4232 | -struct Multiband // the last array dimension is a channel dimension |
4233 | -{ |
4234 | - typedef T value_type; |
4235 | -}; |
4236 | - |
4237 | -template<class T> |
4238 | -struct NumericTraits<Singleband<T> > |
4239 | -: public NumericTraits<T> |
4240 | -{}; |
4241 | - |
4242 | -template<class T> |
4243 | -struct NumericTraits<Multiband<T> > |
4244 | -{ |
4245 | - typedef Multiband<T> Type; |
4246 | -/* |
4247 | - typedef int Promote; |
4248 | - typedef unsigned int UnsignedPromote; |
4249 | - typedef double RealPromote; |
4250 | - typedef std::complex<RealPromote> ComplexPromote; |
4251 | -*/ |
4252 | - typedef Type ValueType; |
4253 | - |
4254 | - typedef typename NumericTraits<T>::isIntegral isIntegral; |
4255 | - typedef VigraFalseType isScalar; |
4256 | - typedef typename NumericTraits<T>::isSigned isSigned; |
4257 | - typedef typename NumericTraits<T>::isSigned isOrdered; |
4258 | - typedef typename NumericTraits<T>::isSigned isComplex; |
4259 | -/* |
4260 | - static signed char zero() { return 0; } |
4261 | - static signed char one() { return 1; } |
4262 | - static signed char nonZero() { return 1; } |
4263 | - static signed char min() { return SCHAR_MIN; } |
4264 | - static signed char max() { return SCHAR_MAX; } |
4265 | - |
4266 | -#ifdef NO_INLINE_STATIC_CONST_DEFINITION |
4267 | - enum { minConst = SCHAR_MIN, maxConst = SCHAR_MIN }; |
4268 | -#else |
4269 | - static const signed char minConst = SCHAR_MIN; |
4270 | - static const signed char maxConst = SCHAR_MIN; |
4271 | -#endif |
4272 | - |
4273 | - static Promote toPromote(signed char v) { return v; } |
4274 | - static RealPromote toRealPromote(signed char v) { return v; } |
4275 | - static signed char fromPromote(Promote v) { |
4276 | - return ((v < SCHAR_MIN) ? SCHAR_MIN : (v > SCHAR_MAX) ? SCHAR_MAX : v); |
4277 | - } |
4278 | - static signed char fromRealPromote(RealPromote v) { |
4279 | - return ((v < 0.0) |
4280 | - ? ((v < (RealPromote)SCHAR_MIN) |
4281 | - ? SCHAR_MIN |
4282 | - : static_cast<signed char>(v - 0.5)) |
4283 | - : (v > (RealPromote)SCHAR_MAX) |
4284 | - ? SCHAR_MAX |
4285 | - : static_cast<signed char>(v + 0.5)); |
4286 | - } |
4287 | -*/ |
4288 | -}; |
4289 | - |
4290 | -template <class T> |
4291 | -class MultibandVectorAccessor |
4292 | -{ |
4293 | - MultiArrayIndex size_, stride_; |
4294 | - |
4295 | - public: |
4296 | - MultibandVectorAccessor(MultiArrayIndex size, MultiArrayIndex stride) |
4297 | - : size_(size), |
4298 | - stride_(stride) |
4299 | - {} |
4300 | - |
4301 | - |
4302 | - typedef Multiband<T> value_type; |
4303 | - |
4304 | - /** the vector's value_type |
4305 | - */ |
4306 | - typedef T component_type; |
4307 | - |
4308 | - typedef VectorElementAccessor<MultibandVectorAccessor<T> > ElementAccessor; |
4309 | - |
4310 | - /** Read the component data at given vector index |
4311 | - at given iterator position |
4312 | - */ |
4313 | - template <class ITERATOR> |
4314 | - component_type const & getComponent(ITERATOR const & i, int idx) const |
4315 | - { |
4316 | - return *(&*i+idx*stride_); |
4317 | - } |
4318 | - |
4319 | - /** Set the component data at given vector index |
4320 | - at given iterator position. The type <TT>V</TT> of the passed |
4321 | - in <TT>value</TT> is automatically converted to <TT>component_type</TT>. |
4322 | - In case of a conversion floating point -> intergral this includes rounding and clipping. |
4323 | - */ |
4324 | - template <class V, class ITERATOR> |
4325 | - void setComponent(V const & value, ITERATOR const & i, int idx) const |
4326 | - { |
4327 | - *(&*i+idx*stride_) = detail::RequiresExplicitCast<component_type>::cast(value); |
4328 | - } |
4329 | - |
4330 | - /** Read the component data at given vector index |
4331 | - at an offset of given iterator position |
4332 | - */ |
4333 | - template <class ITERATOR, class DIFFERENCE> |
4334 | - component_type const & getComponent(ITERATOR const & i, DIFFERENCE const & diff, int idx) const |
4335 | - { |
4336 | - return *(&i[diff]+idx*stride_); |
4337 | - } |
4338 | - |
4339 | - /** Set the component data at given vector index |
4340 | - at an offset of given iterator position. The type <TT>V</TT> of the passed |
4341 | - in <TT>value</TT> is automatically converted to <TT>component_type</TT>. |
4342 | - In case of a conversion floating point -> intergral this includes rounding and clipping. |
4343 | - */ |
4344 | - template <class V, class ITERATOR, class DIFFERENCE> |
4345 | - void |
4346 | - setComponent(V const & value, ITERATOR const & i, DIFFERENCE const & diff, int idx) const |
4347 | - { |
4348 | - *(&i[diff]+idx*stride_) = detail::RequiresExplicitCast<component_type>::cast(value); |
4349 | - } |
4350 | - |
4351 | - template <class U> |
4352 | - MultiArrayIndex size(U) const |
4353 | - { |
4354 | - return size_; |
4355 | - } |
4356 | -}; |
4357 | - |
4358 | -/********************************************************/ |
4359 | -/* */ |
4360 | -/* a few Python utilities */ |
4361 | -/* */ |
4362 | -/********************************************************/ |
4363 | - |
4364 | -namespace detail { |
4365 | - |
4366 | -inline long spatialDimensions(PyObject * obj) |
4367 | -{ |
4368 | - static python_ptr key(PyString_FromString("spatialDimensions"), python_ptr::keep_count); |
4369 | - python_ptr pres(PyObject_GetAttr(obj, key), python_ptr::keep_count); |
4370 | - long res = pres && PyInt_Check(pres) |
4371 | - ? PyInt_AsLong(pres) |
4372 | - : -1; |
4373 | - return res; |
4374 | -} |
4375 | - |
4376 | -/* |
4377 | - * The registry is used to optionally map specific C++ types to |
4378 | - * specific python sub-classes of numpy.ndarray (for example, |
4379 | - * MultiArray<2, Singleband<int> > to a user-defined Python class 'ScalarImage'). |
4380 | - * |
4381 | - * One needs to use NUMPY_ARRAY_INITIALIZE_REGISTRY once in a python |
4382 | - * extension module using this technique, in order to actually provide |
4383 | - * the registry (this is done by vigranumpycmodule and will then be |
4384 | - * available for other modules, too). Alternatively, |
4385 | - * NUMPY_ARRAY_DUMMY_REGISTRY may be used to disable this feature |
4386 | - * completely. In both cases, the macro must not be enclosed by any |
4387 | - * namespace, so it is best put right at the beginning of the file |
4388 | - * (e.g. below the #includes). |
4389 | - */ |
4390 | - |
4391 | -typedef std::map<std::string, std::pair<python_ptr, python_ptr> > ArrayTypeMap; |
4392 | - |
4393 | -VIGRA_EXPORT ArrayTypeMap * getArrayTypeMap(); |
4394 | - |
4395 | -#define NUMPY_ARRAY_INITIALIZE_REGISTRY \ |
4396 | - namespace vigra { namespace detail { \ |
4397 | - ArrayTypeMap * getArrayTypeMap() \ |
4398 | - { \ |
4399 | - static ArrayTypeMap arrayTypeMap; \ |
4400 | - return &arrayTypeMap; \ |
4401 | - } \ |
4402 | - }} // namespace vigra::detail |
4403 | - |
4404 | -#define NUMPY_ARRAY_DUMMY_REGISTRY \ |
4405 | - namespace vigra { namespace detail { \ |
4406 | - ArrayTypeMap * getArrayTypeMap() \ |
4407 | - { \ |
4408 | - return NULL; \ |
4409 | - } \ |
4410 | - }} // namespace vigra::detail |
4411 | - |
4412 | -inline |
4413 | -void registerPythonArrayType(std::string const & name, PyObject * obj, PyObject * typecheck) |
4414 | -{ |
4415 | - ArrayTypeMap *types = getArrayTypeMap(); |
4416 | - vigra_precondition( |
4417 | - types != NULL, |
4418 | - "registerPythonArrayType(): module was compiled without array type registry."); |
4419 | - vigra_precondition( |
4420 | - obj && PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, &PyArray_Type), |
4421 | - "registerPythonArrayType(obj): obj is not a subtype of numpy.ndarray."); |
4422 | - if(typecheck && PyCallable_Check(typecheck)) |
4423 | - (*types)[name] = std::make_pair(python_ptr(obj), python_ptr(typecheck)); |
4424 | - else |
4425 | - (*types)[name] = std::make_pair(python_ptr(obj), python_ptr()); |
4426 | -// std::cerr << "Registering " << ((PyTypeObject *)obj)->tp_name << " for " << name << "\n"; |
4427 | -} |
4428 | - |
4429 | -inline |
4430 | -python_ptr getArrayTypeObject(std::string const & name, PyTypeObject * def = 0) |
4431 | -{ |
4432 | - ArrayTypeMap *types = getArrayTypeMap(); |
4433 | - if(!types) |
4434 | - // dummy registry -> handle like empty registry |
4435 | - return python_ptr((PyObject *)def); |
4436 | - |
4437 | - python_ptr res; |
4438 | - ArrayTypeMap::iterator i = types->find(name); |
4439 | - if(i != types->end()) |
4440 | - res = i->second.first; |
4441 | - else |
4442 | - res = python_ptr((PyObject *)def); |
4443 | -// std::cerr << "Requested " << name << ", got " << ((PyTypeObject *)res.get())->tp_name << "\n"; |
4444 | - return res; |
4445 | -} |
4446 | - |
4447 | -// there are two cases for the return: |
4448 | -// * if a typecheck function was registered, it is returned |
4449 | -// * a null pointer is returned if nothing was registered for either key, or if |
4450 | -// a type was registered without typecheck function |
4451 | -inline python_ptr |
4452 | -getArrayTypecheckFunction(std::string const & keyFull, std::string const & key) |
4453 | -{ |
4454 | - python_ptr res; |
4455 | - ArrayTypeMap *types = getArrayTypeMap(); |
4456 | - if(types) |
4457 | - { |
4458 | - ArrayTypeMap::iterator i = types->find(keyFull); |
4459 | - if(i == types->end()) |
4460 | - i = types->find(key); |
4461 | - if(i != types->end()) |
4462 | - res = i->second.second; |
4463 | - } |
4464 | - return res; |
4465 | -} |
4466 | - |
4467 | -inline bool |
4468 | -performCustomizedArrayTypecheck(PyObject * obj, std::string const & keyFull, std::string const & key) |
4469 | -{ |
4470 | - if(obj == 0 || !PyArray_Check(obj)) |
4471 | - return false; |
4472 | - python_ptr typecheck = getArrayTypecheckFunction(keyFull, key); |
4473 | - if(typecheck == 0) |
4474 | - return true; // no custom test registered |
4475 | - python_ptr args(PyTuple_Pack(1, obj), python_ptr::keep_count); |
4476 | - pythonToCppException(args); |
4477 | - python_ptr res(PyObject_Call(typecheck.get(), args.get(), 0), python_ptr::keep_count); |
4478 | - pythonToCppException(res); |
4479 | - vigra_precondition(PyBool_Check(res), |
4480 | - "NumpyArray conversion: registered typecheck function did not return a boolean."); |
4481 | - return (void*)res.get() == (void*)Py_True; |
4482 | -} |
4483 | - |
4484 | -inline |
4485 | -python_ptr constructNumpyArrayImpl( |
4486 | - PyTypeObject * type, |
4487 | - ArrayVector<npy_intp> const & shape, npy_intp *strides, |
4488 | - NPY_TYPES typeCode, bool init) |
4489 | -{ |
4490 | - python_ptr array; |
4491 | - |
4492 | - if(strides == 0) |
4493 | - { |
4494 | - array = python_ptr(PyArray_New(type, shape.size(), (npy_intp *)shape.begin(), typeCode, 0, 0, 0, 1 /* Fortran order */, 0), |
4495 | - python_ptr::keep_count); |
4496 | - } |
4497 | - else |
4498 | - { |
4499 | - int N = shape.size(); |
4500 | - ArrayVector<npy_intp> pshape(N); |
4501 | - for(int k=0; k<N; ++k) |
4502 | - pshape[strides[k]] = shape[k]; |
4503 | - |
4504 | - array = python_ptr(PyArray_New(type, N, pshape.begin(), typeCode, 0, 0, 0, 1 /* Fortran order */, 0), |
4505 | - python_ptr::keep_count); |
4506 | - pythonToCppException(array); |
4507 | - |
4508 | - PyArray_Dims permute = { strides, N }; |
4509 | - array = python_ptr(PyArray_Transpose((PyArrayObject*)array.get(), &permute), python_ptr::keep_count); |
4510 | - } |
4511 | - pythonToCppException(array); |
4512 | - |
4513 | - if(init) |
4514 | - PyArray_FILLWBYTE((PyArrayObject *)array.get(), 0); |
4515 | - |
4516 | - return array; |
4517 | -} |
4518 | - |
4519 | -// strideOrdering will be ignored unless order == "A" |
4520 | -// TODO: this function should receive some refactoring in order to make |
4521 | -// the rules clear from the code rather than from comments |
4522 | -inline python_ptr |
4523 | -constructNumpyArrayImpl(PyTypeObject * type, ArrayVector<npy_intp> const & shape, |
4524 | - unsigned int spatialDimensions, unsigned int channels, |
4525 | - NPY_TYPES typeCode, std::string order, bool init, |
4526 | - ArrayVector<npy_intp> strideOrdering = ArrayVector<npy_intp>()) |
4527 | -{ |
4528 | - // shape must have at least length spatialDimensions, but can also have a channel dimension |
4529 | - vigra_precondition(shape.size() == spatialDimensions || shape.size() == spatialDimensions + 1, |
4530 | - "constructNumpyArray(type, shape, ...): shape has wrong length."); |
4531 | - |
4532 | - // if strideOrdering is given, it must have at least length spatialDimensions, |
4533 | - // but can also have a channel dimension |
4534 | - vigra_precondition(strideOrdering.size() == 0 || strideOrdering.size() == spatialDimensions || |
4535 | - strideOrdering.size() == spatialDimensions + 1, |
4536 | - "constructNumpyArray(type, ..., strideOrdering): strideOrdering has wrong length."); |
4537 | - |
4538 | - if(channels == 0) // if the requested number of channels is not given ... |
4539 | - { |
4540 | - // ... deduce it |
4541 | - if(shape.size() == spatialDimensions) |
4542 | - channels = 1; |
4543 | - else |
4544 | - channels = shape.back(); |
4545 | - } |
4546 | - else |
4547 | - { |
4548 | - // otherwise, if the shape object also contains a channel dimension, they must be consistent |
4549 | - if(shape.size() > spatialDimensions) |
4550 | - vigra_precondition(channels == (unsigned int)shape[spatialDimensions], |
4551 | - "constructNumpyArray(type, ...): shape contradicts requested number of channels."); |
4552 | - } |
4553 | - |
4554 | - // if we have only one channel, no explicit channel dimension should be in the shape |
4555 | - unsigned int shapeSize = channels == 1 |
4556 | - ? spatialDimensions |
4557 | - : spatialDimensions + 1; |
4558 | - |
4559 | - // create the shape object with optional channel dimension |
4560 | - ArrayVector<npy_intp> pshape(shapeSize); |
4561 | - std::copy(shape.begin(), shape.begin()+std::min(shape.size(), pshape.size()), pshape.begin()); |
4562 | - if(shapeSize > spatialDimensions) |
4563 | - pshape[spatialDimensions] = channels; |
4564 | - |
4565 | - // order "A" means "preserve order" when an array is copied, and |
4566 | - // defaults to "V" when a new array is created without explicit strideOrdering |
4567 | - // |
4568 | - if(order == "A") |
4569 | - { |
4570 | - if(strideOrdering.size() == 0) |
4571 | - { |
4572 | - order = "V"; |
4573 | - } |
4574 | - else if(strideOrdering.size() > shapeSize) |
4575 | - { |
4576 | - // make sure that strideOrdering length matches shape length |
4577 | - ArrayVector<npy_intp> pstride(strideOrdering.begin(), strideOrdering.begin()+shapeSize); |
4578 | - |
4579 | - // adjust the ordering when the channel dimension has been dropped because channel == 1 |
4580 | - if(strideOrdering[shapeSize] == 0) |
4581 | - for(unsigned int k=0; k<shapeSize; ++k) |
4582 | - pstride[k] -= 1; |
4583 | - pstride.swap(strideOrdering); |
4584 | - } |
4585 | - else if(strideOrdering.size() < shapeSize) |
4586 | - { |
4587 | - // make sure that strideOrdering length matches shape length |
4588 | - ArrayVector<npy_intp> pstride(shapeSize); |
4589 | - |
4590 | - // adjust the ordering when the channel dimension has been dropped because channel == 1 |
4591 | - for(unsigned int k=0; k<shapeSize-1; ++k) |
4592 | - pstride[k] = strideOrdering[k] + 1; |
4593 | - pstride[shapeSize-1] = 0; |
4594 | - pstride.swap(strideOrdering); |
4595 | - } |
4596 | - } |
4597 | - |
4598 | - // create the appropriate strideOrdering objects for the other memory orders |
4599 | - // (when strideOrdering already contained data, it is ignored because order != "A") |
4600 | - if(order == "C") |
4601 | - { |
4602 | - strideOrdering.resize(shapeSize); |
4603 | - for(unsigned int k=0; k<shapeSize; ++k) |
4604 | - strideOrdering[k] = shapeSize-1-k; |
4605 | - } |
4606 | - else if(order == "F" || (order == "V" && channels == 1)) |
4607 | - { |
4608 | - strideOrdering.resize(shapeSize); |
4609 | - for(unsigned int k=0; k<shapeSize; ++k) |
4610 | - strideOrdering[k] = k; |
4611 | - } |
4612 | - else if(order == "V") |
4613 | - { |
4614 | - strideOrdering.resize(shapeSize); |
4615 | - for(unsigned int k=0; k<shapeSize-1; ++k) |
4616 | - strideOrdering[k] = k+1; |
4617 | - strideOrdering[shapeSize-1] = 0; |
4618 | - } |
4619 | - |
4620 | - return constructNumpyArrayImpl(type, pshape, strideOrdering.begin(), typeCode, init); |
4621 | -} |
4622 | - |
4623 | -template <class TINY_VECTOR> |
4624 | -inline |
4625 | -python_ptr constructNumpyArrayFromData( |
4626 | - std::string const & typeKeyFull, |
4627 | - std::string const & typeKey, |
4628 | - TINY_VECTOR const & shape, npy_intp *strides, |
4629 | - NPY_TYPES typeCode, void *data) |
4630 | -{ |
4631 | - ArrayVector<npy_intp> pyShape(shape.begin(), shape.end()); |
4632 | - |
4633 | - python_ptr type = detail::getArrayTypeObject(typeKeyFull); |
4634 | - if(type == 0) |
4635 | - type = detail::getArrayTypeObject(typeKey, &PyArray_Type); |
4636 | - |
4637 | - python_ptr array(PyArray_New((PyTypeObject *)type.ptr(), shape.size(), pyShape.begin(), typeCode, strides, data, 0, NPY_WRITEABLE, 0), |
4638 | - python_ptr::keep_count); |
4639 | - pythonToCppException(array); |
4640 | - |
4641 | - return array; |
4642 | -} |
4643 | - |
4644 | - |
4645 | -} // namespace detail |
4646 | - |
4647 | -/********************************************************/ |
4648 | -/* */ |
4649 | -/* NumpyArrayValuetypeTraits */ |
4650 | -/* */ |
4651 | -/********************************************************/ |
4652 | - |
4653 | -template<class ValueType> |
4654 | -struct ERROR_NumpyArrayValuetypeTraits_not_specialized_for_ { }; |
4655 | - |
4656 | -template<class ValueType> |
4657 | -struct NumpyArrayValuetypeTraits |
4658 | -{ |
4659 | - static bool isValuetypeCompatible(PyArrayObject const * obj) |
4660 | - { |
4661 | - return ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType>(); |
4662 | - } |
4663 | - |
4664 | - static ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType> typeCode; |
4665 | - |
4666 | - static std::string typeName() |
4667 | - { |
4668 | - return std::string("ERROR: NumpyArrayValuetypeTraits not specialized for this case"); |
4669 | - } |
4670 | - |
4671 | - static std::string typeNameImpex() |
4672 | - { |
4673 | - return std::string("ERROR: NumpyArrayValuetypeTraits not specialized for this case"); |
4674 | - } |
4675 | - |
4676 | - static PyObject * typeObject() |
4677 | - { |
4678 | - return (PyObject *)0; |
4679 | - } |
4680 | -}; |
4681 | - |
4682 | -template<class ValueType> |
4683 | -ERROR_NumpyArrayValuetypeTraits_not_specialized_for_<ValueType> NumpyArrayValuetypeTraits<ValueType>::typeCode; |
4684 | - |
4685 | -#define VIGRA_NUMPY_VALUETYPE_TRAITS(type, typeID, numpyTypeName, impexTypeName) \ |
4686 | -template <> \ |
4687 | -struct NumpyArrayValuetypeTraits<type > \ |
4688 | -{ \ |
4689 | - static bool isValuetypeCompatible(PyArrayObject const * obj) /* obj must not be NULL */ \ |
4690 | - { \ |
4691 | - return PyArray_EquivTypenums(typeID, PyArray_DESCR((PyObject *)obj)->type_num) && \ |
4692 | - PyArray_ITEMSIZE((PyObject *)obj) == sizeof(type); \ |
4693 | - } \ |
4694 | - \ |
4695 | - static NPY_TYPES const typeCode = typeID; \ |
4696 | - \ |
4697 | - static std::string typeName() \ |
4698 | - { \ |
4699 | - return #numpyTypeName; \ |
4700 | - } \ |
4701 | - \ |
4702 | - static std::string typeNameImpex() \ |
4703 | - { \ |
4704 | - return impexTypeName; \ |
4705 | - } \ |
4706 | - \ |
4707 | - static PyObject * typeObject() \ |
4708 | - { \ |
4709 | - return PyArray_TypeObjectFromType(typeID); \ |
4710 | - } \ |
4711 | -}; |
4712 | - |
4713 | -VIGRA_NUMPY_VALUETYPE_TRAITS(bool, NPY_BOOL, bool, "UINT8") |
4714 | -VIGRA_NUMPY_VALUETYPE_TRAITS(signed char, NPY_INT8, int8, "INT16") |
4715 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned char, NPY_UINT8, uint8, "UINT8") |
4716 | -VIGRA_NUMPY_VALUETYPE_TRAITS(short, NPY_INT16, int16, "INT16") |
4717 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned short, NPY_UINT16, uint16, "UINT16") |
4718 | - |
4719 | -#if VIGRA_BITSOF_LONG == 32 |
4720 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long, NPY_INT32, int32, "INT32") |
4721 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long, NPY_UINT32, uint32, "UINT32") |
4722 | -#elif VIGRA_BITSOF_LONG == 64 |
4723 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long, NPY_INT64, int64, "DOUBLE") |
4724 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long, NPY_UINT64, uint64, "DOUBLE") |
4725 | -#endif |
4726 | - |
4727 | -#if VIGRA_BITSOF_INT == 32 |
4728 | -VIGRA_NUMPY_VALUETYPE_TRAITS(int, NPY_INT32, int32, "INT32") |
4729 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned int, NPY_UINT32, uint32, "UINT32") |
4730 | -#elif VIGRA_BITSOF_INT == 64 |
4731 | -VIGRA_NUMPY_VALUETYPE_TRAITS(int, NPY_INT64, int64, "DOUBLE") |
4732 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned int, NPY_UINT64, uint64, "DOUBLE") |
4733 | -#endif |
4734 | - |
4735 | -#ifdef PY_LONG_LONG |
4736 | -# if VIGRA_BITSOF_LONG_LONG == 32 |
4737 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long long, NPY_INT32, int32, "INT32") |
4738 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long long, NPY_UINT32, uint32, "UINT32") |
4739 | -# elif VIGRA_BITSOF_LONG_LONG == 64 |
4740 | -VIGRA_NUMPY_VALUETYPE_TRAITS(long long, NPY_INT64, int64, "DOUBLE") |
4741 | -VIGRA_NUMPY_VALUETYPE_TRAITS(unsigned long long, NPY_UINT64, uint64, "DOUBLE") |
4742 | -# endif |
4743 | -#endif |
4744 | - |
4745 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_float32, NPY_FLOAT32, float32, "FLOAT") |
4746 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_float64, NPY_FLOAT64, float64, "DOUBLE") |
4747 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_longdouble, NPY_LONGDOUBLE, longdouble, "") |
4748 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_cfloat, NPY_CFLOAT, complex64, "") |
4749 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_float>, NPY_CFLOAT, complex64, "") |
4750 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_cdouble, NPY_CDOUBLE, complex128, "") |
4751 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_double>, NPY_CDOUBLE, complex128, "") |
4752 | -VIGRA_NUMPY_VALUETYPE_TRAITS(npy_clongdouble, NPY_CLONGDOUBLE, clongdouble, "") |
4753 | -VIGRA_NUMPY_VALUETYPE_TRAITS(std::complex<npy_longdouble>, NPY_CLONGDOUBLE, clongdouble, "") |
4754 | - |
4755 | -#undef VIGRA_NUMPY_VALUETYPE_TRAITS |
4756 | - |
4757 | -/********************************************************/ |
4758 | -/* */ |
4759 | -/* NumpyArrayTraits */ |
4760 | -/* */ |
4761 | -/********************************************************/ |
4762 | - |
4763 | -template <class U, int N> |
4764 | -bool stridesAreAscending(TinyVector<U, N> const & strides) |
4765 | -{ |
4766 | - for(int k=1; k<N; ++k) |
4767 | - if(strides[k] < strides[k-1]) |
4768 | - return false; |
4769 | - return true; |
4770 | -} |
4771 | - |
4772 | -template<unsigned int N, class T, class Stride> |
4773 | -struct NumpyArrayTraits; |
4774 | - |
4775 | -template<unsigned int N, class T> |
4776 | -struct NumpyArrayTraits<N, T, StridedArrayTag> |
4777 | -{ |
4778 | - typedef T dtype; |
4779 | - typedef T value_type; |
4780 | - typedef NumpyArrayValuetypeTraits<T> ValuetypeTraits; |
4781 | - static NPY_TYPES const typeCode = ValuetypeTraits::typeCode; |
4782 | - |
4783 | - enum { spatialDimensions = N, channels = 1 }; |
4784 | - |
4785 | - static bool isArray(PyObject * obj) |
4786 | - { |
4787 | - return obj && PyArray_Check(obj); |
4788 | - } |
4789 | - |
4790 | - static bool isClassCompatible(PyObject * obj) |
4791 | - { |
4792 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
4793 | - } |
4794 | - |
4795 | - static bool isValuetypeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4796 | - { |
4797 | - return ValuetypeTraits::isValuetypeCompatible(obj); |
4798 | - } |
4799 | - |
4800 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4801 | - { |
4802 | - return PyArray_NDIM((PyObject *)obj) == N-1 || |
4803 | - PyArray_NDIM((PyObject *)obj) == N || |
4804 | - (PyArray_NDIM((PyObject *)obj) == N+1 && PyArray_DIM((PyObject *)obj, N) == 1); |
4805 | - } |
4806 | - |
4807 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4808 | - { |
4809 | - return ValuetypeTraits::isValuetypeCompatible(obj) && |
4810 | - isShapeCompatible(obj); |
4811 | - } |
4812 | - |
4813 | - template <class U> |
4814 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
4815 | - T *data, TinyVector<U, N> const & stride) |
4816 | - { |
4817 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
4818 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
4819 | - } |
4820 | - |
4821 | - static std::string typeKey() |
4822 | - { |
4823 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", *>"; |
4824 | - return key; |
4825 | - } |
4826 | - |
4827 | - static std::string typeKeyFull() |
4828 | - { |
4829 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", " + |
4830 | - ValuetypeTraits::typeName() + ", StridedArrayTag>"; |
4831 | - return key; |
4832 | - } |
4833 | -}; |
4834 | - |
4835 | -/********************************************************/ |
4836 | - |
4837 | -template<unsigned int N, class T> |
4838 | -struct NumpyArrayTraits<N, T, UnstridedArrayTag> |
4839 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
4840 | -{ |
4841 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
4842 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
4843 | - |
4844 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4845 | - { |
4846 | - return BaseType::isShapeCompatible(obj) && |
4847 | - PyArray_STRIDES((PyObject *)obj)[0] == PyArray_ITEMSIZE((PyObject *)obj); |
4848 | - } |
4849 | - |
4850 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4851 | - { |
4852 | - return BaseType::isValuetypeCompatible(obj) && |
4853 | - isShapeCompatible(obj); |
4854 | - } |
4855 | - |
4856 | - template <class U> |
4857 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
4858 | - T *data, TinyVector<U, N> const & stride) |
4859 | - { |
4860 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
4861 | - return detail::constructNumpyArrayFromData(typeKeyFull(), BaseType::typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
4862 | - } |
4863 | - |
4864 | - static std::string typeKeyFull() |
4865 | - { |
4866 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", " + |
4867 | - ValuetypeTraits::typeName() + ", UnstridedArrayTag>"; |
4868 | - return key; |
4869 | - } |
4870 | -}; |
4871 | - |
4872 | -/********************************************************/ |
4873 | - |
4874 | -template<unsigned int N, class T> |
4875 | -struct NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> |
4876 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
4877 | -{ |
4878 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
4879 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
4880 | - |
4881 | - static bool isClassCompatible(PyObject * obj) |
4882 | - { |
4883 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
4884 | - } |
4885 | - |
4886 | - template <class U> |
4887 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
4888 | - T *data, TinyVector<U, N> const & stride) |
4889 | - { |
4890 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
4891 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
4892 | - } |
4893 | - |
4894 | - static std::string typeKey() |
4895 | - { |
4896 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<*> >"; |
4897 | - return key; |
4898 | - } |
4899 | - |
4900 | - static std::string typeKeyFull() |
4901 | - { |
4902 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<" + |
4903 | - ValuetypeTraits::typeName() + ">, StridedArrayTag>"; |
4904 | - return key; |
4905 | - } |
4906 | -}; |
4907 | - |
4908 | -/********************************************************/ |
4909 | - |
4910 | -template<unsigned int N, class T> |
4911 | -struct NumpyArrayTraits<N, Singleband<T>, UnstridedArrayTag> |
4912 | -: public NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> |
4913 | -{ |
4914 | - typedef NumpyArrayTraits<N, T, UnstridedArrayTag> UnstridedTraits; |
4915 | - typedef NumpyArrayTraits<N, Singleband<T>, StridedArrayTag> BaseType; |
4916 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
4917 | - |
4918 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4919 | - { |
4920 | - return UnstridedTraits::isShapeCompatible(obj); |
4921 | - } |
4922 | - |
4923 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4924 | - { |
4925 | - return UnstridedTraits::isPropertyCompatible(obj); |
4926 | - } |
4927 | - |
4928 | - template <class U> |
4929 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
4930 | - T *data, TinyVector<U, N> const & stride) |
4931 | - { |
4932 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
4933 | - return detail::constructNumpyArrayFromData(typeKeyFull(), BaseType::typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
4934 | - } |
4935 | - |
4936 | - static std::string typeKeyFull() |
4937 | - { |
4938 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Singleband<" + |
4939 | - ValuetypeTraits::typeName() + ">, UnstridedArrayTag>"; |
4940 | - return key; |
4941 | - } |
4942 | -}; |
4943 | - |
4944 | -/********************************************************/ |
4945 | - |
4946 | -template<unsigned int N, class T> |
4947 | -struct NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> |
4948 | -: public NumpyArrayTraits<N, T, StridedArrayTag> |
4949 | -{ |
4950 | - typedef NumpyArrayTraits<N, T, StridedArrayTag> BaseType; |
4951 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
4952 | - |
4953 | - enum { spatialDimensions = N-1, channels = 0 }; |
4954 | - |
4955 | - static bool isClassCompatible(PyObject * obj) |
4956 | - { |
4957 | - return detail::performCustomizedArrayTypecheck(obj, typeKeyFull(), typeKey()); |
4958 | - } |
4959 | - |
4960 | - static bool isShapeCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4961 | - { |
4962 | - return PyArray_NDIM(obj) == N || PyArray_NDIM(obj) == N-1; |
4963 | - } |
4964 | - |
4965 | - static bool isPropertyCompatible(PyArrayObject * obj) /* obj must not be NULL */ |
4966 | - { |
4967 | - return ValuetypeTraits::isValuetypeCompatible(obj) && |
4968 | - isShapeCompatible(obj); |
4969 | - } |
4970 | - |
4971 | - template <class U> |
4972 | - static python_ptr constructor(TinyVector<U, N> const & shape, |
4973 | - T *data, TinyVector<U, N> const & stride) |
4974 | - { |
4975 | - TinyVector<npy_intp, N> npyStride(stride * sizeof(T)); |
4976 | - return detail::constructNumpyArrayFromData(typeKeyFull(), typeKey(), shape, npyStride.begin(), ValuetypeTraits::typeCode, data); |
4977 | - } |
4978 | - |
4979 | - static std::string typeKey() |
4980 | - { |
4981 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Multiband<*> >"; |
4982 | - return key; |
4983 | - } |
4984 | - |
4985 | - static std::string typeKeyFull() |
4986 | - { |
4987 | - static std::string key = std::string("NumpyArray<") + asString(N) + ", Multiband<" + |
4988 | - ValuetypeTraits::typeName() + ">, StridedArrayTag>"; |
4989 | - return key; |
4990 | - } |
4991 | -}; |
4992 | - |
4993 | -/********************************************************/ |
4994 | - |
4995 | -template<unsigned int N, class T> |
4996 | -struct NumpyArrayTraits<N, Multiband<T>, UnstridedArrayTag> |
4997 | -: public NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> |
4998 | -{ |
4999 | - typedef NumpyArrayTraits<N, Multiband<T>, StridedArrayTag> BaseType; |
5000 | - typedef typename BaseType::ValuetypeTraits ValuetypeTraits; |
On Jun 14, 2012, at 08:30 PM, Dmitrijs Ledkovs wrote:
>Barry, can you please review this package as it has interesting history and
>you were the last one to merge it.
What a mess! Sigh. Just one thing stands out.
=== modified file 'include/ vigra/box. hxx' vigra/box. hxx 2011-02-20 23:21:40 +0000 vigra/box. hxx 2012-06-14 20:29:21 +0000
--- include/
+++ include/
> @@ -388,7 +388,7 @@
> if(r.isEmpty())
> return *this;
> if(isEmpty())
> - return operator=(r);
> + return this->operator=(r);
>
> for(unsigned int i = 0; i < DIMENSION; ++i)
> {
> @@ -421,7 +421,7 @@
> if(isEmpty())
> return *this;
> if(r.isEmpty())
> - return operator=(r);
> + return this->operator=(r);
>
> for(unsigned int i = 0; i < DIMENSION; ++i)
> {
=== modified file 'include/ vigra/random_ forest/ rf_ridge_ split.hxx'
[...]
Why are these being modified in the source tree? Is this just quilt/bzr
artifacts? Does it actually build with these changes? Are they in a quilt
patch?