comparison netcdf_read.py @ 0:8da8ec7da45f draft default tip

Uploaded
author mnhn65mo
date Thu, 02 Aug 2018 09:24:38 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:8da8ec7da45f
1 import netCDF4
2 from netCDF4 import Dataset
3 import numpy as np
4 import matplotlib
5 matplotlib.use("Agg")
6 import matplotlib.pyplot as plt
7 from pylab import *
8 import sys
9 import os
10 from scipy import spatial
11 from math import radians, cos, sin, asin, sqrt
12 import itertools
13
14 #####################
15 #####################
16
17 def checklist(dim_list, dim_name, filtre, threshold):
18 if not dim_list:
19 error="Error "+str(dim_name)+" has no value "+str(filtre)+" "+str(threshold)
20 sys.exit(error)
21
22
23 #Return dist in km between two coord
24 #Thx to : https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
25 def haversine(lon1, lat1, lon2, lat2):
26 """
27 Calculate the great circle distance between two points
28 on the earth (specified in decimal degrees)
29 """
30 # convert decimal degrees to radians
31 lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
32
33 # haversine formula
34 dlon = lon2 - lon1
35 dlat = lat2 - lat1
36 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
37 c = 2 * asin(sqrt(a))
38 r = 6371 # Radius of earth in kilometers. Use 3956 for miles
39 return c * r
40
41
42 #Comparison functions, return a list of indexes for the user conditions
43 def is_strict_inf(filename, dim_name, threshold):
44 list_dim=[]
45 for i in range(0,filename.variables[dim_name].size):
46 if filename.variables[dim_name][i] < threshold:
47 list_dim.append(i)
48 checklist(list_dim,dim_name,"<",threshold)
49 return list_dim
50
51 def is_equal_inf(filename, dim_name, threshold):
52 list_dim=[]
53 for i in range(0,filename.variables[dim_name].size):
54 if filename.variables[dim_name][i] <= threshold:
55 list_dim.append(i)
56 checklist(list_dim,dim_name,"<=",threshold)
57 return list_dim
58
59 def is_equal_sup(filename, dim_name, threshold):
60 list_dim=[]
61 for i in range(0,filename.variables[dim_name].size):
62 if filename.variables[dim_name][i] >= threshold:
63 list_dim.append(i)
64 checklist(list_dim,dim_name,">=",threshold)
65 return list_dim
66
67 def is_strict_sup(filename, dim_name, threshold):
68 list_dim=[]
69 for i in range(0,filename.variables[dim_name].size):
70 if filename.variables[dim_name][i] > threshold:
71 list_dim.append(i)
72 checklist(list_dim,dim_name,">",threshold)
73 return list_dim
74
75 def find_nearest(array,value):
76 index = (np.abs(array-value)).argmin()
77 return index
78
79 def is_equal(filename, dim_name, value):
80 try:
81 index=filename.variables[dim_name][:].tolist().index(value)
82 except:
83 index=find_nearest(filename.variables[dim_name][:],value)
84 return index
85
86 def is_between_include(filename, dim_name, threshold1, threshold2):
87 list_dim=[]
88 for i in range(0,filename.variables[dim_name].size):
89 if filename.variables[dim_name][i] >= threshold1 and filename.variables[dim_name][i] <= threshold2:
90 list_dim.append(i)
91 checklist(list_dim,dim_name,">=",threshold1)
92 checklist(list_dim,dim_name,"=<",threshold2)
93 return list_dim
94
95 def is_between_exclude(filename, dim_name, threshold1, threshold2):
96 list_dim=[]
97 for i in range(0,filename.variables[dim_name].size):
98 if filename.variables[dim_name][i] > threshold1 and filename.variables[dim_name][i] < threshold2:
99 list_dim.append(i)
100 checklist(list_dim,dim_name,">",threshold1)
101 checklist(list_dim,dim_name,"<",threshold2)
102 return list_dim
103
104 #######################
105 #######################
106
107 #Get args
108 #Get Input file
109 inputfile=Dataset(sys.argv[1])
110 var_file_tab=sys.argv[2]
111 var=sys.argv[3] #Var chosen by user
112
113 Coord_bool=False
114
115
116 ######################
117 ######################
118 #len_threshold=1000000
119 len_threshold=7000
120 x_percent=0.75
121 threshold_latlon=100
122
123
124 #Check if coord is passed as parameter
125 arg_n=len(sys.argv)-1
126 if(((arg_n-3)%3)!=0):
127 Coord_bool=True #Useful to get closest coord
128 arg_n=arg_n-4 #Number of arg minus lat & lon
129 name_dim_lat=str(sys.argv[-4])
130 name_dim_lon=str(sys.argv[-2])
131 value_dim_lat=float(sys.argv[-3])
132 value_dim_lon=float(sys.argv[-1])
133
134 #Get all lat & lon
135 #try:
136 if True:
137 latitude=np.ma.MaskedArray(inputfile.variables[name_dim_lat])
138 longitude=np.ma.MaskedArray(inputfile.variables[name_dim_lon])
139 lat=latitude;lon=longitude #Usefull to keep the originals lat/lon vect before potentially resize it bellow.
140 len_all_coord=len(lat)*len(lon)
141
142 #print("len all coord "+str(len_all_coord)+" threshold "+str(len_threshold))
143
144 #To avoid case when all_coord is to big and need to much memory
145 #If the vector is too big, reduce it to its third in a loop until its < to the threshold
146 while len_all_coord > len_threshold:
147
148 if len(lat)<threshold_latlon: #If lat and lon are very different and lon is >> than lat. This way only lon is reduce and not lat.
149 x_percent_len_lat=99999999
150 else:
151 x_percent_len_lat=int(x_percent*len(lat))
152
153 if len(lon)<threshold_latlon: #If lat and lon are very different and lat is >> than lon. This way only lat is reduce and not lon.
154 x_percent_len_lon=99999999
155 else:
156 x_percent_len_lon=int(x_percent*len(lon))
157
158 #print("len(lat) :"+str(len(lat))+" x_percent_len_lat "+str(x_percent_len_lat))
159 #print("len(lon) :"+str(len(lon))+" x_percent_len_lon "+str(x_percent_len_lon))
160
161
162 pos_lat_user=find_nearest(lat,value_dim_lat)
163 pos_lon_user=find_nearest(lon,value_dim_lon)
164
165
166 #This part is to avoid having a vector that start bellow 0
167 lat_reduced=int(pos_lat_user-x_percent_len_lat/2-1)
168 if lat_reduced<0:
169 lat_reduced=0
170 lon_reduced=int(pos_lon_user-x_percent_len_lon/2-1)
171 if lon_reduced<0:
172 lon_reduced=0
173 #Opposite here to avoid having vector with len > to len(vector)
174 lat_extended=int(pos_lat_user+x_percent_len_lat/2-1)
175 if lat_extended>len(lat):
176 lat_extended=len(lat)
177 lon_extended=int(pos_lon_user+x_percent_len_lon/2-1)
178 if lon_extended>len(lon):
179 lon_extended=len(lon)
180
181 lat=lat[lat_reduced:lat_extended] #add a test to check if pos_lat_user-x_percent_len_lat/2-1 >0
182 lon=lon[lon_reduced:lon_extended]
183 #print("latreduced : "+str(lat_reduced)+" latextended "+str(lat_extended))
184 #print("lonreduced : "+str(lon_reduced)+" lonextended "+str(lon_extended))
185 #print("lat : "+str(lat))
186 #print("lon : "+str(lon))
187 len_all_coord=len(lat)*len(lon)
188
189 #print ("len_all_coord : "+str(len_all_coord)+". len_lat : "+str(len(lat))+" .len_lon : "+str(len(lon)))
190
191 else:
192 #except:
193 sys.exit("Latitude & Longitude not found")
194
195 #Set all lat-lon pair avaible in list_coord
196 list_coord_dispo=[]
197 for i in lat:
198 for j in lon:
199 list_coord_dispo.append(i);list_coord_dispo.append(j)
200
201 #Reshape
202 all_coord=np.reshape(list_coord_dispo,(lat.size*lon.size,2))
203 #np.set_printoptions(threshold='nan')#to print full vec
204 #print(str(all_coord))
205 noval=True
206
207
208
209 #########################
210 #########################
211
212
213 #Get the file of variables and number of dims : var.tab
214 var_file=open(var_file_tab,"r") #read
215 lines=var_file.readlines() #line
216 dim_names=[]
217 for line in lines: #for every lines
218 words=line.split()
219 if (words[0]==var): #When line match user input var
220 varndim=int(words[1]) #Get number of dim for the var
221 for dim in range(2,varndim*2+2,2): #Get dim names
222 dim_names.append(words[dim])
223 #print ("Chosen var : "+sys.argv[3]+". Number of dimensions : "+str(varndim)+". Dimensions : "+str(dim_names)) #Standard msg
224
225
226 ########################
227 ########################
228
229
230 #Use a dictionary to save every lists of indexes
231 my_dic={} ##d["string{0}".format(x)]
232
233 for i in range(4,arg_n,3):
234 #print("\nDimension name : "+sys.argv[i]+" action : "+sys.argv[i+1]+" .Value : "+sys.argv[i+2]+"\n") #Standard msg
235
236 #Check if the dim selected for filtering is present in the var dimensions.
237 if (sys.argv[i] not in dim_names):
238 print("Warning ! "+sys.argv[i]+" is not a dimension of "+var+".\nThis filter will be skipped\nCheck in the file \"variables\" the dimensions available.\n\n")
239 pass
240
241 my_dic["string{0}".format(i)]="list_index_dim"
242 my_dic_index="list_index_dim"+str(sys.argv[i]) #Possible improvement: Check if lon/lat are not parsed again
243
244 #Apply every user filter. Call function and return list of index wich validate condition for every dim.
245 if (sys.argv[i+1]=="l"): #<
246 my_dic[my_dic_index]=is_strict_inf(inputfile, sys.argv[i], float(sys.argv[i+2]))
247 if (sys.argv[i+1]=="le"): #<=
248 my_dic[my_dic_index]=is_equal_inf(inputfile, sys.argv[i], float(sys.argv[i+2]))
249 if (sys.argv[i+1]=="g"): #>
250 my_dic[my_dic_index]=is_strict_sup(inputfile, sys.argv[i], float(sys.argv[i+2]))
251 if (sys.argv[i+1]=="ge"): #>=
252 my_dic[my_dic_index]=is_equal_sup(inputfile, sys.argv[i], float(sys.argv[i+2]))
253 if (sys.argv[i+1]=="e"): #==
254 my_dic[my_dic_index]=is_equal(inputfile, sys.argv[i], float(sys.argv[i+2]))
255 if (sys.argv[i+1]==":"): #all
256 my_dic[my_dic_index]=np.arange(inputfile.variables[sys.argv[i]].size)
257 if (sys.argv[i+1]=="be"): #between_exclude
258 #Get the 2 thresholds from the arg which looks like "threshold1-threshold2"
259 threshold1=sys.argv[i+2].split("-")[0]
260 threshold2=sys.argv[i+2].split("-")[1]
261 my_dic[my_dic_index]=is_between_exclude(inputfile, sys.argv[i], float(threshold1), float(threshold2))
262 if (sys.argv[i+1]=="bi"): #between_include
263 #Get the 2 thresholds from the arg which looks like "threshold1-threshold2"
264 threshold1=sys.argv[i+2].split("-")[0]
265 threshold2=sys.argv[i+2].split("-")[1]
266 my_dic[my_dic_index]=is_between_include(inputfile, sys.argv[i], float(threshold1), float(threshold2))
267
268 #####################
269 #####################
270
271
272 #If precise coord given.
273 if Coord_bool:
274 while noval: #While no closest coord with valid values is found
275 #Return closest coord avaible
276 tree=spatial.KDTree(all_coord)
277 closest_coord=(tree.query([(value_dim_lat,value_dim_lon)]))
278 cc_index=closest_coord[1]
279
280 closest_lat=float(all_coord[closest_coord[1]][0][0])
281 closest_lon=float(all_coord[closest_coord[1]][0][1])
282
283 #Get coord index into dictionary
284 my_dic_index="list_index_dim"+str(name_dim_lat)
285 my_dic[my_dic_index]=latitude.tolist().index(closest_lat)
286
287 my_dic_index="list_index_dim"+str(name_dim_lon)
288 my_dic[my_dic_index]=longitude.tolist().index(closest_lon)
289
290
291 #All dictionary are saved in the string exec2 which will be exec(). Value got are in vec2
292 exec2="vec2=inputfile.variables['"+var+"']["
293 first=True
294 for i in dim_names: #Every dim are in the right order
295 if not first:
296 exec2=exec2+","
297 dimension_indexes="my_dic[\"list_index_dim"+i+"\"]" #new dim, custom name dic
298 try: #If some error or no specific user choices; every indexes are used for the selected dim.
299 exec(dimension_indexes)
300 except:
301 dimension_indexes=":"
302 exec2=exec2+dimension_indexes #Concatenate dim
303 first=False #Not the first element now
304 exec2=exec2+"]"
305 #print exec2 #To check integrity of the string
306 exec(exec2) #Execution, value are in vec2.
307 #print vec2 #Get the value, standard output
308
309 #Check integrity of vec2. We don't want NA values
310 i=0
311 #Check every value, if at least one non NA is found vec2 and the current closest coords are validated
312 vecsize=vec2.size
313 #print (str(vecsize))
314 if vecsize>1:
315 while i<vecsize:
316 #print (str(vec2))
317 if vec2[i]!="nan":
318 break
319 else:
320 i=i+1
321 else:
322 if vec2!="nan":
323 break
324 else:
325 i=i+1
326
327 if i<vecsize: #There is at least 1 nonNA value
328 noval=False
329 else: #If only NA : pop the closest coord and search in the second closest coord in the next loop.
330 all_coord=np.delete(all_coord,cc_index,0)
331
332
333 #Same as before, dictionary use in exec2. exec(exec2) give vec2 and the values wanted.
334 else:
335 exec2="vec2=inputfile.variables['"+str(sys.argv[3])+"']["
336 first=True
337 for i in dim_names: #Respect order
338 if not first:
339 exec2=exec2+","
340 dimension_indexes="my_dic[\"list_index_dim"+i+"\"]"
341 try: #Avoid error and exit
342 exec(dimension_indexes)
343 except:
344 dimension_indexes=":"
345 exec2=exec2+dimension_indexes
346 first=False
347 exec2=exec2+"]"
348 exec(exec2)
349
350
351 ########################
352 ########################
353
354
355 #This part create the header of every value.
356 #Values of every dim from the var is saved in a list : b[].
357 #All the lists b are saved in the unique list a[]
358 #All the combinations of the dim values inside a[] are the headers of the vec2 values
359
360 #Also write dim_name into a file to make clear header.
361 fo=open("header_names",'w')
362
363 a=[]
364 for i in dim_names:
365 try: #If it doesn't work here its because my_dic= : so there is no size. Except will direcly take size of the dim.
366 size_dim=inputfile[i][my_dic['list_index_dim'+i]].size
367 except:
368 size_dim=inputfile[i].size
369 my_dic['list_index_dim'+i]=range(size_dim)
370
371 #print (i,size_dim) #Standard msg
372 b=[]
373 #Check size is useful since b.append(inputfile[i][my_dic['list_index_dim'+i][0]]) won't work
374 if size_dim>1:
375 for s in range(0,size_dim):
376 b.append(inputfile[i][my_dic['list_index_dim'+i][s]])
377 #print (i,inputfile[i][my_dic['list_index_dim'+i][s]])
378 else:
379 b.append(inputfile[i][my_dic['list_index_dim'+i]])
380 #print (i,inputfile[i][my_dic['list_index_dim'+i]])
381
382 a.append(b)
383 fo.write(i+"\t")
384 if Coord_bool:
385 fo.write("input_lat\t"+"input_lon\t")
386 fo.write(var+"\n")
387 fo.close()
388
389
390 ######################
391 ######################
392
393
394 #Write header in file
395 fo=open("header",'w')
396 for combination in itertools.product(*a):
397 if Coord_bool:
398 fo.write(str(combination)+"_"+str(value_dim_lat)+"_"+str(value_dim_lon)+"\t")
399 else:
400 fo.write(str(combination)+"\t")
401 fo.write("\n")
402 fo.close()
403
404
405 #Write vec2 in a tabular formated file
406 fo=open("sortie.tabular",'w')
407 #print(str(vec2))
408 try:
409 vec2.tofile(fo,sep="\t",format="%s")
410 except:
411 vec3=np.ma.filled(vec2,np.nan)
412 vec3.tofile(fo,sep="\t",format="%s")
413 fo.close()
414
415
416 ######################
417 ######################
418
419
420 #Final sweet msg
421 print (var+" values successffuly extracted from "+sys.argv[1]+" !")