
from pywps import Process, LiteralInput, ComplexInput, ComplexOutput
from pywps import Format

import logging
LOGGER = logging.getLogger('PYWPS')

import matplotlib
# no X11 server ... must be run first
# https://github.com/matplotlib/matplotlib/issues/3466/
matplotlib.use('Agg')

import matplotlib.pylab as plt
import cartopy.crs as ccrs
from netCDF4 import Dataset

AIR_DS = 'https://www.esrl.noaa.gov/psd/thredds/fileServer/Datasets/ncep.reanalysis.derived/surface/air.mon.ltm.nc'


def simple_plot(resource, variable=None, output=None):
    output = output or 'plot.png'
    ds = Dataset(resource)
    values = ds.variables[variable]
    fig = plt.figure(figsize=(20, 10))
    ax = plt.axes(projection=ccrs.PlateCarree())
    plt.contourf(values[0, :, :])
    ax.stock_img()
    ax.coastlines()
    plt.colorbar()
    fig.savefig(output)
    plt.close()
    return output


class SimplePlot(Process):
    def __init__(self):
        inputs = [
            ComplexInput('dataset', 'Dataset', supported_formats=[Format('application/x-netcdf')],
                         default=AIR_DS,
                         abstract='Example: {0}'.format(AIR_DS)),
            LiteralInput('variable', 'Variable', data_type='string',
                         default='air',
                         abstract='Please enter the variable name to be plotted, example: air'),
        ]
        outputs = [
            ComplexOutput('output', 'Simple Plot', supported_formats=[Format('image/png')],
                          as_reference=True),
        ]

        super(SimplePlot, self).__init__(
            self._handler,
            identifier='simple_plot',
            title='Simple Plot',
            abstract='Returns a nice and simple plot.',
            version='1.0',
            inputs=inputs,
            outputs=outputs,
            store_supported=True,
            status_supported=True
        )

    def _handler(self, request, response):
        variable = request.inputs['variable'][0].data
        output = simple_plot(
            resource=request.inputs['dataset'][0].file,
            variable=variable)
        LOGGER.info("produced output: %s", output)
        response.outputs['output'].file = output
        response.update_status("simple_plot done", 100)
        return response

[((6, 9, 6, 35), 'logging.getLogger', 'logging.getLogger', ({(6, 27, 6, 34): '"""PYWPS"""'}, {}), "('PYWPS')", False, 'import logging\n'), ((11, 0, 11, 21), 'matplotlib.use', 'matplotlib.use', ({(11, 15, 11, 20): '"""Agg"""'}, {}), "('Agg')", False, 'import matplotlib\n'), ((22, 9, 22, 26), 'netCDF4.Dataset', 'Dataset', ({(22, 17, 22, 25): 'resource'}, {}), '(resource)', False, 'from netCDF4 import Dataset\n'), ((24, 10, 24, 38), 'matplotlib.pylab.figure', 'plt.figure', (), '', True, 'import matplotlib.pylab as plt\n'), ((26, 4, 26, 33), 'matplotlib.pylab.contourf', 'plt.contourf', ({(26, 17, 26, 32): 'values[(0), :, :]'}, {}), '(values[(0), :, :])', True, 'import matplotlib.pylab as plt\n'), ((29, 4, 29, 18), 'matplotlib.pylab.colorbar', 'plt.colorbar', ({}, {}), '()', True, 'import matplotlib.pylab as plt\n'), ((31, 4, 31, 15), 'matplotlib.pylab.close', 'plt.close', ({}, {}), '()', True, 'import matplotlib.pylab as plt\n'), ((25, 29, 25, 47), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ({}, {}), '()', True, 'import cartopy.crs as ccrs\n'), ((41, 12, 43, 95), 'pywps.LiteralInput', 'LiteralInput', (), '', False, 'from pywps import Process, LiteralInput, ComplexInput, ComplexOutput\n'), ((38, 66, 38, 96), 'pywps.Format', 'Format', ({(38, 73, 38, 95): '"""application/x-netcdf"""'}, {}), "('application/x-netcdf')", False, 'from pywps import Format\n'), ((46, 70, 46, 89), 'pywps.Format', 'Format', ({(46, 77, 46, 88): '"""image/png"""'}, {}), "('image/png')", False, 'from pywps import Format\n')]