GPMデータ読込みプログラムガイド(Python編) GPM Data Loading Program Guide (Python Edition)¶


本書は、netCDF形式のGPMプロダクトおよびGSMaPプロダクトをプログラムで利用する方法を説明します。
また、netCDF形式からGeoTIFF形式ファイルを作成する方法についても説明します( 3.8. GeoTIFF変換(GeoTIFF Conversion) にて説明します)。

This document explains how to load netCDF-format GPM products and GSMaP products with this program.
It also explains how to create GeoTIFF files from netCDF format (see 3.8. GeoTIFF変換(GeoTIFF Conversion) ).

目次(Index)¶


  • 1. 動作環境(Operating Environment)
  • 2. 対象プロダクト(Target Product)
  • 3. サンプルプログラムを用いた利用例(Example Using a Sample Program)
    • 3.1. プロダクトファイルを開く(Opening a Product File)
    • 3.2. プロダクトのアトリビュート、データセットを読み込む(Loading Product Attributes and Datasets)
    • 3.3. データセットの切り出し_緯度経度での切り出し(Dataset Extraction_Based on Latitude and Longitude)
    • 3.4. データセットの切り出し_観測時刻での切り出し(Dataset Extraction_Based on Observation Time)
    • 3.5. 統計量の算出(Calculating Statistics)
    • 3.6. 画像表示(Displaying Image)
    • 3.7. 地図投影表示(Map Projection Display)
    • 3.8. GeoTIFF変換(GeoTIFF Conversion)

1.動作環境(Operating Environment)¶


pythonおよびpipでインストールするモジュールの一覧とバージョンを記載します。
本サンプルプログラムは、pythonバージョン"3.11.13"で確認をしています。
また、pythonで使用するモジュールの一覧を以下の表に示します。pythonモジュールはコマンド「pip install [モジュール名]」でインストールします。

Below is a list of modules and their versions to install with Python and pip.
This sample program has been verified with Python version 3.11.13.
The list of Python modules used is shown in the table below. Python modules are installed with the command "pip install [module name]".

モジュール名(Module Name)動作確認済みバージョン(Version Tested for Functionality)概要(Description)
netCDF41.7.4netCDF形式のファイルを読み書きするためのライブラリ

Library for reading and writing netCDF format files
numpy2.4.1数値計算、統計処理などに使用するライブラリ

Library used for numerical calculations, statistical processing, etc.
matplotlib3.10.8画像描画に使用するライブラリ

Library used for image rendering
cartopy0.25.0Matplotlibと組み合わせて地図描画するためのライブラリ

A library for drawing maps in combination with Matplotlib
rasterio1.4.4GeoTIFF変換に使用するライブラリ

Library used for GeoTIFF conversion
In [ ]:
!pip install netCDF4 numpy matplotlib cartopy rasterio

2.対象プロダクト(Target Product)¶


本書で対象とするプロダクトは、地球観測衛星データ提供システム(G-Portal)で公開される、netCDF形式のGPMプロダクトおよびGSMaPプロダクトを対象とします。

The products targeted in this document are the GPM products and GSMaP products in netCDF format, which are provided through the Earth Observation Satellite Data Provision System (G-Portal).

3.サンプルプログラムを用いた利用例(Example Using a Sample Program)¶


サンプルプログラムでは、3.1.~3.8.に示す基本的な機能を説明します。
また、サンプルプログラムではDPR L3プロダクト(GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc)を用いていますが、
他のアルゴリズム、処理レベルのプロダクトを取り扱う場合は、処理レベルのプロダクトフォーマットを参照の上、
サンプルプログラムで使用しているプロダクト変数名を置き換えてください。
本章では、必要に応じてCOTS編の「3.3. HDF View」を参照し、処理するデータセットを確認して下さい。

The sample program describes the basic functions shown in 3.1. - 3.8.
The sample program uses the DPR L3 product (GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc); if you handle products from other algorithms or processing levels,
refer to the product format for that processing level and replace the product variable names used in the sample program.
In this chapter, refer to '3.3. HDF View' in the COTS section as needed, and check the dataset to be processed.



目的に応じてどこを参照すればよいかを以下の表に示します。
目的に合わせて参照してください。

The table below shows where to refer depending on your purpose.
Please consult it as needed.


ユーザ状況・目的(User situation/Purpose)参照項目(Reference items)理由(Reason)
初めてGPMプロダクトを扱いたい

To handle GPM products for the first time
3.1. プロダクトファイルを開く (Opening a Product File)から順に参照

Refer to the sections in order, starting from 3.1. プロダクトファイルを開く (Opening a Product File).
データを開いて構造や変数、メタデータを可視化する

Open the data to visualize its structure, variables, and metadata.
プロダクトの概要やデータ構造が知りたい

To view the product overview and data structure
3.2. プロダクトのアトリビュート、データセットを読み込む(Loading Product Attributes and Datasets)特定のデータにアクセスしてデータの仕様や品質を確認する

Access specific data and check the data specifications and quality.
ある特定の領域を解析したい

To analyze a specific region
3.3. データセットの切り出し_緯度経度での切り出し(Dataset Extraction_Based on Latitude and Longitude)対象地域のデータだけを抽出して解析効率を上げる

Extract data only for the target region to improve analysis efficiency.
ある特定の期間を解析したい

To analyze a specific period
3.4. データセットの切り出し_観測時刻での切り出し(Dataset Extraction_Based on Observation Time)特定期間のデータだけを抽出して解析効率を上げる

Extract data only for the specified period to improve analysis efficiency.
ある特定のデータで統計量を算出したい

To calculate statistics for a specific dataset
3.5. 統計量の算出(Calculation of Statistics)平均・最大・最小などを算出して傾向を把握する

Compute statistics such as mean, maximum, and minimum to understand trends.
視覚的にデータを認識したい

To visualize the data
3.6. 画像表示(Displaying Image)
3.7. 地図投影表示(Map Projection Display)
データの空間分布を直感的に把握する

Visually grasp the spatial distribution of the data.
V07までGeoTIFFプロダクトを利用していた

Had been using GeoTIFF products up to V07
3.8. GeoTIFF変換(GeoTIFF Conversion)netCDFデータをGeoTIFFに変換してGISで利用する

Convert netCDF data to GeoTIFF for use in GIS.

3.1.プロダクトファイルを開く(Opening a Product File)¶


  • 説明 (Description)
    netCDF形式のプロダクトファイルを開き、グローバルアトリビュートなどのファイルの情報を表示します。

    Open a netCDF format product file and display the file information, such as global attributes.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
In [2]:
import netCDF4

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# ===== 

# netCDFファイルを開きます。
# Open the netCDF file
with netCDF4.Dataset(filename, mode="r") as nc:
    # グローバルアトリビュートなどのファイルの情報を表示します。
    # Display file information such as global attributes.
    print("=== File Information ===")
    print(nc)
=== File Information ===
<class 'netCDF4.Dataset'>
root group (NETCDF4 data model, file format HDF5):
    FileHeader: DOI=;
DOIauthority=http://dx.doi.org/;
DOIshortName=;
AlgorithmID=3DPRD;
AlgorithmVersion=V4.20250606;
FileName=GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc;
SatelliteName=GPM;
InstrumentName=DPR;
GenerationDateTime=2025-09-26T10:02:19.000Z;
StartGranuleDateTime=2025-01-01T00:00:00.000Z;
StopGranuleDateTime=2025-01-01T23:59:59.999Z;
GranuleNumber=;
NumberOfSwaths=0;
NumberOfGrids=1;
GranuleStart=;
TimeInterval=DAY;
ProcessingSystem=JAXA/EORC;
ProductVersion=08X;
EmptyGranule=NOT_EMPTY;
MissingData=;

    FileInfo: DataFormatVersion=8a;
TKCodeBuildVersion=0;
MetadataVersion=8a;
FormatPackage=netCDF-4.9.2;
BlueprintFilename=GPM.V8.3DPRD.blueprint.xml;
BlueprintVersion=BV_69;
TKIOVersion=3.101.8;
MetadataStyle=PVL;
EndianType=LITTLE_ENDIAN;

    JAXAInfo: GranuleFirstScanUTCDateTime=;
GranuleLastScanUTCDateTime=;
TotalQualityCode=Good;
FirstScanLat=;
FirstScanLon=;
LastScanLat=;
LastScanLon=;
NumberOfRainPixelsFS=;
NumberOfRainPixelsHS=;
ProcessingSubSystem=;
ProcessingMode=;
LightSpeed=;
DielectricFactorKa=;
DielectricFactorKu=;

    dimensions(sizes): phony_dim_97(1), phony_dim_21(1), phony_dim_49(1)
    variables(dimensions): <class 'str'> InputFileNames(phony_dim_97), <class 'str'> InputAlgorithmVersions(phony_dim_21), <class 'str'> InputGenerationDateTimes(phony_dim_49)
    groups: GRID

3.2.プロダクトのアトリビュート、データセットを読み込む(Loading Product Attributes and Datasets)¶


  • 説明 (Description)
    プロダクトファイルのグローバルアトリビュート、ディメンジョン、データセットを読み込んで表示します。
    サンプルでは、以下のデータを読み込みます。

    Load and display the global attributes, dimensions, and datasets of a product file.
    In the sample, the following data will be loaded:
    • グローバルアトリビュート (Global attribute):FileHeader
    • ディメンジョン (Dimension):GRID/nlat
    • データセット (Dataset):GRID/precipRateMean

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
nc_gattr_nameFileHeader読み込むグローバルアトリビュート名

Name of the global attribute to read
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateMean読み込む変数名

Name of the variable to read
nc_dim_namenlat読み込むディメンジョン名

Name of the dimension to read
In [3]:
import netCDF4


# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 読み込むデータを設定します。
# Set the data to be read.
nc_gattr_name = "FileHeader"
nc_grp_name = "GRID"
nc_var_name = "precipRateMean"
nc_dim_name = "nlat"

# =====

# ファイルを開きます。
# Open the file.
with netCDF4.Dataset(filename, "r") as nc:
    # グローバルアトリビュート「FileHeader」を表示します。
    # Display the global attribute "FileHeader".
    gattr_file_header = nc.getncattr(nc_gattr_name)
    print(f"[Global Attribute] FileHeader: {gattr_file_header}")
    
    # GRIDグループのディメンジョン「nlat」の長さを表示します。
    # Display the length of the dimension "nlat" in the GRID group.
    grp_grid = nc.groups[nc_grp_name]
    dim_nlat = grp_grid.dimensions[nc_dim_name]
    print(f"[Dimension] nlat: {len(dim_nlat)}\n")
    
    # GRIDグループのデータセット「precipRateMean」の先頭データを表示します。
    # Display the first value of the dataset "precipRateMean" in the GRID group.
    ds_precip_rate_mean = grp_grid.variables[nc_var_name]
    print(f"[Dataset] precipRateMean: {ds_precip_rate_mean[0, 0, 0, 0, 0]}")
[Global Attribute] FileHeader: DOI=;
DOIauthority=http://dx.doi.org/;
DOIshortName=;
AlgorithmID=3DPRD;
AlgorithmVersion=V4.20250606;
FileName=GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc;
SatelliteName=GPM;
InstrumentName=DPR;
GenerationDateTime=2025-09-26T10:02:19.000Z;
StartGranuleDateTime=2025-01-01T00:00:00.000Z;
StopGranuleDateTime=2025-01-01T23:59:59.999Z;
GranuleNumber=;
NumberOfSwaths=0;
NumberOfGrids=1;
GranuleStart=;
TimeInterval=DAY;
ProcessingSystem=JAXA/EORC;
ProductVersion=08X;
EmptyGranule=NOT_EMPTY;
MissingData=;

[Dimension] nlat: 536

[Dataset] precipRateMean: 0.0

3.3.データセットの切り出し_緯度経度での切り出し(Dataset Extraction_Based on Latitude and Longitude)¶


  • 説明 (Description)
    緯度経度毎にデータを持つデータセットを、指定した緯度経度範囲で切り出したデータを作成します。
    サンプルで用いるプロダクトは緯度経度の値を持たない格子データのため、プログラム内で緯度経度を算出します。

    This will create a dataset that contains data for each latitude and longitude by extracting data within a specified latitude and longitude range.
    Since the sample product used is grid data that does not have latitude and longitude values, the program will calculate the latitude and longitude.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
lat_min0.0切り出す領域の最小緯度

Minimum latitude of the extracted region
lat_max67.0切り出す領域の最大緯度

Maximum latitude of the extracted region
lon_min-180.0切り出す領域の最小経度

Minimum longitude of the extracted region
lon_max180.0切り出す領域の最大経度

Maximum longitude of the extracted region
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateMean読み込む変数名

Name of the variable to read
asc_dec0「precipRateMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
nalt0「precipRateMean」の3次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the third dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
In [4]:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import netCDF4
import numpy as np

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを設定します。
# Set the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 本サンプルでは、経度が正の領域のデータを切り出します。
# In this sample, data from regions with positive longitudes are extracted.
lat_min = 0.0    # サンプルプロダクトにおける最小緯度は -67.0°(The minimum latitude in the sample product is -67.0°)
lat_max = 67.0      # サンプルプロダクトにおける最大緯度は 67.0°(The maximum latitude in the sample product is 67.0°)
lon_min = -180.0    # サンプルプロダクトにおける最小経度は -180.0°(The minimum longitude in the sample product is -180.0°)
lon_max = 180.0     # サンプルプロダクトにおける最大経度は 180.0°(The maximum longitude in the sample product is 180.0°)

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateMean"
asc_dec = 0
chd = 0
nalt = 0

# =====

# ファイルを開きます。
# Open the file.
with netCDF4.Dataset(filename, "r") as nc:
    # 緯度経度で切り出したい変数を指定してデータを切り出します。
    # 例では、「precipRateMean」を対象とします。
    # なお、precipRateMeanは、AD、チャネル、高度を持つため、指定して切り出します。
    # Specify the variable to extract by latitude/longitude and extract the data.
    # In this example, "precipRateMean" is the target.
    # Note: precipRateMean has AD (ascending/descending), channel, and altitude dimensions,
    # so specify them when extracting.
    grid = nc.groups[nc_grp_name]
    
    var = grid.variables[nc_var_name]

    # 格子データを緯度経度に変換します。
    # Convert grid data to latitude/longitude.
    nlon_size = var.shape[var.dimensions.index("nlon")]
    nlat_size = var.shape[var.dimensions.index("nlat")]
    lon_vals = -180.0 + (np.arange(nlon_size) + 0.5) * 0.25
    lat_vals = -67.0   + (np.arange(nlat_size) + 0.5) * 0.25

    # 有効範囲の領域から指定した緯度経度の範囲を求めます。
    # Determine the latitude/longitude range to extract from the valid-area region.
    lat_mask = (lat_vals >= lat_min) & (lat_vals <= lat_max)
    if lon_min <= lon_max:
        lon_mask = (lon_vals >= lon_min) & (lon_vals <= lon_max)
    else:
        lon_mask = (lon_vals >= lon_min) | (lon_vals <= lon_max)

    # 有効範囲のデータの有効範囲のみを切り出します。
    # Extract only the valid-area portion of the data.
    target_data = var[asc_dec, chd, nalt]
    lat_idx = np.where(lat_mask)[0]
    lon_idx = np.where(lon_mask)[0]
    lat_start, lat_end = lat_idx[0], lat_idx[-1] + 1
    lon_start, lon_end = lon_idx[0], lon_idx[-1] + 1
    subset = target_data[lon_start:lon_end, lat_start:lat_end]
    cut_data = np.array(subset, dtype=float)

    # 切り出したデータを確認します。
    # サンプルでは緯度のデータを半分にしているため、データ数が半分になっていることを確認します。
    # Verify the extracted data.
    # In this sample the latitude data is halved, so confirm that the number of data points is halved.
    print(f"\nCutting Range:Latitude: {lat_min} ~ {lat_max}, Longitude: {lon_min} ~ {lon_max}")
    print(f"Number of Data Points Before(longitude, latitude): {target_data.shape}")
    print(f"Number of Data Points After(longitude, latitude): {cut_data.shape}")

    # 正しくデータが切り出せていることを確認します。
    # Verify that the data was extracted correctly.
    diff_flag = False
    for lon_idx in range(cut_data.shape[0]):  # 経度方向に全数確認(Check all points in the longitude direction)
        for lat_idx in range(cut_data.shape[1]):  # 緯度方向に切り出した範囲数分確認(Check across the extracted latitude range)
            if cut_data[lon_idx, lat_idx] != target_data[lon_idx, lat_idx + cut_data.shape[1]]:
                # 切り出し範囲が想定と異なる場合
                # If the extracted range differs from expectation
                print("The cutting performed is different from what was expected.")
                diff_flag = True
                break

        if diff_flag is True:
            break

    if diff_flag is False:
        print("The cutting is being performed as anticipated.")
                
Cutting Range:Latitude: 0.0 ~ 67.0, Longitude: -180.0 ~ 180.0
Number of Data Points Before(longitude, latitude): (1440, 536)
Number of Data Points After(longitude, latitude): (1440, 268)
The cutting is being performed as anticipated.

3.4.データセットの切り出し_観測時刻での切り出し(Dataset Extraction_Based on Observation Time)¶


  • 説明 (Description)
    時刻毎にデータを持つデータセットを、指定した時刻の範囲で切り出したデータを作成します。

    Create a dataset with data for each timing by extracting data within a specified time range.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
cut_start_gridtime2025-01-01T17:43:00.000切り出し開始時刻

Extraction start time
cut_end_gridtime2025-01-01T17:43:10.000切り出し終了時刻

Extraction end time
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateNearSurfaceMean読み込む変数名

Name of the variable to read
ac_type0「precipRateNearSurfaceMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateNearSurfaceMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateNearSurfaceMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateNearSurfaceMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
In [5]:
import netCDF4 as nc
import numpy as np

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むファイルパスを設定します。
# Set the file path to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 切り出す時刻の範囲を指定します。
# Specify the time range to extract.
cut_start_gridtime = '2025-01-01T17:43:00.000'
cut_end_gridtime = '2025-01-01T17:43:10.000'

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateNearSurfaceMean"
ac_type = 0
chd = 0

# =====

#----------------------------------------------------
# 関数の定義
# Function definitions
#----------------------------------------------------

def make_valid_gridtime_array(ds: nc.Dataset, ac: int):
    # 指定した昇降方向の時刻データに対し、有効な時刻文字列のデータを生成します。
    # ds:有効データを抽出する対象のプロダクトデータ
    # ac:昇降方向(0:アセンディング、1:ディセンディング)
    # Generate an array of valid timestamp strings for the specified
    # ascending/descending direction.
    # ds: product dataset from which to extract valid data
    # ac: ascending/descending type (0: Ascending, 1: Descending)

    # Asc/Desでグループが異なるため、グループ名を特定します。
    # Determine group name because Asc/Des use different groups.
    if ac == 0:
        grid_time_grp_name = "GridTimeAsc"
    else:
        grid_time_grp_name = "GridTimeDes"

    # 時刻グループを取り出します。
    # Retrieve the time group.
    grp_gridtime = ds.groups[nc_grp_name].groups[grid_time_grp_name]

    # 年が有効なデータ箇所を特定します。
    # Identify positions where Year is valid.
    ds_year = grp_gridtime.variables["Year"][:]
    valid_idx = ~np.ma.getmaskarray(ds_year)    # np.ma.getmaskarrayは無効値個所を抽出するため、逆の値を取得します。(np.ma.getmaskarray extracts invalid-value mask, so invert it.)

    # YYYY-MM-DDThh:mm:ss.ZZZの形式で時刻文字列を作成します。
    # 無効な時刻は、空文字を設定します。
    # Create timestamp strings in the format YYYY-MM-DDThh:mm:ss.ZZZ.
    # For invalid times, set an empty string.
    ds_year_str = np.char.zfill(grp_gridtime.variables["Year"][:].astype('str'), 4)
    ds_month_str = np.char.zfill(grp_gridtime.variables["Month"][:].astype('str'), 2)
    ds_day_str = np.char.zfill(grp_gridtime.variables["DayOfMonth"][:].astype('str'), 2)
    ds_hour_str = np.char.zfill(grp_gridtime.variables["Hour"][:].astype('str'), 2)
    ds_minutes_str = np.char.zfill(grp_gridtime.variables["Minute"][:].astype('str'), 2)
    ds_sec_str = np.char.zfill(grp_gridtime.variables["Second"][:].astype('str'), 2)
    ds_msec_str = np.char.zfill(grp_gridtime.variables["MilliSecond"][:].astype('str'), 3)
    gridtime_array = ds_year_str + '-' + ds_month_str + '-' + ds_day_str + 'T' + ds_hour_str + ':' + ds_minutes_str + ':' + ds_sec_str + '.' + ds_msec_str
    valid_gridtime_array = np.where(valid_idx, gridtime_array, '')
    
    return valid_gridtime_array

#----------------------------------------------------
# スクリプトの実行
# Script execution
#----------------------------------------------------

with nc.Dataset(filename, "r") as ds:
    # 抽出する昇降方向を指定して、格子データにおける有効な時刻範囲を求めます。
    # Specify the ascend/descend type to extract and get the valid time range in the grid data.
    valid_gridtime_array = make_valid_gridtime_array(ds, ac_type)

    # 有効時刻の領域から指定した時刻の範囲を求めます。
    # From the valid-time array, determine range within the specified time range.
    cut_gridtime_idx =(valid_gridtime_array >= cut_start_gridtime) & (valid_gridtime_array <= cut_end_gridtime)

    # 時刻で切り出したい変数を指定してデータを切り出します。
    # 例では、「precipRateNearSurfaceMean」を対象とします。
    # なお、precipRateNearSurfaceMeanはAD、チャネルを持つため、指定して切り出します。
    # Specify the variable to cut by time and extract data.
    # Example targets "precipRateNearSurfaceMean".
    # Note: precipRateNearSurfaceMean has AD and channel dimensions, so specify them.
    grp_grid = ds.groups[nc_grp_name]
    ds_data = grp_grid.variables[nc_var_name][ac_type, chd, :]  # Ascending、チャネル1の格子データ(Grid data for Ascending, channel 1)
    # 切り出し範囲外のデータには、-9999を設定してマスクします。
    # Mask data outside the cut range with -9999.
    mask_ds_data = np.where(cut_gridtime_idx, ds_data, -9999)

    # 有効範囲のみのデータが抽出されたことを確認します。
    # Confirm that only data within the valid range was extracted.
    print(f'Cutting range\t:{cut_start_gridtime} ~ {cut_end_gridtime}' )
    print(f'Data within the Cropping Range\t:Datetime:{valid_gridtime_array[53, 10]}, Before:{ds_data[53, 10]}, After:{mask_ds_data[53, 10]}' )
    print(f'Data Outside the Cropping Range\t:Datetime:{valid_gridtime_array[100, 30]}, Before:{ds_data[100, 30]}, After:{mask_ds_data[100, 30]}' )  
Cutting range	:2025-01-01T17:43:00.000 ~ 2025-01-01T17:43:10.000
Data within the Cropping Range	:Datetime:2025-01-01T17:43:00.806, Before:0.6407565474510193, After:0.6407565474510193
Data Outside the Cropping Range	:Datetime:2025-01-01T19:20:49.445, Before:0.0, After:-9999.0

3.5.統計量の算出(Calculation of Statistics)¶


  • 説明 (Description)
    特定のデータセットを指定し、データから統計量を算出します。統計量として、以下のデータを算出しています。

    Specify a particular dataset and calculate statistics from the data. The following statistics are calculated:
    • データ数(Number of data points)
    • 最大値(Maximum value)
    • 最小値(Minimum value)
    • 平均値(Average value)

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateMean読み込む変数名

Name of the variable to read
asc_dec0「precipRateMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
nalt0「precipRateMean」の3次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the third dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
In [6]:
from netCDF4 import Dataset
import numpy as np

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateMean"
asc_dec = 0
chd = 0
nalt = 0

# =====

#ファイルを開きます。
# Open the file.
with Dataset(filename, "r") as nc:
    # 統計量を算出したい変数を指定します。
    # 例では、「precipRateMean」を対象とします。
    # なお、precipRateMeanは、AD、チャネル、高度を持つため、指定して切り出します。
    # Specify the variable for which to calculate statistics.
    # In this example, the target is "precipRateMean".
    # Note: precipRateMean has AD, channel, and altitude dimensions, so specify them when slicing.
    precip2d = np.ma.getdata(nc.groups[nc_grp_name].variables[nc_var_name][asc_dec, chd, nalt, :, :]).astype(float)

    # 統計量を算出します。
    # 今回はデータ数、最大値、最小値、平均値を算出しています。
    # Calculate statistics.
    # Here we compute the count, maximum, minimum, and mean.
    count = precip2d.size
    max_val = precip2d.max()
    min_val = precip2d.min()
    mean_val = precip2d.mean()

    # 結果を確認します。
    # Check the results.
    print("=== precipRateMean Statistics ===")
    print(f"Number of Data Points: {count}")
    print(f"Maximum Value: {max_val}")
    print(f"Minimum Value: {min_val}")
    print(f"Avarage Value: {mean_val}")
=== precipRateMean Statistics ===
Number of Data Points: 771840
Maximum Value: 54.863338470458984
Minimum Value: 0.0
Avarage Value: 0.018799121543051904

3.6.画像表示(Displaying Image)¶


  • 説明 (Description)
    データセット内の特定のデータにアクセスし、画像として表示します。

    Access specific data in the dataset and display it as an image.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateMean読み込む変数名

Name of the variable to read
asc_dec0「precipRateMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
nalt0「precipRateMean」の3次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the third dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
vmin0.1カラーマップの最小値

colormap minimum value
vmax30.0カラーマップの最大値

colormap maximum value
In [7]:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.colors import LogNorm

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateMean"
asc_dec = 0
chd = 0
nalt = 0

# カラーマップの最大値と最小値を設定します。
# 今回は最小値を0.1,最大値を30.0に設定しています。
# Set the colormap minimum and maximum values.
# Here we set the minimum to 0.1 and the maximum to 30.0.
vmin = 0.1
vmax = 30.0

# =====

# ファイルを開きます。
# Open the file.
with Dataset(filename, "r") as nc:
    # 画像表示したい変数の2D配列を作成します。
    # 例では、「precipRateMean」を対象とします。
    # なお、precipRateMeanは、AD、チャネル、高度を持つため、指定して切り出します。
    # Create the 2D array of the variable to display as an image.
    # In this example, the target is "precipRateMean".
    # Note: precipRateMean has AD, channel, and altitude dimensions, so slice them.
    subset = nc.groups[nc_grp_name].variables[nc_var_name][asc_dec, chd, nalt, :, :]  # shape = (nlon, nlat)
    data = np.array(subset, dtype=float)

    # 画像表示の設定を行います。
    # 表示レンジに合わせてカラーマップを設定します。
    # 0.0 より大きくて vmin 未満の値を vmin に丸めます。
    # Configure the image display settings.
    # Set the colormap according to the display range.
    # For values greater than 0.0 but less than vmin, adjust them to vmin.
    mask_positive_lt_vmin = (data > 0.0) & (data < vmin)
    data[mask_positive_lt_vmin] = vmin
    # vmax より大きい値は vmax に丸めます。
    # For values greater than vmax, adjust them to vmax.
    data[data > vmax] = vmax

    # カラーマップで値が0.0の座標は透過します。
    # 0.0をマスクします。
    # Make coordinates with a value of 0.0 transparent in the colormap.
    # Mask out values equal to 0.0.
    mdata = np.ma.array(data, mask=(data == 0.0))
    base_cmap = plt.get_cmap("jet")
    cmap = matplotlib.colors.ListedColormap(base_cmap(np.linspace(0, 1, 256)))
    cmap.set_bad((0, 0, 0, 0))

    # 画像表示する図のイメージを作成します。
    # 横12,縦5のサイズを指定します。
    # Create the figure for image display.
    # Set figure size to 12x5 (width x height).
    plt.figure(figsize=(12, 5))
    im = plt.imshow( mdata.T, # (rows,cols)に合わせるために配列を転置しています。(Transpose the array to match (rows, cols).)
        origin="lower", # 配列の始まりを左下に指定しています。(Set the origin to the lower-left corner.)
        cmap=cmap, # カラーマップを指定しています。(Specify the colormap.)
        norm=LogNorm(vmin=vmin, vmax=vmax), # 対数スケーリングを設定しています。(Apply logarithmic scaling.)
        extent=[0.0, float(mdata.shape[0]), 0.0, float(mdata.shape[1])], # 座標範囲/順序を指定しています。(Specify coordinate range/order.)
        aspect="auto" # 画像の縦横比を指定しています。(Specify the aspect ratio of the image.)
    )

    # カラーバーを設定します。
    # Add a colorbar.
    cbar = plt.colorbar(im, label="Precipitation Rate (mm/hr)")
    cbar.set_ticks([0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 30])
    cbar.set_ticklabels(["0.1", "0.2", "0.5", "1", "2", "5", "10", "20", "30"])

    # 画像タイトルを設定します。
    # Set the image title.
    plt.title(f"precipRateMean (AD={asc_dec}, chd={chd}, nalt={nalt})")

    # X軸,Y軸ラベルを設定します。
    # Set X and Y axis labels.
    plt.xlabel("nlon")
    plt.ylabel("nlat")

    # 画像を表示します。
    # Display the image.
    plt.tight_layout()
    plt.show()
No description has been provided for this image

3.7.地図投影表示(Map Projection Display)¶


  • 説明 (Description)
    緯度経度ごとに格納されたデータセットを抽出し、地図投影して表示します。

    Extract the dataset stored for each latitude and longitude, and project it onto a map for display.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateMean読み込む変数名

Name of the variable to read
asc_dec0「precipRateMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
nalt0「precipRateMean」の3次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the third dimension of 'precipRateMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
vmin0.1カラーマップの最小値

colormap minimum value
vmax30.0カラーマップの最大値

colormap maximum value
In [8]:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.colors import LogNorm
import cartopy.crs as ccrs
import cartopy.feature as cfeature

# ===== 設定値一覧 =====
# ===== Setting list =====

# 読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateMean"
asc_dec = 0
chd = 0
nalt = 0

# カラーマップの最大値と最小値を設定します。
# 今回は最小値を0.1,最大値を30.0に設定しています。
# Set the colormap minimum and maximum values.
# Here we set the minimum to 0.1 and the maximum to 30.0.
vmin = 0.1
vmax = 30.0

# =====

# ファイルを 開く
# Open the file.
with Dataset(filename, "r") as nc:
    # 地図投影したい変数の2D配列を作成します。
    # 例では、「precipRateMean」を対象とします。
    # なお、precipRateMeanは、AD、チャネル、高度を持つため、指定して切り出します。
    # Create the 2D array of the variable to project on the map.
    # In this example, the target is "precipRateMean".
    # Note: precipRateMean has AD, channel, and altitude dimensions, so slice them.
    subset = nc.groups[nc_grp_name].variables[nc_var_name][asc_dec, chd, nalt, :, :]  # shape = (nlon, nlat)

    # 緯度・経度を配列にして取得します。
    # Generate arrays for longitude and latitude.
    lon_centers = -180.0 + (np.arange(subset.shape[0]) + 0.5) * 0.25
    lat_centers = -67.0 + (np.arange(subset.shape[1]) + 0.5) * 0.25

    # 2D座標グリッドを作成します。(meshgrid の戻り形は (nlat, nlon))
    # Create a 2D coordinate grid. (meshgrid returns shape (nlat, nlon))
    lon2d, lat2d = np.meshgrid(lon_centers, lat_centers)

    # 画像表示の設定を行います。
    # 表示レンジに合わせてカラーマップを設定します。
    # 0.0 より大きくて vmin 未満の値を vmin に丸めます。
    # Configure the image display settings.
    # Set the colormap according to the display range.
    # For values greater than 0.0 but less than vmin, adjust them to vmin.
    data = np.array(subset, dtype=float)
    mask_positive_vmin = (data > 0.0) & (data < vmin)
    data[mask_positive_vmin] = vmin
    # vmax より大きい値は vmax に丸めます。
    # For values greater than vmax, adjust them to vmax.
    data[data > vmax] = vmax

    # カラーマップで値が0.0の座標は透過します。
    # 0.0をマスクします。
    # Make coordinates with a value of 0.0 transparent in the colormap.
    # Mask out values equal to 0.0.
    mdata = np.ma.array(data, mask=(data == 0.0))
    base_cmap = plt.get_cmap("jet")
    cmap = mpl.colors.ListedColormap(base_cmap(np.linspace(0, 1, 256)))
    cmap.set_bad((0, 0, 0, 0))

    # 投影する図のイメージを作成をします。
    # 横12,縦6のサイズを指定しています。
    # Create the figure for the projected map.
    # Specify figure size: width 12, height 6.
    fig = plt.figure(figsize=(12, 6))
    ax = plt.axes(projection=ccrs.PlateCarree()) # 地図投影の設定をしています。(Set up map projection.)
    im = ax.pcolormesh(lon2d, lat2d, mdata.T, # 2Dグリッドと転置した配列を指定しています。(Specify the 2D grid and the transposed array.)
                       transform=ccrs.PlateCarree(), # 座標参照系(CRS)を指定しています。(Specify the coordinate reference system (CRS).)
                       cmap=cmap, # カラーマップを指定しています。(Specify the colormap.)
                       norm=LogNorm(vmin=vmin, vmax=vmax), # 対数スケーリングを設定しています。(Apply logarithmic scaling.)
                       shading="auto") # 描画時のピクセルの扱いを指定しています。(Specify how pixels are shaded during rendering.)

    # カラーバーを設定します。
    # Add a colorbar.
    cbar = plt.colorbar(im, orientation="vertical", pad=0.02)
    cbar.set_label("Precipitation Rate (mm/hr)")
    cbar.set_ticks([0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 30])
    cbar.set_ticklabels(["0.1", "0.2", "0.5", "1", "2", "5", "10", "20", "30"])

    # 地図の装飾を設定します。
    # Add map decorations/features.
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS)
    ax.set_global()
    ax.set_title(f"precipRateMean (AD={asc_dec}, chd={chd}, nalt={nalt})")

    # 緯度・経度の目盛りを設定します。
    # Set latitude and longitude tick marks.
    ax.set_xticks(np.arange(-180, 181, 60), crs=ccrs.PlateCarree())
    ax.set_yticks(np.arange(-60, 61, 30), crs=ccrs.PlateCarree())

    # X軸,Y軸のラベルを設定します。
    # Set X and Y axis labels.
    plt.xlabel("longitude")
    plt.ylabel("latitude")

    # 画像を表示します。
    # Display the image.
    plt.show()
No description has been provided for this image

3.8.GeoTIFF変換(GeoTIFF Conversion)¶


  • 説明 (Description)
    netCDFファイル形式から緯度経度ごとに格納されたデータセットを抽出し、GeoTIFFファイル形式に変換してファイルに出力します。

    Extract datasets stored by latitude and longitude from netCDF file format, convert them to GeoTIFF file format, and output them to a file.

  • 設定値一覧 (Setting list)
    以下に設定値の一覧を示します。必要に応じて、修正してください。

    The following is the list of setting variables. Please modify them as needed.
設定値名(Setting Value Name)設定値例(Example settings)概要(Description)
filenameGPMCOR_DPR_250101_D_L3S_D3Q_08X.nc読み込むプロダクトのファイルパス

File path of the product to read
nc_grp_nameGRID設定値nc_var_nameで設定するデータセットが属するグループ名

Group name of the dataset specified by nc_var_name.
nc_var_nameprecipRateNearSurfaceMean読み込む変数名

Name of the variable to read
asc_dec0「precipRateNearSurfaceMean」の1次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the first dimension of 'precipRateNearSurfaceMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
chd0「precipRateNearSurfaceMean」の2次元目のデータの番号。
取得するデータセットの次元を確認し、適切に変数を設定してください。

Index of the data in the second dimension of 'precipRateNearSurfaceMean'.
Check the dimensions of the dataset you are retrieving and set the variable appropriately.
In [9]:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
from netCDF4 import Dataset
import rasterio
from rasterio.transform import from_origin
from rasterio.crs import CRS

# ===== 設定値一覧 =====
# ===== Setting list =====

#読み込むプロダクトのファイルパスを指定します。
# Specify the file path of the product to read.
filename = "GPMCOR_DPR_250101_D_L3S_D3Q_08X.nc"

# 読み込むデータを設定します。
# Set the data to be read.
nc_grp_name = "GRID"
nc_var_name = "precipRateNearSurfaceMean"
asc_dec = 0
chd = 0

# =====

#ファイルを開きます。
# Open the file.
with Dataset(filename, 'r') as ds:
    # GeoTIFF変換したい変数を指定します。
    # 例では、「precipRateNearSurfaceMean」を対象とします。
    # なお、precipRateNearSurfaceMeanはAD、チャネルを持つため、指定してGeoTIFF変換します。
    # Specify the variable to convert to GeoTIFF.
    # In this example, the target is "precipRateNearSurfaceMean".
    # Note: "precipRateNearSurfaceMean" has AD and channel dimensions, so select them for GeoTIFF conversion.

    var = ds.groups[nc_grp_name].variables[nc_var_name]

    # ピクセルサイズを算出します。
    # Calculate pixel size.
    nlat = var.shape[var.dimensions.index("nlat")]
    nlon = var.shape[var.dimensions.index("nlon")]
    lon_min, lon_max = -180.0, 180.0
    lat_min, lat_max = -67.0, 67.0
    dx = (lon_max - lon_min) / nlon
    dy = (lat_max - lat_min) / nlat

    # GeoTIFF左上の座標を算出します。
    # Compute the top-left coordinate for the GeoTIFF.
    transform = from_origin(lon_min, lat_max, dx, dy) #(-180.0, 67.0, 0.25, 0.25)

    # GeoTIFF用にデータを調整します。
    # データ配列を転置し上下反転しています。
    # Adjust data for GeoTIFF.
    # Transpose the data array and flip it vertically.
    raw = var[asc_dec, chd, :, :] #Ascending、チャネル1の格子データ(Grid data for Ascending and channel 1)
    raw = raw.T
    arr = np.array(raw).astype(np.float32)
    arr = np.flipud(arr)

    # GeoTIFFファイル名を設定しています。
    # Set the GeoTIFF filename.
    out = f"precip_AD{asc_dec}_CH{chd}.tif"

    # GeoTIFF用のメタ情報を設定しています。
    # Set metadata/profile for GeoTIFF.
    profile = {
            'driver': 'GTiff', #フォーマットを指定しています。(Specify format.)
            'dtype': arr.dtype, #データ型を指定しています。(Specify data type.)
            'count': 1, #バンド数を指定しています。(Number of bands.)
            'height': arr.shape[0], #行数を指定しています。(Number of rows.)
            'width': arr.shape[1], #列数を指定しています。(Number of columns.)
            'transform': transform, #画像位置を指定しています。(Image geotransform (location).)
            'crs': CRS.from_epsg(4326), #座標参照系を指定しています。(Coordinate reference system.)
            'compress': 'deflate' #圧縮形式を指定しています。(Compression method.)
    }

# GeoTIFFファイルに書き出します。
# Write out the GeoTIFF file.
with rasterio.open(out, 'w', **profile) as dst:
    dst.write(arr, 1)
    print(f"Create geotiff file. [{out}]")
Create geotiff file. [precip_AD0_CH0.tif]