Challenge to convert a simple IDL code into Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 24 23:16:18 EDT 2014


Cleo Drakos wrote:

> Thanks for your response.
> 
> The IDL code reads the given binary file, and prints out the data inside
> it. The binary file structure is provided using the variable 'data' in the
> IDL code. Then it print the only required data that in side the  'data
> that is precip.
> 
> However when I tried to output the same using python code, it is not
> producing the same result.
> 
> Sorry the last line of python code is print precip.
> 
> Python result is:
> 
> [ -1.00000000e+00  -1.00000000e+00  -1.00000000e+00 ...,  -2.09705293e+09
>   -2.09705293e+09  -2.09705293e+09]
> 
> IDL result is:

I am stunned that you have dumped nearly ten thousand lines of output in our
laps, and expect us to go through it all. I know Gary asked you to copy and
paste the output of the IDL code, but please be reasonable.

Are you able to generate a *smaller* data file, say with twenty values, and
demonstrate the same issue?

Let's go through your code, line by line.


>> Here is IDL code:
>>
>> pro read_binary_file

What does this line "pro read_binary_file" do?

>> file = "3B42RT.2014010318.7.bin"

I assume that just creates a variable called file with a string value.

>> num_lon = 1440
>> num_lat = 480

And again, presumably these is just the obvious two variables.


>> data = {header: bytarr(num_lon*2), precip: intarr(num_lon,num_lat),
>> precip_error: intarr(num_lon,num_lat), $
>>       source_of_estimate: bytarr(num_lon,num_lat), precip_uncal:
>>       intarr(num_lon,num_lat)}

Please explain in as much detail as you can what this does. I think this is
the critical part of the IDL code. We have to understand this precisely to
have any hope of translating it into Python.


>> close, 1
>> openr, 1, file
>> readu, 1, data
>> close, 1

And what these mysterious lines do?


>> precip = swap_endian(data.precip)
>> print, precip
>> end

And these lines. (Presumably print prints the variable, end is the end of
the program.)


>> My attempt in Python is here:
>>
>> fname = '3B42RT.2014010318.7.bin'
>> num_lon = 1440
>> num_lat = 480
>> with open(fname, 'rb') as fi:
>>     contents = fi.read()
>>     precip = struct.unpack_from('>'+str(num_lon*num_lat)+'I', contents,
>>                                 offset = num_lon*2)
>>
>>     precip = np.array(data,dtype=int)
>>     precip data

That last line is meant to be "print data".



-- 
Steven




More information about the Python-list mailing list