-
Notifications
You must be signed in to change notification settings - Fork 0
/
hadUK2json-sun-mon-region.py
86 lines (71 loc) · 2.01 KB
/
hadUK2json-sun-mon-region.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import netCDF4
import numpy as np
import json
from datetime import datetime, timedelta
epoc = datetime(1800,1,1,0,0,0)
startDate = 0
#filename = 'sun_hadukgrid_uk_region_mon-20y_198101-200012'
filename = 'sun_hadukgrid_uk_region_mon_191901-202112'
print("Reading .nc file...")
f = netCDF4.Dataset(filename + '.nc')
#print(f)
md = {}
for x,y in vars(f).items():
md[x] = y
dims ={}
for d in f.dimensions.keys():
dims[d] = {'name' : str(f.dimensions[d].name), 'size' : f.dimensions[d].size }
md['dimensions'] = dims
vvars = {}
for k in f.variables.keys():
locals()[k] = f.variables[k]
vvars[k] = {'dtype' : str(f.variables[k].dtype), 'dimensions' : str(f.variables[k].dimensions), 'attributes' : f.variables[k].__dict__}
md['variables'] = vvars
rn=[]
for x in region:
rn.append(int(x))
md['region'] = rn
rn=[]
for x in geo_region:
rn.append(''.join(x[:].astype(str)).rstrip())
md['geo_region'] = rn
#print("{}".format(time[:]))
rn=[]
for x in time[startDate:]:
rn.append(int(x))
md['time'] = rn
rn = []
for i, x in enumerate(time_bnds[startDate:]):
ro = {}
ro['band'] = i
ro['start'] = int(x[0:1])
ro['end'] = int(x[1:])
ro['month'] = (epoc + timedelta(hours=int(x[0:1]))).strftime('%m')
ro['year'] = (epoc + timedelta(hours=int(x[0:1]))).strftime('%Y')
rn.append(ro)
md['time_bnds'] = rn
#print(rn)
rn=[]
for i, x in enumerate(sun[startDate:]):
ro = {}
ro['time_bnd'] = i
sn = []
for ii, y in enumerate(x, start = 1):
so = {}
#print("{}".format(y))
so['region'] = ii
if y is np.ma.masked:
so['hours'] = 0
else:
so['hours'] = y
sn.append(so)
ro['regions'] = sn
rn.append(ro)
# print(x)
md['sun'] = rn
#print(rn)
#print(json.dumps(md, indent=4))
f.close()
print("Writing .json file....")
with open(filename + '.json', 'w', encoding='utf-8') as f:
json.dump(md, f, ensure_ascii=False, check_circular=True)