Read big endian binary in Python and convert it to ndarray

I will show you how to read a binary dumped two-dimensional array of real numbers from Python. Specifically, the terrain data in here is read. This time, the target is the terrain data used for MSM. As far as the number of grids and latitude / longitude are seen, the data in this directory is the current status. It seems to be compatible with MSM.

According to README

4.file format
 (1)data form
4-byte real number(IEEE754)It is a two-dimensional array of.
The sequence of bytes is big endian.
 (2)Coordinate system
Equal latitude / longitude grid coordinate system.

    (a)Meso Numerical Weather Prediction Model GPV
Number of grids: East-West 481 North-South 505
Lattice spacing: East-West direction 0.0625 degrees north-south direction 0.05 degrees
First grid point: 47th parallel north.6 degrees east longitude 120 degrees
(Omission)
(3)Data storage order
Stores grid points with the same latitude from the first grid point in the east direction in the longitude direction.
It is also stored repeatedly at the latitude just south of it.

... apparently ...

In the example below

Surface geopotential height data
    (a) "TOPO.MSM_5K_20071121"Meso Numerical Weather Prediction Model for GPV

Let's take this data as an example. First, download the data.

$ wget http://database.rish.kyoto-u.ac.jp/arch/jmadata/data/gpv/original/etc/200709/TOPO.MSM_5K_20071121

The rest is working with python. It is assumed that numpy is installed.

import numpy as np
f = open("TOPO.MSM_5K_20071121",mode='rb')
topo = np.fromfile(f, dtype='>f',sep='').reshape(505,481)

You can now load terrain altitude data in the same size as the 505x481 MSM. I read the data as a bigendian 4-byte float with dtype ='> f' in fromfile, save it in a one-dimensional array, and reshape it. By specifying dtype, fromfile can be obtained other than a one-dimensional array, but dt = np.dtype (('> f', (505,481))) Even if you specify it like this, topo.shape = It will be a three-dimensional array like (1,505,481) . I also checked the dtype document, but it seems that it can not be made into a two-dimensional array in one shot with a good feeling.

Let's visualize it to see if it's loaded correctly. For details, please refer to this article.

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import pygrib

grbs = pygrib.open('/temp/Z__C_RJTD_20170102000000_MSM_GPV_Rjp_Lsurf_FH00-15_grib2.bin')
grb = grbs.select(forecastTime=0)[0]
lats, lons = grb.latlons()
flat_lats= np.ravel(lats)
flat_lons= np.ravel(lons)
m = Basemap(llcrnrlat=lats.min(),urcrnrlat=lats.max(), llcrnrlon=lons.min(),urcrnrlon=lons.max())
m.drawcoastlines()
m.contourf(flat_lons, flat_lats, b, latlon=True, tri=True)
plt.colorbar()
plt.show()

image.png

By the way, land and sea distribution data is as follows. image.png

Recommended Posts

Read big endian binary in Python and convert it to ndarray
Convert FBX files to ASCII <-> BINARY in Python
Read CSV file with Python and convert it to DataFrame as it is
Convert timezoned date and time to Unixtime in Python2.7
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
Convert NumPy array "ndarray" to lilt in Python [tolist ()]
How to convert floating point numbers to binary numbers in Python
Deep nesting in Python makes it hard to read
Try to make it using GUI and PyQt in Python
Tips for coding short and easy to read in Python
How to convert Youtube to mp3 and download it super-safely [Python]
Read json in C # and convert to dictionary type (forced)
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
Convert markdown to PDF in Python
Create and read messagepacks in Python
Determine the date and time format in Python and convert to Unixtime
How to install OpenCV on Cloud9 and run it in Python
Convert the result of python optparse to dict and utilize it
Read Python csv and export to txt
Read and write JSON files in Python
Convert from Markdown to HTML in Python
How to use is and == in Python
Convert absolute URLs to relative URLs in Python
How to generate permutations in Python and C ++
Convert PDFs to images in bulk with Python
[Python] How to read data from CIFAR-10 and CIFAR-100
Convert UTF-8 CSV files to read in Excel
How to convert SVG to PDF and PNG [Python]
POST JSON in Python and receive it in PHP
Convert exponential notation float to str in Python
To represent date, time, time, and seconds in Python
How to plot autocorrelation and partial autocorrelation in python
Convert cubic mesh code to WKT in Python
python Binary search It is surprisingly easy to implement bisect.bisect_left and bisect.bisect_right from 0
[Python] How to name table data and output it in csv (to_csv method)
How to read a serial number file in a loop, process it, and graph it
Difference in writing method to read external source code between Ruby and Python
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
I read "Quantum Computer Accelerates Artificial Intelligence" and tried to outline it in Python without using mathematical formulas.
A Python script that crawls RSS in Azure Status and posts it to Hipchat
Read DXF in python
How to convert / restore a string with [] in python
[Python] Convert general-purpose container and class to each other
Convert CIDR notation netmask to dotted decimal notation in Python
Binary search in Python
Read the csv file and display it in the browser
Convert the image in .zip to PDF with Python
Read and write single precision floating point in Python
Write tests in Python to profile and check coverage
I want to replace the variables in the python template file and mass-produce it in another file.
[Python] How to sort dict in list and instance in list
Convert callback-style asynchronous API to async / await in Python
Read json file with Python, format it, and output json
Convert / return class object to JSON format in Python
Read and write NFC tags in python using PaSoRi
[Python] Created a method to convert radix in 1 second
How to use Decorator in Django and how to make it
Convert Webpay Entity type to Dict type (recursively in Python)
I was able to repeat it in Python: lambda
Output a binary dump in binary and revert to a binary file
Binary search in Python (binary search)