最近用到了nc格式的數據,就像詳細瞭解了。
NetCDF全稱爲network Common Data Format,
一個netcdf文件的結構包括以下對象:
1、變量(Variables)
變量對應着真實的物理數據。比如說溫度。
2、維(dimension)
一個維對應着函數中的某個自變量,或者說函數圖象中的一個座標軸,在線性代數中就是一個N維向量的一個分量(這也是維這個名稱的由來)。在netcdf中,一個維具有一個名字和範圍(或者說長度,也就是數學上所說的定義域,可以是離散的點集合或者連續的區間)
3、屬性(Attribute)
屬性對變量值和維的具體物理含義的註釋或者說解釋。因爲變量和維在netcdf中都只是無量綱的數字,要想讓人們明白這些數字的具體含義,就得靠屬性這個對象了。
在netcdf中,屬性由一個屬性名和一個屬性值(一般爲字符串)組成。比如,在某個cdl文件(cdl文件的具體格式在下一節中講述)中有這樣的代碼段
temperature:units = “celsius” ;
前面的temperature是一個已經定義好的變量(Variable),即溫度,冒號後面的units就是屬性名,表示物理單位,=後面的就是units這個屬性的值,爲“celsius” ,即攝氏度,整個一行代碼的意思就是溫度這個物理量的單位爲celsius,很好理解。
1、需要依賴
<!-- https://mvnrepository.com/artifact/edu.ucar/netcdf4 -->
<dependency>
<groupId>edu.ucar</groupId>
<artifactId>netcdf4</artifactId>
<version>4.5.5</version>
</dependency>
2、讀取nc文件樣例
/**
* 從全球nc數據中裁剪指定區域的數據
*
* @param resourPath nc文件所在位置路徑
* @param startLon 指定區域開始的經度
* @param startLat 指定區域開始的緯度
* @param latCount 緯度要讀取多少個點
* @param lonCount 經度要讀取多少個點
* @param begin 從時間緯度的第幾層開始讀取
* @param end 第幾層結束
* @return 指定區域的數據
*/
public static short[][] readNCfile(String resourPath, int latCount, int lonCount, float startLon, float startLat,int begin,
int end) {
try {
NetcdfFile ncFile = NetcdfFile.open(resourPath); //獲取源文件
Variable v = ncFile.findVariable("qpf_ml"); //讀取qpf_ml的變量,
//
short[][] values = null;
for (int i = begin; i < end; i++) { //本讀取的qpf_ml是一個3維數據,時間、經度、維度,一下子把3維數據全部讀出來會很大,時間維度是24層,所以通過遍歷時間維度獲取數據,i爲時間維度的層數
int[] origin = { i, (int) ((latNorth - startLat) * 100), (int) ((startLon - lonEast) * 100) };//origin 設置維度準備從哪個位置開始讀取數據
int[] shape = { 1, latCount, lonCount };//shape 和origin對應,設置讀取多少點後結束
short[][] temp = (short[][]) v.read(origin, shape).reduce(0).copyToNDJavaArray(); //去掉時間維度,變爲二維
if (values != null) {
for (int j = 0; j < latCount; j++) {
for (int k = 0; k < lonCount; k++) {
values[j][k] += temp[j][k];
}
}
}else {
values = temp;
}
}
ncFile.close();
return values;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidRangeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
至此,讀文件結束,下篇會寫如何生成nc文件