Example #1
0
def statCellFraction(gridLimit, gridSpace, valueFile):
    """
    Calculate the fractional value of each grid cell, based on the
    values stored in valueFile.
    Input: gridLimit - dictionary of bounds of the grid
           gridSpace - resolution of the grid to calculate values.
           valueFile - path to the ascii grid file containing values to
                       sample
    Output: array of fractional values, with length equal to the number
            of cells
    Example:
    Notes: Still need to include bounds checking to ensure the valueFile
           data actually covers the gridLimits.
    """
    gLon, gLat, gData = grdRead(valueFile)
    nCells = maxCellNum(gridLimit, gridSpace) + 1
    output = zeros(nCells)
    for cellNum in xrange(nCells):
        cellLon, cellLat = getCellLonLat(cellNum, gridLimit, gridSpace)
        wLon = cellLon
        eLon = cellLon + gridSpace['x']
        nLat = cellLat
        sLat = cellLat - gridSpace['y']

        ii = where((gLon<=eLon) & (gLon>=wLon))
        jj = where((gLat<=nLat) & (gLat>=sLat))
        cellValues = gData[meshgrid(jj[0],ii[0])]

        if abs(cellValues).max() == 0:
            output[cellNum] = average(cellValues)
        else:
            output[cellNum] = average(cellValues)/abs(cellValues).max()
    return output
Example #2
0
def statCellFraction(gridLimit, gridSpace, valueFile):
    """
    Calculate the fractional value of each grid cell, based on the
    values stored in valueFile.
    :param dict gridLimit: Dictionary of bounds of the grid.
    :param dict gridSpace: Resolution of the grid to calculate values.
    :param str valueFile: Path to the ascii grid file containing values to sample.

    :returns: :class:`numpy.ndarray` of fractional values, with length equal to the number
              of cells

    Notes: Still need to include bounds checking to ensure the valueFile
    data actually covers the gridLimits.
    """
    gLon, gLat, gData = grdRead(valueFile)
    nCells = maxCellNum(gridLimit, gridSpace) + 1
    output = np.zeros(nCells)
    for cellNum in xrange(nCells):
        cellLon, cellLat = getCellLonLat(cellNum, gridLimit, gridSpace)
        wLon = cellLon
        eLon = cellLon + gridSpace['x']
        nLat = cellLat
        sLat = cellLat - gridSpace['y']

        ii = np.where((gLon <= eLon) & (gLon >= wLon))
        jj = np.where((gLat <= nLat) & (gLat >= sLat))
        cellValues = gData[np.meshgrid(jj[0], ii[0])]

        if abs(cellValues).max() == 0:
            output[cellNum] = np.average(cellValues)
        else:
            output[cellNum] = np.average(cellValues) / abs(cellValues).max()
    return output
Example #3
0
def _process(argv):
    """
    A wrapper function to provide an interface between the command line
    args and the actual plotField function. This function reads settings
    from a configuration file and then passes those arguments to the
    plotField function.
    """
    if len(argv)==0:
        _usage()
        sys.exit(2)

    logLevel = 'INFO'
    verbose = False
    configFile = flConfigFile()

    try:
        opts, args = getopt.getopt(argv, "c:hl:v", ["config=", "help",
                                                   "loglevel=", "verbose"])
    except getopt.GetoptError:
        _usage()
        sys.exit(2)
    for opt,arg in opts:
        if opt in ("-h", "--help"):
            _usage()
            sys.exit(2)
        elif opt in ("-c", "--config"):
            configFile = arg
        elif opt in ("-l", "--loglevel"):
            logLevel = arg
        elif opt in ("-v", "--verbose"):
            verbose = True

    flStartLog(cnfGetIniValue(configFile, 'Logging', 'LogFile', flConfigFile('.log')),
               cnfGetIniValue(configFile, 'Logging', 'LogLevel', logLevel),
               cnfGetIniValue(configFile, 'Logging', 'Verbose', verbose))

    # Input data:
    inputFile = cnfGetIniValue(configFile, 'Input', 'File')
    inputFormat = cnfGetIniValue(configFile, 'Input', 'Format', os.path.splitext(inputFile)[-1])
    varname = cnfGetIniValue(configFile,'Input','Variable','')
    record = cnfGetIniValue(configFile,'Input','Record',0)
    lvl = cnfGetIniValue(configFile,'Input','Level',0)

    # Output settings - the default is to use the input filename, with
    # the extension replaced by the image format:
    # The smoothing is optional. Set it to the number of grid points to
    # smooth over (recommend the reciprocal of the data resolution in degrees).
    imgfmt = cnfGetIniValue(configFile, 'Output', 'Format','png')
    outputFile = cnfGetIniValue(configFile, 'Output', 'File',
                                "%s.%s" % (os.path.splitext(inputFile)[0], imgfmt))
    smoothing = cnfGetIniValue(configFile, 'Output', 'Smoothing', False)
    cmapName = cnfGetIniValue(configFile, 'Output', 'ColourMap', 'gist_ncar')
    label = cnfGetIniValue(configFile, 'Output', 'Label', '')
    mask = cnfGetIniValue(configFile, 'Output', 'MaskLand', False)
    maskocean = cnfGetIniValue(configFile, 'Output', 'MaskOcean', False)
    fill = cnfGetIniValue(configFile, 'Output', 'FillContours', True)
    title = cnfGetIniValue(configFile,'Plot','Title',None)
    # Load data:
    if inputFormat == '.txt':
        # Attempt to load the dataset:
        try:
            lon,lat,data = grid.grdRead(inputFile)
        except:
            logger.critical("Cannot load input file: %s"%inputFile)
            raise
    elif inputFormat == '.nc':
        try:
            ncobj = nctools.ncLoadFile(inputFile)
            lon = nctools.ncGetDims(ncobj,'lon')
            lat = nctools.ncGetDims(ncobj,'lat')
            data = nctools.ncGetData(ncobj,varname)
            mv = getattr(ncobj.variables[varname],'_FillValue')
            ncobj.close()
        except:
            logger.critical("Cannot load input file: %s"%inputFile)
            raise
        if len(shape(data))==3:
            data = data[record,:,:]
        elif len(shape(data))==4:
            data = data[record,lvl,:,:]

        # Create a masked array:
        datamask = (data==mv)
        data = ma.array(data,mask=datamask)

    else:
        logger.critical("Unknown data format")
        raise IOError

    # Set defaults for the extent of the map to match the data in the
    # input file:
    llLon = min(lon)
    urLon = max(lon)
    llLat = min(lat)
    urLat = max(lat)
    res = 'l'
    dl = 10.

    # Domain settings - can override the default settings:
    domain = cnfGetIniValue(configFile, 'Domain', 'Name', None)
    if domain is not None:
        llLon = cnfGetIniValue(configFile, domain, 'LowerLeftLon', min(lon))
        llLat = cnfGetIniValue(configFile, domain, 'LowerLeftLat', min(lat))
        urLon = cnfGetIniValue(configFile, domain, 'UpperRightLon', max(lon))
        urLat = cnfGetIniValue(configFile, domain, 'UpperRightLat', max(lat))
        res = cnfGetIniValue(configFile, domain, 'Resolution', res)
        dl = cnfGetIniValue(configFile, domain, 'GridInterval', dl)

    [x,y] = meshgrid(lon, lat)

    # Set the scale:
    scaleMin = cnfGetIniValue(configFile, 'Output', 'ScaleMin', 0)
    scaleMax = cnfGetIniValue(configFile, 'Output', 'ScaleMax', 101)
    scaleInt = cnfGetIniValue(configFile, 'Output', 'ScaleInt', 10)
    levels = arange(scaleMin, scaleMax, scaleInt)
    plotField(x,y,data, llLon, llLat, urLon, urLat, res, dl, levels,
              cmapName, smoothing, title=title, xlab='Longitude',
              ylab='Latitude', clab=label, maskland=mask,
              maskocean=maskocean,outputFile=outputFile,fill=fill)

    logger.info("Completed %s"%sys.argv[0])