Exemple #1
0
    class Test(object):
        apply_to = util.Parameterise()

        @apply_to(variable='mean')
        def get_filename(self, params={}):
            return 'canoe'

        @apply_to(period='monthly')
        def get_filename(self, params={}):
            return 'yacht'
Exemple #2
0
    class Test(object):
        apply_to = util.Parameterise()

        @apply_to()
        def get_path(self, params={}):
            return '/usual/path'

        @apply_to(variable='dec')
        def get_path(self, params={}):
            return '/deciles/path'
Exemple #3
0
    class Test(object):
        apply_to = util.Parameterise()

        @apply_to(variable='mean', period='monthly')
        def get_filename(self, params={}):
            return 'Monthly Mean'

        @apply_to(variable='anom', period='monthly')
        def get_filename(self, params={}):
            return 'Monthly Anom'
Exemple #4
0
    class TestSubClass(Test):
        apply_to = util.Parameterise(Test)

        @apply_to(period='monthly')
        def get_path(self, params={}):
            return '/original/data/path'

        @apply_to(period='monthly', variable='dec')
        def get_path(self, params={}):
            return self.get_path(params=params, _ignore=['period'])
Exemple #5
0
    class Test(object):
        apply_to = util.Parameterise()

        @apply_to(period='monthly')
        def get_title(self, params={}):
            return 'Monthly Average'

        @apply_to(variable='anom')
        def get_title(self, params={}):
            return 'Monthly Anom'
Exemple #6
0
class ReynoldsPlotter(SurfacePlotter):
    DATASET = 'reynolds'
    PRODUCT_NAME = "Reynolds SST"

    VARIABLE_MAP = {
        'mean': 'sst',
        'dec': 'sst_dec_cats',
    }

    apply_to = util.Parameterise(SurfacePlotter)

    def get_colormap_strategy(self, params={}):
        return 'nonlinear'

    @apply_to(period='daily')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET],
                            'daily-new-uncompressed')

    def get_prefix(self, params={}):
        prefix = 'reynolds_sst_avhrr-only-v2_'
        if params['period'] == 'daily':
            prefix = 'avhrr-only-v2.'
        return prefix

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']

        #        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        #        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        #        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        #        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        #        grid = self.get_grid(params=args,
        #                             lonrange=(lon_min, lon_max),
        #                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(
            inputLat, inputLon, grid.lats, grid.lons, grid.data)
        value = grid.data[latIndex, lonIndex]
        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value
Exemple #7
0
class SurfacePlotter(object):
    """
    Plot surface data from a netCDF grid.

    Override class hooks to specify the location for data.

    Use the decorator @SurfacePlotter.apply_to to tag methods to bind to
    specific parameters. Most tightly binding function wins.
    """

    BASE_YEAR = '1950'
    FILE_EXTENSION = '.nc'

    apply_to = util.Parameterise()

    # --- get_path ---
    @apply_to()
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET],
                            'averages', params['period'])

    @apply_to(variable='dec')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET],
                            'decile', self.BASE_YEAR, params['period'])

    def get_prefix(self, params={}):
        return ''

    # --- get_suffix ---
    @apply_to(variable='dec')
    def get_suffix(self, params={}):
        return '_dec' + self.FILE_EXTENSION

    @apply_to()
    def get_suffix(self, params={}):
        return self.FILE_EXTENSION

    @apply_to(variable='dec')
    def get_suffix_prelim(self, params={}):
        return '_preliminary_dec' + self.FILE_EXTENSION

    @apply_to()
    def get_suffix_prelim(self, params={}):
        return '_preliminary' + self.FILE_EXTENSION

    def get_formatted_date(self, params={}):
        formatted_date = ''
        if params['variable'] == 'trend':
            if params['period'] == 'monthly':
                formatted_date = "%s, %s to present" % (params['date'].strftime('%B'),
                                      params['baseYear'])
            if params['period'] == '3monthly':
                formatted_date = self._get_formatted_date_trend(params, 3)
            if params['period'] == '6monthly':
                formatted_date = self._get_formatted_date_trend(params, 6)
            if params['period'] == 'yearly':
                formatted_date = '%s to present' % (params['baseYear'])
        else:
            if params['period'] == 'daily':
                formatted_date = params['date'].strftime('%d %B %Y')
            if params['period'] == 'weekly':
                weekdays = util.getWeekDays(params['date'])
                formatted_date = weekdays[0].strftime('%d %B %Y') + ' to ' + weekdays[-1].strftime('%d %B %Y')                 
            if params['period'] == '4weeks':
                formatted_date = params['date'].strftime('%d %B %Y')
            elif params['period'] == '8weeks':
                formatted_date = params['date'].strftime('%d %B %Y')
            elif params['period'] == '12weeks':
                formatted_date = params['date'].strftime('%d %B %Y')
            if params['period'] == 'monthly':
                formatted_date = params['date'].strftime('%B %Y')
            if params['period'] == '3monthly':
                formatted_date = self._get_formatted_date(params, 3)
            if params['period'] == '6monthly':
                formatted_date = self._get_formatted_date(params, 6)
            if params['period'] == '12monthly':
                formatted_date = self._get_formatted_date(params, 12)
            if params['period'] == 'yearly':
                formatted_date = params['date'].strftime('%Y')
        return formatted_date 

    # --- get_formatted_date ---
    def _get_formatted_date(self, params, range):
        months = util.getMonths(params['date'], range)
        return "%s to %s" % (months[0].strftime('%B %Y'),
                             months[-1].strftime('%B %Y'))

    def _get_formatted_date_trend(self, params, range):
        months = util.getMonths(params['date'], range)
        return "%s to %s, %s to present" % (months[0].strftime('%B'),
                                            months[-1].strftime('%B'),
                                            params['baseYear'])


    # --- get_ticks_format ---
    @apply_to()
    def get_ticks_format(self, params={}):
        return '%.1f'
    #GAS remove this code so all colorbars have one decimal place
    @apply_to(variable='mean')
    def get_ticks_format(self, params={}):
        return '%.0f'

    # --- get_labels ---
    @apply_to()
    def get_labels(self, params={}):
        return (None, None)

    @apply_to(variable='dec')
    def get_labels(self, params={}):
        return (['Lowest on \nrecord',
                 'Very much \nbelow average \n[1]',
                 'Below average \n[2-3]',
                 'Average \n[4-7]',
                 'Above average \n[8-9]',
                 'Very much \nabove average \n[10]',
                 'Highest on \nrecord'],
                [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])

    # --- get_ticks ---GAS change if statement to detect pac instead of PI
    @apply_to(variable='mean')
    def get_ticks(self, params={}):
        try:
            if regionConfig.regions[params['area']][0] == 'pac':
                return np.arange(20.0, 32.1, 1.0)
            else:
                pass
        except KeyError:
            pass
        return np.arange(0.0, 32.1, 2.0)

    @apply_to(variable='anom')
    def get_ticks(self, params={}):
        return np.arange(-2.0, 2.01, 0.5)

    @apply_to(variable='dec')
    def get_ticks(self, params={}):
        # range is chosen to match label positions
        return np.arange(0.5, 7.51, 1)

    @apply_to(variable='trend')
    def get_ticks(self, params={}):
        return np.arange(-0.6, 0.61, 0.1)

    @apply_to(variable='alt')
    def get_ticks(self, params={}):
        return np.arange(-300, 300, 50)

    @apply_to(variable='rec')
    def get_ticks(self, params={}):
        return np.arange(-300, 300, 50)

    # --- get_extend ---
    @apply_to()
    def get_extend(self, params={}):
        extend = 'both'
        if params['variable'] == 'dec':
            extend = 'neither'
        else:
            extend = 'both'
        return extend

#    @apply_to(variable='dec')
#    def get_extend(self, params={}):
#        return 'neither'

    # --- get_contour_labels ---
    @apply_to()
    def get_contour_labels(self, params={}):
        return True

    @apply_to(variable='sla')
    def get_contour_labels(self, params={}):
        return False

    #GAS Remove Contour labels
    @apply_to(variable='anom')
    def get_contour_labels(self, params={}):
        return False

    @apply_to(variable='dec')
    def get_contour_labels(self, params={}):
        return False

    # --- get_title ---
#    @apply_to()
    def get_title(self, params={}):
        d = {
            'mean': "Average Sea Surface Temperature",
            'anom': "Average Sea Surface Temperature Anomaly",
            'dec': "Average Sea Surface Temperature Deciles",
            'trend': "Trend",
            'alt': "Sea Level Altimetry",
            'rec': "Sea Level Reconstruction",
            'sla': "Near Real Time Sea Level Anomaly",
            'height': "Sea Level Forecast",
            'ssta': "Sea Surface Temperature Forecast",
            'mursst': "MUR Sea Surface Temperature",
            'sst': "Sea Surface Temperature Forecast"
        }

        return d[params['variable']]

    # --- get_period_name ---
    @apply_to()
    def get_period_name(self, params={}):
        d = {
            'daily': "Daily",
            'weekly': "Weekly",
            '4weeks': "4 Weeks",
            '8weeks': "8 Weeks",
            '12weeks': "12 Weeks",
            'monthly': "Monthly",
            '3monthly': "3 monthly",
            'seasonal': "Seasonal",
            '6monthly': "6 monthly",
            '12monthly': "12 monthly",
            'yearly': "Yearly",
        }

        return d[params['period']]

    # --- get_units ---
    @apply_to()
    def get_units(self, params={}):
        return ur'\u00b0' + 'C' # degrees C

    @apply_to(variable='dec')
    def get_units(self, params={}):
        return ''

    @apply_to(variable='trend')
    def get_units(self, params={}):
        return ur'\u00b0' + 'C/decade' # degrees C/decade

    # --- get_colormap_strategy---
    def get_colormap_strategy(self, params={}):
        return 'discrete'

#    @apply_to()
    def get_colormap(self, params={}):
        cm_name = 'RdBu_r'
        if params.get('variable') == 'mean':
            cm_name = 'jet'
#            cm_name = 'binary'
        return cm_name

#    @apply_to(variable='mean')
#    def get_colormap(self, params={}):
#        return 'jet'

    # --- get_colors ---
    @apply_to()
    def get_colors(self, params={}):
        return None

    @apply_to()
    def get_basemap_colors(self, params={}):
        return None 

    def get_fill_color(self, params={}):
        #return '1.0'
        return '0.02'

    #GAS ---- get_plotstyle ---
    def get_plotstyle(self, params={}):
        style = 'pcolormesh'
        if params['variable'] == 'anom':
            style = 'contourf'
        else:
            style = 'contourf'
        return style

#    @apply_to(variable='anom')
#    def get_plotstyle(self, params={}):
#        return 'contourf'

    #GAS ---- get_contourlines ---
    @apply_to()
    def get_contourlines(self, params={}):
        return True

    @apply_to(variable='mean')
    def get_contourlines(self, params={}):
        return True

    #GAS ---- get_smooth_fac ---
    @apply_to(variable='anom')
    def get_smooth_fac(self, params={}):
        try:
            if regionConfig.regions[params['area']][0] == 'pac':
                return 1
            else:
                pass
        except KeyError:
            pass
        return 20

    @apply_to(variable='dec')
    def get_smooth_fac(self, params={}):
        try:
            if regionConfig.regions[params['area']][0] == 'pac':
                return 1
            else:
                pass
        except KeyError:
            pass
        return 20

    @apply_to()
    def get_smooth_fac(self, params={}):
        return 1

    # --- get_grid ---
    @apply_to()
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)

        return Gridset(self.get_path(params=params), gridvar, params['period'],
                       prefix=self.get_prefix(params=params),
                       suffix=self.get_suffix(params=params),
                       suffix2=self.get_suffix_prelim(params=params),
                       date=params['date'],
                       **kwargs)

    @apply_to(variable='trend')
    def get_grid(self, params={}, **kwargs):
        """
        Request a spatial trend map.
        """

        return TrendGrid(self,
                         base_year=params['baseYear'],
                         period=params['period'],
                         end_month=params['date'].month)

    # ---
    def get_variable_mapping(self, params={}):
        var = params['variable']

        try:
            return self.VARIABLE_MAP[var]
        except KeyError:
            return var

    def getPlotter(self):
        return Plotter()

    def plot(self, outputFilename, **args):
        """
        Plot the thumbnail image and also the east and west map images.
        """

        area = args['area']
        variable = args['variable']

        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + outputFilename + '.png'

        regionLongName = regionConfig.regions[area][2]
        title = regionLongName + '\n'

        if 'period' in args:
            title += "%s %s: %s" % (self.get_period_name(params=args),
                                    self.get_title(params=args),
                                    args['formattedDate'])

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)#GAS
        contourLines = self.get_contourlines(params=args)#GAS
        smoothFactor = self.get_smooth_fac(params=args)#GAS
        colors = self.get_colors(params=args)
        basemap_colors = self.get_basemap_colors(params=args)
        fill_color = self.get_fill_color(params=args)
        colormap_strategy = self.get_colormap_strategy(params=args)
        

        plot = self.getPlotter()

        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        grid = self.get_grid(params=args,
                             lonrange=(lon_min, lon_max),
                             latrange=(lat_min, lat_max))

        plot.plot_surface_data(grid.lats, grid.lons, grid.data,
                               lat_min, lat_max, lon_min, lon_max,
                               output_filename=output_filename,
                               title=title,
                               units=units,
                               cm_edge_values=cb_ticks,
                               cb_tick_fmt=cb_tick_fmt,
                               cb_labels=cb_labels,
                               cb_label_pos=cb_label_pos,
                               colormap_strategy = colormap_strategy,
                               cmp_name=cmap_name,
                               colors = colors,
                          #     fill_color = fill_color,
                               extend=extend,
                               plotStyle=plotStyle,
                               contourLines=contourLines,
                               contourLabels=contourLabels,
                               smoothFactor=smoothFactor,
                               product_label_str=self.PRODUCT_NAME,
                               area=area)
        grid = self.get_grid(params=args)

        if variable == 'dec':
            # Mask out polar region to avoid problem of calculating deciles
            # over sea ice
            grid.data.mask[0:bisect.bisect_left(grid.lats,-60),:] = True
            grid.data.mask[bisect.bisect_left(grid.lats,60):-1,:] = True

        plot.plot_basemaps_and_colorbar(grid.lats, grid.lons, grid.data,
                                        output_filename=output_filename,
                                        units=units,
                                        cm_edge_values=cb_ticks,
                                        cb_tick_fmt=cb_tick_fmt,
                                        cb_labels=cb_labels,
                                        cb_label_pos=cb_label_pos,
                                        cmp_name=cmap_name, extend=extend,
                                        colormap_strategy = colormap_strategy,
                                        colors = colors,
                                        basemap_colors = basemap_colors,
                                        fill_color = fill_color)

        plot.wait()
Exemple #8
0
class CoralPlotterWrapper(SurfacePlotter):
    DATASET = 'coral'
    PRODUCT_NAME = "NOAA Coral Reef Watch"

    VARIABLE_MAP = {
        'daily': 'CRW_BAA_max7d',
        'outlook': 'BAA',
    }

    apply_to = util.Parameterise(SurfacePlotter)

    @apply_to(variable='daily')
    def get_path(self, params={}):
        year = params['date'].year
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'daily',
                            str(year))

    @apply_to(variable='outlook')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'outlook')

    # --- get_prefix ---
#    @apply_to(variable='daily')
#    def get_prefix(self, params={}):
#        return 'baa_max_r07d_b05kmnn_'
#
#    @apply_to(variable='outlook')
#    def get_prefix(self, params={}):
#        return 'outlook_srt_v3_wk_among28_cfsv2_icwk'
#

    def get_prefix(self, params={}):
        prefix = ''
        if params['variable'] == 'daily':
            prefix = 'baa_max_r07d_b05kmnn_'
        else:
            prefix = 'outlook_srt_v3_wk_among28_cfsv2_icwk'
        return prefix

    def get_formatted_date(self, params={}):
        formatted_date = ''
        path = getLastestFile(self.get_path(params=params))
        refDate = datetime.strptime(path[-11:-3], '%Y%m%d')
        startDate = refDate + timedelta(7)

        if params['period'] == 'daily':
            formatted_date = params['date'].strftime('%d %B %Y')
        if params['period'] == '4weeks':
            formatted_date = startDate.strftime('%d %B %Y')
        elif params['period'] == '8weeks':
            incDate = startDate + timedelta(weeks=4)
            formatted_date = incDate.strftime('%d %B %Y')
        elif params['period'] == '12weeks':
            incDate = startDate + timedelta(weeks=8)
            formatted_date = incDate.strftime('%d %B %Y')
        return formatted_date

    # --- get_title ---
#    @apply_to(variable='daily')

    def get_title(self, params={}):
        title = ''
        if (params['variable'] == 'daily'):
            title = 'Coral Bleaching Alert'
        else:
            title = 'Coral Bleaching Outlook'
        return title

    @apply_to(variable='daily')
    def get_ticks(self, params={}):
        return np.arange(6)

    @apply_to(variable='outlook')
    def get_ticks(self, params={}):
        return np.arange(6)

    @apply_to(variable='daily')
    def get_colors(self, params={}):
        return np.array([[200, 250, 250], [255, 240, 0], [250, 170, 10],
                         [240, 0, 0], [150, 0, 0]])

    @apply_to(variable='daily')
    def get_basemap_colors(self, params={}):
        return np.array([[255, 255, 255], [191, 191, 191], [128, 128, 128],
                         [64, 64, 64], [0, 0, 0]])

    @apply_to(variable='outlook')
    def get_colors(self, params={}):
        return np.array([[200, 250, 250], [255, 210, 160], [250, 170, 10],
                         [240, 0, 0], [150, 0, 0]])

    @apply_to(variable='outlook')
    def get_basemap_colors(self, params={}):
        return np.array([[255, 255, 255], [191, 191, 191], [128, 128, 128],
                         [64, 64, 64], [0, 0, 0]])

    def get_fill_color(self, params={}):
        #return '0.59'
        return '0.98'

    def get_colormap_strategy(self, params={}):
        return 'levels'

    #@apply_to(variable='daily')
    def get_plotstyle(self, params={}):
        return 'pcolormesh'


#    @apply_to(variable='daily')

    def get_extend(self, params={}):
        return 'neither'

    @apply_to(variable='daily')
    def get_labels(self, params={}):
        return ([
            'No Stress', 'Watch', 'Warning', 'Alert Level 1', 'Alert Level 2'
        ], [0.5, 1.5, 2.5, 3.5, 4.5])

    @apply_to(variable='outlook')
    def get_labels(self, params={}):
        return ([
            'No Stress', 'Watch', 'Warning', 'Alert Level 1', 'Alert Level 2'
        ], [0.5, 1.5, 2.5, 3.5, 4.5])

    @apply_to(variable='daily')
    def get_units(self, params={}):
        return ''

    @apply_to(variable='daily')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='outlook')
    def get_units(self, params={}):
        return ''

    @apply_to(variable='outlook')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='outlook')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        kwargs.update({'depthrange': (0, 2)})
        grid = CoralGridset(self.get_path(params=params),
                            gridvar,
                            params['period'],
                            prefix=self.get_prefix(params=params),
                            suffix=self.get_suffix(params=params),
                            suffix2=self.get_suffix_prelim(params=params),
                            date=params['date'],
                            **kwargs)
        if params['period'] == '4weeks':
            grid.data = grid.data[0]
        elif params['period'] == '8weeks':
            grid.data = grid.data[1]
        elif params['period'] == '12weeks':
            grid.data = grid.data[2]
        return grid

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']

        #        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        #        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        #        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        #        lon_max = regionConfig.regions[area][1]['urcrnrlon']
        #
        #        grid = self.get_grid(params=args,
        #                             lonrange=(lon_min, lon_max),
        #                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(
            inputLat, inputLon, grid.lats, grid.lons, grid.data)
        value = grid.data[latIndex, lonIndex]
        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value
Exemple #9
0
class SST(Dataset):
    """
    Base class for SST datasets.

    At a minimum dataset class must define:

    class mydataset(SST):
        DATASET = 'mydataset'
        PLOTTER = MyDatasetPlotter
    """

    __form_params__ = {
        'average': bool,
        'trend': bool,
        'runningInterval': int,
        'baseYear': int,
        'lat': float,
        'lon': float,
    }
    __form_params__.update(Dataset.__form_params__)

    __required_params__ = Dataset.__required_params__ + [
        'date',
        'area',
    ]

    __variables__ = [
        'mean',
        'dec',
        'anom',
        'trend',
        'mursst',
    ]

    __plots__ = ['map', 'point']

    apply_to = util.Parameterise(Dataset)

    @property
    def CACHE_URL(self):
        return os.path.join(serverCfg['baseURL'], serverCfg['rasterURL'],
                            serverCfg['cacheDir'][self.DATASET])

    def __init__(self):
        self.product = productName.products[self.DATASET]
        self.plotter = self.PLOTTER()

    @apply_to()
    def get_filename_format(self, params={}):
        return '%(product_name)s_%(area)s_%(formatted_date)s_%(variable)s'

    @apply_to(variable='trend')
    def get_filename_format(self, params={}):
        return '%(product_name)s_%(area)s_%(formatted_date)s_%(variable)s_%(baseYear)s'

    def get_product_name(self, params):

        suffix = {
            'dec': 'Dec',
            'trend': 'Tre',
        }

        key = '%s%s' % (params['period'], suffix.get(params['variable'], ''))
        return self.product[key]

    def get_date_format(self, params={}):
        formatted_date = ''
        format = {
            'daily': '{0.year:4d}{0.month:02d}{0.day:02d}',
            'weekly': '{0.year:4d}{0.month:02d}{0.day:02d}',
            '4weeks': '{0.year:4d}{0.month:02d}{0.day:02d}',
            '8weeks': '{0.year:4d}{0.month:02d}{0.day:02d}',
            '12weeks': '{0.year:4d}{0.month:02d}{0.day:02d}',
            'monthly': '{0.year:4d}{0.month:02d}',
            '3monthly': '{0.year:4d}{0.month:02d}',
            '6monthly': '{0.year:4d}{0.month:02d}',
            '12monthly': '{0.year:4d}{0.month:02d}',
            'yearly': '{0.year:4d}',
        }
        if params['variable'] == 'trend':
            if params['period'] == 'yearly':
                formatted_date = 'annual'
            else:
                formatted_date = '{0.month:02d}'.format(params['date'])
        else:
            formatted_date = format[params['period']].format(params['date'])

        if params['variable'] == 'mean' and params['period'] == 'weekly':
            weekdays = util.getWeekDays(params['date'])
            formatted_date = format[params['period']].format(weekdays[0])

        return formatted_date

    def process_stats(self, params):
        return {}

    def preprocess(self, fileName, **params):
        '''
            Allows the map images to be produced via the URL.
        '''
        pass

    def process(self, params):
        response = {}

        p = params.copy()
        p.update({
            'product_name': self.get_product_name(params=params),
            'formatted_date': self.get_date_format(params=params),
        })

        fileName = self.get_filename_format(params=params) % p
        outputFileName = os.path.join(serverCfg['outputDir'], fileName)

        if params['plot'] == 'map':
            if params['variable'] == 'dec':
                self.plotter.plot(fileName, **params)

            elif not util.check_files_exist(outputFileName,
                                            COMMON_FILES.values()):
                if ('mode' in params) and (params['mode'] == 'preprocess'):
                    response['preproc'] = 'preprocessing...'
                    self.preprocess(fileName, **params)
                else:
                    self.plotter.plot(fileName, **params)

            if not util.check_files_exist(outputFileName,
                                          COMMON_FILES.values()):
                response['error'] = \
                    "Requested image is not available at this time."
            else:
                response.update(
                    util.build_response_object(
                        COMMON_FILES.keys(),
                        os.path.join(serverCfg['baseURL'],
                                     serverCfg['rasterURL'], fileName),
                        COMMON_FILES.values()))
                if params['variable'] == 'mean' and regionConfig.regions[
                        params['area']][0] == 'pac':
                    response['map'] = params['variable'] + '_sub'
                elif params['variable'] in ['chldaily', 'chlmonthly']:
                    response['map'] = 'chlo'
                elif params['variable'] == 'daily':
                    response['map'] = 'coral_daily'
                elif params['variable'] == 'outlook':
                    response['map'] = 'coral_outlook'
                elif params['variable'] == 'mursst':
                    response['map'] = 'mur'
                    response['front'] = os.path.join(
                        serverCfg['baseURL'], serverCfg['rasterURL'],
                        fileName) + EXTRA_FILES['map'] + EXTRA_FILES['front']
                else:
                    response['map'] = params['variable']
                util.touch_files(
                    os.path.join(serverCfg['outputDir'], fileName),
                    COMMON_FILES.values())

            response.update(self.process_stats(params))
        elif params['plot'] == 'point':  #for point value extraction
            (lat, lon), value = self.plotter.extract(**params)
            response['value'] = float(value)

        return response
Exemple #10
0
class MurPlotter(SurfacePlotter):
    DATASET = 'mur'
    PRODUCT_NAME = "MUR SST"

    VARIABLE_MAP = {'mursst': 'sst'}

    apply_to = util.Parameterise(SurfacePlotter)

    @apply_to(variable='mursst', period='daily')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'data',
                            params['area'])

    @apply_to(variable='mursst')
    def get_ticks(self, params={}):
        return np.arange(24.0, 32.1, 0.5)

    def get_colormap_strategy(self, params={}):
        return 'nonlinear'

    # --- get_prefix ---
    def get_prefix(self, params={}):
        prefix = 'MUR_'
        return prefix

    @apply_to(variable='mursst')
    def get_suffix(self, params={}):
        suffix = '_' + params['area'] + self.FILE_EXTENSION
        return suffix

    def get_plotstyle(self, params={}):
        return 'pcolormesh'

    @apply_to(variable='mursst')
    def get_contourlines(self, params={}):
        return False

    def getPlotter(self):
        return FrontPlotter()

    def plot(self, outputFilename, **args):
        """
        Plot the thumbnail image and also the east and west map images.
        """

        area = args['area']
        variable = args['variable']

        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + outputFilename + '.png'

        regionLongName = regionConfig.regions[area][2]
        title = regionLongName + '\n'

        if 'period' in args:
            title += "%s %s: %s" % (self.get_period_name(params=args),
                                    self.get_title(params=args),
                                    args['formattedDate'])

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)  #GAS
        contourLines = self.get_contourlines(params=args)  #GAS
        smoothFactor = self.get_smooth_fac(params=args)  #GAS
        colors = self.get_colors(params=args)
        fill_color = self.get_fill_color(params=args)
        colormap_strategy = self.get_colormap_strategy(params=args)

        plot = self.getPlotter()

        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        grid = self.get_grid(params=args,
                             lonrange=(lon_min, lon_max),
                             latrange=(lat_min, lat_max))
        shapefile = grid.get_filename(self.get_path(params=args),
                                      self.get_prefix(params=args),
                                      self.get_suffix(params=args),
                                      args['date'], args['period'])
        shapefile = os.path.splitext(shapefile)[0]

        plot.plot_surface_data(grid.lats,
                               grid.lons,
                               grid.data,
                               lat_min,
                               lat_max,
                               lon_min,
                               lon_max,
                               output_filename=output_filename,
                               title=title,
                               units=units,
                               cm_edge_values=cb_ticks,
                               cb_tick_fmt=cb_tick_fmt,
                               cb_labels=cb_labels,
                               cb_label_pos=cb_label_pos,
                               colormap_strategy=colormap_strategy,
                               cmp_name=cmap_name,
                               colors=colors,
                               fill_color=fill_color,
                               extend=extend,
                               plotStyle=plotStyle,
                               contourLines=contourLines,
                               contourLabels=contourLabels,
                               smoothFactor=smoothFactor,
                               product_label_str=self.PRODUCT_NAME,
                               area=area,
                               shapefile=shapefile)
        grid = self.get_grid(params=args)

        if variable == 'dec':
            # Mask out polar region to avoid problem of calculating deciles
            # over sea ice
            grid.data.mask[0:bisect.bisect_left(grid.lats, -60), :] = True
            grid.data.mask[bisect.bisect_left(grid.lats, 60):-1, :] = True

        plot.plot_basemaps_and_colorbar(grid.lats,
                                        grid.lons,
                                        grid.data,
                                        output_filename=output_filename,
                                        units=units,
                                        cm_edge_values=cb_ticks,
                                        cb_tick_fmt=cb_tick_fmt,
                                        cb_labels=cb_labels,
                                        cb_label_pos=cb_label_pos,
                                        cmp_name=cmap_name,
                                        extend=extend,
                                        colormap_strategy=colormap_strategy,
                                        colors=colors,
                                        fill_color=fill_color,
                                        regionName=area,
                                        shapefile=shapefile)

        plot.wait()

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']

        #        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        #        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        #        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        #        lon_max = regionConfig.regions[area][1]['urcrnrlon']
        #
        #        grid = self.get_grid(params=args,
        #                             lonrange=(lon_min, lon_max),
        #                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(
            inputLat, inputLon, grid.lats, grid.lons, grid.data)
        value = grid.data[latIndex, lonIndex]
        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value
Exemple #11
0
class ChlorophyllPlotterWrapper(SurfacePlotter):
    DATASET = 'chloro'
    PRODUCT_NAME = "Chlorophyll-A"

    FILL_VALUE = -32767.0

    VARIABLE_MAP = {
        'chldaily': 'chlor_a',
        'chlmonthly': 'chlor_a',
    }

    apply_to = util.Parameterise(SurfacePlotter)

    @apply_to(variable='chldaily')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'daily')

    @apply_to(variable='chlmonthly')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'monthly')

    # --- get_prefix ---
#    @apply_to(variable='chldaily')

    def get_prefix(self, params={}):
        return 'A'

#    @apply_to(variable='chlmonthly')
#    def get_prefix(self, params={}):
#        return 'A'

    @apply_to(variable='chldaily')
    def get_suffix(self, params={}):
        return '.L3m_DAY_CHL_chlor_a_4km' + self.FILE_EXTENSION

    @apply_to(variable='chlmonthly')
    def get_suffix(self, params={}):
        return '.L3m_MO_CHL_chlor_a_4km' + self.FILE_EXTENSION

    # --- get_title ---
    def get_title(self, params={}):
        title = 'Chlorophyll-A'
        return title

    def get_colormap(self, params={}):
        cm_name = 'jet'
        return cm_name

    @apply_to(variable='chldaily')
    def get_ticks(self, params={}):
        return np.array([
            0.01, 0.03, 0.05, 0.07, 0.1, 0.15, 0.2, 0.3, 0.5, 1.0, 2.0, 3.0,
            5.0, 10.0
        ])

    @apply_to(variable='chlmonthly')
    def get_ticks(self, params={}):
        return np.array([
            0.01, 0.03, 0.05, 0.07, 0.1, 0.15, 0.2, 0.3, 0.5, 1.0, 2.0, 3.0,
            5.0, 10.0
        ])

    def get_ticks_format(self, params={}):
        return '%.2f'

    def get_colormap_strategy(self, params={}):
        return 'nonlinear'


#    def get_colormap(self, params={}):
#        return 'coolwarm'

#    @apply_to(variable='daily', period='daily')
#    def get_formatted_date(self, params={}):
#        date = params['date'].timetuple()
#        return '%4d%03d' % (date.tm_year, date.tm_yday)

    def get_plotstyle(self, params={}):
        return 'pcolormesh'

    def get_extend(self, params={}):
        return 'neither'

    def get_fill_color(self, params={}):
        # return '1.0'
        return '0.98'

    @apply_to(variable='chldaily')
    def get_units(self, params={}):
        return 'mg/m' + ur'\u00B3'

    @apply_to(variable='chlmonthly')
    def get_units(self, params={}):
        return 'mg/m' + ur'\u00B3'

    @apply_to(variable='chldaily')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='chlmonthly')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='chldaily', period='daily')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        grid = ChlorophyllGridset(
            self.get_path(params=params),
            gridvar,
            params['period'],
            prefix=self.get_prefix(params=params),
            suffix=self.get_suffix(params=params),
            suffix2=self.get_suffix_prelim(params=params),
            date=params['date'],
            **kwargs)
        return grid

    @apply_to(variable='chlmonthly', period='monthly')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        grid = ChlorophyllMonthlyGridset(
            self.get_path(params=params),
            gridvar,
            params['period'],
            prefix=self.get_prefix(params=params),
            suffix=self.get_suffix(params=params),
            suffix2=self.get_suffix_prelim(params=params),
            date=params['date'],
            **kwargs)
        return grid

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']

        #        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        #        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        #        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        #        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        #        grid = self.get_grid(params=args,
        #                             lonrange=(lon_min, lon_max),
        #                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(
            inputLat, inputLon, grid.lats, grid.lons, grid.data)
        value = grid.data[latIndex, lonIndex]
        if value is ma.masked or value == self.FILL_VALUE:
            raise LandError()
        #return extracted value
        return (lat, lon), value
Exemple #12
0
class Gridset(Grid):
    """
    Generic accessor for sets of grids where grids are separated
    temporally in different files.
    """

    #SUFFIX = '.nc' GAS

    apply_to = util.Parameterise(Grid)

    def __init__(
            self,
            path,
            variable,
            period,
            #prefix=None, suffix=None, date=None, **kwargs):
            prefix=None,
            suffix=None,
            suffix2=None,
            date=None,
            **kwargs):

        assert prefix is not None
        assert suffix is not None
        assert suffix2 is not None
        assert date is not None

        if variable in ("sst", "anom") and period == "weekly":
            weekdays = util.getWeekDays(date)
            date = weekdays[0]

        filename = self.get_filename(path, prefix, suffix, date, period)
        filename2 = self.get_filename(path, prefix, suffix2, date, period)
        #Grid.__init__(self, filename, variable, **kwargs)
        Grid.__init__(self, filename, filename2, variable, **kwargs)

    def get_filename(self, path, prefix, suffix, date, period):
        """
        Returns the filename for a grid file given the specified @path,
        @prefix, @date and @period of the file.
        """
        return os.path.join(
            path, '%s%s%s' %
            (prefix, self.get_filename_date(
                date, params=dict(period=period)), suffix))

#    @apply_to(period='daily')

    def get_filename_date(self, date, **kwargs):
        date_string = ''
        period = kwargs.get('params')['period']
        if period == 'daily':
            date_string = date.strftime('%Y%m%d')
        elif period == 'weekly':
            base_date = datetime.date(1981, 9, 01)
            weeknumber = util.weeks_between(base_date, date)
            weeknumber = '%02d' % weeknumber
            date_string = date.strftime('%Y%m') + '_week_' + str(weeknumber)
        elif period == 'monthly':
            date_string = date.strftime('%Y%m')
        elif period == '3monthly':
            date_string = self._get_filename_date(date, 3)
        elif period == '6monthly':
            date_string = self._get_filename_date(date, 6)
        elif period == '12monthly':
            date_string = self._get_filename_date(date, 12)
        return date_string

#    @apply_to(period='monthly')
#def get_filename_date(self, date, **kwargs):

    def _get_filename_date(self, date, nmonths):
        months = getMonths(date, nmonths)
        return '%imthavg_%s_%s' % (nmonths, months[0].strftime('%Y%m'),
                                   months[-1].strftime('%Y%m'))
Exemple #13
0
    class Uppercase(BaseTest):
        apply_to = util.Parameterise(BaseTest)

        @apply_to()
        def get_b(self, params={}):
            return 'B'
Exemple #14
0
    class BaseTest(object):
        apply_to = util.Parameterise()

        @apply_to()
        def get_a(self, params={}):
            return 'a'
Exemple #15
0
class PoamaPlotterWrapper(SurfacePlotter):
    DATASET = 'poamasla'
    PRODUCT_NAME = "POAMA Forecast"

    VARIABLE_MAP = {
        'height': 'HEIGHT'
    }

    apply_to = util.Parameterise(SurfacePlotter)

    @apply_to(variable='height')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET],
                            'sla')

    def get_colormap(self, params={}):
        cm_name = 'RdBu_r'
        return cm_name

#    @apply_to(variable='height')
#    def get_prefix(self, params={}):
#        return ''

    @apply_to(variable='height')
    def get_ticks(self, params={}):
        return np.arange(-30, 31, 5)

    @apply_to(period='seasonal')
    def get_formatted_date(self, params={}):
        if 'step' in params:
            return params['forecast'][params['step']]['datetime']
        else:
            return ''

    def get_ticks_format(self, params={}):
        return '%d'

    @apply_to(variable='height')
    def get_labels(self, params={}):
        return (self.get_ticks(params=params) * 10, None)

    def get_colormap_strategy(self, params={}):
        return 'nonlinear'

    def get_plotstyle(self, params={}):
        return 'pcolormesh'

    def get_extend(self, params={}):
        return 'both'

    def get_fill_color(self, params={}):
        return '1.0'

    @apply_to(variable='height')
    def get_units(self, params={}):
        return 'mm'

    @apply_to(variable='height')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='height')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        kwargs.update({'depthrange':(0, FORECAST_STEPS - 1)})
        grid =  PoamaGridset(self.get_path(params=params), gridvar, params['period'],
                       prefix=self.get_prefix(params=params),
                       suffix=self.get_suffix(params=params),
                       suffix2=self.get_suffix_prelim(params=params),
                       date=params['date'],
                       **kwargs)
        grid.data = ma.masked_invalid(grid.data)
        return grid

    def plot_basemaps_and_colorbar(self, output, step, args):
        area = args['area']
        variable = args['variable']

        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + output + '.png'

#        regionLongName = regionConfig.regions[area][2]
#        title = regionLongName + '\n'
        title = ''

#        if 'period' in args:
#            title += "%s %s: %s" % (self.get_period_name(params=args),
#                                    self.get_title(params=args),
#                                    args['formattedDate'])

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)#GAS
        contourLines = self.get_contourlines(params=args)#GAS
        smoothFactor = self.get_smooth_fac(params=args)#GAS
        colors = self.get_colors(params=args)
        fill_color = '0.02'
        colormap_strategy = self.get_colormap_strategy(params=args)

        plot = self.getPlotter()
        grid = self.get_grid(params=args)

        plot.plot_basemaps_and_colorbar(grid.lats, grid.lons, grid.data[step],
                                        output_filename=output_filename,
                                        units=units,
                                        cm_edge_values=cb_ticks,
                                        cb_tick_fmt=cb_tick_fmt,
                                        cb_labels=cb_labels,
                                        cb_label_pos=cb_label_pos,
                                        cmp_name=cmap_name, extend=extend,
                                        colormap_strategy = colormap_strategy,
                                        colors = colors,
                                        fill_color = fill_color)

        plot.wait()

    def plot_surface_data(self, output, step, args):
        area = args['area']
        variable = args['variable']
        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + output + '.png'

        regionLongName = regionConfig.regions[area][2]
        title = regionLongName + '\n'

        if 'period' in args:
            title += "%s %s: %s" % (self.get_period_name(params=args),
                                    self.get_title(params=args),
                                    args['formattedDate'])

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)#GAS
        contourLines = self.get_contourlines(params=args)#GAS
        smoothFactor = self.get_smooth_fac(params=args)#GAS
        colors = self.get_colors(params=args)
        fill_color = self.get_fill_color(params=args)
        colormap_strategy = self.get_colormap_strategy(params=args)

        plot = self.getPlotter()

        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        grid = self.get_grid(params=args,
                             lonrange=(lon_min, lon_max),
                             latrange=(lat_min, lat_max))

        plot.plot_surface_data(grid.lats, grid.lons, grid.data[step],
                               lat_min, lat_max, lon_min, lon_max,
                               output_filename=output_filename,
                               title=title,
                               units=units,
                               cm_edge_values=cb_ticks,
                               cb_tick_fmt=cb_tick_fmt,
                               cb_labels=cb_labels,
                               cb_label_pos=cb_label_pos,
                               colormap_strategy = colormap_strategy,
                               cmp_name=cmap_name,
                               colors = colors,
                               fill_color = fill_color,
                               extend=extend,
                               plotStyle=plotStyle,
                               contourLines=contourLines,
                               contourLabels=contourLabels,
                               smoothFactor=smoothFactor,
                               product_label_str=self.PRODUCT_NAME,
                               area=area,
                               boundaryInUse='False')

        plot.wait()

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']
        step = args['step']

#        lat_min = regionConfig.regions[area][1]['llcrnrlat']
#        lat_max = regionConfig.regions[area][1]['urcrnrlat']
#        lon_min = regionConfig.regions[area][1]['llcrnrlon']
#        lon_max = regionConfig.regions[area][1]['urcrnrlon']
#
#        grid = self.get_grid(params=args,
#                             lonrange=(lon_min, lon_max),
#                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        step = int(step)
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(inputLat, inputLon, grid.lats, grid.lons,
                                                     grid.data[step])
        value = grid.data[step][latIndex, lonIndex]

        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value * 10
Exemple #16
0
class MslaPlotter(SurfacePlotter):
    DATASET = DATASET
    
    VARIABLE_MAP = {
        'sla': 'sla'
    }
    
    apply_to = util.Parameterise()
    
    PRODUCT_NAME = "AVISO Ssalto/Duacs SLA"
    
    def __init__(self, variable):
        super(MslaPlotter, self).__init__()
            
    def get_colormap_strategy(self, params={}):
        return 'nonlinear'
    
    def get_grid(self, params, **kwargs):
        gridvar = params['variable'] 
        grid =  MslaGrid(self.get_path(params=params), gridvar, params['period'],
                       prefix=self.get_prefix(params=params),
                       suffix=self.get_suffix(params=params),
                       suffix2=self.get_suffix_prelim(params=params),
                       date=params['date'],
                       **kwargs)
        return grid
    
    def get_ticks(self, params={}):
        return np.arange(-0.3,0.31,0.05)

    def get_ticks_format(self, params={}, **kwargs):
        return '%.0f'
    
    def get_units(self, params={}, **kwargs):
        return 'mm'
    
    @apply_to(variable='sla')
    def get_labels(self, params={}):
        return (((self.get_ticks(params=params) * 1000).astype(np.float16)).astype(int), None)
    
    @apply_to(variable='sla')
    def get_smooth_fac(self, params={}):
        try:
            if regionConfig.regions[params['area']][0] == 'pac':
                return 1
            else:
                pass
        except KeyError:
            pass
        return 30

    @apply_to(period='daily')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'grids', 'daily')

    @apply_to(period='monthly')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'grids', 'monthly')

    @apply_to(period='daily')
    def get_prefix(self, params={}):
        return 'nrt_global_allsat_msla_h_'

    @apply_to(period='monthly')
    def get_prefix(self, params={}):
        return 'nrt_sea_level_'
    
    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']

#        lat_min = regionConfig.regions[area][1]['llcrnrlat']
#        lat_max = regionConfig.regions[area][1]['urcrnrlat']
#        lon_min = regionConfig.regions[area][1]['llcrnrlon']
#        lon_max = regionConfig.regions[area][1]['urcrnrlon']
#
#        grid = self.get_grid(params=args,
#                             lonrange=(lon_min, lon_max),
#                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(inputLat, inputLon, grid.lats, grid.lons,
                                                     grid.data)
        value = grid.data[latIndex, lonIndex]
        value = value * 1000
        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value
Exemple #17
0
class PoamaPlotterWrapper(SurfacePlotter):
    DATASET = 'poamassta'
    PRODUCT_NAME = "POAMA Forecast"

    VARIABLE_MAP = {'ssta': 'SSTA_emn', 'sst': 'SST_emn'}

    apply_to = util.Parameterise(SurfacePlotter)

    @apply_to(variable='ssta')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'ssta')

    @apply_to(variable='sst')
    def get_path(self, params={}):
        return os.path.join(serverCfg['dataDir'][self.DATASET], 'ssta')

    def get_colormap(self, params={}):
        cm_name = 'RdBu_r'
        if params['variable'] == 'sst':
            cm_name = 'jet'
        return cm_name

#    @apply_to(variable='ssta')
#    def get_prefix(self, params={}):
#        return 'asdf'

    @apply_to(variable='ssta')
    def get_ticks(self, params={}):
        return np.arange(-2, 2.5, 0.5)

    @apply_to(variable='sst')
    def get_ticks(self, params={}):
        return np.arange(0, 33, 2)

    @apply_to(variable='ssta', period='seasonal')
    def get_formatted_date(self, params={}):
        if 'step' in params:
            return params['forecast'][params['step']]['datetime']
        else:
            return ''

    @apply_to(variable='sst', period='seasonal')
    def get_formatted_date(self, params={}):
        if 'step' in params:
            return params['forecast'][params['step']]['datetime']
        else:
            return ''

    def get_ticks_format(self, params={}):
        return '%.1f'

    def get_colormap_strategy(self, params={}):
        return 'nonlinear'

    def get_plotstyle(self, params={}):
        return 'pcolormesh'

    def get_extend(self, params={}):
        return 'neither'

    @apply_to(variable='sst')
    def get_extend(self, params={}):
        return 'both'

    @apply_to(variable='ssta', period='seasonal')
    def get_extend(self, params={}):
        return 'both'

    def get_fill_color(self, params={}):
        # return '0.0'
        return '0.02'


#    @apply_to(variable='ssta')
#    def get_units(self, params={}):
#        return 'cm'

    @apply_to(variable='ssta')
    def get_contourlines(self, params={}):
        return False

    @apply_to(variable='sst')
    def get_contourlines(self, params={}):
        return True

    def get_contour_labels(self, params={}):
        return False

    @apply_to(variable='ssta')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        kwargs.update({'depthrange': (0, FORECAST_STEPS - 1)})
        grid = PoamaGridset(self.get_path(params=params),
                            gridvar,
                            params['period'],
                            prefix=self.get_prefix(params=params),
                            suffix=self.get_suffix(params=params),
                            suffix2=self.get_suffix_prelim(params=params),
                            date=params['date'],
                            **kwargs)
        return grid

    @apply_to(variable='sst')
    def get_grid(self, params={}, **kwargs):
        """
        Request a Grid object for this dataset.

        Override this method to access grids in a different way.
        """

        gridvar = self.get_variable_mapping(params=params)
        kwargs.update({'depthrange': (0, FORECAST_STEPS - 1)})
        grid = PoamaGridset(self.get_path(params=params),
                            gridvar,
                            params['period'],
                            prefix=self.get_prefix(params=params),
                            suffix=self.get_suffix(params=params),
                            suffix2=self.get_suffix_prelim(params=params),
                            date=params['date'],
                            **kwargs)
        return grid

    def get_overlay_variable(self, variable):
        if variable in ['sst']:
            return 'sst'
        return ''

    def getOverlayVariableGrid(self, var, date):
        monthName = date[:4].strip()
        monthNumbers = dict((v, k) for k, v in enumerate(calendar.month_abbr))
        monthNumber = monthNumbers[monthName]

        latestFilePath = os.path.join(
            serverCfg['dataDir']['reynolds'], 'climatology',
            'climatology_' + str("%02d" % monthNumber) + '.nc')

        overlayVariable = self.get_overlay_variable(var)
        if overlayVariable != '':
            return Grid(latestFilePath, latestFilePath, overlayVariable,
                        (-90, 90), (0, 360), (0, FORECAST_STEPS))
        return None

    def plot_basemaps_and_colorbar(self, output, step, args):
        area = args['area']
        variable = args['variable']

        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + output + '.png'

        title = ''

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)  #GAS
        contourLines = self.get_contourlines(params=args)  #GAS
        smoothFactor = self.get_smooth_fac(params=args)  #GAS
        colors = self.get_colors(params=args)
        fill_color = self.get_fill_color(params=args)
        colormap_strategy = self.get_colormap_strategy(params=args)

        if variable in ['sst']:
            plot = PoamaSstPlotter()
        else:
            plot = self.getPlotter()

        grid = self.get_grid(params=args)

        # get overlay grid
        annual_clim_label_str = args['formattedDate']
        monthly_clim_label_str = args['formattedDate']

        overlay_grid = None
        if args['formattedDate'] != '':
            overlay_grid = self.getOverlayVariableGrid(variable,
                                                       args['formattedDate'])
            annual_clim_label_str = args['formattedDate'][:4].strip(
            ) + ' Climatology'

        plot.plot_basemaps_and_colorbar(
            grid.lats,
            grid.lons,
            grid.data[step],
            overlay_grid=overlay_grid,
            output_filename=output_filename,
            units=units,
            cm_edge_values=cb_ticks,
            cb_tick_fmt=cb_tick_fmt,
            cb_labels=cb_labels,
            cb_label_pos=cb_label_pos,
            cmp_name=cmap_name,
            extend=extend,
            colormap_strategy=colormap_strategy,
            colors=colors,
            fill_color=fill_color,
            contourLines=contourLines,
            contourLabels=contourLabels,
            annual_clim_label_str=annual_clim_label_str,
            monthly_clim_label_str=monthly_clim_label_str)

        plot.wait()

    def plot_surface_data(self, output, step, args):
        area = args['area']
        variable = args['variable']
        args['formattedDate'] = self.get_formatted_date(params=args)
        output_filename = serverCfg['outputDir'] + output + '.png'

        regionLongName = regionConfig.regions[area][2]
        title = regionLongName + '\n'

        if 'period' in args:
            title += "%s %s: %s" % (self.get_period_name(params=args),
                                    self.get_title(params=args),
                                    args['formattedDate'])

        units = self.get_units(params=args)
        cmap_name = self.get_colormap(params=args)
        cb_ticks = self.get_ticks(params=args)
        cb_tick_fmt = self.get_ticks_format(params=args)
        cb_labels, cb_label_pos = self.get_labels(params=args)
        extend = self.get_extend(params=args)
        contourLabels = self.get_contour_labels(params=args)
        plotStyle = self.get_plotstyle(params=args)  #GAS
        contourLines = self.get_contourlines(params=args)  #GAS
        smoothFactor = self.get_smooth_fac(params=args)  #GAS
        colors = self.get_colors(params=args)
        fill_color = self.get_fill_color(params=args)
        colormap_strategy = self.get_colormap_strategy(params=args)

        if variable in ['sst']:
            plot = PoamaSstPlotter()
        else:
            plot = self.getPlotter()

        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        lon_max = regionConfig.regions[area][1]['urcrnrlon']

        grid = self.get_grid(params=args,
                             lonrange=(lon_min, lon_max),
                             latrange=(lat_min, lat_max))

        # get overlay grid
        annual_clim_label_str = args['formattedDate']
        monthly_clim_label_str = args['formattedDate']

        overlay_grid = None
        if args['formattedDate'] != '':
            overlay_grid = self.getOverlayVariableGrid(variable,
                                                       args['formattedDate'])
            annual_clim_label_str = args['formattedDate'][:4].strip(
            ) + ' Climatology'

        plot.plot_surface_data(
            grid.lats,
            grid.lons,
            grid.data[step],
            lat_min,
            lat_max,
            lon_min,
            lon_max,
            overlay_grid=overlay_grid,
            output_filename=output_filename,
            title=title,
            units=units,
            cm_edge_values=cb_ticks,
            cb_tick_fmt=cb_tick_fmt,
            cb_labels=cb_labels,
            cb_label_pos=cb_label_pos,
            colormap_strategy=colormap_strategy,
            cmp_name=cmap_name,
            colors=colors,
            #                               fill_color = fill_color,
            extend=extend,
            plotStyle=plotStyle,
            contourLines=contourLines,
            contourLabels=contourLabels,
            smoothFactor=smoothFactor,
            product_label_str=self.PRODUCT_NAME,
            area=area,
            boundaryInUse='False',
            annual_clim_label_str=annual_clim_label_str,
            monthly_clim_label_str=monthly_clim_label_str)

        plot.wait()

    def extract(self, **args):

        area = args['area']
        variable = args['variable']
        inputLat = args['lat']
        inputLon = args['lon']
        step = args['step']

        #        lat_min = regionConfig.regions[area][1]['llcrnrlat']
        #        lat_max = regionConfig.regions[area][1]['urcrnrlat']
        #        lon_min = regionConfig.regions[area][1]['llcrnrlon']
        #        lon_max = regionConfig.regions[area][1]['urcrnrlon']
        #
        #        grid = self.get_grid(params=args,
        #                             lonrange=(lon_min, lon_max),
        #                             latrange=(lat_min, lat_max))

        grid = self.get_grid(params=args)

        #extract lat/lon and value
        step = int(step)
        (lat, lon), (latIndex, lonIndex) = Extractor.getGridPoint(
            inputLat, inputLon, grid.lats, grid.lons, grid.data[step])
        value = grid.data[step][latIndex, lonIndex]
        if value is ma.masked:
            raise LandError()
        #return extracted values
        return (lat, lon), value