示例#1
0
    def dynamic(self):

        self.logger.debug("Step: " +
                          str(int(self.thestep + self._d_firstTimeStep)) +
                          "/" + str(int(self._d_nrTimeSteps)))
        self.thestep = self.thestep + 1

        if self.scalarInput:
            # gaugesmap not yet finished. Should be a map with cells that
            # hold the gauges with an unique id
            Precipitation = timeinputscalar(self.precipTss, self.gaugesMap)
            Inflow = cover(0.0)
            #Seepage = cover(timeinputscalar(self.SeepageTss,self.SeepageLoc),0)
            Precipitation = pcrut.interpolategauges(Precipitation,
                                                    self.interpolMethod)
            PotEvaporation = timeinputscalar(self.evapTss, self.gaugesMap)
            PotEvaporation = pcrut.interpolategauges(PotEvaporation,
                                                     self.interpolMethod)
            #self.report(PotEvaporation,'p')
            Temperature = timeinputscalar(self.tempTss, self.gaugesMap)
            Temperature = pcrut.interpolategauges(Temperature,
                                                  self.interpolMethod)
            Temperature = Temperature + self.TempCor
        else:
            Precipitation = cover(
                self.readmap(self.Rain_, 0.0, style=self.P_style), 0.0)
            PotEvaporation = cover(
                self.readmap(self.PET_, 0.0, style=self.PET_style), 0.0)
            #Inflow=cover(self.readmap(self.Inflow),0)
            # These ar ALWAYS 0 at present!!!
            Inflow = pcrut.readmapSave(self.Inflow_, 0.0)
            if self.ExternalQbase:
                Seepage = cover(self.readmap(self.Seepage_, 0.0), 0.0)
            else:
                Seepage = cover(0.0)
            Temperature = self.readmap(self.Temp_, 0.0, style=self.TEMP_style)
            Temperature = Temperature + self.TempCor
            #Inflow=spatial(scalar(0.0))

        # Multiply input parameters with a factor (for calibration etc) -p option in command line
        for k, v in multdynapars.iteritems():
            estr = k + "=" + k + "*" + str(v)
            self.logger.debug("Dynamic Parameter multiplication: " + estr)
            exec estr

        # Direct runoff generation
        if self.ExternalQbase:
            DirectRunoffStorage = self.QuickFlow + Seepage + self.RealQuickFlow
        else:
            DirectRunoffStorage = self.QuickFlow + self.BaseFlow + self.RealQuickFlow

        InwaterMM = max(0.0, DirectRunoffStorage)
        Inwater = (InwaterMM * self.reallength * self.reallength *
                   0.001) / self.timestepsecs  # m3/s
        Inwater = Inwater + Inflow  # Add abstractions/inflows in m^3/sec

        ##########################################################################
        # Runoff calculation via Kinematic wave ##################################
        ##########################################################################
        # per distance along stream
        q = Inwater / self.DCL + self.ForecQ_qmec / self.DCL
        self.OldSurfaceRunoff = self.SurfaceRunoff
        self.SurfaceRunoff = kinematic(self.TopoLdd, self.SurfaceRunoff, q,
                                       self.Alpha, self.Beta, self.Tslice,
                                       self.timestepsecs, self.DCL)  # m3/s
        self.SurfaceRunoffMM = self.SurfaceRunoff * self.QMMConv  # SurfaceRunoffMM (mm) from SurfaceRunoff (m3/s)

        self.updateRunOff()
        InflowKinWaveCell = upstream(self.TopoLdd, self.SurfaceRunoff)
        self.MassBalKinWave = (
            self.KinWaveVolume - self.OldKinWaveVolume
        ) / self.timestepsecs + InflowKinWaveCell + Inwater - self.SurfaceRunoff
        Runoff = self.SurfaceRunoff

        # Updating
        # --------
        # Assume a tss file with as many columns as outpulocs. Start updating for each non-missing value and start with the
        # first column (nr 1). Assumes that outputloc and columns match!

        if self.updating:
            QM = timeinputscalar(self.updateFile,
                                 self.UpdateMap) * self.QMMConv

            # Now update the state. Just add to the Ustore
            # self.UStoreDepth =  result
            # No determine multiplication ratio for each gauge influence area.
            # For missing gauges 1.0 is assumed (no change).
            # UpDiff = areamaximum(QM,  self.UpdateMap) - areamaximum(self.SurfaceRunoffMM, self.UpdateMap)
            UpRatio = areamaximum(QM, self.UpdateMap) / areamaximum(
                self.SurfaceRunoffMM, self.UpdateMap)

            UpRatio = cover(areaaverage(UpRatio, self.TopoId), 1.0)
            # Now split between Soil and Kyn  wave
            UpRatioKyn = min(MaxUpdMult,
                             max(MinUpdMult, (UpRatio - 1.0) * UpFrac + 1.0))
            UpRatioSoil = min(
                MaxUpdMult,
                max(MinUpdMult, (UpRatio - 1.0) * (1.0 - UpFrac) + 1.0))

            # update/nudge self.UStoreDepth for the whole upstream area,
            # not sure how much this helps or worsens things
            #if UpdSoil:
            #    toadd = min((self.UStoreDepth * UpRatioSoil) - self.UStoreDepth,StorageDeficit * 0.95)
            #    self.UStoreDepth = self.UStoreDepth + toadd

            # Update the kinematic wave reservoir up to a maximum upstream distance
            # TODO:  add (much smaller) downstream updating also?
            MM = (1.0 - UpRatioKyn) / self.UpdMaxDist
            UpRatioKyn = MM * self.DistToUpdPt + UpRatioKyn

            self.SurfaceRunoff = self.SurfaceRunoff * UpRatioKyn
            self.SurfaceRunoffMM = self.SurfaceRunoff * self.QMMConv  # SurfaceRunoffMM (mm) from SurfaceRunoff (m3/s)
            # water depth (m)
            #self.WaterLevel=(self.Alpha*(self.SurfaceRunoff**self.Beta))/self.Bw
            # # wetted perimeter (m)
            #P=self.Bw+2*self.WaterLevel
            # Alpha
            #self.Alpha=self.AlpTerm*(P**self.AlpPow)
            self.updateRunOff()
            Runoff = self.SurfaceRunoff

        self.sumprecip = self.sumprecip + Precipitation  #accumulated rainfall for water balance
        self.sumevap = self.sumevap + ActEvap  #accumulated evaporation for water balance
        self.sumpotevap = self.sumpotevap + PotEvaporation
        self.sumptemp = self.sumtemp + Temperature
        self.sumrunoff = self.sumrunoff + self.SurfaceRunoffMM  #accumulated runoff for water balance
        self.sumlevel = self.sumlevel + self.WaterLevel

        # sample timeseries
        # Do runoff and level always
        self.runTss.sample(Runoff)
        self.levTss.sample(self.WaterLevel)
        # Get rest from ini file
        toprinttss = configsection(self.config, 'outputtss')
        for a in toprinttss:
            estr = "self." + self.config.get("outputtss",
                                             a) + "Tss.sample(" + a + ")"
            eval(estr)

        # Print .ini defined outputmaps per timestep
        toprint = configsection(self.config, 'outputmaps')
        for a in toprint:
            eval("self.report(" + a +
                 ", self.Dir + \"/\" + self.runId + \"/outmaps/" +
                 self.config.get("outputmaps", a) + "\")")
示例#2
0
    def initial(self):
        """
    Initial part of the model, executed only once. Is read all static model
    information (parameters) and sets-up the variables used in modelling.
    
    """
        global statistics

        setglobaloption("unittrue")

        self.thestep = scalar(0)
        self.setQuiet(True)
        self.precipTss = "../intss/P.tss"  #: name of the tss file with precipitation data ("../intss/P.tss")
        self.tempTss = "../intss/T.tss"  #: name of the tss file with temperature  data ("../intss/T.tss")

        self.logger.info("running for " + str(self.nrTimeSteps()) +
                         " timesteps")
        self.setQuiet(True)

        # Set and get defaults from ConfigFile here ###################################
        self.scalarInput = int(
            configget(self.config, "model", "ScalarInput", "0"))
        self.Tslice = int(configget(self.config, "model", "Tslice", "1"))
        self.interpolMethod = configget(self.config, "model",
                                        "InterpolationMethod", "inv")
        self.reinit = int(configget(self.config, "model", "reinit", "0"))
        self.fewsrun = int(configget(self.config, "model", "fewsrun", "0"))
        self.OverWriteInit = int(
            configget(self.config, "model", "OverWriteInit", "0"))
        self.MassWasting = int(
            configget(self.config, "model", "MassWasting", "0"))
        self.sCatch = int(configget(self.config, "model", "sCatch", "0"))
        self.intbl = configget(self.config, "model", "intbl", "intbl")
        self.timestepsecs = int(
            configget(self.config, "model", "timestepsecs", "86400"))
        self.P_style = int(configget(self.config, "model", "P_style", "1"))
        self.TEMP_style = int(
            configget(self.config, "model", "TEMP_style", "1"))

        # 2: Input base maps ########################################################
        subcatch = ordinal(
            readmap(self.Dir + "/staticmaps/wflow_subcatch.map"
                    ))  # Determines the area of calculations (all cells > 0)
        subcatch = ifthen(subcatch > 0, subcatch)
        if self.sCatch > 0:
            subcatch = ifthen(subcatch == sCatch, subcatch)

        self.Altitude = readmap(self.Dir + "/staticmaps/wflow_dem") * scalar(
            defined(subcatch))  #: The digital elevation map (DEM)
        self.TopoId = readmap(
            self.Dir + "/staticmaps/wflow_subcatch.map"
        )  #: Map define the area over which the calculations are done (mask)
        self.TopoLdd = readmap(self.Dir + "/staticmaps/wflow_ldd.map"
                               )  #: The local drinage definition map (ldd)
        # read landuse and soilmap and make sure there are no missing points related to the
        # subcatchment map. Currently sets the lu and soil type  type to 1
        self.LandUse = readmap(
            self.Dir +
            "/staticmaps/wflow_landuse.map")  #: Map with lan-use/cover classes
        self.LandUse = cover(self.LandUse, nominal(ordinal(subcatch) > 0))
        self.Soil = readmap(
            self.Dir + "/staticmaps/wflow_soil.map")  #: Map with soil classes
        self.Soil = cover(self.Soil, nominal(ordinal(subcatch) > 0))
        self.OutputLoc = readmap(self.Dir + "/staticmaps/wflow_gauges.map"
                                 )  #: Map with locations of output gauge(s)

        # Temperature correction poer cell to add
        self.TempCor = pcrut.readmapSave(
            self.Dir + "/staticmaps/wflow_tempcor.map", 0.0)

        if self.scalarInput:
            self.gaugesMap = readmap(
                self.Dir + "/staticmaps/wflow_mgauges.map"
            )  #: Map with locations of rainfall/evap/temp gauge(s). Only needed if the input to the model is not in maps
        self.OutputId = readmap(
            self.Dir +
            "/staticmaps/wflow_subcatch.map")  # location of subcatchment

        self.ZeroMap = 0.0 * scalar(subcatch)  #map with only zero's

        # 3: Input time series ###################################################
        self.Rain_ = self.Dir + "/inmaps/P"  #: timeseries for rainfall
        self.Temp_ = self.Dir + "/inmaps/TEMP"  #: temperature

        # Set static initial values here #########################################

        self.Latitude = ycoordinate(boolean(self.Altitude))
        self.Longitude = xcoordinate(boolean(self.Altitude))

        self.logger.info(
            "Linking parameters to landuse, catchment and soil...")

        #HBV Soil params
        self.CFR = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/CFR.tbl", self.LandUse, subcatch,
            self.Soil, 0.05000
        )  # refreezing efficiency constant in refreezing of freewater in snow
        #self.FoCfmax=self.readtblDefault(self.Dir + "/" + self.intbl + "/FoCfmax.tbl",self.LandUse,subcatch,self.Soil, 0.6000)  # correcton factor for snow melt/refreezing in forested and non-forested areas
        self.Pcorr = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/Pcorr.tbl", self.LandUse, subcatch,
            self.Soil, 1.0)  # correction factor for precipitation
        self.RFCF = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/RFCF.tbl", self.LandUse, subcatch,
            self.Soil, 1.0)  # correction factor for rainfall
        self.SFCF = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/SFCF.tbl", self.LandUse, subcatch,
            self.Soil, 1.0)  # correction factor for snowfall
        self.Cflux = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/Cflux.tbl", self.LandUse, subcatch,
            self.Soil, 2.0
        )  # maximum capillary rise from runoff response routine to soil moisture routine

        # HBV Snow parameters
        # critical temperature for snowmelt and refreezing:  TTI= 1.000
        self.TTI = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/TTI.tbl", self.LandUse, subcatch,
            self.Soil, 1.0)
        # TT = -1.41934 # defines interval in which precipitation falls as rainfall and snowfall
        self.TT = self.readtblDefault(self.Dir + "/" + self.intbl + "/TT.tbl",
                                      self.LandUse, subcatch, self.Soil,
                                      -1.41934)
        #Cfmax = 3.75653 # meltconstant in temperature-index
        self.Cfmax = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/Cfmax.tbl", self.LandUse, subcatch,
            self.Soil, 3.75653)
        # WHC= 0.10000        # fraction of Snowvolume that can store water
        self.WHC = self.readtblDefault(
            self.Dir + "/" + self.intbl + "/WHC.tbl", self.LandUse, subcatch,
            self.Soil, 0.1)

        # Determine real slope and cell length
        sizeinmetres = int(
            configget(self.config, "layout", "sizeinmetres", "0"))
        self.xl, self.yl, self.reallength = pcrut.detRealCellLength(
            self.ZeroMap, sizeinmetres)
        self.Slope = slope(self.Altitude)
        self.Slope = ifthen(
            boolean(self.TopoId),
            max(0.001,
                self.Slope * celllength() / self.reallength))

        # Multiply parameters with a factor (for calibration etc) -P option in command line
        for k, v in multpars.iteritems():
            estr = k + "=" + k + "*" + str(v)
            self.logger.info("Parameter multiplication: " + estr)
            exec estr

        self.SnowWater = self.ZeroMap

        # Initializing of variables
        self.logger.info("Initializing of model variables..")
        self.TopoLdd = lddmask(self.TopoLdd, boolean(self.TopoId))
        catchmentcells = maptotal(scalar(self.TopoId))

        # Used to seperate output per LandUse/management classes
        #OutZones = self.LandUse
        #report(self.reallength,"rl.map")
        #report(catchmentcells,"kk.map")
        self.QMMConv = self.timestepsecs / (
            self.reallength * self.reallength * 0.001)  #m3/s --> mm

        self.sumprecip = self.ZeroMap  #: accumulated rainfall for water balance
        self.sumtemp = self.ZeroMap  #accumulated runoff for water balance

        self.logger.info("Create timeseries outputs...")
        toprinttss = configsection(self.config, 'outputtss')

        for a in toprinttss:
            tssName = self.Dir + "/" + self.runId + "/" + self.config.get(
                "outputtss", a)
            estr = "self." + self.config.get(
                "outputtss", a
            ) + "Tss=wf_TimeoutputTimeseries('" + tssName + "', self, self.OutputId,noHeader=False)"
            self.logger.info("Creating tss output: " + a + "(" +
                             self.config.get('outputtss', a) + ")")
            exec estr

        # Save some summary maps
        self.logger.info("Saving summary maps...")
        report(self.Cfmax, self.Dir + "/" + self.runId + "/outsum/Cfmax.map")
        report(self.TTI, self.Dir + "/" + self.runId + "/outsum/TTI.map")
        report(self.TT, self.Dir + "/" + self.runId + "/outsum/TT.map")
        report(self.WHC, self.Dir + "/" + self.runId + "/outsum/WHC.map")
        report(self.xl, self.Dir + "/" + self.runId + "/outsum/xl.map")
        report(self.yl, self.Dir + "/" + self.runId + "/outsum/yl.map")
        report(self.reallength, self.Dir + "/" + self.runId + "/outsum/rl.map")

        self.SaveDir = self.Dir + "/" + self.runId + "/"
        self.logger.info("Starting Dynamic run...")
示例#3
0
    def initial(self):
        """
    Initial part of the model, executed only once. Is read all static model
    information (parameters) and sets-up the variables used in modelling.

    """
        global statistics
        global multpars

        setglobaloption("unittrue")

        self.thestep = scalar(0)
        self.setQuiet(True)
        self.precipTss = "../intss/P.tss"  #: name of the tss file with precipitation data ("../intss/P.tss")
        self.evapTss = "../intss/PET.tss"  #: name of the tss file with potential evap data ("../intss/PET.tss")
        self.tempTss = "../intss/T.tss"  #: name of the tss file with temperature  data ("../intss/T.tss")
        self.inflowTss = "../intss/Inflow.tss"  #: NOT TESTED name of the tss file with inflow data ("../intss/Inflow.tss")
        self.SeepageTss = "../intss/Seepage.tss"  #: NOT TESTED name of the tss file with seepage data ("../intss/Seepage.tss")"

        self.logger.info("running for " + str(self.nrTimeSteps()) +
                         " timesteps")
        self.setQuiet(True)

        # Set and get defaults from ConfigFile here ###################################
        self.scalarInput = int(
            configget(self.config, "model", "ScalarInput", "0"))
        self.Tslice = int(configget(self.config, "model", "Tslice", "1"))
        self.interpolMethod = configget(self.config, "model",
                                        "InterpolationMethod", "inv")
        self.reinit = int(configget(self.config, "model", "reinit", "0"))
        self.fewsrun = int(configget(self.config, "model", "fewsrun", "0"))
        self.OverWriteInit = int(
            configget(self.config, "model", "OverWriteInit", "0"))
        self.updating = int(configget(self.config, "model", "updating", "0"))
        self.updateFile = configget(self.config, "model", "updateFile",
                                    "no_set")

        self.sCatch = int(configget(self.config, "model", "sCatch", "0"))
        self.intbl = configget(self.config, "model", "intbl", "intbl")
        self.timestepsecs = int(
            configget(self.config, "model", "timestepsecs", "86400"))
        self.P_style = int(configget(self.config, "model", "P_style", "1"))
        self.PET_style = int(configget(self.config, "model", "PET_style", "1"))
        self.TEMP_style = int(
            configget(self.config, "model", "TEMP_style", "1"))
        sizeinmetres = int(
            configget(self.config, "layout", "sizeinmetres", "0"))
        alf = float(configget(self.config, "model", "Alpha", "60"))
        Qmax = float(configget(self.config, "model", "AnnualDischarge", "300"))
        self.UpdMaxDist = float(
            configget(self.config, "model", "UpdMaxDist", "100"))
        self.ExternalQbase = int(
            configget(self.config, 'model', 'ExternalQbase', '0'))

        # 2: Input base maps ########################################################
        subcatch = ordinal(
            readmap(self.Dir + "/staticmaps/wflow_subcatch.map"
                    ))  # Determines the area of calculations (all cells > 0)
        subcatch = ifthen(subcatch > 0, subcatch)
        if self.sCatch > 0:
            subcatch = ifthen(subcatch == sCatch, subcatch)

        self.Altitude = readmap(self.Dir + "/staticmaps/wflow_dem") * scalar(
            defined(subcatch))  #: The digital elevation map (DEM)
        self.TopoLdd = readmap(self.Dir + "/staticmaps/wflow_ldd.map"
                               )  #: The local drinage definition map (ldd)
        self.TopoId = readmap(
            self.Dir + "/staticmaps/wflow_subcatch.map"
        )  #: Map define the area over which the calculations are done (mask)
        River = cover(
            boolean(readmap(self.Dir + "/staticmaps/wflow_river.map")), 0
        )  #: river network map. Fro those cell that belong to a river a specific width is used in the kinematic wave caulations
        self.RiverLength = pcrut.readmapSave(
            self.Dir + "/staticmaps/wflow_riverlength.map", 0.0)
        # Factor to multiply riverlength with (defaults to 1.0)
        self.RiverLengthFac = pcrut.readmapSave(
            self.Dir + "/staticmaps/wflow_riverlength_fact.map", 1.0)

        self.OutputLoc = readmap(self.Dir + "/staticmaps/wflow_gauges.map"
                                 )  #: Map with locations of output gauge(s)
        self.InflowLoc = nominal(
            pcrut.readmapSave(
                self.Dir + "/staticmaps/wflow_inflow.map",
                0.0))  #: Map with location of abstractions/inflows.
        self.SeepageLoc = pcrut.readmapSave(
            self.Dir + "/staticmaps/wflow_inflow.map",
            0.0)  #: Seapage from external model (if configured)

        if self.scalarInput:
            self.gaugesMap = readmap(
                self.Dir + "/staticmaps/wflow_mgauges.map"
            )  #: Map with locations of rainfall/evap/temp gauge(s). Only needed if the input to the model is not in maps
        self.OutputId = readmap(
            self.Dir +
            "/staticmaps/wflow_subcatch.map")  # location of subcatchment

        self.ZeroMap = 0.0 * scalar(subcatch)  #map with only zero's

        # 3: Input time series ###################################################
        self.Rain_ = self.Dir + "/inmaps/P"  #: timeseries for rainfall
        self.PET_ = self.Dir + "/inmaps/PET"  #: potential evapotranspiration
        self.Temp_ = self.Dir + "/inmaps/TEMP"  #: temperature
        self.Inflow_ = self.Dir + "/inmaps/IF"  #: in/outflow locations (abstractions)
        self.Seepage_ = self.Dir + "/inmaps/SE"  #: in/outflow locations (abstractions)

        # Set static initial values here #########################################

        self.Latitude = ycoordinate(boolean(self.Altitude))
        self.Longitude = xcoordinate(boolean(self.Altitude))

        self.logger.info(
            "Linking parameters to landuse, catchment and soil...")

        self.Beta = scalar(0.6)  # For sheetflow

        #self.M=lookupscalar(self.Dir + "/" + modelEnv['intbl'] + "/M.tbl" ,self.LandUse,subcatch,self.Soil) # Decay parameter in Topog_sbm
        self.N = lookupscalar(self.Dir + "/" + self.intbl + "/N.tbl",
                              self.LandUse, subcatch,
                              self.Soil)  # Manning overland flow
        self.NRiver = lookupscalar(self.Dir + "/" + self.intbl +
                                   "/N_River.tbl", self.LandUse, subcatch,
                                   self.Soil)  # Manning river

        # Determine real slope and cell length
        self.xl, self.yl, self.reallength = pcrut.detRealCellLength(
            self.ZeroMap, sizeinmetres)
        self.Slope = slope(self.Altitude)
        self.Slope = ifthen(
            boolean(self.TopoId),
            max(0.001,
                self.Slope * celllength() / self.reallength))
        Terrain_angle = scalar(atan(self.Slope))

        # Multiply parameters with a factor (for calibration etc) -P option in command line
        print multpars
        for k, v in multpars.iteritems():
            estr = k + "=" + k + "*" + str(v)
            self.logger.info("Parameter multiplication: " + estr)
            exec estr

        self.N = ifthenelse(River, self.NRiver, self.N)

        # Determine river width from DEM, upstream area and yearly average discharge
        # Scale yearly average Q at outlet with upstream are to get Q over whole catchment
        # Alf ranges from 5 to > 60. 5 for hardrock. large values for sediments
        # "Noah J. Finnegan et al 2005 Controls on the channel width of rivers:
        # Implications for modeling fluvial incision of bedrock"

        upstr = catchmenttotal(1, self.TopoLdd)
        Qscale = upstr / mapmaximum(upstr) * Qmax
        W = (alf *
             (alf + 2.0)**(0.6666666667))**(0.375) * Qscale**(0.375) * (max(
                 0.0001, windowaverage(
                     self.Slope,
                     celllength() * 4.0)))**(-0.1875) * self.N**(0.375)
        RiverWidth = W

        # Which columns/gauges to use/ignore in kinematic wave updating
        self.UpdateMap = self.ZeroMap

        if self.updating:
            touse = numpy.zeros(gaugear.shape, dtype='int')
            for thecol in updateCols:
                idx = (gaugear == thecol).nonzero()
                touse[idx] = thecol
            self.UpdateMap = numpy2pcr(Nominal, touse, 0.0)
            # Calulate distance to updating points (upstream) annd use to scale the correction
            # ldddist returns zer for cell at the gauges so add 1.0 tp result
            self.DistToUpdPt = cover(
                min(
                    ldddist(self.TopoLdd, boolean(cover(self.UpdateMap, 0)), 1)
                    * self.reallength / celllength(), self.UpdMaxDist),
                self.UpdMaxDist)

        # Initializing of variables
        self.logger.info("Initializing of model variables..")
        self.TopoLdd = lddmask(self.TopoLdd, boolean(self.TopoId))
        catchmentcells = maptotal(scalar(self.TopoId))

        # Used to seperate output per LandUse/management classes
        #OutZones = self.LandUse
        #report(self.reallength,"rl.map")
        #report(catchmentcells,"kk.map")
        self.QMMConv = self.timestepsecs / (
            self.reallength * self.reallength * 0.001)  #m3/s --> mm

        self.sumprecip = self.ZeroMap  #: accumulated rainfall for water balance
        self.sumrunoff = self.ZeroMap  #: accumulated runoff for water balance (weigthted for upstream area)
        self.sumlevel = self.ZeroMap  #: accumulated level for water balance
        self.ForecQ_qmec = self.ZeroMap  # Extra inflow to kinematic wave reservoir for forcing in m^/sec
        self.KinWaveVolume = self.ZeroMap
        self.OldKinWaveVolume = self.ZeroMap
        self.Qvolume = self.ZeroMap
        self.Q = self.ZeroMap
        # cntd

        self.Aspect = scalar(aspect(self.Altitude))  # aspect [deg]
        self.Aspect = ifthenelse(self.Aspect <= 0.0, scalar(0.001),
                                 self.Aspect)
        # On Flat areas the Aspect function fails, fill in with average...
        self.Aspect = ifthenelse(defined(self.Aspect), self.Aspect,
                                 areaaverage(self.Aspect, self.TopoId))

        # Set DCL to riverlength if that is longer that the basic length calculated from grid
        drainlength = detdrainlength(self.TopoLdd, self.xl, self.yl)

        self.DCL = max(drainlength, self.RiverLength)  # m
        # Multiply with Factor (taken from upscaling operation, defaults to 1.0 if no map is supplied
        self.DCL = self.DCL * max(1.0, self.RiverLengthFac)

        # water depth (m)
        # set width for kinematic wave to cell width for all cells
        self.Bw = detdrainwidth(self.TopoLdd, self.xl, self.yl)
        # However, in the main river we have real flow so set the width to the
        # width of the river

        self.Bw = ifthenelse(River, RiverWidth, self.Bw)

        # term for Alpha
        self.AlpTerm = pow((self.N / (sqrt(self.Slope))), self.Beta)
        # power for Alpha
        self.AlpPow = (2.0 / 3.0) * self.Beta
        # initial approximation for Alpha

        # Define timeseries outputs There seems to be a bug and the .tss files are
        # saved in the current dir...
        tssName = os.path.join(self.Dir, "outtss", "exf")
        self.logger.info("Create timeseries outputs...")

        toprinttss = configsection(self.config, 'outputtss')
        for a in toprinttss:
            tssName = self.Dir + "/" + self.runId + "/" + self.config.get(
                "outputtss", a)
            estr = "self." + self.config.get(
                "outputtss", a
            ) + "Tss=wf_TimeoutputTimeseries('" + tssName + "', self, self.OutputId,noHeader=False)"
            self.logger.info("Creating tss output: " + a + "(" +
                             self.config.get('outputtss', a) + ")")
            exec estr

        self.runTss = wf_TimeoutputTimeseries(self.Dir + "/" + self.runId +
                                              "/run",
                                              self,
                                              self.OutputLoc,
                                              noHeader=False)
        self.levTss = wf_TimeoutputTimeseries(self.Dir + "/" + self.runId +
                                              "/lev",
                                              self,
                                              self.OutputLoc,
                                              noHeader=False)

        # Save some summary maps
        self.logger.info("Saving summary maps...")
        report(Terrain_angle,
               self.Dir + "/" + self.runId + "/outsum/angle.map")
        report(self.Slope, self.Dir + "/" + self.runId + "/outsum/slope.map")
        report(self.N, self.Dir + "/" + self.runId + "/outsum/N.map")
        report(self.xl, self.Dir + "/" + self.runId + "/outsum/xl.map")
        report(self.yl, self.Dir + "/" + self.runId + "/outsum/yl.map")
        report(self.reallength, self.Dir + "/" + self.runId + "/outsum/rl.map")
        report(self.DCL, self.Dir + "/" + self.runId + "/outsum/DCL.map")
        report(self.Bw, self.Dir + "/" + self.runId + "/outsum/Bw.map")
        report(ifthen(River, self.Bw),
               self.Dir + "/" + self.runId + "/outsum/RiverWidth.map")
        if self.updating:
            report(self.DistToUpdPt,
                   self.Dir + "/" + self.runId + "/outsum/DistToUpdPt.map")

        self.SaveDir = self.Dir + "/" + self.runId + "/"
        self.logger.info("Starting Dynamic run...")