observationoperator.py 39.8 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
39
40
41
42
#!/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
from da.tools.general import create_dirs, to_datetime
from da.ccffdas.emissionmodel import EmisModel 
from da.baseclasses.observationoperator import ObservationOperator

43
44
45
46
47
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()
48
49
50
import xlrd


51
from da.ccffdas import category_info
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
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 ###################

89
model_settings = rc.read('/projects/0/ctdas/awoude/develop/exec/da/rc/stilt/stilt.rc')
90
91
recalc_factors = [1, 1000]
spname = ['CO2', 'CO']
92
93
94


def run_STILT(dacycle, footprint, datepoint, i_species, path, i_member):
95
96
97
98
99
100
101
102
103
104
    """This function reads in STILT footprints and returns hourly concentration data
    Input:
        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
        i_species  : int: index of the species
        i_member   : int: index of the ensemblemember
    Returns:
        float: the concentration increase at the respective location due to the emissions from the respective species"""
    # get the date:
105
    spatial_emissions = get_spatial_emissions(dacycle, i_member, i_species, path, datepoint)
106
107

    # multiply footprint with emissions for each hour in the back trajectory. Indices: Time, Category, lat, lon
108
    foot_flux = (footprint[None, :, :, :] * spatial_emissions[:, :, :, :]).sum()
109
110
111
    concentration_increase = float(recalc_factors[i_species]) * foot_flux
    return concentration_increase

112
@cached
113
def get_spatial_emissions(dacycle, i_member, i_species, path, datepoint):
114
115
116
117
118
119
120
    """ Function that gets the spatial emissions
    Input:
        i_member: int: the index of the member for which the simulation is run
        i_species: int: the index of the species for which the simulation is run
    Returns:
        np.ndarray (3d): the spatial emissions per category, lat and lon"""
    #read spatially distributed emissions calculated with the emission model
121
122
123
124
125
    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)
126
    emisfile = path +'prior_spatial_{0:03d}.nc'.format(i_member) #format: species[SNAP, time, lon, lat]
127
128
    f = io.ct_read(emisfile,method='read')
    emis=f.get_variable(spname[i_species])
129
    emis = emis[:, indices, :, :].astype(np.float32) # index the interesting times
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    f.close()
    return emis

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
    """
    # 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
147
    time_index = int(timediff_hours)
148
149
    return time_index

150
def get_time_indices(datepoint, startdate=None, backtimes=24):
151
152
153
154
    """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)
155
    return slice(time_index - backtimes, time_index)
156
157
158
159

def get_biosphere_concentration(foot, gpp_mem, ter_mem):
    """Function that calculates the atmospheric increase due to the exchange of fluxes over the footprint
    Input:
Woude, Auke van der's avatar
Woude, Auke van der committed
160
161
162
163
164
165
        foot: np.array(times, lat, lon):
            the footprint of the station
        gpp_mem: np.array(nmmebers, time, lat, lon)
            map of the gpp for each member
        ter_mem: np.array(nmembers, time, lat, lon)
            map of the ter for each member
166
    Returns:
Woude, Auke van der's avatar
Woude, Auke van der committed
167
        tuple of 2 floats: GPP and TER in umol/s """
168

Woude, Auke van der's avatar
Woude, Auke van der committed
169
    # First, recalculate to good units
170
171
172
    gpp = gpp_mem[:, :, :, :] * (1./MASS_C) * MOL2UMOL * PERHR2PERS
    ter = ter_mem[:, :, :, :] * (1./MASS_C) * MOL2UMOL * PERHR2PERS

Woude, Auke van der's avatar
Woude, Auke van der committed
173
    # Multiply with the footprint
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
    gpp_increase = - (gpp * foot[None, :, :, :]).sum()
    ter_increase = (ter * foot[None, :, :, :]).sum()

    return gpp_increase, ter_increase

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
190
        self.model_settings = rc.read(filename)
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
        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'])
212
        self.categories = categories # Imported from file at top
Woude, Auke van der's avatar
Woude, Auke van der committed
213
        self.inputdir = dacycle.dasystem['inputdir']
214
        self.paramdict = rc.read(dacycle.dasystem['paramdict'])
215

216
217
218
        with nc.Dataset(dacycle.dasystem['biosphere_fluxdir']) as biosphere_fluxes:
            self.gpp = biosphere_fluxes['GPP'][:].astype(np.float32) 
            self.ter = biosphere_fluxes['TER'][:].astype(np.float32) 
219
220
221
222

        with nc.Dataset(self.dacycle.dasystem['country.mask']) as countries:
            self.masks = countries['country_mask'][:]
            self.country_names = countries['country_names'][:]
Woude, Auke van der's avatar
Woude, Auke van der committed
223
224
        self.nffparams = int(self.dacycle.dasystem['nffparameters'])
        self.nbioparams = int(self.dacycle.dasystem['nbioparameters'])
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

    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"""

        # 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
258
        self.param_inputdir = self.dacycle.dasystem['inputdir']
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
        #list all observation locations and species
        self.lat = []
        self.lon = []
        self.hgt = []
        self.obsnc = []
        self.mmass = []
        self.sitenames=[]
        self.recalc_factors = []
        infile = os.path.join(self.obsdir, self.obsfile)    
        f = open(infile, 'r')
        lines = f.readlines()
        f.close()
        self.spname = []
        
        # Parse input file
        for line in lines:
            if line[0] == '#': continue
            else:
                ct_, filename, lat, lon, height, species_name, species_mass, recalc_factor, *_ = line.split(',')
                two_names = any(x in filename for x in ['UW', 'DW'])
                sitename = ('_'.join(filename.split('_')[1:2 + two_names]))
                ct = int(ct_) - 1 # Set the counter
                self.obsnc.append(filename)
                self.sitenames.append(sitename)
                if species_name in self.spname:
                    if species_name == self.spname[0]:
                        self.lat.append(lat)
                        self.lon.append(lon)
                        self.hgt.append(height)
                else:
                    self.spname.append(species_name)
                    self.mmass.append(species_mass)
                    self.recalc_factors.append(recalc_factor)
                    if ct == 0:
                        self.lat.append(lat)
                        self.lon.append(lon)
                        self.hgt.append(height)
                    
        self.temporal_var = []
        for k, v in self.categories.items():
            self.temporal_var.append(v['temporal'])
        #set time control variables for this cycle
        if do_pseudo==0:
            self.timestartkey = dtm.datetime(self.dacycle['time.sample.start'].year,
                                             self.dacycle['time.sample.start'].month,
                                             self.dacycle['time.sample.start'].day,
                                             self.dacycle['time.sample.start'].hour, 0)
            self.timefinishkey = dtm.datetime(self.dacycle['time.sample.end'].year,
                                              self.dacycle['time.sample.end'].month,
                                              self.dacycle['time.sample.end'].day,
                                              self.dacycle['time.sample.end'].hour, 0)
        elif do_pseudo==1:
            self.timestartkey = dtm.datetime(self.dacycle['time.fxstart'].year,
                                             self.dacycle['time.fxstart'].month,
                                             self.dacycle['time.fxstart'].day,
                                             self.dacycle['time.fxstart'].hour, 0)
            self.timefinishkey = dtm.datetime(self.dacycle['time.finish'].year,
                                              self.dacycle['time.finish'].month,
                                              self.dacycle['time.finish'].day,
                                              self.dacycle['time.finish'].hour, 0)
        self.prepare_c14()
        
        self.run_dynamic_emis_model()

        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)    

    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"""
332
        logging.info('Calculating the emissions; entering Emismodel.py')
333
334
335
        emismodel = EmisModel()
        emismodel.setup(self.dacycle)
        self.emismodel = emismodel
336
337
338
339
        backtimes = 24 + int(self.dacycle['time.cycle']) * 24 # extra hours in backtime
        indices = get_time_indices(self.dacycle['time.sample.end'], backtimes=backtimes)
        emismodel.get_emis(self.dacycle, self.allsamples, indices=indices, do_pseudo=0)
        logging.info('Emissions calculated')
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366

    def prepare_biosphere(self, datepoint):
        """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"""
        
        # First, get the time indices
        indices = get_time_indices(datepoint)
        
        # Get the biosphere flux
        gpp = self.gpp[indices]
        ter = self.ter[indices]
        
        self.gpp_mem = np.zeros((self.forecast_nmembers, *gpp.shape))
        self.ter_mem = np.zeros_like(self.gpp_mem)
        for mem in range(self.forecast_nmembers):
        # multiply with the statevectorvalues
            param_values = self.param_values[mem]
            gpp_new = np.zeros_like(gpp)
            ter_new = np.zeros_like(ter)
            for i, country in enumerate(self.country_names):
                self.country = country
                country = b''.join(np.array(country)).decode()
        
                country_mask = self.masks[i]
367
                index_in_state = self.emismodel.find_in_state(param_values, country.upper(), 'bio', return_index=True)
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
                if index_in_state: param_value = param_values[index_in_state]
                else: param_value = 1
                gpp_country = country_mask[None, :, :] * gpp[:, :, :] * param_value
                ter_country = country_mask[None, :, :] * ter[:, :, :] * param_value
                gpp_new += gpp_country
                ter_new += ter_country
            self.gpp_mem[mem] = gpp_new
            self.ter_mem[mem] = ter_new

    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


        file = self.model_settings['biosphere_fluxdir']
        dis_eq_flux = self.get_nc_variable(file, 'TER_dC14')
        self.dis_eq_flux = dis_eq_flux


        file = self.model_settings['nuclear_fluxdir']
        nuc_flux = self.get_nc_variable(file, 'E_14CO2_nuc')
        self.nuc_flux = nuc_flux

    ### !!!! Only cache if made dependent on datepoint/datetime !!!!
    def get_time_index_nc(self, 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
        """
        if time == None:
            # Get the time of the current cycle
            time = self.dacycle['time.start']
        # Get the start date of all cycles
        if not startdate: startdate = self.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
414
        time_index = int(timediff_hours)
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
        return time_index
    
    def get_time_indices(self, datepoint, startdate=None):
        """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 = self.get_time_index_nc(datepoint, startdate=startdate)
        return slice(time_index - int(self.model_settings['num_backtimes']), time_index)

   # @cached
    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']

        # Flip, because the times are negative
445
        return np.flipud(footprint).astype(np.float32)
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579

    #@cached 
    def get_background(self, i_species, site, datepoint):
        """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: 
            i_species: int: the index of the species for which the background should be found
            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)

        species_name = self.spname[i_species]

        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:
            i_species: int: the index of the species for which the background should be found
            i_loc    : int: the index of the locatin for which the background should be found
            datepoint: datetime for which the background concentration should be found.
        Returns:
            float: background concentration
            """

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

    def get_biosphere_concentration(self, foot, gpp_mem, ter_mem):
        """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 """
    
        # First, get the footprint
        gpp = gpp_mem[:, :, :, :] * (1./MASS_C) * MOL2UMOL * PERHR2PERS
        ter = ter_mem[:, :, :, :] * (1./MASS_C) * MOL2UMOL * PERHR2PERS
    
        gpp_increase = - (gpp * foot[None, :, :, :]).sum(axis=(1,2,3))
        ter_increase = (ter * foot[None, :, :, :]).sum(axis=(1,2,3))
    
    #    logging.debug('GGP flux = {0:.3}; TER flux = {1:.3}'.format(gpp_increase, ter_increase))
    
        return gpp_increase, ter_increase


#    @cached
    def get_c14_concentration(self, datepoint,  gpp, ter, ff_flux, background):
        """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
        
        nuc_flux = self.nuc_flux
        nuc_flux = (nuclear_time_profile[:, None, None] * nuc_flux[None,:] * self.foot).sum() 
        nuc_flux *= (1./MASS_14CO2) * KMOL2UMOL * PERYR2PERS

        # 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]
        # 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)
                       (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
        # Conversion 14CO2 in ppm to DELTA ----
        co2_total = ff_flux + gpp + ter + nuc_flux + background
        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

#    @cached
    def get_nc_variable(self, file, fluxname):
        """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][:]
        data.close()
        return fluxmap
580

581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    def run_forecast_model(self,dacycle,do_pseudo,adv):
        self.prepare_run(do_pseudo,adv)
        self.run(dacycle,do_pseudo)
        self.save_data()
#        self.run_breakdown()

    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
607
            indices = get_time_indices(datepoint)
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636

            if datepoint != previously_done_datepoint: 
                # If it is a new date, we need a new biosphere prior
                # Note that this could be optimised because we just
                # Shift the time index by one. However, this takes 
                # Only about half a second
                self.prepare_biosphere(datepoint)
            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)

            try: # If there is a concentration returned, add this to the calculated concentrations. 
                 # Otherwise, keep the Nans.
                 if any(concentrations): calculated_concentrations[i, :] = concentrations
            except: pass #calculated_concentrations = np.delete(calculated_concentrations, i, axis=0)

            # Set the time and site 
637
638
639
            previously_done_datepoint = datepoint
            previous_day = datepoint.day
            previously_done_site = site
640
641
642
643
644
        # 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
645
        logging.debug('Cache info: {}'.format(get_spatial_emissions.cache_info()))
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669

    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]
        i_species = self.spname.index(species.upper())
        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
670
        # First, add noise (this represents errors in the transport model
671
        noise = np.random.normal(0, sample.mdm)
Woude, Auke van der's avatar
Woude, Auke van der committed
672

673
674
675
676
677
678
        # 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
679
            func = partial(run_STILT, self.dacycle, self.foot, datepoint, i_species, self.inputdir)
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
            # 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] = {}
            bio_fluxes = self.get_biosphere_concentration(self.foot, self.gpp_mem, self.ter_mem)           
            nee = np.array(sum(bio_fluxes))
            
            self.c14_dict[site][datepoint]['bio'] = bio_fluxes[:]
            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] = {}
                    bio_fluxes = self.get_biosphere_concentration(self.foot, self.gpp_mem, self.ter_mem)           
                
                    self.c14_dict[site][datepoint]['bio'] = bio_fluxes[:]
                    
                    # 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):
                gpp = self.c14_dict[site][datepoint]['bio'][0][mem]               
                ter = self.c14_dict[site][datepoint]['bio'][1][mem]
                ff_flux = self.c14_dict[site][datepoint]['ff'][mem] 
                c14concentrations[mem] = self.get_c14_concentration(datepoint, gpp, ter, ff_flux, self.get_background_orig('CO2'))
Woude, Auke van der's avatar
Woude, Auke van der committed
762
            return c14concentrations + noise
763
764
765
766
767
768
769
770
771
        

        # 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 """
772
        # Create a new file
773
774
775
        f = io.CT_CDF(self.simulated_file, method='create')
        logging.debug('Creating new simulated observation file in ObservationOperator (%s)' % self.simulated_file)

776
        # Save the id of the observation
777
778
779
780
781
782
783
784
785
786
787
        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)

788
        # Save the simulated mole fraction
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
        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