473,624 Members | 2,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python/C API, Numeric Python, Type Conversion

1 New Member
Hi,

I am posting here to seek for help on type conversion between Python (Numeric Python) and C.

Attachment A is a math function written in C, which is called by a Python program. I had studied SWIG and Python/C API a bit. I was able to pass numeric array (Numeric Python) into the C function and access/change these arrays.

Problem I am having is that I couldn't quite get the array converted back to some PyObject or something that Python Interpreter can understand. So, alternatively I passed an empty numeric array as well as other arguments, and had return value(result) stored in that chunk of place. It sort of worked. However, if such function was called few times, it would result in segmentation fault.

This is a lousy way to get around the return type matter, and probably is causing seg fault. Besides a correct type conversion, a proper SWIG interface probably could've saved all the fuss, maybe? ( attachment B is the SWIG interface I am using for this function)

I am trying to study more on C API section of NumPy document, and to gain more knowledge off SWIG(which I only understand very basic way of it). Any feedback will be great. Thanks for your time, friends. Truly appreicate your precious time.

Ronnie


P.S. Those PyObject pointers are created with Numeric.Array( data, Numeric,Float64 ).


Attachment A
Expand|Select|Wrap|Line Numbers
  1. /*
  2. *******************************************************************************
  3. *
  4. *  Function Name : 
  5. *     cressman()
  6. *  
  7. *  Usage :
  8. *     PyObject* cressman
  9. *     (int nx,int ny,PyObject* result,PyObject* us,PyObject* rlats, PyObject* 
  10. *      rlons, int nst,float disinf,float slon,float elon,float slat,float elat)
  11. *
  12. *  Description :
  13. *     Objective analysis by Cressman method
  14. *
  15. *  Aumument :
  16. *     nx(I)    : x-dimension of grid data 
  17. *     ny(I)    : y-dimension of grid data
  18. *     result(I): an empty result set
  19. *     us(I)    : input station data                
  20. *     rlons(I) : x-coordinate of station
  21. *     rlats(I) : y-coordinate of station
  22. *     nst(I)   : number of station data
  23. *     disinf(I): influence radius distance(km)
  24. *     slon(I)  : x-coordinate of start grid longitude
  25. *     elon(I)  : x-coordinate of end grid longitude
  26. *     slat(I)  : y-coordinate of start grid latitude
  27. *     elat(I)  : y-coordinate of end grid latitude
  28. *     
  29. *   Data Files : None
  30. *  
  31. *   Called Function :
  32. *     ardist()    
  33. *
  34. *   Return Value : 
  35. *      data    : grid data value    
  36. *
  37. *   Linking Lib : None
  38. *
  39. ***************************************************************************                         
  40. */
  41. PyObject* cressman
  42. (int nx,int ny,PyObject* result,PyObject* us,PyObject* rlats, PyObject* rlons, int nst,float disinf,float slon,float elon,float slat,float elat)
  43. {
  44.    if( nst < 1)
  45.        return;
  46.  
  47.    // initialization    
  48.    float xdelta,ydelta,disinf2,wsum,usum,xx,yy;
  49.    float **data;
  50.    float data_ave, sum;
  51.    int i,j,k,count;
  52.  
  53.    // PyObject(python-C API) related 
  54.    PyArrayObject *p_us, *p_rlats, *p_rlons, *p_result;
  55.    double *array_us, *array_rlats, *array_rlons, *array_result;
  56.  
  57.    p_us= (PyArrayObject *) us;
  58.    p_rlats= (PyArrayObject *) rlats;
  59.    p_rlons= (PyArrayObject *) rlons;
  60.    p_result= (PyArrayObject *) result;
  61.  
  62.    if ( nst != p_us->dimensions[0])
  63.        return;
  64.  
  65.    array_us = (double*) p_us->data;
  66.    array_rlats = (double*) p_rlats->data;
  67.    array_rlons = (double*) p_rlons->data;
  68.    array_result = (double*) p_result->data;
  69.  
  70.    // find out data avg
  71.    sum=0;
  72.    count=0;
  73.    for (i=0;i<nst;i++)
  74.    { 
  75.        if (array_us[i]>spv)
  76.        {
  77.            sum+=array_us[i];
  78.            count++;
  79.        }
  80.    }
  81.    if (count!=0)
  82.        data_ave= sum / count;
  83.  
  84.    xdelta = (elon - slon)/(nx -1);  
  85.    ydelta = (elat- slat)/(ny -1);
  86.    disinf2 = pow(disinf,2);
  87.  
  88.    for( i = 0; i < ny; i++)
  89.    {
  90.         for( j = 0; j < nx; j++)
  91.         {
  92.              wsum = 0.;
  93.              usum = 0.;
  94.              xx = slon + j*xdelta;
  95.              yy = slat + i*ydelta;
  96.  
  97.              for( k = 0; k < nst; k++)
  98.              {
  99.                   if( array_us[k] <= spv )
  100.                       continue;
  101.  
  102.                   //ardist just a function that calculates distance between 2 points
  103.                   float adist = ardist(array_rlons[k],array_rlats[k],xx,yy);
  104.                   if( adist > disinf )
  105.                       continue;
  106.                   float adist2 =  pow(adist,2);
  107.                   float w = (disinf2 - adist2)/(disinf2+adist2);
  108.  
  109.                   wsum = wsum + w;
  110.                   usum = usum + (w*array_us[k]);       
  111.              }
  112.              if( wsum != 0 )
  113.                  //data[i][j] = usum/wsum;
  114.                  array_result[i*nx+j] = usum/wsum;
  115.              else
  116.                  //data[i][j] = data_ave;
  117.                  array_result[i*nx+j] = data_ave;
  118.  
  119.         }
  120.    }
  121.    return result;       
  122. }
  123.  
Attachment B - SWIG interface
Expand|Select|Wrap|Line Numbers
  1.  /* objmod.i */
  2.  %module objmod
  3.  %{
  4.  /* Put header files here or function declarations like below */
  5.  PyObject* cressman(int nx,int ny,PyObject* result,PyObject* us,
  6.                      PyObject* rlats,PyObject* rlons,int nst,float disinf,
  7.                      float slon,float elon,float slat,float elat);
  8.  float ardist(float rlon,float rlat,float xx,float yy);
  9.  %}
  10.  
  11.  extern PyObject* cressman(int nx,int ny,PyObject* result,PyObject* us,
  12.                             PyObject* rlats,PyObject* rlons,int nst,float disinf,
  13.                             float slon,float elon,float slat,float elat);
  14.  extern float ardist(float rlon,float rlat,float xx,float yy);
  15.  
Aug 6 '07 #1
0 2106

Sign in to post your reply or Sign up for a free account.

Similar topics

467
21419
by: mike420 | last post by:
THE GOOD: 1. pickle 2. simplicity and uniformity 3. big library (bigger would be even better) THE BAD:
1
1976
by: youngdubliner | last post by:
I'm having a problem ........ I've stripped all my code to help isolate the problem. Its seems to be with importing numarray when python is embedded in C. I have a simple C program it Opens Python imports a script and then Closes Python like so .......
2
3101
by: martino | last post by:
Hi, I am trying to install NumPy (v23.8) onder Macosx (panther version). Python (v2.3) is bundled into panther and I installed the IDE on top of that. After having untarred the source distribution in the desktop directory and typed >python setup.py install as recommended in the attached documentation, I get: running install
96
6299
by: Gustav Hållberg | last post by:
I tried finding a discussion around adding the possibility to have optional underscores inside numbers in Python. This is a popular option available in several "competing" scripting langauges, that I would love to see in Python. Examples: 1_234_567 0xdead_beef 3.141_592
3
3385
by: PL | last post by:
I want to pass a 2D array from Python to C++, manipulate it in C++ (for example, add 1 to each element) and pass it back to Python. With these building blocks I will be able to figure out all the rest of what I need to do for my project. I am very familiar with Python, but less so with C++ and Boost or SWIG. Does anyone have an example with all steps that I can follow? More specifically I am looking for the C++ code, ".i" file for...
2
4441
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include <time.h>
135
4255
by: robinsiebler | last post by:
I've never had any call to use floating point numbers and now that I want to, I can't! *** Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) on win32. *** 0.29999999999999999 0.29999999999999999
3
2320
by: Ethan Furman | last post by:
len wrote: I've never had the (mis?)fortune to work with COBOL -- what are the files like? Fixed format, or something like a dBase III style? I
0
8234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8677
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8620
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8474
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6110
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5563
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
1482
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.