def valueReport(val,valName,outDir): #-return global and country values #-open text files valNameFile= '%s\\%s.txt' % (outDir,valName) if year == staYear and month == staMonth: valName= open(valNameFile,'w') else: valName= open(valNameFile,'a') #-calculate country value (km3/year) cntValue= pcr.areatotal(val,country)/conv for nrCnt in range(cntTot+1): if year == staYear and month == staMonth: valName.write('%d ' % (nrCnt)) for nrCnt in range(cntTot+1): cntPoint= pcr.ifthen(countryLocations==int(nrCnt),cntValue) cntPoint= pcr.cellvalue(pcr.maptotal(cntPoint),int(1))[0] if nrCnt==int(0): valName.write('\n%04d %02d ' % (year,month)) else: valName.write('%02f ' % (cntPoint)) #-calculate global total (km3/year) glbValue= pcr.maptotal(val)/conv glbPoint= pcr.cellvalue(glbValue,int(1))[0] valName.write('%02f' % (glbPoint)) #-close text files valName.close() return cntValue,glbValue,valName
def test_03(self): """ nonspatial condition in ifthen """ nr_rows = 2 nr_cols = 3 nr_cells = nr_rows * nr_cols pcraster.setclone(nr_rows, nr_cols, 5, 1, 1) raster = pcraster.ifthen(pcraster.boolean(1), pcraster.scalar(4.567)) for idx in range(1, nr_cells + 1): value, isValid = pcraster.cellvalue(raster, idx) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 4.567, 6) raster = pcraster.ifthen(pcraster.boolean(0), pcraster.scalar(4.567)) for idx in range(1, nr_cells + 1): value, isValid = pcraster.cellvalue(raster, idx) self.assertEqual(isValid, False) raster = pcraster.ifthen(pcraster.scalar(1), pcraster.scalar(4.567)) for idx in range(1, nr_cells + 1): value, isValid = pcraster.cellvalue(raster, idx) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 4.567, 6) raster = pcraster.ifthen(pcraster.scalar(0), pcraster.scalar(4.567)) for idx in range(1, nr_cells + 1): value, isValid = pcraster.cellvalue(raster, idx) self.assertEqual(isValid, False)
def getMinMaxMean(mapFile,ignoreEmptyMap=False): mn = pcr.cellvalue(pcr.mapminimum(mapFile),1)[0] mx = pcr.cellvalue(pcr.mapmaximum(mapFile),1)[0] nrValues = pcr.cellvalue(pcr.maptotal(pcr.scalar(pcr.defined(mapFile))), 1 ) [0] #/ getNumNonMissingValues(mapFile) if nrValues == 0.0 and ignoreEmptyMap: return 0.0,0.0,0.0 else: return mn,mx,(getMapTotal(mapFile) / nrValues)
def testCellValueNonSpatial(self): raster = pcraster.readmap("abs_Expr.map") value, isValid = pcraster.cellvalue(pcraster.mapmaximum(raster), 1, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertEqual(value, 14.0) value, isValid = pcraster.cellvalue(pcraster.mapmaximum(raster), 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertEqual(value, 14.0)
def testCellValueNonSpatial(self): raster = self._read_set_clone("abs_Expr.map") value, isValid = pcraster.cellvalue(pcraster.mapmaximum(raster), 1, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 14.0) value, isValid = pcraster.cellvalue(pcraster.mapmaximum(raster), 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 14.0)
def boundingBox(pcrmap): ''' derive the bounding box for a map, return xmin,ymin,xmax,ymax ''' bb = [] xcoor = pcr.xcoordinate(pcrmap) ycoor = pcr.ycoordinate(pcrmap) xmin = pcr.cellvalue(pcr.mapminimum(xcoor), 1, 1)[0] xmax = pcr.cellvalue(pcr.mapmaximum(xcoor), 1, 1)[0] ymin = pcr.cellvalue(pcr.mapminimum(ycoor), 1, 1)[0] ymax = pcr.cellvalue(pcr.mapmaximum(ycoor), 1, 1)[0] return [math.floor(xmin), math.floor(ymin), math.ceil(xmax), math.ceil(ymax)]
def test_01(self): """ divide float by field """ raster = pcraster.readmap("abs_Expr.map") result = 1 / raster value, isValid = pcraster.cellvalue(result, 1) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 0.5) value, isValid = pcraster.cellvalue(result, 2) self.assertEqual(isValid, True) self.assertAlmostEqual(value, -0.142857, 6) value, isValid = pcraster.cellvalue(result, 3) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 0.285714, 6) value, isValid = pcraster.cellvalue(result, 4) self.assertEqual(isValid, True) self.assertAlmostEqual(value, -0.117647, 6) value, isValid = pcraster.cellvalue(result, 5) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 0.277778, 6) value, isValid = pcraster.cellvalue(result, 6) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(result, 7) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(result, 8) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 0.0714286, 6) value, isValid = pcraster.cellvalue(result, 9) self.assertEqual(isValid, True) self.assertAlmostEqual(value, -1.25)
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 as 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()
def test_3(self): """ test nonspatials nominals in != with scalar raster""" raster = pcraster.readmap("abs_Expr.map") result = raster != -7 value, isValid = pcraster.cellvalue(result, 1) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 2) self.assertEqual(isValid, True) self.assertEqual(value, 0) value, isValid = pcraster.cellvalue(result, 3) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 4) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 5) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 6) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(result, 7) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 8) self.assertEqual(isValid, True) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(result, 9) self.assertEqual(isValid, True) self.assertEqual(value, 1)
def testCellValueNonSpatial(self): pcraster.setclone("abs_Expr.map") raster = pcraster.readmap("abs_Expr.map") value, isValid = pcraster.cellvalue(mapmaximum(raster), 1, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, float)) self.assertEqual(value, 14.0) value, isValid = pcraster.cellvalue(mapmaximum(raster), 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, float)) self.assertEqual(value, 14.0)
def testCellValueOrdinal(self): raster = pcraster.ordinal(self._read_set_clone("areaarea_Class.map")) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 6) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, False)
def testCellValueOrdinal(self): raster = pcraster.ordinal(pcraster.readmap("areaarea_Class.map")) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 6) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, False)
def testCellValueOrdinal(self): pcraster.setclone("areaarea_Class.map") raster = ordinal(pcraster.readmap("areaarea_Class.map")) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 6) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, False)
def testNotEqualsLdd(self): ldd = pcraster.readmap("accu_Ldd.map") nonSpatial = pcraster._pcraster._newNonSpatialField(5) raster = pcraster.pcrne("accu_Ldd.map", 5) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertEqual(value, True) value, isValid = pcraster.cellvalue(raster, 22) self.assertEqual(isValid, True) self.assertEqual(value, False) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assertEqual(value, True)
def test_7(self): """ test cover and nonspatial arguments """ pcraster.setclone(3, 4, 1, 1, 1) # Pointless cover, but previously returned a None result = cover(1.3, 2.3) value, isValid = pcraster.cellvalue(result, 1) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.3) value, isValid = pcraster.cellvalue(result, 4) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.3)
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 as 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()
def testReportNonSpatial(self): raster = pcraster.readmap("abs_Expr.map") max1 = pcraster.mapmaximum(raster) value, isValid = pcraster.cellvalue(max1, 1) self.assertTrue(isinstance(value, float)) self.assertEqual(isValid, True) self.assertEqual(value, 14.0) pcraster.report(max1, "maximum.map") max2 = pcraster.readmap("maximum.map") for i in range(1, 8): value, isValid = pcraster.cellvalue(max2, i) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 14.0)
def update_z(df, pcr_map): """ Update the 'z' column of the DataFrame with the 'x' and 'y' columns. Missing values in pcr_map are left unaltered ---------- Parameters: df: DataFrame with 'x', 'y', and 'z' columns pcr_map: PCRaster map with new values for 'z'. """ columns = list('xyz') df.columns = columns df_out = df.copy() pcr_map = pcr.scalar(pcr_map) for idx, row in df.loc[:, columns].iterrows(): x, y, z = list(row) row_nr, col_nr = pcr_coord(x, y) try: new_z, validity = pcr.cellvalue(pcr_map, row_nr, col_nr) if validity == True: df_out.loc[idx, 'z'] = new_z else: df_out.loc[idx, 'z'] = z except (ValueError, OverflowError): df_out.loc[idx, 'z'] = z return df_out
def getCellValues(pointMap, mapList=[], columns=[]): """ Get the cell values of the maps in mapList at the locations of pointMap """ #-determine where the indices are True arr = pcr.pcr2numpy(pcr.boolean(pointMap), 0).astype('bool') indices = np.where(arr == True) #-loop over the points in pointMap pcr.setglobaloption('unitcell') ll = [] for rowIdx, colIdx in zip(indices[0], indices[1]): line = [] line.append(rowIdx) line.append(colIdx) for pcrMap in mapList: line.append( pcr.cellvalue(pcrMap, np.int(rowIdx + 1), np.int(colIdx + 1))[0]) ll.append(line) #-optionally add column names if len(columns) == len(mapList): columnNames = ['rowIdx', 'colIdx'] + columns else: columnNames = ['rowIdx', 'colIdx'] + \ ['map' + str(ii) for ii in range(1, 1 + len(mapList), 1)] #-return as Pandas DataFrame return pd.DataFrame(np.array(ll), columns=columnNames)
def updateTrachytopes(inFile, outFile, roughCodeMap): """ input: inFile: path to ascii trachytope file with columns x, y, 0, code, fraction outFile: path to outfile with ascii trachytopes roughCodeMap: pcraster map with roughness codes output: new trachytope file """ #-read the trachtope data into a DataFrame columns = ['x', 'y', 'z', 'code', 'frac'] trachytopes = pd.DataFrame(data=np.loadtxt(inFile), columns=columns) nrCols = pcr.clone().nrCols() nrRows = pcr.clone().nrRows() #-get cell value for each line in trachytope DataFrame for cnt in xrange(len(trachytopes)): xcoord = trachytopes.loc[cnt, 'x'] ycoord = trachytopes.loc[cnt, 'y'] row, col = pcr_coord(xcoord, ycoord) if col > nrCols: roughCode, validCell = 102, False elif row <= 0: roughCode, validCell = 102, False else: roughCode, validCell = pcr.cellvalue(roughCodeMap, row, col) if validCell == True: trachytopes.loc[cnt, 'code'] = roughCode groupedCodes = trachytopes.groupby(by=['x', 'y', 'z', 'code']).sum() groupedCodes.reset_index(inplace=True) np.savetxt(outFile, groupedCodes.values, fmt='%.4f %.4f %.0f %.0f %.4f') return groupedCodes
def printCellValue(x,repStr= 'map value',location= 1): #-returns the cell value at the location specified # it tests whether this is a tuple or not of the format row, column try: value,valid= pcr.cellvalue(x,location[1],location[0]) posStr= 'at row column: %d, %d' % (location,[0],location[1]) except: try: value,valid= pcr.cellvalue(x,location) posStr= 'at cell location: %d' % location except: value= x valid= True posStr= 'global float' if valid: print repStr+(' %f ' % value)+posStr return value
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: if pcraster.cellvalue(self._spatialId, cell)[1] == True and pcraster.cellvalue(self._spatialId, cell)[0] == cellId: index = cell found = True cell += 1 if cell > nrCells: raise RuntimeError("could not find a cell with the index number %d" % (cellId)) return index
def test_5(self): """ test windowaverage and kernel size larger than raster """ filename = "windowaverage_Expr.map" pcraster.setclone(filename) raster = pcraster.readmap(filename) result1 = windowaverage(raster, 18) result2 = mapmaximum(result1) value, isValid = pcraster.cellvalue(result2, 1) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.708333, places=6) pcraster.setglobaloption("unitcell") result1 = windowaverage(raster, 9) result2 = mapmaximum(result1) value, isValid = pcraster.cellvalue(result2, 1) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.708333, places=6)
def testNotEqualsLdd(self): pcraster.setclone("accu_Ldd.map") ldd = pcraster.readmap("accu_Ldd.map") nonSpatial = pcraster._pcraster._newNonSpatialField(5) # we need to explicitly cast PODs to ldd (or directional) # when using the multicore module #raster = mcop.pcrmcNE("accu_Ldd.map", 5) raster = mcop.pcrmcNE("accu_Ldd.map", pcraster.ldd(5)) warnings.warn("Difference between pcraster and multicore module...") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertEqual(value, True) value, isValid = pcraster.cellvalue(raster, 22) self.assertEqual(isValid, True) self.assertEqual(value, False) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assertEqual(value, True)
def checkmap(name, value, map, flagmap, find): """ check maps if they fit to the mask map """ s = [name, value] MMaskMap = 0 if flagmap: amap = scalar(defined(MMaskMap)) try: smap = scalar(defined(map)) except: msg = "Map: " + name + " in " + value + " does not fit" if name == "LZAvInflowMap": msg += "\nTry to execute the initial run first" raise LisfloodError(msg) mvmap = maptotal(smap) mv = pcraster.cellvalue(mvmap, 1, 1)[0] s.append(mv) less = maptotal(ifthenelse(defined(MMaskMap), amap - smap, scalar(0))) s.append(pcraster.cellvalue(less, 1, 1)[0]) less = mapminimum(scalar(map)) s.append(pcraster.cellvalue(less, 1, 1)[0]) less = maptotal(scalar(map)) s.append(pcraster.cellvalue(less, 1, 1)[0] / mv) if mv > 0 else s.append('0') less = mapmaximum(scalar(map)) s.append(pcraster.cellvalue(less, 1, 1)[0]) if find > 0: if find == 2: s.append('last_Map_used') else: s.append('') else: s.append(0) s.append(0) s.append(float(map)) s.append(float(map)) s.append(float(map)) if checkmap.called == 1: # FIXME omg print ("%-25s%-40s%11s%11s%11s%11s%11s" % ("Name", "File/Value", "nonMV", "MV", "min", "mean", "max")) print ("%-25s%-40s%11i%11i%11.2f%11.2f%11.2f" % (s[0], s[1][-39:], s[2], s[3], s[4], s[5], s[6])) return
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): _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): self._sampleAddresses.append(self._getIndex(cellId)) 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 test_1(self): """ test nonspatials nominal in ifthenelse with scalar raster""" pcraster.setclone("and_Expr1.map") result = ifthenelse(boolean(1.0 == 2.0), \ scalar(3.0), 4.0) self.assertEqual(pcraster.cellvalue(result, 1)[0], 4.0) result = ifthenelse(boolean(1.0 == 2.0), \ scalar(3.0), 4) self.assertEqual(pcraster.cellvalue(result, 1)[0], 4.0) result = ifthenelse(boolean(2.0 == 2.0), \ 3.0, scalar(4.0)) self.assertEqual(pcraster.cellvalue(result, 1)[0], 3.0) result = ifthenelse(boolean(2.0 == 2.0), \ 3, scalar(4.0)) self.assertEqual(pcraster.cellvalue(result, 1)[0], 3.0)
def test_6(self): """ test cover and nonspatial first arguments """ pcraster.setclone(3, 4, 1, 1, 1) raster = pcraster.uniform(1) msg = "pcraster.multicore cover: argument nr 2 is of type 'scalar', legal type is 'nominal'" self.assertRaisesRegex(RuntimeError, msg, pcraster.cover, 1, 2.4) self.assertRaisesRegex(RuntimeError, msg, pcraster.cover, 1, raster) # Pointless cover, but previously returned a None result = cover(1.2, raster) value, isValid = pcraster.cellvalue(result, 1) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.2) value, isValid = pcraster.cellvalue(result, 4) self.assertEqual(isValid, True) self.assertAlmostEqual(value, 1.2)
def testCellValueDirectional(self): raster = self._read_set_clone("nodirection_Expr.map") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertAlmostEqual(value, math.radians(280)) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertAlmostEqual(value, math.radians(25)) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertAlmostEqual(value, -1.0) value, isValid = pcraster.cellvalue(raster, 7) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertAlmostEqual(value, math.radians(7))
def testCellValueDirectional(self): raster = pcraster.readmap("nodirection_Expr.map") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertAlmostEqual(value, math.radians(280)) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertAlmostEqual(value, math.radians(25)) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertAlmostEqual(value, -1.0) value, isValid = pcraster.cellvalue(raster, 7) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.FloatType)) self.assertAlmostEqual(value, math.radians(7))
def testCellValueNominal(self): raster = pcraster.readmap("areaarea_Class.map") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 6) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assert_(isinstance(value, int)) self.assertEqual(value, 4)
def _int(self): if self.isSpatial(): raise Exception( "The integer value for PCRaster spatial data types is ambiguous.") result = None value, isValid = pcraster.cellvalue(self, 0) if isValid: result = int(value) return result
def testCellValueNominal(self): pcraster.setclone("areaarea_Class.map") raster = nominal(pcraster.readmap("areaarea_Class.map")) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 6) value, isValid = pcraster.cellvalue(raster, 5) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 4)
def _float(self): if self.isSpatial(): raise Exception( "The floating point value for PCRaster spatial data types is ambiguous.") result = None value, isValid = pcraster.cellvalue(self, 0) if isValid: result = float(value) return result
def testCellValueScalar(self): pcraster.setclone("abs_Expr.map") raster = scalar(pcraster.readmap("abs_Expr.map")) value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 2.0) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, -7.0) value, isValid = pcraster.cellvalue(raster, 3) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 3.5) value, isValid = pcraster.cellvalue(raster, 6) self.assertEqual(isValid, False) value, isValid = pcraster.cellvalue(raster, 7) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 0.0) value, isValid = pcraster.cellvalue(raster, 8) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, float)) self.assertEqual(value, 14.0)
def testCellValueLdd(self): raster = pcraster.readmap("accu_Ldd.map") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(raster, 22) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 5) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assert_(isinstance(value, types.IntType)) self.assertEqual(value, 4)
def _bool(self): if self.isSpatial(): raise Exception( "The truth value for PCRaster spatial data types is ambiguous. " "See the section Boolean operations in the PCRaster Python manual.") result = None value, isValid = pcraster.cellvalue(self, 0) if isValid: result = bool(value) return result
def testCellValueLdd(self): raster = self._read_set_clone("accu_Ldd.map") value, isValid = pcraster.cellvalue(raster, 1) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 2) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 2) value, isValid = pcraster.cellvalue(raster, 9) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 1) value, isValid = pcraster.cellvalue(raster, 22) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 5) value, isValid = pcraster.cellvalue(raster, 25) self.assertEqual(isValid, True) self.assertTrue(isinstance(value, int)) self.assertEqual(value, 4)
def testNonSpatialCreation(self): value = 198329008 nonSpatial = nominal(value) self.assertEqual(pcraster.cellvalue(nonSpatial, 1)[0], value) # OK value = 10000 i = 0 while i < 100: nonSpatial = nominal(value) self.assertEqual(pcraster.cellvalue(nonSpatial, 1)[0], value) value += 13 i += 1 # Not OK bugzilla144 = False if not bugzilla144: print("skipped bugzilla144") else: value = 198329008 i = 0 while i < 100: nonSpatial = nominal(value) self.assertEqual(pcraster.cellvalue(nonSpatial, 1)[0], value) value += 13 i += 1 # Bug is in the _PCRaster/_PCRaster.cc: # newNonSpatialIntegralField code. # CW Jul-14/2008 CW can not trace it back to newNonSpatialIntegralField value = 198329012 nonSpatial = nominal(value) self.assertEqual(pcraster.cellvalue(nonSpatial, 1)[0], value) value = 198329020 nonSpatial = nominal(value) self.assertEqual(pcraster.cellvalue(nonSpatial, 1)[0], value)
def testIfThenElse(self): pcraster.setclone("and_Expr1.map") exceptionThrown = False try: result = ifthenelse(1.0 == 2.0, 3.0, 4.0) except RuntimeError as exception: message = str(exception) self.assertTrue(message.find("conversion function to pick a data type") != -1) exceptionThrown = True self.assertTrue(exceptionThrown) result = ifthenelse(boolean(1.0 == 2.0), \ scalar(3.0), scalar(4.0)) self.assertEqual(pcraster.cellvalue(result, 1)[0], 4.0)
def testCellValueBoolean(self): raster = boolean(pcraster.readmap("and_Expr1.map")) value, isValid = pcraster.cellvalue(raster, 1) self.valueTest(value, isValid, True, int, True) value, isValid = pcraster.cellvalue(raster, 2) self.valueTest(value, isValid, True, int, True) value, isValid = pcraster.cellvalue(raster, 3) self.valueTest(value, isValid, True, int, False) value, isValid = pcraster.cellvalue(raster, 4) self.valueTest(value, isValid, True, int, False) value, isValid = pcraster.cellvalue(raster, 5) self.valueTest(value, isValid, False, None, None) value, isValid = pcraster.cellvalue(raster, 6) self.valueTest(value, isValid, True, int, False) value, isValid = pcraster.cellvalue(raster, 7) self.valueTest(value, isValid, True, int, True) value, isValid = pcraster.cellvalue(raster, 8) self.valueTest(value, isValid, True, int, True) value, isValid = pcraster.cellvalue(raster, 9) self.valueTest(value, isValid, True, int, False)
def test001(self): """Test mcpercentiles""" percentileLevels = [0.01, 0.5, 0.99] realisationNumbers = range(1, 100) timesteps = [0] names = ["concentration_without_mv", "concentration_with_mv"] percentiles = mcpercentiles(names, percentileLevels, realisationNumbers, timesteps) for level in percentileLevels: name = "concentration_without_mv_{0}.map".format(level) self.assertTrue(os.path.isfile(name)) raster = pcraster.readmap(name) for i in range(1, 7): value, valid = pcraster.cellvalue(raster, i) self.assertTrue(valid) self.assertAlmostEqual(value, i + (level * (len(realisationNumbers) - 1)), 5) name = "concentration_with_mv_{0}.map".format(level) self.assertTrue(os.path.isfile(name)) raster = pcraster.readmap(name) for i in range(1, 7): value, valid = pcraster.cellvalue(raster, i) self.assertTrue(valid) if level < 0.50: self.assertAlmostEqual(value, i + (level * (len(realisationNumbers)- 1 - 1)), 5) elif level > 0.50: self.assertAlmostEqual(value, i + (level * (len(realisationNumbers)- 1 - 1)) + 1, 5) else: self.assertAlmostEqual(value, i + (level * (len(realisationNumbers)- 1 - 1)) + 0.5, 5)
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): _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): self._sampleAddresses.append(self._getIndex(cellId)) 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 arbitraryMapEquals(self, firstMap, secondMap): import math def floatEquals(float1, float2): threshold = 1e-6 return math.fabs(float1 - float2) <= threshold if((firstMap.dataType() == _pcraster.Scalar) | \ (firstMap.dataType() == _pcraster.Directional)): result = _pcraster._closeAtTolerance(firstMap, secondMap) else: result = pcraster.pcreq(firstMap, secondMap) minMap = pcraster.mapminimum(pcraster.spatial(pcraster.scalar(result))) value, isValid = pcraster.cellvalue(minMap, 1) assert isValid return floatEquals(value, 1.0)
def initial(self): raster = self.readmap("plus") # value, isValid = pcraster.cellvalue(raster, 1) assert isValid == False # value, isValid = pcraster.cellvalue(raster, 2) assert isValid == True assert value == 8 # value, isValid = pcraster.cellvalue(raster, 3) assert isValid == True assert value == 2 # value, isValid = pcraster.cellvalue(raster, 4) assert isValid == True assert value == 2 # value, isValid = pcraster.cellvalue(raster, 5) assert isValid == False # value, isValid = pcraster.cellvalue(raster, 6) assert isValid == True assert value == -6 # value, isValid = pcraster.cellvalue(raster, 7) assert isValid == True assert value == 100 # value, isValid = pcraster.cellvalue(raster, 8) assert isValid == True assert value == -7 # value, isValid = pcraster.cellvalue(raster, 9) assert isValid == True assert value == 16 self.report(raster, "static")