observationoperator.py 37.5 KB
Newer Older
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
#!/usr/bin/env python
# stilt_tools.py

"""
Author : W. He
Adapted by Ingrid Super, last revisions 14-8-2018
Adapted by Auke van der Woude, 09-2019 -- ...

Revision History:
| -- Basing on Wouter's codes, replace the TM5 model with the STILT model, April 2015.
| -- Expanding code to include C14 and a biosphere module 
This module holds specific functions needed to use the STILT model within the data assimilation shell. It uses the information
from the DA system in combination with the generic stilt.rc files.

The STILT model is now controlled by a python subprocess. This subprocess consists of an MPI wrapper (written in C) that spawns
a large number ( N= nmembers) of STILT model instances under mpirun, and waits for them all to finish.

#The design of the system assumes that the stilt function are executed using R codes, and is residing in a
#directory specified by the ${RUNDIR} of a stilt rc-file. This stilt rc-file name is taken from the data assimilation rc-file. Thus,

"""
import shutil
import os
import sys
import logging
import pickle
import datetime as dtm
import numpy as np
from numpy import array, logical_and
import glob
import subprocess
import netCDF4 as nc

from functools import partial
from multiprocessing import Process, Pool

import da.tools.io4 as io
import da.tools.rc as rc
Woude, Auke van der's avatar
Woude, Auke van der committed
39
import da.tools.sibtools as st
40
41
42
43
from da.tools.general import create_dirs, to_datetime
from da.ccffdas.emissionmodel import EmisModel 
from da.baseclasses.observationoperator import ObservationOperator

44
45
#import matplotlib.pyplot as plt

46
47
48
49
50
try: # Import memoization. This speeds up the functions a lot.
    from memoization import cached
except: # The memoization package is not always included. Import the memoization from #functools
    from functools import lru_cache as cached
    cached = cached()
51
52
53
import xlrd


54
from da.ccffdas import category_info
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
categories = category_info.categories
# global constants, which will be used in the following classes
identifier = 'WRF-STILT'
version = '1.0'

### Constants for the calculation of fluxes
MASS_C              = 12.00
MASS_C_14           = 14.00
MASS_CO             = 28.01                                                          # kg/kmol
MASS_CO2            = 44.01                                                          # kg/kmol
MASS_14CO2          = 46.00                                                          # kg/kmol
Aabs             = 226.                                                           # Bq/kgC         Absolute radiocarbon standard (Mook and van der Plicht, 1999)
dt_obs           = 0.                                                             # s              time between sampling and measuring
d13C             = -9.                                                            # per mille
Nav              = 6.023e23                                                       # molecules/mole Avogadro's number
tau_14CO2        = 5700 * 365*24*3600.                                            # s              half life time of 14CO2
lambda_14CO2     = np.log(2)/tau_14CO2                                            # s-1            radioactive decay

MOL2UMOL = 1.0e6
KMOL2UMOL= 1.0e9
PERHR2PERS = 1.0/(3600.)
PERYR2PERS = 1.0/(365.*24.*3600.)
epsilon_14CO2_gpp = -36.                                                         # per mille
alpha_14CO2_gpp   = 1 + epsilon_14CO2_gpp/1000.                                  # = 0.964
Rstd            = 1.36e-12                                                       # kg 14C / kgC     # 4.48e-12                                  #  kg 14CO2/kgC (according to Fabian)
delta_14CO2_bg   =    44.6                                                        # per mille
delta_14CO2_ff   = -1000.0                                                        # per mille
delta_14CO2_bf   =  -200.0                                                        # per mille (2*-18 per mille for C3 plants, email dd 28/05/2019)
delta_14CO2_nuc  =  0.7e15                                                        # per mille

R_14CO2_ff = (delta_14CO2_ff /1000. + 1) * Rstd                                 # scalar 0.0
R_14CO2_bf = (delta_14CO2_bf /1000. + 1) * Rstd                                 # scalar 1.501e-12
R_14CO2_bg = (delta_14CO2_bg /1000. + 1) * Rstd                                 # scalar 1.577e-12
epsilon_14CO2_gpp = -36.                                                         # per mille
alpha_14CO2_gpp   = 1 + epsilon_14CO2_gpp/1000.                                  # = 0.964
################### Begin Class STILT ###################

92
model_settings = rc.read('/projects/0/ctdas/awoude/develop/exec/da/rc/stilt/stilt.rc')
93
recalc_factors = {'CO2': 1, 'CO': 1000}
94
spname = ['CO2', 'CO']
95
96


Woude, Auke van der's avatar
Woude, Auke van der committed
97
def run_STILT(dacycle, footprint, datepoint, species, path, i_member):
98
99
    """This function reads in STILT footprints and returns hourly concentration data
    Input:
Woude, Auke van der's avatar
Woude, Auke van der committed
100
101
102
        footprint: np.array: the footprint of the station
        datepoint: datepoint: datetime: the datepoint for which the concentrations should be calculated
        site       : str: name of the location
103
        species    : str: the species
104
105
106
        i_member   : int: index of the ensemblemember
    Returns:
        float: the concentration increase at the respective location due to the emissions from the respective species"""
107
    # get the emission data:
Woude, Auke van der's avatar
Woude, Auke van der committed
108
    spatial_emissions = get_spatial_emissions(dacycle, i_member, species, path, datepoint)
109
110

    # multiply footprint with emissions for each hour in the back trajectory. Indices: Time, Category, lat, lon
111
112
113
114
    if dacycle.dasystem['cat.sum_emissions']:
        foot_flux = (footprint * spatial_emissions).sum()
    else: 
        foot_flux = (footprint[:, None, :, :] * spatial_emissions[:, :, :, :]).sum()
115
    concentration_increase = float(recalc_factors[species]) * foot_flux
116
117
    return concentration_increase

118
@cached
Woude, Auke van der's avatar
Woude, Auke van der committed
119
def get_spatial_emissions(dacycle, i_member, species, path, datepoint):
120
121
122
    """ Function that gets the spatial emissions
    Input:
        i_member: int: the index of the member for which the simulation is run
123
        species:  str: the species for which the simulation is run
124
125
126
    Returns:
        np.ndarray (3d): the spatial emissions per category, lat and lon"""
    #read spatially distributed emissions calculated with the emission model
127
128
129
130
    backtimes = 24 + int(dacycle['time.cycle']) * 24 # extra hours in backtime
    backtimes = dtm.timedelta(hours=backtimes)
    start_time = (dacycle['time.sample.end'] - backtimes)
    indices = get_time_indices(datepoint, start_time)
Woude, Auke van der's avatar
Woude, Auke van der committed
131

132
    emisfile = path +'prior_spatial_{0:03d}.nc'.format(i_member) #format: species[SNAP, time, lon, lat]
133
    f = io.ct_read(emisfile,method='read')
134
    emis=f.get_variable(species)
135
    emis = emis[indices].astype(np.float32) # index the interesting times
136
    f.close()
137
138
139
140

    #plt.figure()
    #plt.imshow(np.log(emis[0, 0, :, :]), cmap='binary')
    #plt.savefig('ff.png')
141
142
    return emis

Woude, Auke van der's avatar
Woude, Auke van der committed
143

144
145
146
147
148
def get_time_index_nc(time=None, startdate=None):
    """Function that gets the time index from the flux files
    based on the cycletime and the first time in all the files (hardcoded in stilt.rc)
    Input:
        time: datetime.datetime: The time for which the index needs to be found. Default: current time cycle datetime
Woude, Auke van der's avatar
Woude, Auke van der committed
149
        startdate: datetime: The time at which the data's first index is
150
151
152
153
154
155
156
157
158
    """
    # Get the start date of all cycles
    if not startdate: startdate = model_settings['files_startdate']
    if isinstance(startdate, str):
        startdate = dtm.datetime.strptime(startdate, '%Y-%m-%d %H:%M:%S')
    # Get the difference between the current and the start
    # Note that this is in hours, and thus assumes that the flux files are hourly as well
    timediff = time - startdate
    timediff_hours = int(timediff.total_seconds()/3600) # 1hour could also be softcoded from time.cycle
159
    time_index = int(timediff_hours)
160
161
    return time_index

162
def get_time_indices(datepoint, startdate=None, backtimes=24):
163
164
165
166
    """Function that gets the time indices in the flux files
    Because if the footprint is for 24 hours back, we need the fluxes 24 hours back"""

    time_index = get_time_index_nc(datepoint, startdate=startdate)
167
    return slice(time_index - backtimes, time_index)
168
169
170
171
172
173
174
175
176
177
178
179

class STILTObservationOperator(ObservationOperator):
    def __init__(self, filename, dacycle=None):   #only the filename used to specify the location of the stavector file for wrf-stilt runs
        """ The instance of an STILTObservationOperator is application dependent """
        self.ID = identifier    # the identifier gives the model name
        self.version = version       # the model version used
        self.restart_filelist = []
        self.output_filelist = []
        self.outputdir = None # Needed for opening the samples.nc files created

        logging.info('Observation Operator initialized: %s (%s)' % (self.ID, self.version))

Woude, Auke van der's avatar
Woude, Auke van der committed
180
        self.model_settings = rc.read(filename)
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
        if dacycle != None:
            self.dacycle = dacycle
        else:
            self.dacycle = {}

        self.startdate=None

    def setup(self, dacycle):
        """ Execute all steps needed to prepare the ObsOperator for use inside CTDAS,
         only done at the very first cycle normally """
        self.dacycle = dacycle
        self.outputdir = dacycle['dir.output']
        self.obsoperator_rc = dacycle['da.obsoperator.rc'] #stilt_footprint.rc
        self.obsfile = dacycle.dasystem['obs.input.id']
        self.obsdir = dacycle.dasystem['datadir']
        self.nrloc = int(dacycle.dasystem['obs.input.nr'])
        self.nrspc = int(dacycle.dasystem['obs.spec.nr']) 
        self.nrcat = int(dacycle.dasystem['obs.cat.nr'])
        self.bgswitch = int(dacycle.dasystem['obs.bgswitch'])
        self.bgfile = dacycle.dasystem['obs.background']
        self.btime = int(dacycle.dasystem['run.backtime'])
Woude, Auke van der's avatar
Woude, Auke van der committed
202

203
        self.categories = categories # Imported from file at top
Woude, Auke van der's avatar
Woude, Auke van der committed
204
        self.inputdir = dacycle.dasystem['inputdir']
205

Woude, Auke van der's avatar
Woude, Auke van der committed
206
207
208
209
210
211
212
213
        self.pftfile = dacycle.dasystem['file.pft']

        self.lon_start = float(dacycle.dasystem['domain.lon.start'])
        self.lon_end =   float(dacycle.dasystem['domain.lon.end'])
        self.lat_start = float(dacycle.dasystem['domain.lat.start'])
        self.lat_end =   float(dacycle.dasystem['domain.lat.end'])
        
        self.domain_shape = (int(dacycle.dasystem['domain.lat.num']), int(dacycle.dasystem['domain.lon.num']))
Woude, Auke van der's avatar
test    
Woude, Auke van der committed
214

Woude, Auke van der's avatar
Woude, Auke van der committed
215
216
        self.nffparams = int(self.dacycle.dasystem['nffparameters'])
        self.nbioparams = int(self.dacycle.dasystem['nbioparameters'])
217

Woude, Auke van der's avatar
Woude, Auke van der committed
218

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    def get_initial_data(self, samples):
        """Function that loads the initial data to the observation operator"""
        self.allsamples = samples
        self.samples = samples.datalist
        datelist = [sample.xdate for sample in self.samples]
        self.datelist = sorted(datelist)
        logging.info('Added samples to the observation operator')

    def prepare_run(self,do_pseudo,adv):
        """ Prepare the running of the actual forecast model, for example compile code
        1) Set general parameters (name of outfile, number of members)
        2) Parse the input obsfile (self.obsfile)
        3) Add the data from the obsfile to the ObservationOperator instance
        4) Find out what model will be used for which emissions
        Args:
            do_pseudo: bool:
                0 if ensemble run needs to be done
                1 if pseudo_observations are used 
        Returns:
            None"""
Woude, Auke van der's avatar
Woude, Auke van der committed
239
240
241
242
        backtimes = 24 + int(self.dacycle['time.cycle']) * 24 # extra hours in backtime
        backtimes_dtm = dtm.timedelta(hours=backtimes)
        self.start_time = (self.dacycle['time.sample.end'] - backtimes_dtm)
        self.indices = get_time_indices(self.dacycle['time.sample.end'], backtimes=backtimes)
243
244
245
246
247
248
249
250
251
252
253
254

        # Define the name of the file that will contain the modeled output of each observation
        if adv==0:
            self.simulated_file = os.path.join(self.outputdir,
                                               'samples_simulated.%s.nc' % self.dacycle['time.sample.stamp'])
        else:
            self.simulated_file = os.path.join(self.outputdir,
                                               'samples_simulated.%s.adv.nc' % self.dacycle['time.sample.stamp'])
        
        # Set the number of ensemble members
        self.forecast_nmembers = int(self.dacycle['da.optimizer.nmembers'])
        # Set the inputdir
Woude, Auke van der's avatar
Woude, Auke van der committed
255
        self.param_inputdir = self.dacycle.dasystem['inputdir']
256
257
        self.temporal_var = [v['temporal'] for k, v in self.categories.items()]

258
259
        #set time control variables for this cycle
        if do_pseudo==0:
260
261
            self.timestartkey = self.dacycle['time.sample.start']
            self.timefinishkey = self.dacycle['time.sample.end']
262
        elif do_pseudo==1:
263
264
265
            self.timestartkey = self.dacycle['time.fxstart']
            self.timefinishkey = self.dacycle['time.finish']

266
267
268
269
270
271
        param_values = []
        for mem in range(self.forecast_nmembers):
            with nc.Dataset(self.param_inputdir + '/parameters.{0:03}.nc'.format(mem)) as ds:
                param_values.append(ds['parametervalues'][:])
        self.param_values = np.asarray(param_values)    

Woude, Auke van der's avatar
Woude, Auke van der committed
272
273
274
275
276
277
278
279
280
281
        logging.info('Running emismodel')
        self.run_dynamic_emis_model()
        logging.info('Getting biosphere fluxes')
        self.get_biosphere_emissions()
        logging.info('Preparing biosphere emissions')
        self.prepare_biosphere()
        logging.info('Preparing C14')
        self.prepare_c14()


282
283
284
    def run_dynamic_emis_model(self):
        """Function that runs the dynamic emission model and writes the spatial emissions and time profiles to nc files
        based on emismodel.py"""
285
        logging.info('Calculating the emissions; entering Emismodel.py')
286
287
288
        emismodel = EmisModel()
        emismodel.setup(self.dacycle)
        self.emismodel = emismodel
289
        emismodel.get_emis(self.dacycle, indices=self.indices)
290
        logging.info('Emissions calculated')
291

Woude, Auke van der's avatar
Woude, Auke van der committed
292
293
    def get_biosphere_emissions(self):
        with nc.Dataset(self.dacycle.dasystem['biosphere_fluxdir']) as biosphere_fluxes:
294
295
296
297
298
            nee = np.flip(biosphere_fluxes['NEE'][self.indices, :, :].astype(np.float32), axis=1)
        self.nee = nee
        #plt.figure()
        #plt.imshow(nee[0, :, :], cmap='binary')
        #plt.savefig('nee.png')
Woude, Auke van der's avatar
Woude, Auke van der committed
299
300

    def prepare_biosphere(self):
301
302
303
304
305
        """Function that prepares the biosphere fluxes on a map
        Input:
            datepoint: datetime.datetime: time for which the biosphere fluxes should be prepared
        Returns: 
            None, writes the biosphere fluxes to self"""
Woude, Auke van der's avatar
Woude, Auke van der committed
306
        logging.debug('Preparing biosphere')
307
308
        
        # First, get the time indices
Woude, Auke van der's avatar
Woude, Auke van der committed
309
310
        indices = self.indices

311
312
313
314
315
316
317
        with nc.Dataset(self.pftfile) as ds:
            pftdata = np.flipud(ds['pft'][:]).astype(int)
        self.pftdata = pftdata
    
        #plt.figure()
        #plt.imshow(pftdata[:, :], cmap='binary')
        #plt.savefig('pft.png')
Woude, Auke van der's avatar
Woude, Auke van der committed
318
319

        logging.debug('Starting paint-by-number')
320
        pool = Pool(self.forecast_nmembers)
Woude, Auke van der's avatar
Woude, Auke van der committed
321
        # Create the function that calculates the conentration
322
323

        func = partial(self.paint_by_number, self.nee, self.param_values, 
324
                       pftdata, self.emismodel.find_in_state, self.average2d, self.domain_shape)
325
        scaled_nees = pool.map(func, list(range(self.forecast_nmembers)))
Woude, Auke van der's avatar
Woude, Auke van der committed
326
327
        pool.close()
        pool.join()
328
329
        self.nee_mem = np.asarray(scaled_nees) # Indices: mem, time, *domain_shape
        
Woude, Auke van der's avatar
Woude, Auke van der committed
330
        logging.debug('Paint-by-number done, biosphere prepared')
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
        
        self.write_biosphere_fluxes(self.nee_mem[0, self.btime:, :, :])
    
    def write_biosphere_fluxes(self, values, qual='prior'):
        # Write the biosphere fluxes to a file
        bio_emis_file = os.path.join(self.outputdir, 'bio_emissions_{}_{}.nc'.format(qual, self.dacycle['time.sample.start'].strftime('%Y%m%d')))
        f = io.CT_CDF(bio_emis_file, method='create')
        dimtime= f.add_dim('time', values.shape[0])
        dimlat = f.add_dim('lat', values.shape[1])
        dimlon = f.add_dim('lon', values.shape[2])

        savedict = io.std_savedict.copy()
        savedict['name'] = 'CO2'
        savedict['long_name'] = 'Biosphere CO2 emissions'
        savedict['units'] = "micromole/m2/s"
        dims = dimtime + dimlat + dimlon
        savedict['dims'] = dims
        savedict['values'] = values
        savedict['dtype'] = 'float'
        f.add_data(savedict)
        f.close()

        #plt.figure()
        #plt.imshow(np.log(self.nee_mem[0, 0, :, :]), cmap='binary')
        #plt.savefig('bio.png')
Woude, Auke van der's avatar
Woude, Auke van der committed
356
357

    @staticmethod
358
359
360
361
362
363
364
    def average2d(arr, new_shape):
        """ Function to average the paint-by-colour NEE to the domain size"""
        shape = (new_shape[0], arr.shape[0] // new_shape[0],
                 new_shape[1], arr.shape[1] // new_shape[1])
        return arr.reshape(shape).mean(-1).mean(1)

    @staticmethod
365
366
367
368
    def paint_by_number(nee, all_param_values, pftdata, 
                        find_in_state, average2d, domain_shape, member):

        scaled_nees = np.zeros((len(nee), *domain_shape), dtype=np.float32)
Woude, Auke van der's avatar
Woude, Auke van der committed
369
        all_lutypes = np.unique(pftdata.reshape(-1))
370
371
        param_values = all_param_values[member]
        newnee = np.zeros_like(nee)
Woude, Auke van der's avatar
Woude, Auke van der committed
372
        for lutype_ind, lutype in enumerate(all_lutypes):
373
374
375
376
377
378
379
380
381
            index_in_state = find_in_state(param_values, 'BIO', str(lutype), return_index=True)
            if index_in_state:
                param_value = param_values[index_in_state]
            else: param_value = 1
            mask = np.where(pftdata == lutype, 1, 0)
            newnee += (nee * mask * param_value)
        for i, n in enumerate(newnee):
            scaled_nees[i] = average2d(n, domain_shape)
        return scaled_nees
382
383
384
385
386
387
388
389
390
391

    def prepare_c14(self):
        """Function that loads the nuclear power temporal variation"""
        # Get the time profiles of the nuclear plants
        temp_distribution_file = self.model_settings['nuclear_timeprofiledir']
        workbook      = xlrd.open_workbook(temp_distribution_file)
        worksheet     = workbook.sheet_by_name('Sheet1')
        time_profile_nuc = np.array(worksheet.col_values(19))
        self.nuc_time_profile = time_profile_nuc

Woude, Auke van der's avatar
Woude, Auke van der committed
392
393
394
        file = self.model_settings['biosphere_fluxdir']
        self.dis_eq_flux = self.get_nc_variable(file, 'TER_dC14', np.float32)[self.indices, :, :]

395
        file = self.model_settings['nuclear_fluxdir']
Woude, Auke van der's avatar
Woude, Auke van der committed
396
        self.nuc_flux = self.get_nc_variable(file, 'E_14CO2_nuc', np.float32)
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416

    def get_foot(self, site,  datepoint):
        """Function that gets the footprint for the current time and site.
        Returns a 3D np.array with dims (time, lat, lon)
        Input:
            i_loc: number of location. Requires object to have a 'sitenames' property
            datepoint: datetime of the footprint to be found.
        Returns:
            np.array (3d): Footprint with as indices time, lat, lon
            """

        path = self.model_settings['footdir'] + '/' + site.upper() + '24'
        fname = path + '/footprint_{0}_{1}x{2:02d}x{3:02d}x{4:02d}*.nc'.format(site.upper(),
                                                                               datepoint.year,
                                                                               datepoint.month,
                                                                               datepoint.day,
                                                                               datepoint.hour)
        f = glob.glob(fname)[0]
        footprint = nc.Dataset(f)['foot']

417
418
419
420
421
422
        #plt.figure()
        #plt.imshow(np.log(footprint[0, :, :]), cmap='binary')
        #plt.title(site)
        #plt.savefig('foot.png')


423
        # Flip, because the times are negative
424
        return np.flipud(footprint).astype(np.float32)
425

426
    def get_background(self, species, site, datepoint):
427
428
429
        """Function that finds the center of mass of the first footprint and the time corresponding to it.
            and finds the concentration in the center of mass. This is used as the background.
        Input: 
430
            species: str:  the species for which the background should be found
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
            i_loc    : int: the index of the locatin for which the background should be found
            datepoint: datetime.datetime: the datetime of the background concentration
        Returns:
            float: background concentration
            """
        from scipy import ndimage
        
        # First, get the footprint and find the first time of influence
        foot = self.foot
        start_influence = -1 # In backtimes
        total_influence = 0
        while total_influence < 0.0000001:
            start_influence += 1
            total_influence = fp[start_influence].sum()
        
        # Get the center of mass of the first influence
        center_of_mass = ndimage.measurements.center_of_mass(fp[start_influence])
        center_of_mass = np.array(np.rint(center_of_mass), dtype=int)

450
        species_name = self.spname[species]
451
452
453
454
455
456
457
458
459
460
461
462
463

        index  = self.get_time_index_nc() - (int(self.model_settings['num_backtimes']) - start_influence)
        
        # Find the concentration at the center of mass at the correct time.
        background_file = self.model_settings['bgfdir'] + '/background.nc'
        background_map  = nc.Dataset(background_file)[species_name]
        background_conc = background_map[index, center_of_mass[0], center_of_mass[1]]
        
        return background_conc
    
    def get_background_orig(self, species):
        """Function that finds the background concentration, non-time dependent and hard-coded.
        Input:
464
            species: the species for which the background should be found
465
466
467
468
469
470
471
        Returns:
            float: background concentration
            """

        backgrounds = {'CO2': 406.15, 'CO': 127.2, 'C14': 0}
        return backgrounds[species]

Woude, Auke van der's avatar
Woude, Auke van der committed
472
    def get_biosphere_concentration(self, foot, nee_mem, datepoint):
473
474
475
476
477
478
479
480
481
482
        """Function that calculates the atmospheric increase due to the exchange of fluxes over the footprint
        Input:
            i_member: int: member number for which the biosphere concentration should be calculated
            site: str: location for which the concentration should be calculated
            total: bool, optional: Whether to returned summed values or gpp and ter seperately as tuple
        Returns:
            if total == True:
                float: The total biosphere flux in umol/s
            else:
                tuple of 2 floats: GPP and TER in umol/s """
Woude, Auke van der's avatar
Woude, Auke van der committed
483
484
485
        indices = get_time_indices(datepoint, self.start_time)
        nee_increase = (nee_mem[:, indices, :, :] * foot[None, :, :, :]).sum(axis=(1,2,3)) # (1./MASS_C) * MOL2UMOL * PERHR2PERS
        return nee_increase
486
487


Woude, Auke van der's avatar
Woude, Auke van der committed
488
    def get_c14_concentration(self, datepoint,  nee, ff_flux, background):
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        """Function that gets the c14 concentration based on the emissions by the biosphere, 
            fossil fuels and nuclear power. The constants are defined at the top of this script.
        Input: 
            datepoint: datepoint: datetime for which the c14 concentration should be calculated
            gpp: float: The gross primary production in umol/s
            ter: float: The total ecosystem respiration in umol/s
            ff_flux: float: The fossil fuel flux in umol/s
            background: float: The background CO2 concentration
        Returns: 
            float: The C14 in ppm
            float: Delta(14C) """
        # Get the time indices
        indices = get_time_indices(datepoint)
        # Get the fluxes from the nuclear plants
        nuclear_time_profile = np.array(self.nuc_time_profile[indices], dtype=float)
        # Get the fluxes and multiply them by the footprint and time profile
        # Note that the unit is already in Delta notation
        
Woude, Auke van der's avatar
Woude, Auke van der committed
507
508
        nuc_flux = self.nuc_flux
        nuc_flux = (nuclear_time_profile[:, None, None] * nuc_flux[None,:] * self.foot).sum() 
509
510
        nuc_flux *= (1./MASS_14CO2) * KMOL2UMOL * PERYR2PERS

Woude, Auke van der's avatar
Woude, Auke van der committed
511
512
513
514
        # now get the disequilibrium flux
        delta_14CO2_ter = (self.dis_eq_flux[indices] * self.foot).sum()
       
        R_14CO2_ter = (delta_14CO2_ter/1000. + 1) * Rstd # [nt,nlat,nlon] 1.639e-12 [1.557e-12 - 1.787e-12]
515
516
517
518
519
520
        # Now, calculate to ppm
        co2_14_ff = ff_flux   * R_14CO2_ff * MASS_C / MASS_C_14
        co2_14_bg = background* R_14CO2_bg * MASS_C / MASS_C_14
        
        # Calculate the total c14 in the sample (ppm)
        co2_14_total = (co2_14_ff + # The C14 due to FF emissions (should be 0)
Woude, Auke van der's avatar
Woude, Auke van der committed
521
522
523
524
525
                       (alpha_14CO2_gpp * R_14CO2_bg * gpp) + # The C14 taken up due to GPP 
                                                               # (note that GPP is negative)
                       (R_14CO2_ter * ter) + # The C14 from the disequilibrium flux
                       nuc_flux +  # The C14 from the nuclera power plants
                       co2_14_bg) # The C14 that was already in the air
526
        # Conversion 14CO2 in ppm to DELTA ----
Woude, Auke van der's avatar
Woude, Auke van der committed
527
        co2_total = ff_flux + gpp + ter + nuc_flux + background
528
529
530
531
532
533
534
        Rm           = (co2_14_total * MASS_14CO2) / (co2_total * MASS_CO2)   # ppm to mass ratio (kg 14CO2 / kgCO2)
        A14          = Rm * lambda_14CO2 * 1e3*Nav / MASS_14CO2 # kg14CO2/kgCO2 * 1/s * molecules/kmole / (kg14CO2/kmole14CO2) = molecules 14CO2 / kgCO2 / s 
        As           = A14 * MASS_CO2 / MASS_C # Bq/kgC-CO2
        Asn = As * ( 1 - 2 * (25+d13C)/1000.)  # Bq/kgC-CO2
        delta_14CO2 = (Asn * np.exp(lambda_14CO2 * dt_obs) / Aabs -1) * 1000.# per mille
        return delta_14CO2

Woude, Auke van der's avatar
Woude, Auke van der committed
535
536
537
538
539
540
541
542
543
544
545
546
547
    def get_nc_variable(self, file, fluxname, dtype):
        """Helper function that gets the values from an nc file
        Input: 
            file: str: filename of the nc file of which the value should be taken
            fluxname: str: name of the variable in the file
        Returns:
            np.ndarray: the values in the nc file"""
        data = nc.Dataset(file)
        fluxmap = data[fluxname][:]
        fluxmap = fluxmap.astype(dtype)
        data.close()
        return fluxmap

548
    def run_forecast_model(self,dacycle,do_pseudo,adv):
Woude, Auke van der's avatar
Woude, Auke van der committed
549
        logging.info('Preparing run...')
550
        #self.make_observations(dacycle)
551
        self.prepare_run(do_pseudo,adv)
Woude, Auke van der's avatar
Woude, Auke van der committed
552
        logging.info('Starting to simulate concentrations...')
553
554
555
        self.run(dacycle,do_pseudo)
        self.save_data()

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574

    def make_observations(self, dacycle, do_pseudo=0, adv=0):
        logging.info('Prepare run...')
        self.prepare_run(do_pseudo, adv)
        logging.info('Starting to simulate concentrations...')
        import pandas as pd
        import copy
        all_samples = copy.deepcopy(self.samples)
        sites = set([sample.code.split('/')[1].split('_')[1] for sample in all_samples])
        print(sites)
        for site in sites:
            current_samples = [sample for sample in all_samples if site in sample.code]
            self.samples = current_samples
            self.run(dacycle, do_pseudo)
            times = [sample.xdate for sample in current_samples]
            df = pd.DataFrame(self.calculated_concentrations, times, columns=['concentration'])
            df.to_csv(site + dtm.datetime.strftime(dacycle['time.sample.start'], "%Y%m%d") +  '.csv')
        save_and_submit(dacycle, statevector)

575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    def run(self, dacycle, do_pseudo):
        """Function that calculates the simulated concentrations for all samples
        Loops over all samples, looks for relevant information (e.g. footprint)
        and forwards this information to the 'calc_concentrations' function
        Stores the information in this object"""
        # Initialise a list with the calculated concentrations. To be filled in this function.
        calculated_concentrations = np.zeros((len(self.samples), self.forecast_nmembers))
        calculated_concentrations[:, :] = np.nan
        # Initialise a datepoint that has been done. For now, this is None
        previously_done_datepoint = None; previous_day = None
        previously_done_site      = None
        self.integrated_samples = {}
        c14_dict = {}
        # Loop over all samples
        for i, sample in enumerate(self.samples):
            # CHeck if this sample should be simulated
            if sample.flag == 99 and not sample.samplingstrategy == 'pseudointegratedsample': continue
            # Check if it is a new date
            self.sample = sample
            datepoint = sample.xdate
Woude, Auke van der's avatar
Woude, Auke van der committed
595

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
            if datepoint.day != previous_day:
                logging.debug('Working on year {}, month {}, day {}'.format(datepoint.year, datepoint.month, datepoint.day))
            # We are now ready to make a simulation for this datepoint

            # Check if this is a new site:
            two_names = any(x in sample.code for x in ['UW', 'DW'])
            site = '_'.join(sample.code.split('_')[1:2 + two_names])
            if site != previously_done_site or datepoint != previously_done_datepoint:
                # If we already have the footprint for this time and site
                # We do not need a new one. Else, load the new footprint
                self.foot = self.get_foot(site, datepoint)

                if not site in c14_dict: c14_dict[site] = {}
                self.c14_dict = c14_dict
            concentrations = self.calc_concentrations(sample)

612
613
614
            # If there is a concentration returned, add this to the calculated concentrations. 
            # Otherwise, keep the Nans.
            if concentrations is not None: calculated_concentrations[i, :] = concentrations
615
616

            # Set the time and site 
617
618
619
            previously_done_datepoint = datepoint
            previous_day = datepoint.day
            previously_done_site = site
620

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        # This is how ingrid did it, so I will too...
        self.mod = np.array(calculated_concentrations)

        # add the calculated concentrations to the object
        self.calculated_concentrations = calculated_concentrations

    def calc_concentrations(self, sample):
        """Function that calculates the concentration for a sample and all members.
        Gets the relevant information from the sample and then calculates the concentration
        Can also handle integrated samples.
        Input: 
            sample: object: MoleFractionSample for which the concentration should be calculated
        Returns:
            float: The calculated concentration
                If the sample is an pseudo-sample (for an integrated sample):
                returns None"""
        # Get the information for calculating the concentration:
        # The species, the sitename, the datepoint
        # Note that these could also be passed from the function that calls this function
        species = sample.species[:3]
        datepoint = sample.xdate
#        logging.debug('{} {}'.format(datepoint, sample.species))
        two_names = any(x in sample.code for x in ['UW', 'DW'])
        site = '_'.join(sample.code.split('_')[1:2 + two_names])
        
        # Get the background concentration
        background = self.get_background_orig(species.upper())

Woude, Auke van der's avatar
Woude, Auke van der committed
649
        # First, add noise (this represents errors in the transport model
650
        noise = np.random.normal(0, sample.mdm)
651
        #noise = 0
Woude, Auke van der's avatar
Woude, Auke van der committed
652

653
654
655
656
657
658
        # Some different cases for different species.
        # First case: Species is not c14:
        # Then calculate the increase in conc due to ff emissions
        if not 'C14' in species.upper():
            pool = Pool(self.forecast_nmembers)
            # Create the function that calculates the conentration
Woude, Auke van der's avatar
Woude, Auke van der committed
659
            func = partial(run_STILT, self.dacycle, self.foot, datepoint, species, self.inputdir)
660
661
662
663
664
665
666
667
668
669
670
671
672
673
            # We need to run over all members
            memberlist = list(range(0, self.forecast_nmembers))
            
            ff_increase = pool.map(func, memberlist)
            pool.close()
            pool.join()
            ff_increase = np.array(ff_increase)
        # Second case: SPecies is CO2. 
        # Then also calculate for the biosphere increase.
        # Also store the FF and BIO increase to calculate C14
        if species.upper() == 'CO2':
            # Initialise a dictionary that holds the biosphere and FF fluxes from this time and site.
            if not datepoint in self.c14_dict[site].keys():
                self.c14_dict[site][datepoint] = {}
Woude, Auke van der's avatar
Woude, Auke van der committed
674
675
            nee = self.get_biosphere_concentration(self.foot, self.nee_mem, datepoint)

Woude, Auke van der's avatar
Woude, Auke van der committed
676
            self.c14_dict[site][datepoint]['bio'] = nee[:]
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
            self.c14_dict[site][datepoint]['ff'] =  ff_increase[:]

        # If not the species is CO2, the NEE is 0.
        else: nee = np.zeros(self.forecast_nmembers)

        # If the species is a pseudo sample for an integrated sample:
        # We have to pretend like it's a C14 sample, but not return the measurement.
        if sample.species.upper() == 'C14_PSEUDO':
            if sample.samplingstrategy == 'pseudointegratedsample':
                # If this is the first timestep for the integrated sample:
                # Initialise a dict that will hold the concentrations.
                if not site in self.integrated_samples.keys():
                    self.integrated_samples[site] = {'times': [], 'concentrations': []}

                # We check if the CO2 fluxes are already calculated        
                if not sample.xdate in self.c14_dict[site]:
                    # If the CO2 concentrations are not yet calculated for this sample:
                    # We calculate these fluxes. First the biosphere
                    self.c14_dict[site][sample.xdate] = {}
Woude, Auke van der's avatar
Woude, Auke van der committed
696
                    nee = self.get_biosphere_concentration(self.foot, self.nee_mem, datepoint)
697
                
Woude, Auke van der's avatar
Woude, Auke van der committed
698
                    self.c14_dict[site][datepoint]['nee'] = nee[:]
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
                    
                    # Pretend the sample is a CO2 sample, so that the FF increase is calculated
                    sample.species = 'CO2'
                    ff_increase = self.calc_concentrations(sample)
                    # Store the calculate ffCO2
                    self.c14_dict[site][datepoint]['ff'] = ff_increase[:] - self.get_background_orig('CO2')

                # Now, we have all things needed to calculate the C14. We do this by using this very funciton
                # And pretend the species is C14.
                sample.species = 'C14'
                c14_from_integrated = self.calc_concentrations(sample)
                # Now, we add the calculated concentration to the object.
                self.integrated_samples[site]['concentrations'].append(c14_from_integrated)
                self.integrated_samples[site]['times'].append(sample.xdate)
                return

        # Third case: The sample is an integrated sample.
        if sample.species.upper() == 'C14_INTEGRATED':    
            if sample.samplingstrategy == 'integrated':
                # As the datalist is sorted, we already have calculated all samples needed
                # Calculate the average.
                concentrations = np.array(self.integrated_samples[site]['concentrations'])
                integrated_conc = concentrations.mean(axis=0)
                self.integrated_conc = integrated_conc
                self.integrated_samples[site] = {'concentrations': [], 'times': []}
                # Return the concentration and add to the concentrations
                return integrated_conc


        # If the sample is a targeted sample of C14 (Or we pretend it is):
        # Calculate the C14 concentration and return it.
        if sample.species.upper() == 'C14':
            c14concentrations = np.zeros(self.forecast_nmembers)
            if not datepoint in  self.c14_dict[site]:
                sample.species = 'CO2'
                _ = self.calc_concentrations(sample)
                sample.species = 'C14'
            for mem in range(self.forecast_nmembers):
Woude, Auke van der's avatar
Woude, Auke van der committed
737
                nee = self.c14_dict[site][datepoint]['nee'][mem]
738
                ff_flux = self.c14_dict[site][datepoint]['ff'][mem] 
Woude, Auke van der's avatar
Woude, Auke van der committed
739
                c14concentrations[mem] = self.get_c14_concentration(datepoint, nee, ff_flux, self.get_background_orig('CO2'))
Woude, Auke van der's avatar
Woude, Auke van der committed
740
            return c14concentrations + noise
741
742
743
744
745
746
747
748
749
        

        # If the species is NOT c14, return the atmospheric concentration.
        new_conc = nee + ff_increase + background + noise
        self.new_conc = new_conc
        return new_conc

    def save_data(self):
        """ Write the data that is needed for a restart or recovery of the Observation Operator to the save directory """
750
        # Create a new file
751
752
753
        f = io.CT_CDF(self.simulated_file, method='create')
        logging.debug('Creating new simulated observation file in ObservationOperator (%s)' % self.simulated_file)

754
        # Save the id of the observation
755
756
757
758
759
760
761
762
763
764
765
        dimid = f.createDimension('obs_num', size=None)
        dimid = ('obs_num',)
        savedict = io.std_savedict.copy() 
        savedict['name'] = "obs_num"
        savedict['dtype'] = "int"
        savedict['long_name'] = "Unique_Dataset_observation_index_number"
        savedict['units'] = ""
        savedict['dims'] = dimid
        savedict['comment'] = "Unique index number within this dataset ranging from 0 to UNLIMITED."
        f.add_data(savedict,nsets=0)

766
        # Save the simulated mole fraction
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
        dimmember = f.createDimension('nmembers', size=self.forecast_nmembers)
        dimmember = ('nmembers',)
        savedict = io.std_savedict.copy() 
        savedict['name'] = "model"
        savedict['dtype'] = "float"
        savedict['long_name'] = "mole_fraction_of_trace_gas_in_air"
        savedict['units'] = "mol tracer (mol air)^-1"
        savedict['dims'] = dimid + dimmember
        savedict['comment'] = "Simulated model value"
        f.add_data(savedict,nsets=0)
        
        f_in = io.ct_read(self.dacycle['ObsOperator.inputfile'],method='read') 
        ids = f_in.get_variable('obs_num')
        
        for i,data in enumerate(zip(ids,self.mod)):
            f.variables['obs_num'][i] = data[0]
            f.variables['model'][i,:] = data[1]
        f.close()
        f_in.close()
        

################### End Class STILT ###################


if __name__ == "__main__":
    pass