Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the datatype of an ndarray in C

Tags:

c

numpy

Could anyone tell me how to check the data type of an ndarray that has been passed to C code?

In the concrete example I would like to call a different function if the datatype of the array is float32 or double/float64. So something like

if( Dtype(MyArray) == NPY_FLOAT )
{
   DoSomething_float( MyArray );
}
else
{
   DoSomething_double( MyArray );
}

I already found

PyTypeNum_ISFLOAT(num)
PyDataType_ISFLOAT(descr)
PyArray_ISFLOAT(obj)

In the numpy C API, but I don't understand how to use those. I've already tried to find an instructive example but have found none.

like image 663
Magellan88 Avatar asked Jan 12 '13 15:01

Magellan88


People also ask

How do you find the type of an array?

Well, you can get the element type of the array: Type type = array. GetType(). GetElementType();

What is the datatype of array in C?

Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures.

Which data type array is?

An array type is a user-defined data type consisting of an ordered set of elements of a single data type. An ordinary array type has a defined upper bound on the number of elements and uses the ordinal position as the array index.

What are the 3 types of arrays?

There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.


2 Answers

you are almost there, as you are looking for PyArray_TYPE:

int typ=PyArray_TYPE(MyArray);

switch(typ) {
case NPY_FLOAT:
    DoSomething_single(MyArray);
    break;
case NPY_DOUBLE:
    DoSomething_double(MyArray);
    break;
default:
    error("unknown type %d of MyArray\n", typ);
}
like image 199
umläute Avatar answered Oct 04 '22 15:10

umläute


The long, convoluted way of doing this, if you are dealing with a PyArrayObject* arr, would be to check arr->descr->type or arr->descr->type_numwhich holds:

char PyArray_Descr.type A traditional character code indicating the data type

int PyArray_Descr.type_num A number that uniquely identifies the data type. For new data-types, this number is assigned when the data-type is registered

As @umlauete answer points out, there are cleaner ways of incorporating that into your code, but it is always a good thing to know what's in your PyArrayObject and PyArray_Descrstructs. And always "read the docs, Luke!"

like image 31
Jaime Avatar answered Oct 04 '22 16:10

Jaime