-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile_data_processor.py
344 lines (283 loc) · 12 KB
/
profile_data_processor.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 16:41:00 2020
@author: imchugh
"""
#------------------------------------------------------------------------------
### IMPORTS ###
#------------------------------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
#------------------------------------------------------------------------------
### CONSTANTS ###
#------------------------------------------------------------------------------
R = 8.3143
CO2_molar_mass = 44
VALID_SITES = [
'Boyagin', 'CumberlandPlain', 'HowardSprings', 'Litchfield', 'Whroo',
'Warra', 'WombatStateForest'
]
COLORS_DICT = {
'rtmc': {
'background_color': (30/255, 30/255, 30/255),
'font_color': 'white'
},
'standard': {
'background_color': 'white',
'font_color': 'black'
}
}
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
### CLASSES ###
#------------------------------------------------------------------------------
class profile():
def __init__(self, ds, site='Unknown'):
self.dataset = ds
self.site = site
def get_heights(self):
"""Get gas sampling intake array heights in m"""
return list(self.dataset.Height.data)
def get_layer_depths(self):
"""Get distance in metres between intakes"""
heights = self.get_heights()
return np.array(heights) - np.array([0] + heights[:-1])
def _get_layer_names(self):
"""Get name suffixes for layers"""
layer_elems = [
str(int(x)) if int(x) == x else str(x)
for x in [0] + self.get_heights()
]
return [
f'{layer_elems[i-1]}-{layer_elems[i]}m'
for i in range(1, len(layer_elems))
]
def get_CO2_density(self, as_df=False):
"""Calculate the density in mgCO2 m^-3 from ideal gas law"""
CO2_const = R / CO2_molar_mass
da = (
self.dataset.P * 1000 /
(CO2_const * (self.dataset.Tair + 273.15)) *
self.dataset.CO2 / 10**3
)
da.name = 'CO2_density'
if not as_df: return da
return _get_dataframe(da)
def get_CO2_density_as_layers(self, as_df=False):
"""Get the layer mean CO2 density (lowest layer is assumed to be
constant between ground and lowermost intake, other layers are
simple mean of upper and lower bounds of layer)"""
density_da = self.get_CO2_density()
da_list = []
da_list.append(
density_da.sel(Height=density_da.Height[0])
.reset_coords('Height', drop=True)
)
for i in range(1, len(density_da.Height)):
da_list.append(
density_da.sel(Height=density_da.Height[i-1: i+1])
.mean('Height')
)
layer_da = xr.concat(da_list, dim='Layer')
layer_da['Layer'] = self._get_layer_names()
layer_da = layer_da.transpose()
if not as_df: return layer_da
return _get_dataframe(layer_da)
def get_delta_CO2_storage(self, as_df=False):
"""Get storage term"""
layer_da = self.get_CO2_density_as_layers()
layer_da = layer_da / 44 * 10**3 # Convert g m^-3 to umol m^-3
diff_da = layer_da - layer_da.shift(Time=1) # Difference
diff_da = diff_da / 1800 # Divide by time interval
depth_scalar = xr.DataArray(self.get_layer_depths(), dims='Layer')
depth_scalar['Layer'] = diff_da.Layer.data
diff_da = diff_da * depth_scalar
diff_da['Layer'] = ['dCO2s_{}'.format(x) for x in diff_da.Layer.data]
diff_da.name = 'delta_CO2_storage'
if not as_df: return diff_da
return _get_dataframe(diff_da)
def get_summed_delta_CO2_storage(self, as_df=False):
"""Get storage term summed over all layers"""
da = self.get_delta_CO2_storage()
if not as_df: return da.sum('Layer', skipna=False)
return da.sum('Layer', skipna=False).to_dataframe()
def plot_diel_storage_mean(
self, output_to_file=None, open_window=True, rtmc_opt=False
):
"""Plot the diel mean"""
# Organise the data
df = self.get_delta_CO2_storage(as_df=True)
df['dCO2s_sum'] = df.sum(axis=1, skipna=False)
diel_df = df.groupby([df.index.hour, df.index.minute]).mean()
diel_df.index = np.arange(len(diel_df)) / 2
diel_df.index.name = 'Time'
# Now plot
if not open_window:
plt.ioff()
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
ax.set_xlim([0, 24])
ax.set_xticks([0,4,8,12,16,20,24])
ax.axhline(0, color='black', ls=':')
colour_idx = np.linspace(0, 1, len(diel_df.columns[:-1]))
labs = [x.split('_')[1] for x in diel_df.columns]
for i, var in enumerate(diel_df.columns[:-1]):
color = plt.cm.cool(colour_idx[i])
ax.plot(diel_df[var], label = labs[i], color = color)
ax.plot(diel_df[diel_df.columns[-1]], label = labs[-1],
color='grey')
ax.legend(loc=[0.65, 0.18], frameon=False, ncol=2)
col_scheme = 'standard'
if rtmc_opt:
col_scheme = 'rtmc'
self._set_plot_configs(
fig=fig,
ax=ax,
which=col_scheme,
xlabel='$Time$',
ylabel='$S_c\/(\mu mol\/CO_2\/m^{-2}\/s^{-1})$',
legend_loc='lower right',
title='$CO_2\/storage\/evolution\/by\/layer$'
)
if output_to_file: plt.savefig(fname=output_to_file)
plt.ion()
def plot_time_series(self, output_to_file=None, open_window=True):
"""Plot the time series"""
df = self.get_delta_CO2_storage(as_df=True)
strip_vars_list = [var.split('_')[1] for var in df.columns]
if not open_window:
plt.ioff()
fig, ax = plt.subplots(1, 1, figsize = (12, 8))
fig.patch.set_facecolor('white')
colour_idx = np.linspace(0, 1, len(df.columns))
ax.tick_params(axis = 'x', labelsize = 14)
ax.tick_params(axis = 'y', labelsize = 14)
ax.set_xlabel('$Date$', fontsize = 18)
ax.set_ylabel('$S_c\/(\mu mol\/CO_2\/m^{-2}\/s^{-1})$', fontsize = 18)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.plot(self.get_summed_delta_CO2_storage(as_df=True),
label = 'Total', color = 'grey')
for i, var in enumerate(df.columns):
color = plt.cm.cool(colour_idx[i])
plt.plot(df[var], label = strip_vars_list[i], color = color)
plt.legend(loc='lower left', frameon = False, ncol = 2)
if output_to_file: plt.savefig(fname=output_to_file)
plt.ion()
def plot_vertical_evolution_mean(
self, output_to_file, open_window=True, rtmc_opt=False
):
# Get data into shape
df = self.dataset.to_dataframe().unstack()['CO2']
grp_df = df.groupby([df.index.hour, df.index.minute]).mean()
grp_df.index = np.linspace(0, 23.5, 48)
grp_df.columns.name = 'Height'
transform_df = pd.concat([grp_df.loc[x] for x in np.linspace(0,21,8)], axis=1).T
transform_df.index.name = 'Time'
# Switch off plotting for background processing
if not open_window:
plt.ioff()
# Plot data
fig, ax = plt.subplots(1, 1, figsize = (10, 10))
colour_idx = np.linspace(0, 1, len(transform_df))
for i, time in enumerate(transform_df.index):
color = plt.cm.jet(colour_idx[i])
ax.plot(
transform_df.loc[time], transform_df.columns,
color=color, lw=2,
label=f'{str(int(time)).zfill(2)}00')
# Configure plot
col_scheme = 'standard'
if rtmc_opt:
col_scheme = 'rtmc'
title = '$CO_2\/time\/evolution\/by\/height$'
self._set_plot_configs(
fig=fig,
ax=ax,
which=col_scheme,
xlabel='$CO_2\/(\mu mol/mol)$',
ylabel='$Height\/(m)$',
legend_loc='upper right',
title=title
)
# Output options
if output_to_file: plt.savefig(fname=output_to_file)
plt.ion()
def _set_plot_configs(self, fig, ax, which, **kwargs):
detail_color = COLORS_DICT[which]['font_color']
bkgrnd_color = COLORS_DICT[which]['background_color']
fig.patch.set_facecolor(color=bkgrnd_color)
ax.set_facecolor(color=bkgrnd_color)
for axis in ['x', 'y']:
ax.tick_params(axis=axis, color=detail_color, labelcolor=detail_color)
for spine in ['right', 'top']:
ax.spines[spine].set_visible(False)
ax.set_xlabel(kwargs['xlabel'], fontsize=18, color=detail_color)
ax.set_ylabel(kwargs['ylabel'], fontsize=18, color=detail_color)
ax.spines['left'].set_color(detail_color)
ax.spines['bottom'].set_color(detail_color)
ax.legend(
loc=kwargs['legend_loc'], frameon=False, labelcolor=detail_color
)
if which == 'rtmc':
fig.suptitle(kwargs['title'], fontsize=20, color=detail_color)
def write_to_csv(self, file_name):
df = self.get_delta_CO2_storage(as_df=True)
df['dCO2s_total'] = self.get_summed_delta_CO2_storage(as_df=True)
df.to_csv(file_name, index_label='DateTime')
def write_to_netcdf(self, file_path, attrs=None):
df = self.get_delta_CO2_storage(as_df=True)
df['dCO2s_total'] = self.get_summed_delta_CO2_storage(as_df=True)
ds = df.to_xarray()
ds.attrs = {'Site': self.site,
'Heights (m)': ', '.join([str(i) for i in
self.get_heights()]),
'Layer depths (m)': ', '.join([str(i) for i in
self.get_layer_depths()])}
if attrs: ds.attrs.update(attrs)
ds.Time.encoding = {'units': 'days since 1800-01-01',
'_FillValue': None}
ds.to_netcdf(file_path, format='NETCDF4')
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
### FUNCTIONS ###
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def _get_dataframe(this_da):
df = this_da.to_dataframe().unstack()
df.columns = df.columns.droplevel(0)
if df.columns.dtype == object:
return df[this_da[this_da.dims[1]].data]
return df
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def get_site_profile_dataset(site):
if not site in VALID_SITES:
raise KeyError('Site not recognised!')
if site == 'Boyagin':
import Boyagin_profile as prof_mod
elif site == 'CumberlandPlain':
import CumberlandPlain_profile as prof_mod
elif site == 'HowardSprings':
import HowardSprings as prof_mod
elif site == 'Litchfield':
import Litchfield as prof_mod
elif site == 'Warra':
import Warra as prof_mod
elif site == 'Whroo':
import Whroo as prof_mod
elif site == 'WombatStateForest':
import WSF as prof_mod
return prof_mod.return_data()
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def get_site_profile_class(site):
return profile(
ds=get_site_profile_dataset(site=site),
site=site
)
#------------------------------------------------------------------------------