Ejemplo n.º 1
0
def test_build_response_object():
    o = util.build_response_object(['a', 'b', 'c'], 'canoe',
                                   ['.png', '.jpg', '.txt'])

    assert o == {
        'a': 'canoe.png',
        'b': 'canoe.jpg',
        'c': 'canoe.txt',
    }
Ejemplo n.º 2
0
    def process(self, params):
        response = {}

        if 'date' not in params:
            raise MissingParameter("Missing parameter 'date'")
        elif 'area' not in params:
            raise MissingParameter("Missing parameter 'area'")

        variableStr = params['variable']
        areaStr = params['area']
        periodStr = params['period']

        plotter = MslaPlotter(variableStr)

        if params['plot'] == 'map':
            if periodStr == 'daily':
                dateStr = params['date'].strftime('%Y%m%d')
                fileName = seaGraph % (seaLevelProduct['daily'], variableStr,
                                       areaStr, dateStr)
            elif periodStr == 'monthly':
                dateStr = params['date'].strftime('%Y%m')
                fileName = seaGraph % (seaLevelProduct['monthly'], variableStr,
                                       areaStr, dateStr)
            else:
                assert 0, "Should not be reached"

            outputFileName = serverCfg['outputDir'] + fileName

            if not util.check_files_exist(outputFileName,
                                          COMMON_FILES.values()):
                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()))
                response['map'] = 'poamasla'

                util.touch_files(
                    os.path.join(serverCfg['outputDir'], fileName),
                    COMMON_FILES.values())
        elif params['plot'] == 'point':  #for point value extraction
            (lat, lon), value = plotter.extract(**params)
            response['value'] = float(value)
        return response
Ejemplo n.º 3
0
    def plot_rec(self, params):
        response = {}

        if params['plot'] == 'ts':
            if 'lon' not in params or 'lat' not in params:
                raise MissingParameter(
                    "'lat' or 'lon' not present in parameters")

            # FIXME: snap to grid location
            loc = '%i_%i' % (params['lat'] * 1000, params['lon'] * 1000)
            params['tidalGaugeName'] = '%g%s %g%s' % (
                abs(params['lat']), 'N' if params['lat'] >= 0 else 'S',
                abs(params['lon']), 'E' if params['lon'] >= 0 else 'W')

            fileName = seaChart % (seaLevelProduct['monthly'],
                                   loc, 'rec')
            outputFileName = os.path.join(serverCfg['outputDir'], fileName)

            if not os.path.exists(outputFileName + '.png'):
                plotTimeseries(outputFileName, **params)

            if not os.path.exists(outputFileName + '.png'):
                responseObj['error'] = \
                    "Requested image is not available at this time."
            else:
                response.update(util.build_response_object(
                    [ 'recimg', 'rectxt' ],
                    os.path.join(serverCfg['baseURL'],
                                 serverCfg['rasterURL'],
                                 fileName),
                    [ '.png', '.txt' ]))
                util.touch_files(os.path.join(serverCfg['outputDir'],
                                              fileName),
                                 [ '.png', '.txt' ])
        else: # map
            response.update(self.plot_surface(params))

        return response
Ejemplo n.º 4
0
    def plot_gauge(self, params):
        response = {}

        if 'tidalGaugeId' not in params:
            raise ValidationError("Variable 'gauge' requires a 'tidalGaugeId'")
        elif params['plot'] != 'ts':
            raise ValidationError("Plot must be 'ts'")

        tid = params['tidalGaugeId']

        params['tidalGaugeName'] = tidalGaugeConfig.tidalGauge[tid]['name']
        params['lat'] = tidalGaugeConfig.tidalGauge[tid]['lat']
        params['lon'] = tidalGaugeConfig.tidalGauge[tid]['lon']

        fileName = seaChart % (seaLevelProduct['monthly'], tid, 'tid')
        outputFileName = os.path.join(serverCfg['outputDir'], fileName)

        FILES = ['.png', '.csv']

        plotTidalGauge(outputFileName, **params)

        if not util.check_files_exist(outputFileName, FILES):
            responseObj['error'] = \
                "Requested image is not available at this time."
        else:
            response.update(util.build_response_object(
                [ 'tidimg', 'tidtxt' ],
                os.path.join(serverCfg['baseURL'],
                             serverCfg['rasterURL'],
                             fileName),
                FILES))
            util.touch_files(os.path.join(serverCfg['outputDir'],
                                          fileName),
                             FILES)

        return response
Ejemplo n.º 5
0
    def process(self, params):
        response = {}

        varName = params['variable']
        regionStr = params['area']
        periodStr = params['period']
        inputDate = params["date"]
        date = inputDate.strftime('%Y%m%d')
        yearStr = '%04i' % inputDate.year
        monthStr = '%02i' % inputDate.month
        yearMonthStr = yearStr + monthStr


        if params['plot'] == 'point': #for point value extraction
            (lat, lon), value = extract(**params)
            response['value'] = float(value)
            return response
        elif params['plot'] == 'xsections':
#        if ('lat' in params) and ('lon' in params):
#            plot_subsurface = True
            # Display error if variable selected for subsurface plot is invalid
            if not (varName == 'temp' or varName == 'salt'):
                response['error'] = "To display a depth cross section, please select either Temperature or Salinity variables."
                return response
#        else:
#            plot_subsurface = False

#        if plot_subsurface:
            lat_cnt = params['lat']
            lon_cnt = np.mod(params['lon'], 360.0)

            if (0 <= lon_cnt <= 360) and (-90 <= lat_cnt <= 90):
                lon_str = '%.2fE' % lon_cnt
                if lat_cnt >= 0:
                    lat_str = '%.2fN' % lat_cnt
                else:
                    lat_str = '%.2fS' % abs(lat_cnt)

                regionStr = '%s_%s' % (lat_str, lon_str)
                regionStr = regionStr.replace('.', '')
            else:
                response['error'] = "Invalid lat/lon coordinates"
                return response

            plot_filename = '%s_%s_%s_%s' % (branProduct[periodStr],
                                             varName, yearMonthStr, regionStr)
            plot_filename_fullpath = os.path.join(server_config['outputDir'],
                                                  plot_filename)
            basemap_filename = '%s_%s_%s' % (branProduct[periodStr],
                                             varName, yearMonthStr)
            basemap_filename_fullpath = os.path.join(server_config['outputDir'],
                                                     basemap_filename)

            # Generate basemap if does not exist
            if not check_basemap_exists(basemap_filename_fullpath):
                plot_surface_data(varName, date, periodStr, yearStr, monthStr, regionStr,
                                  basemap_filename_fullpath, basemap_only=True)

            # Determine plot settings
            if varName == 'temp':
                unitStr = ur'\u00b0' + 'C'
                varLongName = 'Surface and Subsurface Temperature Profile'
                cb_ticks = np.arange(16.0, 30.1, 1.0)
            elif varName == 'salt':
                unitStr = 'PSU'
                varLongName = 'Surface and Subsurface Salinity Profile'
                cb_ticks = np.arange(33, 37.1, 0.5)

            # Load sub-surface data
            if periodStr == 'monthly':
                title_date_str = params['date'].strftime('%B %Y')
                input_data_file = os.path.join(server_config['dataDir']['bran'],
                                              periodStr, varName,
                                              '%s_%s_%s.nc4' % (varName,
                                                                yearStr,
                                                                monthStr))
            else:
                # FIXME: this is horrific
                monthInt = int(''.join(i for i in periodStr if i.isdigit()))
                months = dateRange.getMonths(date, monthInt)
                title_date_str = months[0].strftime('%B %Y') + ' to ' + months[-1].strftime('%B %Y')
                input_data_file = os.path.join(server_config['dataDir']['bran'],
                                              'averages', periodStr, varName,
                                              BRAN_VERSION + '_%smthavg_%s_%s.nc4' % (monthInt, months[0].strftime('%Y%m'), months[-1].strftime('%Y%m')))
            titleStr = varLongName + ': \n' + title_date_str + '\n'

            lats1, lons1, zlevels1, zonal_data = \
                branPlotterNew.load_BRAN_data(input_data_file, varName,
                                              lat_cnt, lat_cnt,
                                              lon_cnt - 5.0, lon_cnt + 5.0,
                                              depth_min=0.0, depth_max=300.0)
            lats2, lons2, zlevels2, meridional_data = \
                branPlotterNew.load_BRAN_data(input_data_file, varName,
                                              lat_cnt - 5.0, lat_cnt + 5.0,
                                              lon_cnt, lon_cnt,
                                              depth_min=0.0, depth_max=300.0)

            # Load surface data
            lats, lons, zlevels, data = \
                branPlotterNew.load_BRAN_data(input_data_file, varName,
                                              -999.0, 999.0, -999.0, 999.0)

            # Generate subsurface plot
            branPlotterNew.plot_BRAN_depth_slice(zlevels1, lats2, lons1,
                                                 zonal_data, meridional_data,
                                                 lats, lons, data,
                                                 lat_cnt, lon_cnt,
                                                 output_filename=plot_filename_fullpath + '.png',
                                                 units=unitStr, title=titleStr,
                                                 cb_ticks=cb_ticks,
                                                 product_label_str=PRODUCT_LABEL)
        elif params['plot'] == 'map':
            # Plot surface data
            plot_filename = '%s_%s_%s_%s' % (branProduct[periodStr],
                                             varName, yearMonthStr, regionStr)
            plot_filename_fullpath = os.path.join(server_config['outputDir'],
                                                  plot_filename)
            basemap_filename = plot_filename
            basemap_filename_fullpath = plot_filename_fullpath

            if not check_basemap_and_plot_exists(plot_filename_fullpath):
                # If drawing currents, determine vector plot settings
                if varName in ['uv', 'uveta']:
                    lat_min = regionConfig.regions[regionStr][1]['llcrnrlat']
                    lat_max = regionConfig.regions[regionStr][1]['urcrnrlat']
                    lon_min = regionConfig.regions[regionStr][1]['llcrnrlon']
                    lon_max = regionConfig.regions[regionStr][1]['urcrnrlon']

                    draw_every, arrow_scale = \
                        branPlotterNew.get_vector_plot_settings(lat_min,
                                                                lat_max,
                                                                lon_min,
                                                                lon_max)

                    # Display error if chosen region is too large for
                    # displaying currents
                    if (draw_every is None) or (arrow_scale is None):
                        response['error'] = "The region is too large for displaying currents.  Please select a smaller region and try again."
                        return response
                else:
                    draw_every, arrow_scale = None, None

                plot_surface_data(varName, date, periodStr, yearStr, monthStr, regionStr,
                                  basemap_filename_fullpath,
                                  plot_filename_fullpath=plot_filename_fullpath,
                                  basemap_only=False, draw_every=draw_every,
                                  arrow_scale=arrow_scale)

        if check_basemap_exists(basemap_filename_fullpath) and \
           check_plot_exists(plot_filename_fullpath):

            response.update(util.build_response_object(
                            COMMON_FILES.keys(),
                            os.path.join(server_config['baseURL'],
                                         server_config['rasterURL'],
                                         basemap_filename),
                            COMMON_FILES.values()))
            response['img'] = os.path.join(server_config['baseURL'],
                                           server_config['rasterURL'],
                                           plot_filename + '.png')
            if params['variable'] == 'temp':
                if regionConfig.regions[params['area']][0] == 'pac':
                    response['map'] = 'mean_sub'
                else:
                    response['map'] = 'mean'
            elif params['variable'] == 'salt':
                response['map'] = 'salt'
            elif params['variable'] == 'uv':
                response['map'] = 'uv'

            util.touch_files(os.path.join(server_config['outputDir'],
                                          plot_filename),
                             COMMON_FILES.values())
            util.touch_files(os.path.join(plot_filename_fullpath),
                             [ COMMON_FILES['img'] ])
        else:
            response['error'] = "Requested image is not available at this time."

        return response
Ejemplo n.º 6
0
    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