473,574 Members | 3,066 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 2103

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

Similar topics

467
21321
by: mike420 | last post by:
THE GOOD: 1. pickle 2. simplicity and uniformity 3. big library (bigger would be even better) THE BAD:
1
1974
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
3100
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
6280
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
3384
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...
2
4437
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
4209
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
2318
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
7841
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...
0
7758
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7856
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...
1
5651
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...
0
5335
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...
0
3773
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3793
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1099
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...

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.