コード例 #1
0
ファイル: wf_Timeoutput.py プロジェクト: vortechbv/OpenDA
    def __init__(self, tssFilename, model, idMap=None, noHeader=False):
        """

    """

        if not isinstance(tssFilename, str):
            raise Exception(
                "timeseries output filename must be of type string")

        self._outputFilename = tssFilename
        self._maxId = 1
        self._spatialId = None
        self._spatialDatatype = None
        self._spatialIdGiven = False
        self._userModel = model
        self._writeHeader = not noHeader
        # array to store the timestep values
        self._sampleValues = None

        _idMap = False
        #if isinstance(idMap, str) or isinstance(idMap, PCRaster._PCRaster.Field):
        if isinstance(idMap, str) or isinstance(idMap,
                                                PCRaster._pcraster.Field):
            _idMap = True

        nrRows = self._userModel.nrTimeSteps() - self._userModel.firstTimeStep(
        ) + 1

        if _idMap:
            self._spatialId = idMap
            if isinstance(idMap, str):
                self._spatialId = PCRaster.readmap(idMap)

            _allowdDataTypes = [
                PCRaster.Nominal, PCRaster.Ordinal, PCRaster.Boolean
            ]
            if self._spatialId.dataType() not in _allowdDataTypes:
                raise Exception(
                    "idMap must be of type Nominal, Ordinal or Boolean")

            if self._spatialId.isSpatial():
                self._maxId, valid = PCRaster.cellvalue(
                    PCRaster.mapmaximum(PCRaster.ordinal(self._spatialId)), 1)
            else:
                self._maxId = 1

            # cell indices of the sample locations
            self._sampleAddresses = []
            for cellId in range(1, self._maxId + 1):
                thecellId = self._getIndex(cellId)
                if thecellId != 0:
                    self._sampleAddresses.append(thecellId)
                else:
                    print "CellId " + str(cellId) + " not found."

            self._spatialIdGiven = True
            nrCols = self._maxId
            self._sampleValues = [[Decimal("NaN")] * nrCols
                                  for _ in [0] * nrRows]
        else:
            self._sampleValues = [[Decimal("NaN")] * 1 for _ in [0] * nrRows]
コード例 #2
0
monthlyArchiveFile= 'cru_alpha_sc_results.zip'
specificQArchiveFile= 'cru_specificrunoff_results.zip'
rootQSpecFileNames= ['waterrunoff%s.map','landrunoff%s.map']
rootQFileName= 'qc'
MV= -999.
startYear= 1958; endYear= 2001
yearList= range(startYear,endYear+1)
rootR3AVGFileName= 'r3_avg%s.map'
LDD= pcr.readmap('glwd_lddlake.map')
LDDBasins= pcr.readmap('glwd130m_ldd.map')
cellArea= pcr.readmap('cellarea30.map')
fracWat= pcr.readmap('glwd130m_fracw.map')
lakeMask= pcr.readmap('lake.map') != 0
catchments= pcr.catchment(LDDBasins,pcr.pit(LDDBasins))
pcr.report(catchments,'catchments.map')
maximumCatchmentID= pcr.cellvalue(pcr.mapmaximum(pcr.scalar(catchments)),1)[0]
catchmentSizeLimit= 0.

#-main
#-opening zip file
print 'extracting information from zip file'
currentPath= os.getcwd()
zipArchive= zipfile.ZipFile(monthlyArchiveFile)

print 'processing maps: discharge over %d-%d' % (startYear,endYear)
iCnt= 0
yearStartPos= len(rootQFileName)
yearEndPos= yearStartPos+4
#-loop through zip file and retrieve relevant maps
for fileName in zipArchive.namelist():
  if rootQFileName in fileName and not 'ini' in fileName:
コード例 #3
0
ファイル: wf_Timeoutput.py プロジェクト: vortechbv/OpenDA
class wf_TimeoutputTimeseries(object):
    """
  Class to create pcrcalc timeoutput style timeseries
  """
    def __init__(self, tssFilename, model, idMap=None, noHeader=False):
        """

    """

        if not isinstance(tssFilename, str):
            raise Exception(
                "timeseries output filename must be of type string")

        self._outputFilename = tssFilename
        self._maxId = 1
        self._spatialId = None
        self._spatialDatatype = None
        self._spatialIdGiven = False
        self._userModel = model
        self._writeHeader = not noHeader
        # array to store the timestep values
        self._sampleValues = None

        _idMap = False
        #if isinstance(idMap, str) or isinstance(idMap, PCRaster._PCRaster.Field):
        if isinstance(idMap, str) or isinstance(idMap,
                                                PCRaster._pcraster.Field):
            _idMap = True

        nrRows = self._userModel.nrTimeSteps() - self._userModel.firstTimeStep(
        ) + 1

        if _idMap:
            self._spatialId = idMap
            if isinstance(idMap, str):
                self._spatialId = PCRaster.readmap(idMap)

            _allowdDataTypes = [
                PCRaster.Nominal, PCRaster.Ordinal, PCRaster.Boolean
            ]
            if self._spatialId.dataType() not in _allowdDataTypes:
                raise Exception(
                    "idMap must be of type Nominal, Ordinal or Boolean")

            if self._spatialId.isSpatial():
                self._maxId, valid = PCRaster.cellvalue(
                    PCRaster.mapmaximum(PCRaster.ordinal(self._spatialId)), 1)
            else:
                self._maxId = 1

            # cell indices of the sample locations
            self._sampleAddresses = []
            for cellId in range(1, self._maxId + 1):
                thecellId = self._getIndex(cellId)
                if thecellId != 0:
                    self._sampleAddresses.append(thecellId)
                else:
                    print "CellId " + str(cellId) + " not found."

            self._spatialIdGiven = True
            nrCols = self._maxId
            self._sampleValues = [[Decimal("NaN")] * nrCols
                                  for _ in [0] * nrRows]
        else:
            self._sampleValues = [[Decimal("NaN")] * 1 for _ in [0] * nrRows]

    def _getIndex(self, cellId):
        """
    returns the cell index of a sample location
    """
        nrCells = PCRaster.clone().nrRows() * PCRaster.clone().nrCols()
        found = False
        cell = 1
        index = 0

        while found == False and cell <= nrCells:
            if PCRaster.cellvalue(self._spatialId,
                                  cell)[1] == True and PCRaster.cellvalue(
                                      self._spatialId, cell)[0] == cellId:
                index = cell
                found = True
            cell += 1

        return index

    def sample(self, expression):
        """
    Sampling the current values of 'expression' at the given locations for the current timestep
    """

        arrayRowPos = self._userModel.currentTimeStep(
        ) - self._userModel.firstTimeStep()

        #if isinstance(expression, float):
        #  expression = PCRaster.scalar(expression)

        try:
            # store the data type for tss file header
            if self._spatialDatatype == None:
                self._spatialDatatype = str(expression.dataType())
        except AttributeError, e:
            datatype, sep, tail = str(e).partition(" ")
            msg = "Argument must be a PCRaster map, type %s given. If necessary use data conversion functions like scalar()" % (
                datatype)
            raise AttributeError(msg)

        if self._spatialIdGiven:
            if expression.dataType() == PCRaster.Scalar or expression.dataType(
            ) == PCRaster.Directional:
                tmp = PCRaster.areaaverage(PCRaster.spatial(expression),
                                           PCRaster.spatial(self._spatialId))
            else:
                tmp = PCRaster.areamajority(PCRaster.spatial(expression),
                                            PCRaster.spatial(self._spatialId))

            col = 0
            for cellIndex in self._sampleAddresses:
                value, valid = PCRaster.cellvalue(tmp, cellIndex)
                if not valid:
                    value = Decimal("NaN")

                self._sampleValues[arrayRowPos][col] = value
                col += 1
        else:
            if expression.dataType() == PCRaster.Scalar or expression.dataType(
            ) == PCRaster.Directional:
                tmp = PCRaster.maptotal(PCRaster.spatial(expression))\
                      / PCRaster.maptotal(PCRaster.scalar(PCRaster.defined(PCRaster.spatial(expression))))
            else:
                tmp = PCRaster.mapmaximum(PCRaster.maptotal(PCRaster.areamajority(PCRaster.spatial(expression),\
                      PCRaster.spatial(PCRaster.nominal(1)))))

            value, valid = PCRaster.cellvalue(tmp, 1)
            if not valid:
                value = Decimal("NaN")

            self._sampleValues[arrayRowPos] = value

        if self._userModel.currentTimeStep() == self._userModel.nrTimeSteps():
            self._writeTssFile()