Commit ba66ebb2 authored by Espen Sollum's avatar Espen Sollum
Browse files

Added background directory

parent faf58bac
# -*- coding: utf-8 -*-
"""Contains all recognized background formats.
Automatically loads all pre-defined models as sub-modules of pycif.models
"""
from __future__ import absolute_import
from os.path import dirname, basename, isdir
import glob
modules = glob.glob(dirname(__file__) + "/*")
__all__ = [basename(f) for f in modules
if isdir(f) and not f.endswith('.py')]
from . import register
from __future__ import absolute_import
import os
from types import MethodType
from pycif.utils import path
from pycif.utils.check import verbose
from .read_conc import read_conc
from .calc_init import calc_init
requirements = {'domain': {'name': 'FLEXPART', 'version': 'std', 'empty': False}}
import os
import pandas as pd
import xarray as xr
import numpy as np
from datetime import datetime, timedelta
import pycif.utils.check as check
from pycif.utils.netcdf import readnc
from pycif.utils.dates import j2d
def calc_init(self, model, dir_initconc, file_initconc, **kwargs):
""" Calculate background concentration contribution to observations
Args:
self: the background plugin
model: the model plugin
"""
pass
import os
import pandas as pd
import xarray as xr
import numpy as np
from datetime import datetime, timedelta
import pycif.utils.check as check
from pycif.utils.netcdf import readnc
from pycif.utils.dates import j2d
def read_conc(self, model, dir_initconc, file_initconc, **kwargs):
""" Read and load background concentrations. Interpolate to model grid.
Args:
self: the background Plugin
model: the model plugin
dir_initconc, file_initconc: concentrations directory and file format
"""
# Constants for geopotential height calculation
GASC = 8.314 # ideal gas constant (J/K/mol)
TS = 288.15 # surface temperature (K)
GC = 9.81 # gravitational acceleration (m/s2)
MMOL = 0.02894 # (kg/mol)
PSURF = 101325 # surface pressure (Pa)
# Available files in the directory
list_files = os.listdir(dir_initconc)
dates_available = []
for f in list_files:
try:
dates_available.append(datetime.strptime(f, file_initconc))
except:
continue
dates_available = np.array(dates_available)
# If available, read files from one month before and after simulation window.
# Note: subsimu_dates not properly implemented yet
files_conc = pd.date_range(model.subsimu_dates[0] - pd.DateOffset(months=1),
model.subsimu_dates[-1] + pd.DateOffset(months=1),
freq='MS').strftime(file_initconc).tolist()
conc_all = None
for file_conc in files_conc:
if datetime.strptime(file_conc, file_initconc) in dates_available:
data, prs, lat, lon = readnc(os.path.join(dir_initconc, file_conc),
[self.varname_conc, 'pressure', 'latitude', 'longitude'])
# Convert to center coordinates
lat = lat + (lat[1] - lat[0])/2.
lon = lon + (lon[1] - lon[0])/2.
# calculate geopotential height for each layer
nz = data.shape[1]
geoh = np.zeros(nz)
for kz in range(nz):
geoh[kz] = (GASC*TS/GC/MMOL)*np.log(PSURF/prs[kz])
xmod = xr.DataArray(data[0, :, :, :].T,
coords={'lon' : lon, 'lat' : lat, 'height' : geoh},
dims=('lon', 'lat', 'height'))
# Interpolate to model grid (horizontally)
xmod_hor = xmod[:, :, :].interp(coords={'lon' : model.domain.lonc_glob,
'lat' : model.domain.latc_glob},
method='linear',
kwargs={'fill_value' : None})
# Interpolate to model grid (vertically)
# Use nearest neighbor below or above height of available data
height_temp = np.array(model.domain.heights)
height_temp[height_temp < geoh[0]] = geoh[0]
height_temp[height_temp > geoh[-1]] = geoh[-1]
xmod_ver = xmod_hor.interp(coords={'height' : height_temp},
method='linear',
kwargs={'fill_value' : None})
xmod_ver['height'] = np.array(model.domain.heights)
# Use middle of month to represent the time of concentration data TODO: check
xmod_ver['time'] = datetime.strptime(file_conc, file_initconc) + timedelta(days=14)
if conc_all is None:
conc_all = xmod_ver
else:
conc_all = xr.concat([conc_all, xmod_ver], 'time')
return conc_all
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import flexpart
from pycif.utils.classes.background import Background
Background.register_plugin('FLEXPART', 'nc', flexpart)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment