Skip to content

Commit

Permalink
add tropical nights process
Browse files Browse the repository at this point in the history
  • Loading branch information
cehbrecht committed Aug 6, 2018
1 parent b476de0 commit 94a8bc6
Show file tree
Hide file tree
Showing 7 changed files with 166 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ecaswps/default.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@ parallelprocesses = 2
level = INFO
file = ecaswps.log
format = %(asctime)s] [%(levelname)s] line=%(lineno)s module=%(module)s %(message)s

[ophidia]
username = demo
password = demo
server = localhost
port = 11732
2 changes: 2 additions & 0 deletions ecaswps/processes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from .wps_sleep import Sleep
from .wps_index_tn import TropicalNights

processes = [
Sleep(),
TropicalNights(),
]
76 changes: 76 additions & 0 deletions ecaswps/processes/wps_index_tn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import os
from pywps import Process, LiteralInput, ComplexOutput
from pywps import Format
from pywps.app.Common import Metadata


# ALLOWED_VALUES = {
# 'model':
# 'ACCESS1-0 ACCESS1-3 bcc-csm1-1 bcc-csm1-1-m BNU-ESM CanCM4 '
# 'CanESM2 CCSM4 CESM1-BGC CESM1-CAM5 CESM1-WACCM CMCC-CM CMCC-CMS '
# 'CNRM-CM5 CSIRO-Mk3-6-0 EC-EARTH FGOALS-g2 FIO-ESM GFDL-CM2p1 '
# 'GFDL-CM3 GFDL-ESM2G GFDL-ESM2M GISS-E2-H GISS-E2-H-CC GISS-E2-R '
# 'GISS-E2-R-CC HadCM3 HadGEM2-AO HadGEM2-CC HadGEM2-ES inmcm4 '
# 'IPSL-CM5A-LR IPSL-CM5A-MR IPSL-CM5B-LR MIROC4h MIROC5 MIROC-ESM '
# 'MIROC-ESM-CHEM MPI-ESM-LR MPI-ESM-MR MRI-CGCM3 NorESM1-M NorESM1-ME'.split(),
# 'experiment':
# 'rcp45 rcp60 rcp8'.split(),
# }


class TropicalNights(Process):
def __init__(self):
inputs = [
LiteralInput('dataset', 'Dataset',
data_type='string'),
# LiteralInput('model', 'Model',
# default='HadGEM2-ES', data_type='string',
# allowed_values=ALLOWED_VALUES['model']),
# LiteralInput('experiment', 'Experiment',
# default='rcp45', data_type='string',
# allowed_values=ALLOWED_VALUES['experiment']),
# LiteralInput('start_year', 'Start Year',
# default='2010', data_type='integer'),
# LiteralInput('end_year', 'End Year',
# default='2020', data_type='integer'),
]
outputs = [
ComplexOutput('output', 'Output plot',
abstract='Map of Trophical Nights',
as_reference=True,
supported_formats=[Format('image/png')])
]

super(TropicalNights, self).__init__(
self._handler,
identifier='tropical_nights',
version='1.0',
title='Tropical Nights',
abstract='Computes the Tropical Nights index: '
'starting from the daily minimum temperature (1980-1990) TN, '
'the Tropical Nights index is the number of days where TN > T '
'(T is a reference temperature, e.g. 20 degree celsius)',
profile='',
metadata=[
Metadata('ECASLab', 'https://ecaslab.dkrz.de/home.html'),
],
inputs=inputs,
outputs=outputs,
store_supported=True,
status_supported=True
)

def _handler(self, request, response):
from ecaswps.toolbox import tropical_nights
response.update_status('Calculting TN ...', 0)
# output in workdir
output_filename = os.path.join(self.workdir, 'output.png')
# start TN
tropical_nights(
dataset=request.inputs['dataset'][0].data,
output=output_filename)
# store result
response.outputs['output'].file = output_filename
# done
response.update_status('TN done', 100)
return response
76 changes: 76 additions & 0 deletions ecaswps/toolbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from PyOphidia import cube

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np

from pywps import configuration


def tropical_nights(dataset, ouput):
cube.Cube.setclient(
username=configuration.get_config_value('ophidia', 'username'),
password=configuration.get_config_value('ophidia', 'password'),
server=configuration.get_config_value('ophidia', 'server'),
port=configuration.get_config_value('ophidia', 'port'))
# # Import source data (minimum temperature °K)
mintemp = cube.Cube(
src_path=dataset,
measure='temp2',
import_metadata='yes',
imp_dim='time',
imp_concept_level='d',
vocabulary='CF',
hierarchy='oph_base|oph_base|oph_time',
ncores=4,
description='Min Temps'
)
# Identify the tropical nights
tropicalnights = mintemp.apply(
query="oph_predicate('OPH_FLOAT','OPH_INT',measure,'x-293.15','>0','1','0')"
)
# Count the number of tropical nights
count = tropicalnights.reduce2(
operation='sum',
dim='time',
concept_level='y',
)
# # Plot the result
firstyear = count.subset(subset_filter=1, subset_dims='time')
data = firstyear.export_array(show_time='yes')
lat = data['dimension'][0]['values'][:]
lon = data['dimension'][1]['values'][:]
var = data['measure'][0]['values'][:]
var = np.reshape(var, (len(lat), len(lon)))
# cartopy plot
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
ax.set_global()
plt.contourf(lon, lat, var, 60, transform=ccrs.PlateCarree())
# Save the plot by calling plt.savefig() BEFORE plt.show()
plt.savefig(ouput)
plt.title('Tropical Nights (year 1980)')
plt.show()
#
# fig = plt.figure(figsize=(15, 15), dpi=100)
# # ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
#
# map = Basemap(
# projection='cyl',
# llcrnrlat=-90,
# urcrnrlat=90,
# llcrnrlon=0,
# urcrnrlon=360,
# resolution='c')
#
# map.drawcoastlines()
# map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
# map.drawmeridians(np.arange(-180, 180, 30), labels=[0, 0, 0, 1])
#
# x, y = map(*np.meshgrid(lon, lat))
# clevs = np.arange(0, 371, 10)
#
# cnplot = map.contourf(x, y, var, clevs, cmap=plt.cm.jet)
# cbar = map.colorbar(cnplot, location='right')
4 changes: 4 additions & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ dependencies:
- jinja2
- click
- psutil
# ophidia
- pyophidia
- numpy
- cartopy
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ exclude =
build,
dist,
src,
examples,

[doc8]
ignore-path = docs/build,docs/source/_templates,docs/source/_static
Expand Down
1 change: 1 addition & 0 deletions tests/test_wps_caps.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ def test_wps_caps():
'/ows:Identifier')
assert sorted(names.split()) == [
'sleep',
'tropical_nights',
]

0 comments on commit 94a8bc6

Please sign in to comment.