├── modules ├── __init__.py ├── routing.py ├── groundwater.py ├── dynamic_veg.py ├── inca.py ├── musle.py ├── hspf.py ├── snow.py ├── reservoirs.py ├── dhsvm.py ├── shetran.py ├── lakes.py ├── sediment_transport.py ├── mmf.py └── advanced_routing.py ├── .gitignore ├── resorder.txt ├── utilities ├── timecalc.py ├── pedotransfer.py ├── reporting.py └── netcdf2PCraster.py ├── hargreaves.py ├── ET.py ├── subzone.py ├── README.md ├── rootzone.py ├── reporting.csv └── LICENSE.TXT /modules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.pyo -------------------------------------------------------------------------------- /resorder.txt: -------------------------------------------------------------------------------- 1 | order steps 2 | 1 0 3 | 2 0 4 | 3 0 5 | 6 0 6 | 9 0 7 | 10 0 8 | 11 0 9 | 13 0 10 | 14 0 11 | 15 0 12 | 16 0 13 | 17 0 14 | 20 0 15 | 22 0 16 | 24 0 17 | 25 0 18 | 26 0 19 | 27 0 20 | 28 0 21 | 30 0 22 | 32 0 23 | 33 0 24 | 4 1 25 | 5 1 26 | 8 1 27 | 18 1 28 | 29 1 29 | 31 1 30 | 7 2 31 | 19 2 32 | 12 3 33 | 21 3 34 | 23 4 35 | 34 5 36 | -------------------------------------------------------------------------------- /utilities/timecalc.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2019 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, W. Immerzeel, S. Khanal, A. Lutz, G. Simons, W. Terink 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | #-Function to return the julian day of the year 24 | def julian(self): 25 | y= self.curdate.year 26 | start= self.datetime.datetime(y,1,1).toordinal() 27 | current= self.curdate.toordinal() 28 | day= current-start+1 29 | return day, 1 30 | 31 | #-Function to calculate the number of timesteps for the model run 32 | def timesteps(self): 33 | nrTimeSteps = (self.enddate - self.startdate).days + 1 34 | print('Running SPHY for '+str(self.startdate.day)+'-'+str(self.startdate.month)+'-'+str(self.startdate.year)+' through '+str(self.enddate.day)+'-'+str(self.enddate.month)+'-'+str(self.enddate.year)) 35 | print('with '+str(nrTimeSteps)+' daily timesteps') 36 | return nrTimeSteps -------------------------------------------------------------------------------- /hargreaves.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | # -Extraterrestrial radiation 24 | def extrarad(self, pcr): 25 | DayNo = self.timecalc.julian(self)[0] 26 | LatRad = self.Lat * (self.pi / 180) 27 | dr = 1 + 0.033 * pcr.cos((2 * self.pi * DayNo) / 365) 28 | delta = 0.409 * pcr.sin(((2 * self.pi * DayNo) / 365) - 1.39) 29 | omegas = pcr.acos(-1 * pcr.tan(LatRad) * pcr.tan(delta)) 30 | Ra = ( 31 | ((24 * 60) / self.pi) 32 | * self.Gsc 33 | * dr 34 | * ( 35 | pcr.scalar(omegas) * pcr.sin(LatRad) * pcr.sin(delta) 36 | + pcr.cos(LatRad) * pcr.cos(delta) * pcr.sin(omegas) 37 | ) 38 | ) 39 | return Ra 40 | 41 | 42 | # -Modified Hargreaves for calculation of ETref 43 | def Hargreaves(pcr, ra, temp, tempmax, tempmin): 44 | ETref = pcr.max( 45 | 0.0023 * 0.408 * ra * (temp + 17.8) * (pcr.max(tempmax - tempmin, 0)) ** 0.5, 0 46 | ) 47 | return ETref 48 | -------------------------------------------------------------------------------- /ET.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | # -Function to calculate the potential evapotranspiration 24 | def ETpot(etr, kc): 25 | etpot = etr * kc 26 | return etpot 27 | 28 | 29 | # -Function to calculate the actual evapotranspiration 30 | def ETact(pcr, etpot, rootwater, rootsat, etreddry, rainfrac): 31 | etredwet = pcr.ifthenelse(rootwater >= rootsat, pcr.scalar(0), 1) 32 | etact = pcr.ifthenelse( 33 | rainfrac > 0, pcr.min(etpot * etreddry * etredwet, rootwater), 0 34 | ) 35 | return etact 36 | 37 | 38 | # -Determine plant water stress for calculation of actual evapotranspiration 39 | def ks(self, pcr, etpot): 40 | TAW = self.RootField - self.RootDry 41 | p = pcr.max(pcr.min(self.PMap + 0.04 * (5 - etpot), 0.8), 0.1) 42 | RAW = TAW * p 43 | RootPWS = self.RootField - RAW 44 | Ks = pcr.max( 45 | pcr.min((self.RootWater - self.RootDry) / (RootPWS - self.RootDry), 1), 0 46 | ) 47 | return Ks 48 | -------------------------------------------------------------------------------- /subzone.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | # -Function to calculate capillary rise 24 | def CapilRise(pcr, subfield, subwater, capmax, rootwater, rootsat, rootfield): 25 | subrelwat = pcr.max(pcr.min((subwater / subfield), 1), 0) 26 | rootrelwat = pcr.max(pcr.min((rootwater / rootfield), 1), 0) 27 | caprise = pcr.min(subwater, capmax * (1 - rootrelwat) * subrelwat) 28 | caprise = pcr.min( 29 | caprise, rootsat - rootwater 30 | ) # adding caprise can not exceed saturated rootwater content 31 | return caprise 32 | 33 | 34 | # -Function to calculate percolation from subsoil (only if groundwater module is used) 35 | def SubPercolation(pcr, subwater, subfield, subTT, gw, gwsat): 36 | subperc = pcr.ifthenelse( 37 | (gw < gwsat) & ((subwater - subfield) > 0), 38 | (subwater - subfield) * (1 - pcr.exp(-1 / subTT)), 39 | 0, 40 | ) 41 | return subperc 42 | 43 | 44 | # -Function to calculate drainage from subsoil (only if groundwater module is NOT used) 45 | def SubDrainage(pcr, subwater, subfield, subsat, drainvel, subdrainage, subTT): 46 | subexcess = pcr.max(subwater - subfield, 0) 47 | subexcessfrac = subexcess / (subsat - subfield) 48 | sublateral = subexcessfrac * drainvel 49 | subdrainage = (sublateral + subdrainage) * (1 - pcr.exp(-1 / subTT)) 50 | subdrainage = pcr.max(pcr.min(subdrainage, subwater), 0) 51 | return subdrainage 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spatial Processes in HYdrology (SPHY) model 2 | Version 3.1 3 | 4 | The Spatial Processes in Hydrology (SPHY) model is a hydrological modeling tool suitable for a wide range of water resource management applications. SPHY is a state-of-the-art, easy to use, robust tool, that can be applied for operational as well as strategic decision support. The SPHY model has been applied and tested in various studies ranging from real-time soil moisture predictions in flat lands, to operational reservoir inflow forecasting applications in mountainous catchments, irrigation scenarios in the Nile Basin, and detailed climate change impact studies in the snow- and glacier-melt dominated the Himalayan region. 5 | 6 | With respect to version 3.0, the code in version 3.1 has an improved procedure for bias-correcting meteorological forcing and increased flexibility for defining simulation periods. 7 | 8 | Journal paper SPHY v2.0 9 | 14 | 15 | Acknowledgements
16 | The development and publication of the SPHY model source code, its binaries, GUIs, and case-studies has been supported through various (research) projects that were partly or completely funded by the following organizations: 17 |
    18 |
  • International Centre for Integrated Mountain Development (ICIMOD)
  • 19 |
  • European Space Agency (ESA)
  • 20 |
  • Asian Development Bank (ADB)
  • 21 |
  • World Bank
  • 22 |
  • Rijksdienst voor Ondernemend Nederland (RVO)
  • 23 |
  • NUFFIC
  • 24 |
25 | We are very grateful to these organizations that made the development of the SPHY model possible. 26 | We hope to continue to collaborate with these organizations in the future in order to further develop and improve the SPHY model and its interfaces. 27 | 28 |
Copyright
29 | Copyright (C) 2013-2025 FutureWater. The Spatial Processes in HYdrology (SPHY) model is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. 30 | 31 | Contact: 32 | sphy@futurewater.nl 33 | -------------------------------------------------------------------------------- /rootzone.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | # -Function to calculate surface runoff 24 | def RootRunoff(self, pcr, rainfrac, rain): 25 | # -Infiltration excess surface runoff 26 | if self.InfilFLAG == 1: 27 | # -Infiltration capacity, scaled based on rootwater content and ksat and corrected for paved surface 28 | Infil_cap = ( 29 | self.K_eff 30 | * self.RootKsat 31 | / 24 32 | * (1 + ((self.RootSat - self.RootWater) / self.RootSat)) ** self.Labda_Infil 33 | ) 34 | 35 | # -Infiltration 36 | Infil_excess = pcr.ifthenelse( 37 | (self.Alpha * rain) > Infil_cap, 38 | rain - ((self.Alpha * rain - Infil_cap) ** 2) / (self.Alpha**2 * rain), 39 | rain, 40 | ) 41 | Saturated_excess = self.RootSat - self.RootWater 42 | Infil = pcr.max(0, pcr.min(Infil_excess, Saturated_excess)) * ( 43 | 1 - self.pavedFrac 44 | ) 45 | 46 | # -Surface runoff 47 | rootrunoff = rain - Infil 48 | 49 | # -Saturation excess surface runoff 50 | else: 51 | # -Assume infiltration capacity to be equal to saturated hydraulic conductivity 52 | Infil_cap = self.RootKsat 53 | 54 | # -Infiltration 55 | Infil = pcr.max(0, pcr.min(rain, Infil_cap, self.RootSat - self.RootWater)) 56 | # -Runoff 57 | rootrunoff = pcr.ifthenelse(rainfrac > 0, rain - Infil, 0) 58 | 59 | return rootrunoff, Infil 60 | 61 | 62 | # -Function to calculate rootzone drainage 63 | def RootDrainage(pcr, rootwater, rootdrain, rootfield, rootsat, drainvel, rootTT): 64 | rootexcess = pcr.max(rootwater - rootfield, 0) 65 | rootexcessfrac = rootexcess / (rootsat - rootfield) 66 | rootlat = rootexcessfrac * drainvel 67 | rootdrainage = pcr.max( 68 | pcr.min( 69 | rootexcess, 70 | rootlat * (1 - pcr.exp(-1 / rootTT)) + rootdrain * pcr.exp(-1 / rootTT), 71 | ), 72 | 0, 73 | ) 74 | return rootdrainage 75 | 76 | 77 | # -Function to calculate rootzone percolation 78 | def RootPercolation(pcr, rootwater, subwater, rootfield, rootTT, subsat): 79 | rootexcess = pcr.max(rootwater - rootfield, 0) 80 | rootperc = rootexcess * (1 - pcr.exp(-1 / rootTT)) 81 | rootperc = pcr.ifthenelse( 82 | subwater >= subsat, 0, pcr.min(subsat - subwater, rootperc) 83 | ) 84 | rootperc = pcr.max(pcr.min(rootperc, rootexcess), 0) 85 | return rootperc 86 | 87 | 88 | # -Function to calculate the right fraction between the two fluxes 89 | def CalcFrac(pcr, rootwater, rootfield, rootdrain, rootperc): 90 | rootexcess = pcr.max(rootwater - rootfield, 0) 91 | frac = ((rootdrain + rootperc) - rootexcess) / (rootdrain + rootperc) 92 | rootdrain = rootdrain - (rootdrain * frac) 93 | rootperc = rootperc - (rootperc * frac) 94 | return rootdrain, rootperc 95 | -------------------------------------------------------------------------------- /reporting.csv: -------------------------------------------------------------------------------- 1 | name,map,avg,timeseries,filename,comment 2 | wbal,NONE,NONE,NONE,wbal,WATER BALANCE (Can only select daily output) 3 | # ONLY FOR LAKE AND/OR RESERVOIR MODULE,,,,, 4 | TotStor,NONE,NONE,NONE,TotS,REPORT TOTAL STORAGE (only D or F options are logical) 5 | RainStor,NONE,NONE,NONE,RainS,REPORT STORAGE FROM RAINFALL (only D or F options are logical) 6 | SnowStor,NONE,NONE,NONE,SnowS,REPORT STORAGE FROM SNOW RUNOFF (only D or F options are logical) 7 | GlacStor,NONE,NONE,NONE,GlacS,REPORT STORAGE FROM GLACIER RUNOFF (only D or F options are logical) 8 | BaseStor,NONE,NONE,NONE,BaseS,REPORT STORAGE FROM BASEFLOW RUNOFF (only D or F options are logical) 9 | # FLUXES IN MM,,,,, 10 | TotPrec,M,NONE,NONE,Prec,PREC 11 | TotPrecF,NONE,NONE,NONE,PrecF,PREC; CORRECTED FOR FRACTION 12 | TotPrecEF,NONE,NONE,NONE,PrecEF,EFFECTIVE PRECIPITATION; CORRECTED FOR FRACTION 13 | LAI,NONE,NONE,NONE,LAI,LEAF AREA INDEX 14 | TotIntF,NONE,NONE,NONE,IntF,INTERCEPTION; CORRECTED FOR FRACTION 15 | TotRain,NONE,NONE,NONE,Rain,RAIN 16 | TotRainF,NONE,NONE,NONE,RainF,RAIN; CORRECTED FOR FRACTION 17 | TotETref,M,NONE,NONE,ETr,ETREF 18 | TotETrefF,NONE,NONE,NONE,ETrF,ETREF; CORRECTED FOR FRACTION 19 | TotETpot,NONE,NONE,NONE,ETp,ETPOT 20 | TotETpotF,NONE,NONE,NONE,ETpF,ETPOT; CORRECTED FOR FRACTION 21 | TotETact,Y,NONE,NONE,ETa,ETACT 22 | TotETactF,NONE,NONE,NONE,ETaF,ETACT; CORRECTED FOR FRACTION 23 | PlantStress,NONE,MA,NONE,Pws,PLANT WATER STRESS 24 | TotSnow,NONE,NONE,NONE,Snow,SNOWFALL 25 | TotSnowF,NONE,NONE,NONE,SnowF,SNOWFALL; CORRECTED FOR FRACTION 26 | TotSnowMelt,NONE,NONE,NONE,SMel,SNOWMELT 27 | TotSnowMeltF,NONE,NONE,NONE,SMelF,SNOWMELT; CORRECTED FOR FRACTION 28 | TotGlacMelt,NONE,NONE,NONE,Gmel,GLACIER MELT 29 | TotGlacMeltF,NONE,NONE,NONE,GMelF,GLACIER MELT; CORRECTED FOR FRACTION 30 | Infil,NONE,NONE,NONE,Infil,INFILTRATION 31 | TotRootRF,M,NONE,NONE,Rootr,ROOTZONE RUNOFF; CORRECTED FOR FRACTION 32 | TotRootDF,M,NONE,NONE,Rootd,ROOTZONE DRAINAGE; CORRECTED FOR FRACTION 33 | TotRootPF,NONE,NONE,NONE,Rootp,ROOTZONE PERCOLATION; CORRECTED FOR FRACTION 34 | TotSubDF,NONE,NONE,NONE,Subd,SUBZONE DRAINAGE; CORRECTED FOR FRACTION 35 | TotSubPF,NONE,NONE,NONE,Subp,SUBZONE PERCOLATION; CORRECTED FOR FRACTION 36 | TotCapRF,NONE,NONE,NONE,Capr,CAPILARY RISE; CORRECTED FOR FRACTION 37 | TotSeepF,NONE,NONE,NONE,Seep,SEEPAGE; CORRECTED FOR FRACTION 38 | TotGlacPercF,NONE,NONE,NONE,Glacp,GLACIER PERCOLATION; CORRECTED FOR FRACTION 39 | TotGwRechargeF,M,NONE,NONE,Gwre,GROUNDWATER RECHARGE; CORRECTED FOR FRACTION 40 | GWL,NONE,NONE,NONE,Gwl,GROUNDWATER LEVEL in m below surface (Can only select daily output) 41 | TotRainRF,NONE,NONE,NONE,Rainr,RAIN RUNOFF; CORRECTED FOR FRACTION 42 | TotSnowRF,NONE,NONE,NONE,Snowr,SNOW RUNOFF; CORRECTED FOR FRACTION 43 | TotGlacRF,NONE,NONE,NONE,Glacr,GLACIER RUNOFF; CORRECTED FOR FRACTION 44 | TotBaseRF,NONE,NONE,NONE,Baser,BASEFLOW RUNOFF; CORRECTED FOR FRACTION 45 | TotRF,M,NONE,NONE,Totr,TOTAL RUNOFF OF ALL FRACTIONS 46 | # STORAGE IN CANOPY AND SOIL LAYERS,,,,, 47 | StorCanop,NONE,Y,NONE,Canop,CANOPY STORAGE 48 | StorSnow,NONE,Y,NONE,SnowS,SNOW STORAGE 49 | StorRootW,NONE,Y,NONE,Rootw,ROOTZONE STORAGE 50 | StorSubW,NONE,Y,NONE,Subw,SUBSOIL STORAGE 51 | StorGroundW,NONE,Y,NONE,GrndW,GROUNDWATER STORAGE 52 | # ROUTED STREAMFLOW FLUXES IN M3/S (only D or F options are logical) ,,,,, 53 | SubSurfRAtot,NONE,NONE,NONE,SSTot,ROUTED SUBSURFACE RUNOFF 54 | RootRRAtot,NONE,NONE,NONE,RRTot,ROUTED ROOT SURFACE RUNOFF 55 | RootDRAtot,NONE,NONE,NONE,RDTot,ROUTED ROOT DRAINAGE RUNOFF 56 | RainRAtot,NONE,NONE,NONE,RTot,ROUTED RAIN RUNOFF 57 | SnowRAtot,NONE,NONE,NONE,STot,ROUTED SNOW RUNOFF 58 | GlacRAtot,NONE,NONE,NONE,GTot,ROUTED GLACIER RUNOFF 59 | BaseRAtot,NONE,NONE,NONE,BTot,ROUTED BASEFLOW RUNOFF 60 | QallRAtot,NONE,NONE,D,QAll,ROUTED TOTAL RUNOFF 61 | # SEDIMENT YIELD,,,,, 62 | DetRn,NONE,NONE,NONE,DetRn,DETACHMENT BY RAIN in metric tons per cell area 63 | DetRun,NONE,NONE,NONE,DetRun,DETACHMENT BY RUNOFF in metric tons per cell area 64 | SDepFld,NONE,NONE,NONE,SDpFld,IN FIELD SEDIMENT DEPOSITION in metric tons per cell area 65 | SedTrans,NONE,NONE,NONE,STrans,SEDIMENT TRANSPORTED in metric tons per cell area 66 | SedDep,NONE,NONE,NONE,Sdep,SEDIMENT DEPOSITION in metric tons per cell area 67 | SedYld,NONE,NONE,NONE,SdYld,SEDIMENT YIELD AT STATIONS in metric tons 68 | SedFlux,NONE,NONE,NONE,SdFlux,SEDIMENT FLUX AT STATIONS in metric tons 69 | TC,NONE,NONE,NONE,TC,TRANSPORT CAPACITY in metric tons 70 | -------------------------------------------------------------------------------- /modules/routing.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | print("routing module imported") 23 | 24 | 25 | def ROUT(pcr, q, oldq, flowdir, kx): 26 | rr = (q * 0.001 * pcr.cellarea()) / (24 * 3600) 27 | ra = pcr.accuflux(flowdir, rr) 28 | ra = (1 - kx) * ra + kx * oldq 29 | return ra 30 | 31 | 32 | # -init routing processes 33 | def init(self, pcr, config): 34 | self.FlowDir = pcr.readmap(self.inpath + config.get("ROUTING", "flowdir")) 35 | try: 36 | self.kx = pcr.readmap(self.inpath + config.get("ROUTING", "kx")) 37 | except: 38 | self.kx = config.getfloat("ROUTING", "kx") 39 | 40 | 41 | # -initial conditions routing 42 | def initial(self, pcr, config): 43 | # -initial routed total runoff 44 | try: 45 | self.QRAold = config.getfloat("ROUT_INIT", "QRA_init") 46 | except: 47 | try: 48 | self.QRAold = pcr.readmap(self.inpath + config.get("ROUT_INIT", "QRA_init")) 49 | except: 50 | self.QRAold = 0 51 | # -initial routed runoff for the individual components 52 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 53 | for i in pars: 54 | try: 55 | setattr( 56 | self, 57 | i + "RAold", 58 | pcr.readmap(self.inpath + config.get("ROUT_INIT", i + "RA_init")), 59 | ) 60 | setattr(self, i + "RA_FLAG", True) 61 | except: 62 | try: 63 | setattr(self, i + "RAold", config.getfloat("ROUT_INIT", i + "RA_init")) 64 | setattr(self, i + "RA_FLAG", True) 65 | except: 66 | setattr(self, i + "RA_FLAG", False) 67 | 68 | 69 | # -dynamic routing processes 70 | def dynamic(self, pcr, TotR): 71 | # -Rout total runoff 72 | Q = self.routing.ROUT(pcr, TotR, self.QRAold, self.FlowDir, self.kx) 73 | self.QRAold = Q 74 | self.reporting.reporting(self, pcr, "QallRAtot", Q) 75 | if self.mm_rep_FLAG == 1 and self.QTOT_mm_FLAG == 1: 76 | self.QTOTSubBasinTSS.sample( 77 | ((Q * 3600 * 24) / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir)) * 1000 78 | ) 79 | 80 | # -Routing of surface runoff, root drainage, rain, snow, glacier and baseflow 81 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 82 | for i in pars: 83 | if getattr(self, i + "RA_FLAG") == 1: 84 | try: 85 | ParsRA = self.routing.ROUT( 86 | pcr, 87 | getattr(self, i + "R"), 88 | getattr(self, i + "RAold"), 89 | self.FlowDir, 90 | self.kx, 91 | ) 92 | except: 93 | ParsRA = self.routing.ROUT( 94 | pcr, 95 | eval(i + "R"), 96 | getattr(self, i + "RAold"), 97 | self.FlowDir, 98 | self.kx, 99 | ) 100 | setattr(self, i + "RAold", ParsRA) 101 | self.reporting.reporting(self, pcr, i + "RAtot", ParsRA) 102 | if ( 103 | self.mm_rep_FLAG == 1 104 | and getattr(self, "Q" + i.upper() + "_mm_FLAG") == 1 105 | ): 106 | setattr( 107 | self, 108 | "Q" + i.upper() + "SubBasinTSS.sample", 109 | ( 110 | (ParsRA * 3600 * 24) 111 | / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir) 112 | ) 113 | * 1000, 114 | ) 115 | 116 | return Q 117 | -------------------------------------------------------------------------------- /modules/groundwater.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | print("groundwater module imported") 23 | 24 | 25 | # -Function to calculate groundwater recharge 26 | def GroundWaterRecharge(pcr, deltagw, gwrecharge, subperc, glacperc): 27 | gwseep = (1 - pcr.exp(-1 / deltagw)) * (subperc + glacperc) 28 | gwrecharge = (pcr.exp(-1 / deltagw) * gwrecharge) + gwseep 29 | return gwrecharge 30 | 31 | 32 | # -Function to calculate baseflow 33 | def BaseFlow(pcr, gw, baser, gwrecharge, basethresh, alphagw): 34 | baser = pcr.ifthenelse( 35 | gw <= basethresh, 36 | 0, 37 | (baser * pcr.exp(-alphagw) + gwrecharge * (1 - pcr.exp(-alphagw))), 38 | ) 39 | return baser 40 | 41 | 42 | # -Function to calculate the groundwater height, taken from the bottom of the gw layer (zero reference) 43 | def HLevel(pcr, Hgw, alphagw, gwrecharge, yield_gw): 44 | Hgw = (Hgw * pcr.exp(-alphagw)) + ( 45 | (gwrecharge * (1 - pcr.exp(-alphagw))) / (800 * yield_gw * alphagw) 46 | ) 47 | return Hgw 48 | 49 | 50 | # -init groundwater processes 51 | def init(self, pcr, config): 52 | pars = ["GwDepth", "GwSat", "deltaGw", "BaseThresh", "alphaGw", "YieldGw"] 53 | for i in pars: 54 | try: 55 | setattr(self, i, pcr.readmap(self.inpath + config.get("GROUNDW_PARS", i))) 56 | except: 57 | setattr(self, i, config.getfloat("GROUNDW_PARS", i)) 58 | 59 | 60 | # -initial conditions groundwater 61 | def initial(self, pcr, config): 62 | # -initial groundwater recharge 63 | try: 64 | self.GwRecharge = config.getfloat("GROUNDW_INIT", "GwRecharge") 65 | except: 66 | self.GwRecharge = pcr.readmap( 67 | self.inpath + config.get("GROUNDW_INIT", "GwRecharge") 68 | ) 69 | # -initial baseflow 70 | try: 71 | self.BaseR = config.getfloat("GROUNDW_INIT", "BaseR") 72 | except: 73 | self.BaseR = pcr.readmap(self.inpath + config.get("GROUNDW_INIT", "BaseR")) 74 | # -initial groundwater storage 75 | try: 76 | self.Gw = config.getfloat("GROUNDW_INIT", "Gw") 77 | except: 78 | self.Gw = pcr.readmap(self.inpath + config.get("GROUNDW_INIT", "Gw")) 79 | # -initial groundwater level 80 | try: 81 | self.H_gw = config.getfloat("GROUNDW_INIT", "H_gw") 82 | except: 83 | self.H_gw = pcr.readmap(self.inpath + config.get("GROUNDW_INIT", "H_gw")) 84 | self.H_gw = pcr.max( 85 | (self.RootDepthFlat + self.SubDepthFlat + self.GwDepth) / 1000 - self.H_gw, 0 86 | ) 87 | 88 | 89 | # -dynamic groundwater processes 90 | def dynamic(self, pcr, ActSubPerc, GlacPerc): 91 | # GwOld = self.Gw 92 | # -Groundwater recharge 93 | self.GwRecharge = self.groundwater.GroundWaterRecharge( 94 | pcr, self.deltaGw, self.GwRecharge, ActSubPerc, GlacPerc 95 | ) 96 | # -Report groundwater recharge 97 | self.reporting.reporting(self, pcr, "TotGwRechargeF", self.GwRecharge) 98 | # -Update groundwater storage 99 | self.Gw = self.Gw + self.GwRecharge 100 | # -Baseflow 101 | self.BaseR = self.groundwater.BaseFlow( 102 | pcr, self.Gw, self.BaseR, self.GwRecharge, self.BaseThresh, self.alphaGw 103 | ) 104 | # -Update groundwater storage 105 | self.Gw = self.Gw - self.BaseR 106 | # -Report groundwater storage 107 | self.reporting.reporting( 108 | self, pcr, "StorGroundW", self.Gw * (1 - self.openWaterFrac) 109 | ) 110 | # -Correct for open-water fraction 111 | self.BaseR = self.BaseR * (1 - self.openWaterFrac) 112 | # -Report Baseflow 113 | self.reporting.reporting(self, pcr, "TotBaseRF", self.BaseR) 114 | # -Calculate groundwater level 115 | self.H_gw = self.groundwater.HLevel( 116 | pcr, self.H_gw, self.alphaGw, self.GwRecharge, self.YieldGw 117 | ) 118 | # -Report groundwater level 119 | self.reporting.reporting( 120 | self, 121 | pcr, 122 | "GWL", 123 | ((self.SubDepthFlat + self.RootDepthFlat + self.GwDepth) / 1000 - self.H_gw) 124 | * -1, 125 | ) 126 | -------------------------------------------------------------------------------- /modules/dynamic_veg.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | print("dynamic vegetation module imported") 23 | 24 | 25 | # -Function that returns crop factor (Kc) and maximum storage (Smax) 26 | def Veg_function( 27 | pcr, ndvi, fpar_max, fpar_min, lai_max, ndvi_min, ndvi_max, kc_min, kc_max 28 | ): 29 | SR = (1 + ndvi) / (1 - ndvi) 30 | SR_max = (1 + ndvi_max) / (1 - ndvi_max) 31 | SR_min = (1 + ndvi_min) / (1 - ndvi_min) 32 | FPAR = pcr.min((SR - SR_min) / (SR_max - SR_min) * (fpar_max - fpar_min), 0.95) 33 | LAI = lai_max * pcr.log10(1 - FPAR) / pcr.log10(1 - fpar_max) 34 | Smax = 0.935 + 0.498 * LAI - 0.00575 * (LAI**2) 35 | Kc = kc_min + (kc_max - kc_min) * pcr.max( 36 | pcr.min((ndvi - ndvi_min) / (ndvi_max - ndvi_min), 1), 0 37 | ) 38 | return Kc, Smax, LAI 39 | 40 | 41 | # -Function that returns the interception, precipitation throughfall, and remaining storage 42 | def Inter_function(pcr, S, Smax, Etr): 43 | PreT = pcr.max(0, S - Smax) 44 | S = S - PreT 45 | Int = pcr.min(1.5 * Etr, S) 46 | S = S - Int 47 | return Int, PreT, S 48 | 49 | 50 | # -init processes dynamic vegetation 51 | def init(self, pcr, config): 52 | # -set the ndvi map series to be read 53 | self.ndvi = self.inpath + config.get("DYNVEG", "NDVI") 54 | # -read the vegetation parameters 55 | LAImax_table = self.inpath + config.get("DYNVEG", "LAImax") 56 | self.LAImax = pcr.lookupscalar(LAImax_table, self.LandUse) 57 | pars = ["NDVImax", "NDVImin", "NDVIbase", "KCmax", "KCmin", "FPARmax", "FPARmin"] 58 | for i in pars: 59 | try: 60 | setattr(self, i, pcr.readmap(self.inpath + config.get("DYNVEG", i))) 61 | except: 62 | setattr(self, i, config.getfloat("DYNVEG", i)) 63 | 64 | 65 | # -initial conditions dynamic vegetation 66 | def initial(self, pcr): 67 | # -initial canopy storage 68 | self.Scanopy = 0 69 | # -initial ndvi if first map is not provided 70 | self.ndviOld = pcr.scalar((self.NDVImax + self.NDVImin) / 2) 71 | # -set initial kc value to one, if kc map is not available for first timestep 72 | self.KcOld = pcr.scalar(1) 73 | 74 | 75 | # -dynamic processes dynamic vegetation 76 | def dynamic(self, pcr, pcrm, np, Precip, ETref): 77 | # -try to read the ndvi map series. If not available, then use ndvi old 78 | try: 79 | ndvi = pcr.readmap(pcrm.generateNameT(self.ndvi, self.counter)) 80 | except: 81 | ndvi = self.ndviOld 82 | self.ndviOld = ndvi 83 | # -fill missing ndvi values with average 84 | ndviAvg = np.nanmean(pcr.pcr2numpy(ndvi, np.nan)) 85 | ndvi = pcr.cover(ndvi, float(ndviAvg)) 86 | # -set maximum value to 0.999 87 | ndvi = pcr.min(ndvi, 0.999) 88 | 89 | # -calculate the vegetation parameters 90 | vegoutput = self.dynamic_veg.Veg_function( 91 | pcr, 92 | ndvi, 93 | self.FPARmax, 94 | self.FPARmin, 95 | self.LAImax, 96 | self.NDVImin, 97 | self.NDVImax, 98 | self.KCmin, 99 | self.KCmax, 100 | ) 101 | # -Kc 102 | self.Kc = vegoutput[0] 103 | # -LAI 104 | self.LAI = vegoutput[2] 105 | # -report leaf area index 106 | self.reporting.reporting(self, pcr, "LAI", self.LAI) 107 | 108 | # -Update canopy storage 109 | self.Scanopy = self.Scanopy + Precip 110 | # -interception and effective precipitation 111 | intercep = self.dynamic_veg.Inter_function(pcr, self.Scanopy, vegoutput[1], ETref) 112 | # -interception 113 | Int = intercep[0] 114 | Int = Int * (1 - self.openWaterFrac) 115 | # -report interception corrected for fraction 116 | self.reporting.reporting(self, pcr, "TotIntF", Int * (1 - self.GlacFrac)) 117 | # -effective precipitation 118 | Precip = intercep[1] 119 | # -Report effective precipitation corrected for fraction 120 | self.reporting.reporting(self, pcr, "TotPrecEF", Precip * (1 - self.GlacFrac)) 121 | # -canopy storage 122 | self.Scanopy = intercep[2] 123 | # -Report effective precipitation corrected for fraction 124 | self.reporting.reporting( 125 | self, pcr, "StorCanop", self.Scanopy * (1 - self.openWaterFrac) 126 | ) 127 | 128 | return Precip 129 | -------------------------------------------------------------------------------- /modules/inca.py: -------------------------------------------------------------------------------- 1 | # Soil erosion module using the INCA soil erosion model 2 | # Copyright (C) 2020 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | 19 | print('INCA module imported') 20 | 21 | #-Detachment of soil particles by raindrop impact (kg/km2) 22 | def DetachmentRaindrop(self, pcr, c_X1, p_Sed, E_SP, V, CG): 23 | p = p_Sed / (24 * 60 * 60) * 1e-3 24 | S_SP = pcr.max(0, 1 - CG - self.NoErosion_INCA) * c_X1 * p * E_SP**(10 / (10 - V)) * 8.64 * 1e10 25 | return S_SP 26 | 27 | #-Detachment of soil particles by runoff (kg/km2) 28 | def DetachmentRunoff(self, pcr, q_dr, S_SP, S_TC, E_FL, a1, a2, a3, CG, A, L): 29 | K = a1 * E_FL * 86400 * ((A * q_dr) / L - a2)**a3 30 | S_FL = pcr.max(0, pcr.ifthenelse(S_TC + K == 0, 0, K * (S_TC - S_SP) / (S_TC + K)) * pcr.max(0, 1 - self.NoErosion_INCA)) 31 | 32 | #-set values in channels to 0 in case channels should be excluded 33 | if self.exclChannelsFLAG == 1: 34 | S_FL = S_FL * self.Hillslope 35 | return S_FL, K 36 | 37 | #-Transport capacity of the flow (kg/km2) 38 | def TransportCapacity(self, pcr, q_dr, a4, a5, a6, A, L): 39 | S_TC = a4 * 86400 * ((A * q_dr) / L - a5)**a6 40 | return S_TC 41 | 42 | #-Update sediment store (kg/km2) 43 | def UpdateSedimentStore(self, pcr, S_SP, S_FL, S_TC, K): 44 | if self.exclChannelsFLAG == 1: 45 | dStore_dt = pcr.ifthenelse(self.Hillslope == 1, -K * (S_SP - S_TC) / (S_TC + K), S_SP) 46 | else: 47 | dStore_dt = -K * (S_SP - S_TC) / (S_TC + K) 48 | dStore_dt = pcr.ifthenelse(S_TC + K == 0, 0, dStore_dt) 49 | 50 | S_store = pcr.max(0, self.S_store + pcr.ifthenelse(self.S_store + S_SP > S_TC, S_SP - S_TC, dStore_dt)) 51 | return S_store 52 | 53 | #-Mass of sediment transported (kg/km2) 54 | def sedimentTransported(self, pcr, S_SP, S_FL, S_TC): 55 | M_Out = pcr.ifthenelse(self.S_store + S_SP > S_TC, S_TC, S_SP + S_FL) * pcr.max(0, 1 - self.NoErosion_INCA) 56 | return M_Out 57 | 58 | #-init processes inca 59 | def init(self, pcr, config): 60 | #-read table with INCA landuse specific model parameters 61 | pcr.setglobaloption('matrixtable') 62 | inca_table = self.inpath + config.get('INCA', 'inca_table') 63 | self.V_INCA = pcr.lookupscalar(inca_table, 1, self.LandUse) 64 | self.GC_INCA = pcr.lookupscalar(inca_table, 2, self.LandUse) 65 | try: 66 | self.a4_INCA = config.getfloat('INCA', 'a4') 67 | except: 68 | self.a4_INCA = pcr.lookupscalar(inca_table, 3, self.LandUse) 69 | self.NoErosion_INCA = pcr.lookupscalar(inca_table, 4, self.LandUse) 70 | pcr.setglobaloption('columntable') 71 | 72 | #-read other model parameters 73 | self.c_x1_INCA = config.getfloat('INCA', 'c_x1') 74 | self.a1_INCA = config.getfloat('INCA', 'a1') 75 | self.a2_INCA = config.getfloat('INCA', 'a2') 76 | self.a3_INCA = config.getfloat('INCA', 'a3') 77 | self.a5_INCA = config.getfloat('INCA', 'a5') 78 | self.a6_INCA = config.getfloat('INCA', 'a6') 79 | self.E_SP_INCA = config.getfloat('INCA', 'E_SP') 80 | self.E_FL_INCA = config.getfloat('INCA', 'E_FL') 81 | 82 | #-Determine cell size and slope length 83 | self.A_INCA = pcr.cellarea() * 1e-6 84 | alpha = pcr.atan(self.Slope) 85 | self.L_INCA = pcr.celllength() * 1e-3 / pcr.cos(alpha) 86 | 87 | #-Initiate sediment store variable 88 | self.S_store = self.DEM * 0 89 | 90 | #-dynamic processes inca 91 | def dynamic(self, pcr, Precip, Q): 92 | #-determine canopy cover from LAI 93 | if self.DynVegFLAG == 1: 94 | V_INCA = pcr.min(9.999, pcr.min(1, self.LAI) * 10) 95 | else: 96 | V_INCA = self.V_INCA 97 | 98 | #-determine detachment of soil particles by raindrop impact (kg/km2) 99 | S_SP = self.inca.DetachmentRaindrop(self, pcr, self.c_x1_INCA, Precip, self.E_SP_INCA, V_INCA, self.GC_INCA) 100 | 101 | #-report detachment of soil particles by raindrop impact (ton / cell) 102 | self.reporting.reporting(self, pcr, 'DetRn', S_SP * pcr.cellarea() * 1e-9) 103 | 104 | #-Determine transport capacity of the flow (kg/km2) 105 | S_TC = self.inca.TransportCapacity(self, pcr, Q, self.a4_INCA, self.a5_INCA, self.a6_INCA, self.A_INCA, self.L_INCA) 106 | 107 | #-determine detachment of soil particles by runoff (kg/km2) 108 | S_FL, K = self.inca.DetachmentRunoff(self, pcr, Q, S_SP, S_TC, self.E_FL_INCA, self.a1_INCA, self.a2_INCA, self.a3_INCA, self.GC_INCA, self.A_INCA, self.L_INCA) 109 | 110 | #-report detachment of soil particles by runoff (ton / cell) 111 | self.reporting.reporting(self, pcr, 'DetRun', S_FL * pcr.cellarea() * 1e-9) 112 | 113 | #-determine mass of sediment in transport (kg/km2) 114 | sed = self.inca.sedimentTransported(self, pcr, S_SP, S_FL, S_TC) 115 | 116 | #-update sediment store (kg/km2) 117 | self.S_store = self.inca.UpdateSedimentStore(self, pcr, S_SP, S_FL, S_TC, K) 118 | 119 | #-report sediment in transport (ton / cell) 120 | self.reporting.reporting(self, pcr, 'SedTrans', sed * pcr.cellarea() * 1e-9) 121 | 122 | return sed 123 | -------------------------------------------------------------------------------- /modules/musle.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | # Equations to calculate sediment yield accoding to the soil loss equation (Williams, 1995) 24 | # from rootzone import RootRunoff 25 | 26 | print("MUSLE module imported") 27 | 28 | 29 | # -Modified unviversal soil loss equation to calculate sediment yield (metric tons) 30 | def MUSLE(self, pcr, Q_surf, q_peak): 31 | sed = ( 32 | 11.8 33 | * (Q_surf * q_peak * self.ha_area) ** 0.56 34 | * self.K_USLE 35 | * self.C_USLE 36 | * self.P_USLE 37 | * self.LS_USLE 38 | * self.CFRG 39 | ) 40 | sed = (sed / 10000) * pcr.cellarea() # conversion to ton / cell 41 | return sed 42 | 43 | 44 | # -Peak runoff (m3/s) 45 | def q_peak(self, pcr, Runoff): 46 | q_peak = (self.Alpha_tc * Runoff * pcr.cellarea()) / ( 47 | 3600000 * self.Tc 48 | ) # peak runoff in m3/s 49 | return q_peak 50 | 51 | 52 | # -LS topographic factor 53 | def LS_ULSE(self, pcr): 54 | m = 0.6 * (1 - pcr.exp(-35.835 * self.Slope)) 55 | alpha_hill = pcr.atan(self.Slope) 56 | L_hill = pcr.celllength() / pcr.cos(alpha_hill) 57 | LS = ((L_hill / 22.1) ** m) * ( 58 | 65.41 * pcr.sin(alpha_hill) ** 2 + 4.56 * pcr.sin(alpha_hill) + 0.065 59 | ) 60 | return LS 61 | 62 | 63 | # -K factor 64 | def K_USLE(self, pcr): 65 | # ksat_hourly = self.RootKsat / 24 / self.RootKsatFrac 66 | ksat_hourly = self.RootKsat / 24 67 | M_textural = (self.RootSiltMap * 100 + 0) * (100 - self.RootClayMap * 100) 68 | permeability = pcr.scalar(ksat_hourly > 150) * 1 69 | permeability = ( 70 | permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 50, ksat_hourly < 150)) * 2 71 | ) 72 | permeability = ( 73 | permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 15, ksat_hourly < 50)) * 3 74 | ) 75 | permeability = ( 76 | permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 5, ksat_hourly < 15)) * 4 77 | ) 78 | permeability = ( 79 | permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 1, ksat_hourly < 5)) * 5 80 | ) 81 | permeability = permeability + pcr.scalar(ksat_hourly < 1) * 6 82 | s = 2 83 | K_USLE = ( 84 | ( 85 | 2.1 * 10**-4 * M_textural**1.14 * (12 - self.RootOMMap) 86 | + 3.25 * (s - 2) 87 | + 2.5 * (permeability - 3) 88 | ) 89 | / 100 90 | ) * 0.1317 91 | return K_USLE 92 | 93 | 94 | # -Time of concentration 95 | def Tc(self, pcr): 96 | slope_adjusted = pcr.ifthenelse( 97 | self.Slope < 0.0025, self.Slope + 0.0005, self.Slope 98 | ) 99 | alpha_hill = pcr.atan(slope_adjusted) 100 | L = pcr.celllength() / pcr.cos(alpha_hill) 101 | # -Kirpich channel flow time of concentration 102 | T_ch = 0.0195 * L**0.77 * slope_adjusted**-0.385 103 | # -Kerby overland flow time of concentration 104 | T_ov = 1.44 * (L * self.N) ** 0.467 * slope_adjusted**-0.235 105 | Tc = (T_ch + T_ov) / 60 # conversion to hours 106 | return Tc 107 | 108 | 109 | # -init processes musle 110 | def init(self, pcr, config): 111 | # -read table with MUSLE C-factor and retardance coefficient values per landuse class 112 | pcr.setglobaloption("matrixtable") 113 | musle_table = self.inpath + config.get("MUSLE", "musle_table") 114 | self.C_USLE = pcr.lookupscalar(musle_table, 1, self.LandUse) 115 | self.N = pcr.lookupscalar(musle_table, 2, self.LandUse) 116 | pcr.setglobaloption("columntable") 117 | 118 | # -read P-factor values map or float 119 | try: 120 | self.P_USLE = pcr.readmap(self.inpath + config.get("MUSLE", "P_USLE")) 121 | except: 122 | self.P_USLE = config.getfloat("MUSLE", "P_USLE") 123 | 124 | # -when pedotransfer module is used, calculate the K-factor based on texture maps, else read K-factor values from table 125 | if self.PedotransferFLAG == 1: 126 | self.K_USLE = self.musle.K_USLE(self, pcr) 127 | else: 128 | self.K_USLE = pcr.readmap(self.inpath + config.get("MUSLE", "K_USLE")) 129 | 130 | # -calculate other input parameters 131 | self.LS_USLE = self.musle.LS_ULSE(self, pcr) 132 | self.CFRG = pcr.exp(-0.053 * (self.RockFrac * 100)) 133 | self.Tc = self.musle.Tc(self, pcr) 134 | self.Alpha_tc = 1 - pcr.exp(2 * self.Tc * pcr.ln(1 - (self.Alpha / 2))) 135 | self.ha_area = pcr.cellarea() / 10000 136 | 137 | 138 | # -dynamic processes musle 139 | def dynamic(self, pcr, Runoff): 140 | # -determine peak runoff 141 | q_peak = self.musle.q_peak(self, pcr, Runoff) # -peak runoff in m3/s 142 | 143 | # -determine soil erosion 144 | sed = self.musle.MUSLE(self, pcr, Runoff, q_peak) # -sediment yield in ton 145 | 146 | # -report sediment in transport (ton / cell) 147 | self.reporting.reporting(self, pcr, "SedTrans", sed) 148 | -------------------------------------------------------------------------------- /utilities/pedotransfer.py: -------------------------------------------------------------------------------- 1 | # Tool to determine soil hydraulic properties from texture and organic matter input maps, 2 | # based on the pedotransfer function from Saxton & Rawls (2006) 3 | # Copyright (C) 2016-2019 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 4 | # Email: jeekhout@cebas.csic.es 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | 20 | #-function to calculate the wilting point (1500 kPa, %) 21 | def Dry(pcr, self, sand, clay, OM, bulk): 22 | #-1500 kPa moisture, first solution, %v (Eq. 1) 23 | dry_first = -0.024 * sand + 0.487 * clay + 0.006 * OM + 0.005 * sand * OM - 0.013 * clay * OM + 0.068 * sand * clay + 0.031 24 | #-1500 kPa moisture, %v (Eq. 1) 25 | dry = dry_first + (0.14 * dry_first - 0.02) 26 | return dry 27 | 28 | 29 | #-function to calculate the field capacity (33 kPa, %) 30 | def Field(pcr, self, sand, clay, OM, bulk): 31 | #-33 kPa moisture, first solution, %v (Eq. 2) 32 | field_first = -0.251 * sand + 0.195 * clay + 0.011 * OM + 0.006 * sand * OM - 0.027 * clay * OM + 0.452 * sand * clay + 0.299 33 | #-33 kPa moisture, normal density, %v (Eq. 2) 34 | field = field_first + (1.283 * field_first**2 - 0.374 * field_first - 0.015) 35 | return field 36 | 37 | 38 | #-function to calculate the saturated water content (0 kPa, %) 39 | def Sat(pcr, self, sand, clay, OM, bulk): 40 | #-SAT-33 kPa moisture, first solution, %v (Eq. 3) 41 | poros_first = 0.278 * sand + 0.034 * clay + 0.022 * OM - 0.018 * sand * OM - 0.027 * clay * OM - 0.584 * sand * clay + 0.078 42 | #-SAT-33 kPa moisture, normal density, %v (Eq. 3) 43 | poros = poros_first + (0.636 * poros_first - 0.107) 44 | #-Saturated moisture (0 kPa), normal density, %v (Eq. 5) 45 | sat = poros + self.pedotransfer.Field(pcr, self, sand, clay, OM, bulk) - 0.097 * sand + 0.043 46 | return sat 47 | 48 | 49 | #-function to calculate the field capacity adjusted for density (33 kPa, %) and saturated water content adjusted for density (0 kPa, %) 50 | def FieldAdj(pcr, self, sand, clay, OM, bulk): 51 | #-Normal density, g cm-3 (Eq. 6) 52 | density = (1-self.pedotransfer.Sat(pcr, self, sand, clay, OM, bulk))*2.65 53 | #-Adjusted density, g cm-3 (Eq. 7) 54 | density_adj = density * bulk 55 | #-Saturated moisture (0 kPa), adjusted density, %v (Eq. 8) 56 | sat_adj_dens = 1 - density_adj/2.65 57 | #-33 kPa moisture, adjusted density, %v (Eq. 9) 58 | field_adj_dens = self.pedotransfer.Field(pcr, self, sand, clay, OM, bulk) + 0.2 * (self.pedotransfer.Sat(pcr, self, sand, clay, OM, bulk) - sat_adj_dens) 59 | #-SAT-33 kPa moisture, adjusted density, %v (Eq. 10) 60 | poros_adj_dens = sat_adj_dens - field_adj_dens 61 | return field_adj_dens, poros_adj_dens, sat_adj_dens 62 | 63 | 64 | #-function to calculate the saturated hydraulic conductivity (mm/day) 65 | def KSat(pcr, self, sand, clay, OM, bulk): 66 | #-Calculate wilting, field capacity and porosity 67 | dry = self.pedotransfer.Dry(pcr, self, sand, clay, OM, bulk) 68 | temp = self.pedotransfer.FieldAdj(pcr, self, sand, clay, OM, bulk) 69 | field_adj_dens = temp[0] 70 | poros_adj_dens = temp[1] 71 | #-Inverse of B (Eq. 18) 72 | lamda = (pcr.log10(field_adj_dens) - pcr.log10(dry)) / (pcr.log10(1500) - pcr.log10(33)) 73 | #-Saturated conductivity (matric soil), mm/day (Eq. 16) 74 | ksat = (1930 * (poros_adj_dens)**(3 - lamda)) * 24 75 | return ksat 76 | 77 | #-function to calculate the wilting point based on previous pedotransfer functions 78 | def Wilt(pcr, self, np): 79 | #-Determine exponents B and A for logarithmic function 80 | B = (np.log(1500) - np.log(33)) / (pcr.ln(self.RootFieldMap) - pcr.ln(self.RootDryMap)) 81 | A = pcr.exp(np.log(33) + B * pcr.ln(self.RootFieldMap)) 82 | 83 | #-Wilting point based on logarithmic function 84 | wilt = (100 / A)**(-1/B) 85 | return wilt 86 | 87 | #-init pedotransfer processes 88 | def init(self, pcr, config, np): 89 | self.RootSandMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootSandMap')) / 100 90 | self.RootClayMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootClayMap')) / 100 91 | self.RootSiltMap = 1 - self.RootSandMap - self.RootClayMap 92 | self.RootOMMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootOMMap')) 93 | try: 94 | self.RootBulkMap = config.getfloat('PEDOTRANSFER','RootBulkMap') 95 | except: 96 | self.RootBulkMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootBulkMap')) 97 | 98 | self.SubSandMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','SubSandMap')) / 100 99 | self.SubClayMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','SubClayMap')) / 100 100 | self.SubOMMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','SubOMMap')) 101 | try: 102 | self.SubBulkMap = config.getfloat('PEDOTRANSFER','SubBulkMap') 103 | except: 104 | self.SubBulkMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','SubBulkMap')) 105 | 106 | self.RootDryMap = self.pedotransfer.Dry(pcr, self, self.RootSandMap, self.RootClayMap, self.RootOMMap, self.RootBulkMap) 107 | temp = self.pedotransfer.FieldAdj(pcr, self, self.RootSandMap, self.RootClayMap, self.RootOMMap, self.RootBulkMap) 108 | self.RootFieldMap = temp[0] * self.RootFieldFrac 109 | self.RootSatMap = temp[2] * self.RootSatFrac 110 | self.RootFieldMap = pcr.min(self.RootSatMap - 0.0001, self.RootFieldMap) 111 | self.RootWiltMap = self.pedotransfer.Wilt(pcr, self, np) * self.RootWiltFrac 112 | self.RootDryMap = self.RootDryMap * self.RootDryFrac 113 | self.RootKsat = self.pedotransfer.KSat(pcr, self, self.RootSandMap, self.RootClayMap, self.RootOMMap, self.RootBulkMap) * self.RootKsatFrac 114 | self.RootDrainVel = self.RootKsat * self.Slope 115 | 116 | temp = self.pedotransfer.FieldAdj(pcr, self, self.SubSandMap, self.SubClayMap, self.SubOMMap, self.SubBulkMap) 117 | self.SubFieldMap = temp[0] 118 | self.SubSatMap = temp[2] 119 | self.SubKsat = self.pedotransfer.KSat(pcr, self, self.SubSandMap, self.SubClayMap, self.SubOMMap, self.SubBulkMap) 120 | -------------------------------------------------------------------------------- /modules/hspf.py: -------------------------------------------------------------------------------- 1 | # Soil erosion module using the HSPF soil erosion model 2 | # Copyright (C) 2020 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | 19 | print('HSPF module imported') 20 | 21 | #-Detachment of soil particles by raindrop impact (ton/acre) 22 | def DetachmentRaindrop(self, pcr, DELT60, CR, SMPF, KRER, RAIN, JRER): 23 | DET = DELT60 * pcr.max(0, (1 - CR - self.NoErosion_HSPF)) * SMPF * KRER * (RAIN / DELT60)**JRER 24 | return DET 25 | 26 | #-Detached sediment in storage (ton/acre) 27 | def SedimentStorage(self, pcr, DETS, AFFIX, DET): 28 | DETS = DETS * (1 - AFFIX) + DET 29 | 30 | return DETS 31 | 32 | #-Detachment of soil particles by washoff (ton/acre) 33 | def DetachmentWashoff(self, pcr, STCAP, DETS, SURO, SURS, CR): 34 | WSSD = pcr.ifthenelse(STCAP > DETS, DETS * SURO / (SURS + SURO), STCAP * SURO / (SURS + SURO)) * (1 - self.NoErosion_HSPF) 35 | 36 | return WSSD 37 | 38 | #-Detachment of soil particles from the soil matrix (ton/acre) 39 | def DetachmentSoilScour(self, pcr, SURO, SURS, DELT60, KGER, JGER): 40 | SCRSD = SURO / (SURS + SURO) * DELT60 * KGER * ((SURS + SURO)/DELT60)**JGER * (1 - self.NoErosion_HSPF) 41 | 42 | #-set values in channels to 0 in case channels should be excluded 43 | if self.exclChannelsFLAG == 1: 44 | SCRSD = SCRSD * self.Hillslope 45 | 46 | return SCRSD 47 | 48 | #-Transport capacity (ton/acre) 49 | def TransportCapacity(self, pcr, DELT60, KSER, SURO, SURS, JSER): 50 | STCAP = DELT60 * KSER * ((SURS + SURO)/DELT60)**JSER * (1 - self.NoErosion_HSPF) 51 | 52 | return STCAP 53 | 54 | #-K factor (-) 55 | def K_HSPF(self, pcr): 56 | ksat_hourly = self.RootKsat / 24 57 | M_textural = (self.RootSiltMap * 100 + 0) * (100 - self.RootClayMap * 100) 58 | permeability = pcr.scalar(ksat_hourly > 150) * 1 59 | permeability = permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 50, ksat_hourly < 150)) * 2 60 | permeability = permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 15, ksat_hourly < 50)) * 3 61 | permeability = permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 5, ksat_hourly < 15)) * 4 62 | permeability = permeability + pcr.scalar(pcr.pcrand(ksat_hourly > 1, ksat_hourly < 5)) * 5 63 | permeability = permeability + pcr.scalar(ksat_hourly < 1) * 6 64 | s = 2 65 | K_HSPF = ((2.1 * 10**-4 * M_textural**1.14 * (12 - self.RootOMMap) + 3.25 * (s - 2) + 2.5 * (permeability - 3))/100) 66 | return K_HSPF 67 | 68 | #-init processes hspf 69 | def init(self, pcr, config): 70 | #-read table with HSPF landuse specific model parameters 71 | pcr.setglobaloption('matrixtable') 72 | hspf_table = self.inpath + config.get('HSPF', 'hspf_table') 73 | self.CR_HSPF = pcr.lookupscalar(hspf_table, 1, self.LandUse) 74 | try: 75 | self.KGER_HSPF = config.getfloat('HSPF', 'KGER') 76 | except: 77 | self.KGER_HSPF = pcr.lookupscalar(hspf_table, 2, self.LandUse) 78 | self.NoErosion_HSPF = pcr.lookupscalar(hspf_table, 3, self.LandUse) 79 | pcr.setglobaloption('columntable') 80 | 81 | #-read other model parameters 82 | self.JRER_HSPF = config.getfloat('HSPF', 'JRER') 83 | self.KSER_HSPF = config.getfloat('HSPF', 'KSER') 84 | self.JSER_HSPF = config.getfloat('HSPF', 'JSER') 85 | self.JGER_HSPF = config.getfloat('HSPF', 'JGER') 86 | self.AFFIX_HSPF = config.getfloat('HSPF', 'AFFIX') 87 | 88 | #-initial sediment storage 89 | self.DETS_HSPF = 0 90 | self.SURSold = 0 91 | 92 | #-define some constants 93 | self.acre_m2_HSPF = 4046.9 94 | self.inch_mm_HSPF = 25.4 95 | 96 | #-read P-factor values map or float 97 | try: 98 | self.P_HSPF = pcr.readmap(self.inpath + config.get('HSPF', 'P_USLE')) 99 | except: 100 | self.P_HSPF = config.getfloat('HSPF', 'P_USLE') 101 | 102 | #-when pedotransfer module is used, calculate the K-factor based on texture maps, else read K-factor values from the config file 103 | if self.PedotransferFLAG == 1: 104 | self.K_HSPF = self.hspf.K_HSPF(self, pcr) 105 | else: 106 | try: 107 | self.K_HSPF = pcr.readmap(self.inpath + config.get('HSPF', 'KRER')) 108 | except: 109 | self.K_HSPF = config.getfloat('HSPF', 'KRER') 110 | 111 | 112 | #-dynamic processes hspf 113 | def dynamic(self, pcr, np, Precip, Runoff): 114 | #-determine daily precipitation in inch 115 | Precip_inch = Precip / self.inch_mm_HSPF 116 | 117 | #-get acre to m2 transformation value 118 | acre_m2_HSPF = self.acre_m2_HSPF 119 | 120 | #-determine detachment of soil particles by raindrop impact (ton/acre) 121 | DET = self.hspf.DetachmentRaindrop(self, pcr, 24, self.CR_HSPF, self.P_HSPF, self.K_HSPF, Precip_inch, self.JRER_HSPF) 122 | 123 | #-determine the sediment storage (ton/acre) 124 | self.DETS_HSPF = self.hspf.SedimentStorage(self, pcr, self.DETS_HSPF, self.AFFIX_HSPF, DET) 125 | 126 | #-determine the surface water storage 127 | SURS = 0 128 | 129 | #-determine the surface outflow (inch) (= routed runoff) 130 | SURO = pcr.max(0.0001, Runoff / self.inch_mm_HSPF) 131 | 132 | #-determine transport capacity (ton/acre) 133 | STCAP = self.hspf.TransportCapacity(self, pcr, 24, self.KSER_HSPF, SURO, SURS, self.JSER_HSPF) 134 | 135 | #-determine detachment of soil particles by washoff (ton/acre) 136 | WSSD = self.hspf.DetachmentWashoff(self, pcr, STCAP, self.DETS_HSPF, SURO, SURS, self.CR_HSPF) 137 | 138 | #-report detachment of soil particles by raindrop impact (ton / cell) 139 | self.reporting.reporting(self, pcr, 'DetRn', WSSD * (pcr.cellarea() / acre_m2_HSPF)) 140 | 141 | #-update sediment storage 142 | self.DETS_HSPF = self.DETS_HSPF - WSSD 143 | 144 | #-determine detachment of soil particles from the soil matrix (ton/acre) 145 | SCRSD = self.hspf.DetachmentSoilScour(self, pcr, SURO, SURS, 24, self.KGER_HSPF, self.JGER_HSPF) 146 | 147 | #-report detachment of soil particles by runoff (ton / cell) 148 | self.reporting.reporting(self, pcr, 'DetRun', SCRSD * (pcr.cellarea() / acre_m2_HSPF)) 149 | 150 | #-determine mass of sediment in transport (ton/acre) 151 | sed = WSSD + SCRSD 152 | 153 | #-report sediment in transport (ton / cell) 154 | self.reporting.reporting(self, pcr, 'SedTrans', sed * (pcr.cellarea() / acre_m2_HSPF)) 155 | 156 | return sed 157 | -------------------------------------------------------------------------------- /modules/snow.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | print("snow module imported") 24 | 25 | 26 | # -Function to calculate the potential snow melt 27 | def PotSnowMelt(pcr, temp, tempmax, ddfs): 28 | thour = pcr.scalar(0) 29 | for ij in range(1, 25, 1): 30 | th_max = pcr.max(0, (temp + (tempmax - temp) * pcr.cos(3.1415 * ij / 12))) 31 | thour = thour + th_max 32 | melt = thour * ddfs / 24 33 | return melt 34 | 35 | 36 | # -Function to calculate the actual snow melt 37 | def ActSnowMelt(pcr, snowstore, potmelt): 38 | melt = pcr.min(snowstore, potmelt) 39 | return melt 40 | 41 | 42 | # -Function that updates the snow storage 43 | def SnowStoreUpdate(pcr, snowstore, snow, actmelt, temp, snowwatstore): 44 | snowstore = ( 45 | snowstore 46 | + snow 47 | - actmelt 48 | + pcr.ifthenelse(temp < 0, pcr.scalar(snowwatstore), 0) 49 | ) 50 | return snowstore 51 | 52 | 53 | # -Function that determines the maximum amount of water that can be stored in the snowpack 54 | def MaxSnowWatStorage(snowsc, snowstore): 55 | maxsnowwatstore = snowsc * snowstore 56 | return maxsnowwatstore 57 | 58 | 59 | # -Function to calculate the actual snow water storage 60 | def SnowWatStorage(pcr, temp, maxsnowwatstore, snowwatstore, actmelt, rain): 61 | snowwatstore = pcr.ifthenelse( 62 | temp < 0, 0, pcr.min(maxsnowwatstore, snowwatstore + actmelt + rain) 63 | ) 64 | return snowwatstore 65 | 66 | 67 | # -Function to calculate the total snow storage (snowstore + snowwatstore) 68 | def TotSnowStorage(snowstore, snowwatstore, snowfrac, rainfrac): 69 | totalsnowstore = (snowstore + snowwatstore) * (snowfrac + rainfrac) 70 | return totalsnowstore 71 | 72 | 73 | # -Function to calculate runoff from snow 74 | def SnowR(pcr, snowwatstore, maxsnowwatstore, actmelt, rain, oldsnowwatstore, snowfrac): 75 | snowr = pcr.ifthenelse( 76 | snowwatstore == maxsnowwatstore, 77 | (((actmelt + rain) - (snowwatstore - oldsnowwatstore)) * snowfrac), 78 | 0, 79 | ) 80 | return snowr 81 | 82 | 83 | # -init snow processes 84 | def init(self, pcr, config): 85 | pars = ["Tcrit", "SnowSC", "DDFS", "SnowF", "SnowCth"] 86 | for i in pars: 87 | try: 88 | setattr(self, i, pcr.readmap(self.inpath + config.get("SNOW", i))) 89 | except: 90 | setattr(self, i, config.getfloat("SNOW", i)) 91 | 92 | 93 | # -initial snow processes 94 | def initial(self, pcr, config): 95 | try: 96 | self.SnowStore = config.getfloat("SNOW_INIT", "SnowIni") 97 | except: 98 | self.SnowStore = pcr.readmap(self.inpath + config.get("SNOW_INIT", "SnowIni")) 99 | # -initial water stored in snowpack 100 | try: 101 | self.SnowWatStore = config.getfloat("SNOW_INIT", "SnowWatStore") 102 | except: 103 | self.SnowWatStore = pcr.readmap( 104 | self.inpath + config.get("SNOW_INIT", "SnowWatStore") 105 | ) 106 | self.TotalSnowStore = self.SnowStore + self.SnowWatStore 107 | 108 | 109 | # -dynamic snow processes 110 | def dynamic( 111 | self, 112 | pcr, 113 | Temp, 114 | TempMax, 115 | Precip, 116 | Snow_GLAC, 117 | ActSnowMelt_GLAC, 118 | SnowFrac, 119 | RainFrac, 120 | SnowR_GLAC, 121 | ): 122 | # -Snow and rain differentiation 123 | Snow = pcr.ifthenelse(Temp >= self.Tcrit, 0, Precip) 124 | Rain = pcr.ifthenelse(Temp < self.Tcrit, 0, Precip) 125 | # -Report Snow for entire cell (snow+glacier fraction) 126 | self.reporting.reporting(self, pcr, "TotSnow", Snow) 127 | self.reporting.reporting( 128 | self, pcr, "TotSnowF", Snow * (1 - self.GlacFrac) + Snow_GLAC 129 | ) 130 | # -Snow melt sonu added 131 | PotSnowMelt = pcr.ifthenelse( 132 | TempMax < 0, 0, self.snow.PotSnowMelt(pcr, Temp, TempMax, self.DDFS) 133 | ) 134 | ActSnowMelt = self.snow.ActSnowMelt(pcr, self.SnowStore, PotSnowMelt) 135 | # -Report snow melt for entire cell (snow+glacier fraction) 136 | self.reporting.reporting(self, pcr, "TotSnowMelt", ActSnowMelt) 137 | self.reporting.reporting( 138 | self, pcr, "TotSnowMeltF", ActSnowMelt * (1 - self.GlacFrac) + ActSnowMelt_GLAC 139 | ) 140 | # -Update snow store 141 | self.SnowStore = self.snow.SnowStoreUpdate( 142 | pcr, self.SnowStore, Snow, ActSnowMelt, Temp, self.SnowWatStore 143 | ) 144 | # -Caclulate the maximum amount of water that can be stored in snowwatstore 145 | MaxSnowWatStore = self.snow.MaxSnowWatStorage(self.SnowSC, self.SnowStore) 146 | OldSnowWatStore = self.SnowWatStore 147 | # -Calculate the actual amount of water stored in snowwatstore 148 | self.SnowWatStore = self.snow.SnowWatStorage( 149 | pcr, TempMax, MaxSnowWatStore, self.SnowWatStore, ActSnowMelt, Rain 150 | ) 151 | # -Changes in total water storage in snow (SnowStore and SnowWatStore) 152 | OldTotalSnowStore = self.TotalSnowStore 153 | self.TotalSnowStore = ( 154 | self.snow.TotSnowStorage(self.SnowStore, self.SnowWatStore, SnowFrac, RainFrac) 155 | + self.TotalSnowStore_GLAC 156 | ) # for entire cell 157 | # -Report Snow storage 158 | self.reporting.reporting(self, pcr, "StorSnow", self.TotalSnowStore) 159 | # -Determine if cell is covered with snow 160 | SnowCover = pcr.ifthenelse( 161 | self.TotalSnowStore > self.SnowCth, pcr.scalar(1), pcr.scalar(0) 162 | ) 163 | self.reporting.reporting(self, pcr, "SCover", SnowCover) 164 | self.reporting.reporting( 165 | self, pcr, "StorSnowW", self.SnowWatStore 166 | ) # sonu added note this is only SnowWatStore 167 | # -Snow runoff 168 | SnowR = ( 169 | self.snow.SnowR( 170 | pcr, 171 | self.SnowWatStore, 172 | MaxSnowWatStore, 173 | ActSnowMelt, 174 | Rain, 175 | OldSnowWatStore, 176 | SnowFrac, 177 | ) 178 | + SnowR_GLAC 179 | ) # for entire cell 180 | ##sonu added snow infiltration## 181 | SnowSoil = SnowR * self.SnowF 182 | SnowR = SnowR * (1 - self.SnowF) 183 | SnowR = SnowR * (1 - self.openWaterFrac) 184 | # -Report Snow runoff 185 | self.reporting.reporting(self, pcr, "TotSnowRF", SnowR) 186 | 187 | return Rain, SnowR, SnowSoil, OldTotalSnowStore 188 | -------------------------------------------------------------------------------- /modules/reservoirs.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | print("Reservoir module imported") 23 | 24 | 25 | # -Advanced reservoir 26 | def QAdv(self, pcr): 27 | DayNo = self.timecalc.julian(self)[0] 28 | # -determine if it is flood or dry season 29 | S1 = pcr.ifthenelse( 30 | self.ResFlStart < self.ResFlEnd, 31 | pcr.ifthenelse( 32 | DayNo >= self.ResFlStart, 33 | pcr.ifthenelse(DayNo <= self.ResFlEnd, pcr.boolean(1), pcr.boolean(0)), 34 | pcr.boolean(0), 35 | ), 36 | pcr.ifthenelse( 37 | DayNo >= self.ResFlEnd, 38 | pcr.ifthenelse(DayNo >= self.ResFlStart, pcr.boolean(1), pcr.boolean(0)), 39 | pcr.ifthenelse( 40 | DayNo <= self.ResFlEnd, 41 | pcr.ifthenelse( 42 | DayNo <= self.ResFlStart, pcr.boolean(1), pcr.boolean(0) 43 | ), 44 | pcr.boolean(0), 45 | ), 46 | ), 47 | ) 48 | 49 | S_avail = pcr.max(self.StorRES - self.ResPVOL, 0) 50 | Q = pcr.max( 51 | pcr.ifthenelse( 52 | S1, 53 | self.ResMaxFl * S_avail / (self.ResEVOL - self.ResPVOL), 54 | self.ResDemFl * S_avail / (self.ResEVOL - self.ResPVOL), 55 | ), 56 | self.StorRES - self.ResEVOL, 57 | ) 58 | return Q 59 | 60 | 61 | # -Simple reservoir 62 | def QSimple(self, pcr): 63 | Q = pcr.max( 64 | pcr.min( 65 | self.ResKr * self.StorRES * (self.StorRES / self.ResSmax) ** self.ResB, 66 | self.StorRES, 67 | ), 68 | self.StorRES - self.ResSmax, 69 | ) 70 | return Q 71 | 72 | 73 | # -Calculates reservoir outflow and the fraction to release, depending on the type of reservoir (simple or advanced) 74 | def QRes(self, pcr): 75 | if self.ResSimple and self.ResAdvanced: 76 | Qout = pcr.ifthenelse( 77 | self.ResFunc == 1, 78 | QSimple(self, pcr), 79 | pcr.ifthenelse(self.ResFunc == 2, QAdv(self, pcr), 0), 80 | ) 81 | elif self.ResSimple: 82 | Qout = pcr.ifthenelse(self.ResFunc == 1, QSimple(self, pcr), 0) 83 | else: 84 | Qout = pcr.ifthenelse(self.ResFunc == 2, QAdv(self, pcr), 0) 85 | 86 | return Qout 87 | 88 | 89 | # -init processes reservoirs 90 | def init(self, pcr, config): 91 | # -set the option to calculate the reservoir inflow, outflow and storage per component 92 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 93 | for i in pars: 94 | var = "Rep" + i + "_FLAG" 95 | setattr(self, var, config.getint("REPORTING", var)) 96 | 97 | pcr.setglobaloption("matrixtable") 98 | # nominal map with reservoir IDs 99 | self.ResID = pcr.cover( 100 | pcr.readmap(self.inpath + config.get("RESERVOIR", "ResId")), 0 101 | ) 102 | # boolean map with stations that are not reservoirs 103 | self.LocationsNoRes = pcr.ifthenelse( 104 | pcr.pcrand(pcr.scalar(self.Locations) > 0, pcr.scalar(self.ResID) == 0), 105 | pcr.boolean(1), 106 | pcr.boolean(0), 107 | ) 108 | 109 | # lookup table with operational scheme to use (simple or advanced) 110 | ResFunc_Tab = self.inpath + config.get("RESERVOIR", "ResFuncStor") 111 | # Reservoir function 112 | self.ResFunc = pcr.cover(pcr.lookupscalar(ResFunc_Tab, 1, self.ResID), 0) 113 | try: 114 | # lookup table with coefficients for simple reservoirs 115 | ResSimple_Tab = self.inpath + config.get("RESERVOIR", "ResSimple") 116 | # Read coefficients for simple reservoirs 117 | self.ResKr = pcr.lookupscalar(ResSimple_Tab, 1, self.ResID) 118 | self.ResB = pcr.lookupscalar(ResSimple_Tab, 2, self.ResID) 119 | self.ResSmax = ( 120 | pcr.lookupscalar(ResSimple_Tab, 3, self.ResID) * 10**6 121 | ) # convert to m3 122 | self.ResSimple = True 123 | except: 124 | self.ResSimple = False 125 | try: 126 | # lookup table with coefficients for advanced reservoirs 127 | ResAdvanced_Tab = self.inpath + config.get("RESERVOIR", "ResAdv") 128 | # Read coefficients for advanced reservoirs 129 | self.ResEVOL = ( 130 | pcr.lookupscalar(ResAdvanced_Tab, 1, self.ResID) * 10**6 131 | ) # convert to m3 132 | self.ResPVOL = ( 133 | pcr.lookupscalar(ResAdvanced_Tab, 2, self.ResID) * 10**6 134 | ) # convert to m3 135 | self.ResMaxFl = ( 136 | pcr.lookupscalar(ResAdvanced_Tab, 3, self.ResID) * 10**6 137 | ) # convert to m3/d 138 | self.ResDemFl = ( 139 | pcr.lookupscalar(ResAdvanced_Tab, 4, self.ResID) * 10**6 140 | ) # convert to m3/d 141 | self.ResFlStart = pcr.lookupscalar(ResAdvanced_Tab, 5, self.ResID) 142 | self.ResFlEnd = pcr.lookupscalar(ResAdvanced_Tab, 6, self.ResID) 143 | self.ResAdvanced = True 144 | except: 145 | self.ResAdvanced = False 146 | pcr.setglobaloption("columntable") 147 | 148 | 149 | # -initial conditions reservoirs 150 | def initial(self, pcr, config): 151 | ResStor_Tab = self.inpath + config.get("RESERVOIR", "ResFuncStor") 152 | ResStor = ( 153 | pcr.cover(pcr.lookupscalar(ResStor_Tab, 2, self.ResID), 0) * 10**6 154 | ) # convert to m3 155 | try: 156 | self.StorRES = self.StorRES + ResStor 157 | # -Qfrac for reservoir cells should be zero, else 1 158 | self.QFRAC = pcr.ifthenelse(self.ResID != 0, pcr.scalar(0), self.QFRAC) 159 | except: 160 | self.StorRES = ResStor 161 | # -Qfrac for reservoir cells should be zero, else 1 162 | self.QFRAC = pcr.ifthenelse(self.ResID != 0, pcr.scalar(0), 1) 163 | 164 | 165 | # -initial conditions reporting reservoirs 166 | def initial_reporting(self, pcr, pcrm): 167 | self.ResInTSS = pcrm.TimeoutputTimeseries( 168 | "ResInTSS", self, self.ResID, noHeader=True 169 | ) 170 | self.ResOutTSS = pcrm.TimeoutputTimeseries( 171 | "ResOutTSS", self, self.ResID, noHeader=True 172 | ) 173 | self.ResStorTSS = pcrm.TimeoutputTimeseries( 174 | "ResStorTSS", self, self.ResID, noHeader=True 175 | ) 176 | self.ResETaTSS = pcrm.TimeoutputTimeseries( 177 | "ResETaTSS", self, self.ResID, noHeader=True 178 | ) 179 | self.ResInCalTSS = pcrm.TimeoutputTimeseries( 180 | "ResInCalTSS", self, self.ResID, noHeader=True 181 | ) 182 | # -set reporting of water balances for individual components 183 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 184 | for i in pars: 185 | if eval("self." + i + "RA_FLAG") and getattr(self, "Rep" + i + "_FLAG"): 186 | setattr( 187 | self, 188 | "Res" + i + "InTSS", 189 | pcrm.TimeoutputTimeseries( 190 | "Res" + i + "InTSS", self, self.ResID, noHeader=True 191 | ), 192 | ) 193 | setattr( 194 | self, 195 | "Res" + i + "OutTSS", 196 | pcrm.TimeoutputTimeseries( 197 | "Res" + i + "OutTSS", self, self.ResID, noHeader=True 198 | ), 199 | ) 200 | setattr( 201 | self, 202 | "Res" + i + "StorTSS", 203 | pcrm.TimeoutputTimeseries( 204 | "Res" + i + "StorTSS", self, self.ResID, noHeader=True 205 | ), 206 | ) 207 | -------------------------------------------------------------------------------- /utilities/reporting.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2019 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, W. Immerzeel, S. Khanal, A. Lutz, G. Simons, W. Terink 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | 23 | #-Function to report the output 24 | def REPM(self, pcr, tot, var, fname, outops, TSS=False, MAP=False, AVG=False): 25 | dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 26 | if self.calendar.isleap(self.curdate.year): 27 | dim[1] = 29 28 | 29 | if self.calendar.isleap(self.curdate.year): 30 | ydays = 366 31 | else: 32 | ydays = 365 33 | 34 | if outops == 'Day': 35 | if TSS: 36 | TSS.sample(var) 37 | if MAP: 38 | self.report(var, self.outpath + fname) 39 | tot = 0 40 | 41 | elif outops == 'Month': 42 | tot = tot + var 43 | if self.curdate.day == dim[self.curdate.month-1]: 44 | if TSS: 45 | TSS.sample(tot) 46 | if MAP: 47 | self.report(tot, self.outpath + fname + 'M') 48 | if AVG: 49 | self.report(tot / dim[self.curdate.month-1], self.outpath + fname + 'M') 50 | tot = 0 51 | 52 | elif outops == 'Year': 53 | if self.timecalc.julian(self)[0] != ydays: 54 | tot = tot + var 55 | else: 56 | tot = tot + var 57 | if TSS: 58 | TSS.sample(tot) 59 | if MAP: 60 | self.report(tot, self.outpath + fname + 'Y') 61 | if AVG: 62 | self.report(tot / ydays, self.outpath + fname + 'Y') 63 | tot = 0 64 | 65 | elif outops == 'MonthSum': 66 | if self.curdate.day != dim[self.curdate.month-1] and self.curdate.year >= self.startYear + self.spinUpYears: 67 | tot[self.curdate.month-1] = tot[self.curdate.month-1] + var 68 | if self.curdate.day == dim[self.curdate.month-1] and self.curdate.year == self.endYear: 69 | pcr.report(tot[self.curdate.month-1] / (self.simYears), self.outpath + fname + 'SumM' + str(self.curdate.month).zfill(2) + '.map') 70 | 71 | elif outops == 'YearSum': 72 | if self.curdate.year >= self.startYear + self.spinUpYears: 73 | tot = tot + var 74 | if self.curdate == self.enddate: 75 | pcr.report(tot / (self.simYears), self.outpath + fname + 'SumY.map') 76 | 77 | elif outops == 'MonthAvg': 78 | if self.curdate.day != dim[self.curdate.month-1] and self.curdate.year >= self.startYear + self.spinUpYears: 79 | tot[self.curdate.month-1] = tot[self.curdate.month-1] + var / dim[self.curdate.month-1] 80 | elif self.curdate.day == dim[self.curdate.month-1] and self.curdate.year == self.endYear: 81 | pcr.report(tot[self.curdate.month-1] / (self.simYears), self.outpath + fname + 'AvgM' + str(self.curdate.month).zfill(2) + '.map') 82 | 83 | elif outops == 'YearAvg': 84 | if self.curdate.year >= self.startYear + self.spinUpYears: 85 | tot = tot + var / ydays 86 | if self.curdate == self.enddate: 87 | pcr.report(tot / (self.simYears), self.outpath + fname + 'AvgY.map') 88 | 89 | else: 90 | if self.curdate != self.enddate: 91 | tot = tot + var 92 | else: 93 | pcr.report(tot, self.outpath + fname + '.map') 94 | tot = 0 95 | return tot 96 | 97 | #-Function to initialise the reporting 98 | def reporting(self, pcr, tot, var): 99 | for outops in ['Day','Month','Year','Final','MonthSum','YearSum','MonthAvg','YearAvg']: 100 | try: 101 | TSS = eval('self.' + tot + '_' + outops + 'TS') 102 | except: 103 | TSS = False 104 | try: 105 | MAP = eval('self.' + tot + '_' + outops + '_map') 106 | except: 107 | MAP = False 108 | try: 109 | AVG = eval('self.' + tot + '_' + outops + '_avg') 110 | except: 111 | AVG = False 112 | if TSS or MAP or AVG: 113 | setattr(self, tot + '_'+outops, REPM(self, pcr, eval('self.'+tot+'_'+outops), var, eval('self.'+tot+'_fname'), outops, TSS, MAP, AVG)) 114 | 115 | #-read reporting from csv file 116 | def initial(self, pcr, csv, pcrm): 117 | #-set reporting options and read initial values 118 | with open(self.inpath + self.RepTab, 'r') as f: 119 | next(f) # skip headings 120 | reader = csv.reader(f, delimiter=',') 121 | for row in reader: 122 | if row[0][:1] != '#': 123 | i = row[0] 124 | mapoutops = row[1] 125 | avgoutops = row[2] 126 | TSoutops = row[3] 127 | if mapoutops == 'NONE' and avgoutops == 'NONE' and TSoutops == 'NONE': 128 | print(i + ' will NOT be reported') 129 | else: 130 | print(i + ' will be reported') 131 | fname = row[4] 132 | setattr(self, i+'_fname', fname) 133 | setattr(self, i, 0.) # use this instead of the commented part above, because it is more logical to always zero as initial condition for reporting 134 | if mapoutops != 'NONE': 135 | mapoutops = mapoutops.split("+") 136 | for j in mapoutops: 137 | if j == 'D': 138 | setattr(self, i+'_Day', eval('self.'+i)) 139 | setattr(self, i+'_Day_map', 1) 140 | elif j == 'M': 141 | setattr(self, i+'_Month', eval('self.'+i)) 142 | setattr(self, i+'_Month_map', 1) 143 | elif j == 'Y': 144 | setattr(self, i+'_Year', eval('self.'+i)) 145 | setattr(self, i+'_Year_map', 1) 146 | elif j == 'MS': 147 | setattr(self, i+'_MonthSum', {m: self.DEM * 0 for m in range(0, 13, 1)}) 148 | setattr(self, i+'_MonthSum_map', 1) 149 | elif j == 'YS': 150 | setattr(self, i+'_YearSum', eval('self.'+i)) 151 | setattr(self, i+'_YearSum_map', 1) 152 | else: 153 | setattr(self, i+'_Final', eval('self.'+i)) 154 | setattr(self, i+'_Final_map', 1) 155 | if avgoutops != 'NONE': 156 | avgoutops = avgoutops.split("+") 157 | for j in avgoutops: 158 | if j == 'M': 159 | setattr(self, i+'_Month', eval('self.'+i)) 160 | setattr(self, i+'_Month_avg', 1) 161 | elif j == 'Y': 162 | setattr(self, i+'_Year', eval('self.'+i)) 163 | setattr(self, i+'_Year_avg', 1) 164 | elif j == 'MA': 165 | setattr(self, i+'_MonthAvg', {m: self.DEM * 0 for m in range(0, 13, 1)}) 166 | setattr(self, i+'_MonthAvg_avg', 1) 167 | elif j == 'YA': 168 | setattr(self, i+'_YearAvg', eval('self.'+i)) 169 | setattr(self, i+'_YearAvg_avg', 1) 170 | if TSoutops != 'NONE': 171 | TSoutops = TSoutops.split("+") 172 | for j in TSoutops: 173 | if j == 'D': 174 | setattr(self, i+'_Day', eval('self.'+i)) 175 | setattr(self, i+'_DayTS', eval('pcrm.TimeoutputTimeseries("'+fname+'DTS'+'", self, self.Locations, noHeader=False)')) 176 | elif j == 'M': 177 | setattr(self, i+'_Month', eval('self.'+i)) 178 | setattr(self, i+'_MonthTS', eval('pcrm.TimeoutputTimeseries("'+fname+'MTS'+'", self, self.Locations, noHeader=False)')) 179 | elif j == 'Y': 180 | setattr(self, i+'_Year', eval('self.'+i)) 181 | setattr(self, i+'_YearTS', eval('pcrm.TimeoutputTimeseries("'+fname+'YTS'+'", self, self.Locations, noHeader=False)')) -------------------------------------------------------------------------------- /modules/dhsvm.py: -------------------------------------------------------------------------------- 1 | # Soil erosion module using the DHSVM soil erosion model 2 | # Copyright (C) 2020 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | 19 | print('DHSVM module imported') 20 | 21 | #-Detachment of soil particles by raindrop impact (kg/m2/s) 22 | def DetachmentRaindrop(self, pcr, k_r, F_w, C_G, C_C, M_R, M_D): 23 | D_R = k_r * F_w * pcr.max(0, 1 - C_G - self.NoErosion_DHSVM) * (pcr.max(0, 1 - C_C) * M_R + M_D) 24 | return D_R 25 | 26 | #-Rainfall drop momentum (kg2/s3) 27 | def MomentumRainDrop(self, pcr, np, precSum): 28 | #-store daily precipitation 29 | precipDaily = precSum 30 | 31 | #-determine sum over all raster cells 32 | precIntTotal = np.sum(pcr.pcr2numpy(precSum, 0)) 33 | 34 | #-initiate hour counter and set M_r to 0 35 | hour = 0 36 | M_R = self.DEM * 0 37 | 38 | #-while precipitation sum is larger than 0 39 | while (precIntTotal > 0): 40 | #-determine hourly rainfall intensity 41 | I = pcr.max(0, self.Alpha * precipDaily - ((self.Alpha**2 * precipDaily) / 2) * hour) 42 | 43 | #-determine coefficient alpha 44 | alpha = pcr.scalar(I >= 100) * 11.75 * 1e-8 45 | alpha = alpha + pcr.scalar(pcr.pcrand(I >= 50, I < 100)) * 6.12 * 1e-8 46 | alpha = alpha + pcr.scalar(pcr.pcrand(I >= 10, I < 50)) * 3.75 * 1e-8 47 | alpha = alpha + pcr.scalar(I < 10) * 2.69 * 1e-8 48 | 49 | #-determine coefficient beta 50 | beta = pcr.scalar(I >= 100) * 1.2821 51 | beta = beta + pcr.scalar(pcr.pcrand(I >= 50, I < 100)) * 1.4242 52 | beta = beta + pcr.scalar(pcr.pcrand(I >= 10, I < 50)) * 1.5545 53 | beta = beta + pcr.scalar(I < 10) * 1.6896 54 | 55 | #-calculate rainfall drop momentum based on hourly precipitation intensity and multiply with 1/24 56 | M_R_hour = alpha * I**beta * 1/24 57 | 58 | #-add to daily rainfall drop momentum 59 | M_R = M_R + M_R_hour 60 | 61 | #-determine sum over all raster cells 62 | precIntTotal = np.sum(pcr.pcr2numpy(I, 0)) 63 | 64 | #-increase hour with 1 65 | hour += 1 66 | return M_R 67 | 68 | #-Leaf drip momentum (kg2 / s3) 69 | def MomentumLeafDrip(self, pcr, D, X, rho, DRAIN, g, C_C): 70 | #-determine coefficient a 71 | a = pcr.scalar(pcr.pcrand(D >= 0.033, X >= 7.5)) * 5.14 72 | a = a + pcr.scalar(pcr.pcrand(D >= 0.033, X < 7.5)) * 1.93 73 | a = a + pcr.scalar(D < 0.033) * 0 74 | 75 | #-determine coefficient b 76 | b = pcr.scalar(pcr.pcrand(D >= 0.033, X >= 7.5)) * 660 77 | b = b + pcr.scalar(pcr.pcrand(D >= 0.033, X < 7.5)) * 1640 78 | b = b + pcr.scalar(D < 0.033) * 2200 79 | 80 | #-Ratio M/beta (m) 81 | M_beta = a + b * D 82 | #-Leaf drip fall speed (m/s) 83 | V = (M_beta * g * (1 - pcr.exp(-2*X/M_beta)))**0.5 84 | #-Set the proportion of the drainage that falls as leaf drip equal to the canopy cover 85 | DRIP = C_C 86 | #-Determine the momentum squared for leaf drip (kg2 / s3) 87 | M_D = (((V * rho * self.pi * D**3) / 6)**2 * DRIP * DRAIN) / ((self.pi * D**3) / 6) 88 | return M_D 89 | 90 | #-Detachment of soil particles by runoff (kg/m2/s) 91 | def DetachmentRunoff(self, pcr, beta_de, dy, v_s, TC, C_G): 92 | D_of = beta_de * dy * v_s * TC * pcr.max(0, 1 - self.NoErosion_DHSVM) 93 | 94 | #-set values in channels to 0 in case channels should be excluded 95 | if self.exclChannelsFLAG == 1: 96 | D_of = D_of * self.Hillslope 97 | return D_of 98 | 99 | #-Detachment efficiency (-) 100 | def DetachmentEfficiency(self, pcr, C_s): 101 | beta_de = 0.79 * pcr.exp(-0.6 * C_s) 102 | return beta_de 103 | 104 | #-Settling velocity (m/s) 105 | def SettlingVelocity(self, pcr, g, rho_s, rho, nu, d50): 106 | #-Initial guess of the settling velocity (m/s) 107 | v_s = (4/3 * g * (rho_s / rho) - 1)**0.5 * d50 108 | #-Reynolds number (-) 109 | Rn = (v_s * d50) / nu 110 | #-Drag coefficient (-) 111 | Cd = (24 / Rn) + (3 / (Rn**0.5)) + 0.34 112 | #-Settling velocity (m/s) 113 | v_s = ((4/3 * g * ((rho_s/rho) - 1) * d50) / Cd)**0.5 114 | return v_s 115 | 116 | #-Stream power (kg/m/s3) 117 | def StreamPower(self, pcr, rho, g, Q, S): 118 | SP = rho * g * Q * S 119 | return SP 120 | 121 | #-Transport capacity (m3/m3) 122 | def TransportCapacity(self, pcr, d50, rho, rho_s, S, h, g, SP, SP_cr): 123 | TC = (0.05 / (d50 * (rho_s / rho - 1)**2)) * ((S * h) / g)**0.5 * pcr.max(0, (SP - SP_cr)) 124 | return TC 125 | 126 | #-Water depth (m), flow velocity (m/s) 127 | def Manning(self, pcr, Q, n, WD_ratio, S): 128 | #-Determine flow area and water depth 129 | A = ((Q * n * (2 * ((WD_ratio**2 + 1) / WD_ratio)**0.5)**(2/3)) / S**0.5)**(3/4) 130 | h = (A / WD_ratio)**0.5 131 | 132 | #-Set minimum value for flow area and water depth 133 | h = pcr.max(self.h_min_DHSVM, h) 134 | return h 135 | 136 | #-init processes dhsvm 137 | def init(self, pcr, config): 138 | #-read table with DHSVM landuse specific model parameters 139 | pcr.setglobaloption('matrixtable') 140 | dhsvm_table = self.inpath + config.get('DHSVM', 'dhsvm_table') 141 | self.D_DHSVM = pcr.lookupscalar(dhsvm_table, 1, self.LandUse) 142 | self.X_DHSVM = pcr.lookupscalar(dhsvm_table, 2, self.LandUse) 143 | self.C_G_DHSVM = pcr.lookupscalar(dhsvm_table, 3, self.LandUse) 144 | self.C_C_table_DHSVM = pcr.lookupscalar(dhsvm_table, 4, self.LandUse) 145 | self.n_table_DHSVM = pcr.lookupscalar(dhsvm_table, 5, self.LandUse) 146 | self.root_cohesion_DHSVM = pcr.lookupscalar(dhsvm_table, 6, self.LandUse) 147 | self.NoErosion_DHSVM = pcr.lookupscalar(dhsvm_table, 7, self.LandUse) 148 | 149 | #-read table with soil cohesion per soil class 150 | self.SoilClass_DHSVM = pcr.readmap(self.inpath + config.get('DHSVM', 'SoilClass')) 151 | dhsvm_cohesion_table = self.inpath + config.get('DHSVM', 'dhsvm_cohesion_table') 152 | self.soil_cohesion_DHSVM = pcr.lookupscalar(dhsvm_cohesion_table, 1, self.SoilClass_DHSVM) 153 | pcr.setglobaloption('columntable') 154 | 155 | #-determine overall cohesion from soil and root cohesion 156 | self.C_s_DHSVM = self.soil_cohesion_DHSVM + self.root_cohesion_DHSVM 157 | 158 | #-read other model parameters 159 | self.WD_ratio_DHSVM = config.getfloat('DHSVM', 'WD_ratio') 160 | self.rho_DHSVM = config.getfloat('DHSVM', 'rho') 161 | self.rho_s_DHSVM = config.getfloat('DHSVM', 'rho_s') 162 | self.deltaClay_DHSVM = config.getfloat('DHSVM', 'deltaClay') * 1e-6 163 | self.deltaSilt_DHSVM = config.getfloat('DHSVM', 'deltaSilt') * 1e-6 164 | self.deltaSand_DHSVM = config.getfloat('DHSVM', 'deltaSand') * 1e-6 165 | self.k_r_DHSVM = config.getfloat('DHSVM', 'k_r') 166 | self.h_min_DHSVM = config.getfloat('DHSVM', 'h_min') 167 | self.SP_crit_DHSVM = config.getfloat('DHSVM', 'SP_crit') 168 | 169 | #-define constants 170 | self.F_w_DHSVM = 1 171 | self.g_DHSVM = 9.81 172 | self.visc_DHSVM = 1e-06 173 | 174 | #-determine median grain size 175 | if self.PedotransferFLAG == 1: 176 | self.D50_DHSVM = pcr.ifthenelse(self.RootClayMap > 0.5, pcr.scalar(self.deltaClay_DHSVM), 0) 177 | self.D50_DHSVM = pcr.ifthenelse(self.RootClayMap + self.RootSiltMap > 0.5, self.deltaClay_DHSVM + (self.deltaSilt_DHSVM - self.deltaClay_DHSVM) * (0.5 - self.RootClayMap) / self.RootSiltMap, 0) + self.D50_DHSVM 178 | self.D50_DHSVM = pcr.ifthenelse(self.RootClayMap + self.RootSiltMap < 0.5, self.deltaSilt_DHSVM + (self.deltaSand_DHSVM - self.deltaSilt_DHSVM) * (self.RootSandMap - 0.5) / self.RootSandMap, 0) + self.D50_DHSVM 179 | else: 180 | self.D50_DHSVM = config.getfloat('DHSVM', 'D50') * 1e-6 181 | 182 | #-dynamic processes dhsvm 183 | def dynamic(self, pcr, np, Precip, Q): 184 | #-determine canopy cover from LAI 185 | if self.DynVegFLAG == 1: 186 | C_C_DHSVM = pcr.min(1, self.LAI) 187 | else: 188 | C_C_DHSVM = self.C_C_table_DHSVM 189 | 190 | #-determine rainfall drop momentum (kg2/s3) 191 | M_R = self.dhsvm.MomentumRainDrop(self, pcr, np, Precip) 192 | 193 | #-determine water drainage rate from canopy (m/s) 194 | DRAIN = Precip * 1e-3 / (24 * 60 * 60) 195 | 196 | #-determine leaf drop momentum (kg2/s3) 197 | M_D = self.dhsvm.MomentumLeafDrip(self, pcr, self.D_DHSVM, self.X_DHSVM, self.rho_DHSVM, DRAIN, self.g_DHSVM, C_C_DHSVM) 198 | 199 | #-determine detachment of soil particles by raindrop impact (kg/m2/s) 200 | D_R = self.dhsvm.DetachmentRaindrop(self, pcr, self.k_r_DHSVM, self.F_w_DHSVM, self.C_G_DHSVM, C_C_DHSVM, M_R, M_D) 201 | 202 | #-report detachment of soil particles by raindrop impact (ton / cell) 203 | self.reporting.reporting(self, pcr, 'DetRn', D_R * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 204 | 205 | #-determine water depth (m) and width of the flow (m) 206 | h = self.dhsvm.Manning(self, pcr, Q, self.n_table_DHSVM, self.WD_ratio_DHSVM, self.Slope) 207 | 208 | #-determine detachment efficiency (-) 209 | beta_de = self.dhsvm.DetachmentEfficiency(self, pcr, self.C_s_DHSVM) 210 | 211 | #-determine settling velocity (m/s) 212 | v_s = self.dhsvm.SettlingVelocity(self, pcr, self.g_DHSVM, self.rho_s_DHSVM, self.rho_DHSVM, self.visc_DHSVM, self.D50_DHSVM) 213 | 214 | #-determine stream power (kg m/s3) 215 | SP = self.dhsvm.StreamPower(self, pcr, self.rho_DHSVM, self.g_DHSVM, Q, self.Slope) 216 | 217 | #-determine transport capacity (m3/m3) 218 | TC = self.dhsvm.TransportCapacity(self, pcr, self.D50_DHSVM, self.rho_DHSVM, self.rho_s_DHSVM, self.Slope, h, self.g_DHSVM, SP, self.SP_crit_DHSVM) 219 | 220 | #-determine detachment of soil particles by runoff (kg/m2/s) 221 | D_of = self.dhsvm.DetachmentRunoff(self, pcr, beta_de, pcr.celllength(), v_s, TC, self.C_G_DHSVM) 222 | 223 | #-report detachment of soil particles by runoff (ton / cell) 224 | self.reporting.reporting(self, pcr, 'DetRun', D_of * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 225 | 226 | #-determine mass of sediment in transport (kg/m2/s) 227 | sed = D_R + D_of 228 | 229 | #-report sediment in transport (ton / cell) 230 | self.reporting.reporting(self, pcr, 'SedTrans', sed * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 231 | 232 | return sed 233 | -------------------------------------------------------------------------------- /modules/shetran.py: -------------------------------------------------------------------------------- 1 | # Soil erosion module using the SHETRAN soil erosion model 2 | # Copyright (C) 2020 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | 19 | print('SHETRAN module imported') 20 | 21 | #-Detachment of soil particles by raindrop impact (kg/m2/s) 22 | def DetachmentRaindrop(self, pcr, k_r, F_w, C_g, C_r, M_r, M_d): 23 | D_r = k_r * F_w * pcr.max(0, 1 - C_g - C_r - self.NoErosion_SHETRAN) * (M_r + M_d) 24 | return D_r 25 | 26 | #-Rainfall drop momentum (kg2/s3) 27 | def MomentumRainDrop(self, pcr, np, C_c, precSum): 28 | #-store daily precipitation 29 | precipDaily = precSum 30 | 31 | #-determine sum over all raster cells 32 | precIntTotal = np.sum(pcr.pcr2numpy(precSum, 0)) 33 | 34 | #-initiate hour counter and set M_r to 0 35 | hour = 0 36 | M_r = self.DEM * 0 37 | 38 | #-while precipitation sum is larger than 0 39 | while (precIntTotal > 0): 40 | #-determine hourly rainfall intensity 41 | I = pcr.max(0, self.Alpha * precipDaily - ((self.Alpha**2 * precipDaily) / 2) * hour) 42 | 43 | a_1 = pcr.scalar(I >= 100) * 11.737 * 1e-8 44 | a_1 = a_1 + pcr.scalar(pcr.pcrand(I >= 50, I < 100)) * 6.1192 * 1e-8 45 | a_1 = a_1 + pcr.scalar(pcr.pcrand(I >= 10, I < 50)) * 3.7514 * 1e-8 46 | a_1 = a_1 + pcr.scalar(I < 10) * 2.6893 * 1e-8 47 | 48 | b_1 = pcr.scalar(I >= 100) * 1.2821 49 | b_1 = b_1 + pcr.scalar(pcr.pcrand(I >= 50, I < 100)) * 1.4242 50 | b_1 = b_1 + pcr.scalar(pcr.pcrand(I >= 10, I < 50)) * 1.5545 51 | b_1 = b_1 + pcr.scalar(I < 10) * 1.6896 52 | 53 | #-calculate rainfall drop momentum based on hourly precipitation intensity and multiply with 1/24 54 | M_r_hour = (1 - C_c) * a_1 * I**b_1 * 1/24 55 | 56 | #-add to daily rainfall drop momentum 57 | M_r = M_r + M_r_hour 58 | 59 | #-determine sum over all raster cells 60 | precIntTotal = np.sum(pcr.pcr2numpy(I, 0)) 61 | 62 | #-increase hour with 1 63 | hour += 1 64 | return M_r 65 | 66 | #-Leaf drip momentum (kg2/s3) 67 | def MomentumLeafDrip(self, pcr, d_l, X, rho, DRAINA, g, C_c): 68 | a_2 = pcr.scalar(pcr.pcrand(d_l >= 0.033, X >= 7.5)) * 5.14 69 | a_2 = a_2 + pcr.scalar(pcr.pcrand(d_l >= 0.033, X < 7.5)) * 1.93 70 | a_2 = a_2 + pcr.scalar(d_l < 0.033) * 0 71 | 72 | b_2 = pcr.scalar(pcr.pcrand(d_l >= 0.033, X >= 7.5)) * 660 73 | b_2 = b_2 + pcr.scalar(pcr.pcrand(d_l >= 0.033, X < 7.5)) * 1640 74 | b_2 = b_2 + pcr.scalar(d_l < 0.033) * 2200 75 | 76 | M_beta = a_2 + b_2 * d_l 77 | V_d = (M_beta * g * (1 - pcr.exp(-2*X/M_beta)))**0.5 78 | 79 | L_d = C_c 80 | 81 | M_d = self.pi / 6 * V_d**2 * rho**2 * d_l**3 * L_d * DRAINA 82 | return M_d 83 | 84 | #-Detachment of soil particles by runoff (kg/m2/s) 85 | def DetachmentRunoff(self, pcr, k_f, C_r, tau, tau_cr, C_g): 86 | D_q = pcr.ifthenelse(tau > tau_cr, k_f * pcr.max(0, 1 - C_g - C_r - self.NoErosion_SHETRAN) * (tau/tau_cr - 1), 0) 87 | 88 | #-set values in channels to 0 in case channels should be excluded 89 | if self.exclChannelsFLAG == 1: 90 | D_q = D_q * self.Hillslope 91 | return D_q 92 | 93 | #-Water depth (m) and flow width (m) 94 | def Manning(self, pcr, Q, n, WD_ratio, S): 95 | A = ((Q * n * (2 * ((WD_ratio**2 + 1) / WD_ratio)**0.5)**(2/3)) / S**0.5)**(3/4) 96 | h = (A / WD_ratio)**0.5 97 | l = WD_ratio * h 98 | return h, l 99 | 100 | #-Shear stress (N/m2) 101 | def ShearStress(self, pcr, rho, g, h, S): 102 | tau = rho * g * h * S 103 | return tau 104 | 105 | #-Critical shear stress (N/m2) 106 | def ShearStressCritical(self, pcr, tau, rho_s, rho, g, D_50, nu): 107 | R_star = pcr.max(0.03, (D_50 * (tau / rho)**0.5) / nu) 108 | 109 | a_3 = pcr.scalar(R_star > 400) * 0.056 110 | a_3 = a_3 + pcr.scalar(pcr.pcrand(R_star > 135, R_star <= 400)) * 0.03 111 | a_3 = a_3 + pcr.scalar(pcr.pcrand(R_star > 30, R_star <= 135)) * 0.013 112 | a_3 = a_3 + pcr.scalar(pcr.pcrand(R_star > 6, R_star <= 30)) * 0.033 113 | a_3 = a_3 + pcr.scalar(pcr.pcrand(R_star > 1, R_star <= 6)) * 0.1 114 | a_3 = a_3 + pcr.scalar(pcr.pcrand(R_star >= 0.03, R_star <= 1)) * 0.1 115 | 116 | b_3 = pcr.scalar(R_star > 400) * 0 117 | b_3 = b_3 + pcr.scalar(pcr.pcrand(R_star > 135, R_star <= 400)) * 0.1 118 | b_3 = b_3 + pcr.scalar(pcr.pcrand(R_star > 30, R_star <= 135)) * 0.28 119 | b_3 = b_3 + pcr.scalar(pcr.pcrand(R_star > 6, R_star <= 30)) * 0 120 | b_3 = b_3 + pcr.scalar(pcr.pcrand(R_star > 1, R_star <= 6)) * -0.62 121 | b_3 = b_3 + pcr.scalar(pcr.pcrand(R_star >= 0.03, R_star <= 1)) * -0.3 122 | 123 | tau_cr = (rho_s - rho) * g * D_50 * a_3 * R_star**b_3 124 | return tau_cr 125 | 126 | 127 | #-Capacity particulate transport rate for overland flow (m3/s) 128 | def Capacity(self, pcr, np, tau, tau_cr, rho, rho_s, g, h, l, Q, D50, S): 129 | if self.CapacityEquation == 1: # Yalin (1963) 130 | a = 2.45 * (tau_cr / ((rho_s - rho) * g * D50))**0.5 * (rho_s / rho)**(-0.4) 131 | delta = pcr.max(tau / tau_cr - 1, 0) 132 | 133 | G_tot = 0.635 * (tau / rho)**0.5 * l * D50 * delta * (1 - 1 / (a * pcr.max(1e-6, delta)) * pcr.ln(1 + a * delta)) 134 | elif self.CapacityEquation == 2: # Engelund & Hansen (1963) 135 | G_tot = pcr.ifthenelse(h > 0, (0.05 * Q**2 * S**(3/2)) / ((g * h)**0.5 * (rho_s / rho - 1)**2 * D50 * l), 0) 136 | return G_tot 137 | 138 | #-Mass of sediment transported (kg/m2/s) 139 | def sedimentTransported(self, pcr, D_r, D_q, G_tot, rho_s): 140 | #-determine transport capacity in (kg/m2/s) 141 | TC = G_tot * rho_s / pcr.cellarea() 142 | sed = pcr.ifthenelse(D_r + D_q < TC, D_r + D_q, TC) 143 | return sed 144 | 145 | #-init processes shetran 146 | def init(self, pcr, config): 147 | #-read table with SHETRAN landuse specific model parameters 148 | pcr.setglobaloption('matrixtable') 149 | shetran_table = self.inpath + config.get('SHETRAN', 'shetran_table') 150 | self.d_l_SHETRAN = pcr.lookupscalar(shetran_table, 1, self.LandUse) 151 | self.X_SHETRAN = pcr.lookupscalar(shetran_table, 2, self.LandUse) 152 | self.C_g_SHETRAN = pcr.lookupscalar(shetran_table, 3, self.LandUse) 153 | self.C_c_table_SHETRAN = pcr.lookupscalar(shetran_table, 4, self.LandUse) 154 | self.n_table_SHETRAN = pcr.lookupscalar(shetran_table, 5, self.LandUse) 155 | self.NoErosion_SHETRAN = pcr.lookupscalar(shetran_table, 6, self.LandUse) 156 | pcr.setglobaloption('columntable') 157 | 158 | #-read other model parameters 159 | self.WD_ratio_SHETRAN = config.getfloat('SHETRAN', 'WD_ratio') 160 | self.rho_SHETRAN = config.getfloat('SHETRAN', 'rho') 161 | self.rho_s_SHETRAN = config.getfloat('SHETRAN', 'rho_s') 162 | self.deltaClay_SHETRAN = config.getfloat('SHETRAN', 'deltaClay') * 1e-6 163 | self.deltaSilt_SHETRAN = config.getfloat('SHETRAN', 'deltaSilt') * 1e-6 164 | self.deltaSand_SHETRAN = config.getfloat('SHETRAN', 'deltaSand') * 1e-6 165 | self.CapacityEquation = config.getint('SHETRAN', 'capacityEquation') 166 | self.k_r_SHETRAN = config.getfloat('SHETRAN', 'k_r') 167 | self.k_f_SHETRAN = config.getfloat('SHETRAN', 'k_f') 168 | 169 | #-define some constants 170 | self.F_w_SHETRAN = 1 171 | self.g_SHETRAN = 9.81 172 | self.nu_SHETRAN = 1e-06 173 | 174 | #-determine median grain size 175 | if self.PedotransferFLAG == 1: 176 | self.D50_SHETRAN = pcr.ifthenelse(self.RootClayMap > 0.5, pcr.scalar(self.deltaClay_SHETRAN), 0) 177 | self.D50_SHETRAN = pcr.ifthenelse(self.RootClayMap + self.RootSiltMap > 0.5, self.deltaClay_SHETRAN + (self.deltaSilt_SHETRAN - self.deltaClay_SHETRAN) * (0.5 - self.RootClayMap) / self.RootSiltMap, 0) + self.D50_SHETRAN 178 | self.D50_SHETRAN = pcr.ifthenelse(self.RootClayMap + self.RootSiltMap < 0.5, self.deltaSilt_SHETRAN + (self.deltaSand_SHETRAN - self.deltaSilt_SHETRAN) * (self.RootSandMap - 0.5) / self.RootSandMap, 0) + self.D50_SHETRAN 179 | else: 180 | self.D50_SHETRAN = config.getfloat('SHETRAN', 'D50') * 1e-6 181 | 182 | 183 | #-dynamic processes shetran 184 | def dynamic(self, pcr, np, Precip, Q): 185 | #-determine canopy cover from LAI 186 | if self.DynVegFLAG == 1: 187 | C_c_SHETRAN = pcr.min(1, self.LAI) 188 | else: 189 | C_c_SHETRAN = self.C_c_table_SHETRAN 190 | 191 | #-determine rainfall drop momentum (kg2/s3) 192 | M_r = self.shetran.MomentumRainDrop(self, pcr, np, C_c_SHETRAN, Precip) 193 | 194 | #-determine water drainage rate from canopy (m/s) 195 | DRAINA = Precip * 1e-3 / (24 * 60 * 60) 196 | 197 | #-determine leaf drop momentum (kg2/s3) 198 | M_d = self.shetran.MomentumLeafDrip(self, pcr, self.d_l_SHETRAN, self.X_SHETRAN, self.rho_SHETRAN, DRAINA, self.g_SHETRAN, C_c_SHETRAN) 199 | 200 | #-determine detachment of soil particles by raindrop impact (kg/m2/s) 201 | D_r = self.shetran.DetachmentRaindrop(self, pcr, self.k_r_SHETRAN, self.F_w_SHETRAN, self.C_g_SHETRAN, self.RockFrac, M_r, M_d) 202 | 203 | #-report detachment of soil particles by raindrop impact (ton / cell) 204 | self.reporting.reporting(self, pcr, 'DetRn', D_r * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 205 | 206 | #-determine water depth (m) and width of the flow (m) 207 | h, l = self.shetran.Manning(self, pcr, Q, self.n_table_SHETRAN, self.WD_ratio_SHETRAN, self.Slope) 208 | 209 | #-determine shear stress (N/m2) 210 | tau = self.shetran.ShearStress(self, pcr, self.rho_SHETRAN, self.g_SHETRAN, h, self.Slope) 211 | 212 | #-determine shear stress (N/m2) 213 | tau_cr = self.shetran.ShearStressCritical(self, pcr, tau, self.rho_s_SHETRAN, self.rho_SHETRAN, self.g_SHETRAN, self.D50_SHETRAN, self.nu_SHETRAN) 214 | 215 | #-determine detachment of soil particles by runoff (kg/m2/s) 216 | D_q = self.shetran.DetachmentRunoff(self, pcr, self.k_f_SHETRAN, self.RockFrac, tau, tau_cr, self.C_g_SHETRAN) 217 | 218 | #-report detachment of soil particles by runoff (ton / cell) 219 | self.reporting.reporting(self, pcr, 'DetRun', D_q * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 220 | 221 | #-Determine transport capacity of the flow (m3/s) 222 | G_tot = self.shetran.Capacity(self, pcr, np, tau, tau_cr, self.rho_SHETRAN, self.rho_s_SHETRAN, self.g_SHETRAN, h, l, Q, self.D50_SHETRAN, self.Slope) 223 | 224 | #-determine mass of sediment in transport (kg/m2/s) 225 | sed = self.shetran.sedimentTransported(self, pcr, D_r, D_q, G_tot, self.rho_s_SHETRAN) 226 | 227 | #-report sediment in transport (ton / cell) 228 | self.reporting.reporting(self, pcr, 'SedTrans', sed * pcr.cellarea() * 1e-3 * (24 * 60 * 60)) 229 | 230 | return sed 231 | -------------------------------------------------------------------------------- /modules/lakes.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | print("Lake module imported") 23 | 24 | 25 | # -Function that updates the lake storage and lake level given a measured lake level. If no lake 26 | # level is measured, then the actual storage is not updated with a measured level. The function 27 | # returns the updated storage and lake level 28 | def UpdateLakeHStore(self, pcr, pcrm): 29 | # -buffer actual storage 30 | OldStorage = self.StorRES 31 | # -Check if measured lake levels area available 32 | try: 33 | LakeLevel = pcr.readmap(pcrm.generateNameT(self.LLevel, self.counter)) 34 | Level = True 35 | except: 36 | Level = False 37 | if Level: 38 | # -update lake storage according to measured water level 39 | self.StorRES = pcr.ifthenelse( 40 | self.UpdateLakeLevel, 41 | pcr.ifthenelse( 42 | pcr.defined(LakeLevel), 43 | pcr.ifthenelse( 44 | self.LakeSH_Func == 1, 45 | self.LakeSH_exp_a * pcr.exp(self.LakeSH_exp_b * LakeLevel), 46 | pcr.ifthenelse( 47 | self.LakeSH_Func == 2, 48 | self.LakeSH_pol_a1 * LakeLevel + self.LakeSH_pol_b, 49 | pcr.ifthenelse( 50 | self.LakeSH_Func == 3, 51 | (self.LakeSH_pol_a2 * LakeLevel**2) 52 | + self.LakeSH_pol_a1 * LakeLevel 53 | + self.LakeSH_pol_b, 54 | (self.LakeSH_pol_a3 * LakeLevel**3) 55 | + (self.LakeSH_pol_a2 * LakeLevel**2) 56 | + (self.LakeSH_pol_a1 * LakeLevel + self.LakeSH_pol_b), 57 | ), 58 | ), 59 | ), 60 | self.StorRES, 61 | ), 62 | self.StorRES, 63 | ) 64 | # prevent storage becoming negative for whatever reason 65 | self.StorRES = pcr.max(self.StorRES, 0) 66 | # -Update the lake level based on the storage for lakes where no levels are measured 67 | LakeLevel = pcr.ifthenelse( 68 | self.UpdateLakeLevel, 69 | pcr.ifthenelse( 70 | pcr.defined(LakeLevel), 71 | LakeLevel, 72 | pcr.ifthenelse( 73 | self.LakeHS_Func == 1, 74 | self.LakeHS_exp_a * pcr.exp(self.LakeHS_exp_b * self.StorRES), 75 | pcr.ifthenelse( 76 | self.LakeHS_Func == 2, 77 | self.LakeHS_pol_a1 * self.StorRES + self.LakeHS_pol_b, 78 | pcr.ifthenelse( 79 | self.LakeHS_Func == 3, 80 | (self.LakeHS_pol_a2 * self.StorRES**2) 81 | + self.LakeHS_pol_a1 * self.StorRES 82 | + self.LakeHS_pol_b, 83 | (self.LakeHS_pol_a3 * self.StorRES**3) 84 | + (self.LakeHS_pol_a2 * self.StorRES**2) 85 | + self.LakeHS_pol_a1 * self.StorRES 86 | + self.LakeHS_pol_b, 87 | ), 88 | ), 89 | ), 90 | ), 91 | pcr.ifthenelse( 92 | self.LakeHS_Func == 1, 93 | self.LakeHS_exp_a * pcr.exp(self.LakeHS_exp_b * self.StorRES), 94 | pcr.ifthenelse( 95 | self.LakeHS_Func == 2, 96 | self.LakeHS_pol_a1 * self.StorRES + self.LakeHS_pol_b, 97 | pcr.ifthenelse( 98 | self.LakeHS_Func == 3, 99 | (self.LakeHS_pol_a2 * self.StorRES**2) 100 | + self.LakeHS_pol_a1 * self.StorRES 101 | + self.LakeHS_pol_b, 102 | (self.LakeHS_pol_a3 * self.StorRES**3) 103 | + (self.LakeHS_pol_a2 * self.StorRES**2) 104 | + self.LakeHS_pol_a1 * self.StorRES 105 | + self.LakeHS_pol_b, 106 | ), 107 | ), 108 | ), 109 | ) 110 | 111 | else: 112 | # if no lake level map is available, then calculate the h based on storages 113 | LakeLevel = pcr.ifthenelse( 114 | self.LakeHS_Func == 1, 115 | self.LakeHS_exp_a * pcr.exp(self.LakeHS_exp_b * self.StorRES), 116 | pcr.ifthenelse( 117 | self.LakeHS_Func == 2, 118 | self.LakeHS_pol_a1 * self.StorRES + self.LakeHS_pol_b, 119 | pcr.ifthenelse( 120 | self.LakeHS_Func == 3, 121 | (self.LakeHS_pol_a2 * self.StorRES**2) 122 | + self.LakeHS_pol_a1 * self.StorRES 123 | + self.LakeHS_pol_b, 124 | (self.LakeHS_pol_a3 * self.StorRES**3) 125 | + (self.LakeHS_pol_a2 * self.StorRES**2) 126 | + self.LakeHS_pol_a1 * self.StorRES 127 | + self.LakeHS_pol_b, 128 | ), 129 | ), 130 | ) 131 | self.StorRES = pcr.ifthenelse(self.LakeID != 0, self.StorRES, OldStorage) 132 | return LakeLevel, self.StorRES 133 | 134 | 135 | # -function that calculates the fraction of lake storage that is available for routing, and the lake outflow 136 | def QLake(self, pcr, LakeLevel): 137 | Qout = pcr.ifthenelse( 138 | self.LakeQH_Func == 1, 139 | self.LakeQH_exp_a * pcr.exp(self.LakeQH_exp_b * LakeLevel), 140 | pcr.ifthenelse( 141 | self.LakeQH_Func == 2, 142 | self.LakeQH_pol_a1 * LakeLevel + self.LakeQH_pol_b, 143 | pcr.ifthenelse( 144 | self.LakeQH_Func == 3, 145 | (self.LakeQH_pol_a2 * LakeLevel**2) 146 | + self.LakeQH_pol_a1 * LakeLevel 147 | + self.LakeQH_pol_b, 148 | (self.LakeQH_pol_a3 * LakeLevel**3) 149 | + (self.LakeQH_pol_a2 * LakeLevel**2) 150 | + self.LakeQH_pol_a1 * LakeLevel 151 | + self.LakeQH_pol_b, 152 | ), 153 | ), 154 | ) 155 | Qout = pcr.max(0, Qout) 156 | Qout = Qout * 3600 * 24 # -convert to m3/d 157 | Qout = pcr.cover(Qout, 0) # -for non-lake cells, Qout is zero 158 | return Qout 159 | 160 | 161 | # -init processes lake 162 | def init(self, pcr, config): 163 | # -set the option to calculate the lake inflow, outflow and storage per component 164 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 165 | for i in pars: 166 | var = "Rep" + i + "_FLAG" 167 | setattr(self, var, config.getint("REPORTING", var)) 168 | 169 | pcr.setglobaloption("matrixtable") 170 | # nominal map with lake IDs 171 | self.LakeID = pcr.cover(pcr.readmap(self.inpath + config.get("LAKE", "LakeId")), 0) 172 | # lookup table with function for each lake (exp, 1-order poly, 2-order poly, 3-order poly) 173 | LakeFunc_Tab = self.inpath + config.get("LAKE", "LakeFunc") 174 | # lookup table with Qh-coeficients for each lake 175 | LakeQH_Tab = self.inpath + config.get("LAKE", "LakeQH") 176 | # lookup table with Sh-coeficients for each lake 177 | LakeSH_Tab = self.inpath + config.get("LAKE", "LakeSH") 178 | # lookup table with hS-coeficients for each lake 179 | LakeHS_Tab = self.inpath + config.get("LAKE", "LakeHS") 180 | # create lake coefficient maps 181 | self.LakeQH_Func = pcr.lookupnominal(LakeFunc_Tab, 1, self.LakeID) 182 | self.LakeSH_Func = pcr.lookupnominal(LakeFunc_Tab, 2, self.LakeID) 183 | self.LakeHS_Func = pcr.lookupnominal(LakeFunc_Tab, 3, self.LakeID) 184 | # Read QH coefficients 185 | self.LakeQH_exp_a = pcr.lookupscalar(LakeQH_Tab, 1, self.LakeID) 186 | self.LakeQH_exp_b = pcr.lookupscalar(LakeQH_Tab, 2, self.LakeID) 187 | self.LakeQH_pol_b = pcr.lookupscalar(LakeQH_Tab, 3, self.LakeID) 188 | self.LakeQH_pol_a1 = pcr.lookupscalar(LakeQH_Tab, 4, self.LakeID) 189 | self.LakeQH_pol_a2 = pcr.lookupscalar(LakeQH_Tab, 5, self.LakeID) 190 | self.LakeQH_pol_a3 = pcr.lookupscalar(LakeQH_Tab, 6, self.LakeID) 191 | # Read SH coefficients 192 | self.LakeSH_exp_a = pcr.lookupscalar(LakeSH_Tab, 1, self.LakeID) 193 | self.LakeSH_exp_b = pcr.lookupscalar(LakeSH_Tab, 2, self.LakeID) 194 | self.LakeSH_pol_b = pcr.lookupscalar(LakeSH_Tab, 3, self.LakeID) 195 | self.LakeSH_pol_a1 = pcr.lookupscalar(LakeSH_Tab, 4, self.LakeID) 196 | self.LakeSH_pol_a2 = pcr.lookupscalar(LakeSH_Tab, 5, self.LakeID) 197 | self.LakeSH_pol_a3 = pcr.lookupscalar(LakeSH_Tab, 6, self.LakeID) 198 | # Read HS coefficients 199 | self.LakeHS_exp_a = pcr.lookupscalar(LakeHS_Tab, 1, self.LakeID) 200 | self.LakeHS_exp_b = pcr.lookupscalar(LakeHS_Tab, 2, self.LakeID) 201 | self.LakeHS_pol_b = pcr.lookupscalar(LakeHS_Tab, 3, self.LakeID) 202 | self.LakeHS_pol_a1 = pcr.lookupscalar(LakeHS_Tab, 4, self.LakeID) 203 | self.LakeHS_pol_a2 = pcr.lookupscalar(LakeHS_Tab, 5, self.LakeID) 204 | self.LakeHS_pol_a3 = pcr.lookupscalar(LakeHS_Tab, 6, self.LakeID) 205 | # -read water level maps and parameters if available 206 | try: 207 | self.UpdateLakeLevel = pcr.readmap( 208 | self.inpath + config.get("LAKE", "updatelakelevel") 209 | ) 210 | self.LLevel = self.inpath + config.get("LAKE", "LakeFile") 211 | print("measured lake levels will be used to update lake storage") 212 | except: 213 | pass 214 | pcr.setglobaloption("columntable") 215 | 216 | 217 | # -initial conditions lakes 218 | def initial(self, pcr, config): 219 | LakeStor_Tab = self.inpath + config.get("LAKE", "LakeStor") 220 | self.StorRES = ( 221 | pcr.cover(pcr.lookupscalar(LakeStor_Tab, 1, self.LakeID), 0) * 10**6 222 | ) # convert to m3 223 | # -Qfrac for lake cells should be zero, else 1 224 | self.QFRAC = pcr.ifthenelse(self.LakeID != 0, pcr.scalar(0), 1) 225 | 226 | 227 | # -initial conditions reporting lakes 228 | def initial_reporting(self, pcr, pcrm): 229 | self.LakeInTSS = pcrm.TimeoutputTimeseries( 230 | "LakeInTSS", self, self.LakeID, noHeader=True 231 | ) 232 | self.LakeOutTSS = pcrm.TimeoutputTimeseries( 233 | "LakeOutTSS", self, self.LakeID, noHeader=True 234 | ) 235 | self.LakeStorTSS = pcrm.TimeoutputTimeseries( 236 | "LakeStorTSS", self, self.LakeID, noHeader=True 237 | ) 238 | # -set reporting of water balances for individual components 239 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 240 | for i in pars: 241 | if eval("self." + i + "RA_FLAG") and getattr(self, "Rep" + i + "_FLAG"): 242 | setattr( 243 | self, 244 | "Lake" + i + "InTSS", 245 | pcrm.TimeoutputTimeseries( 246 | "Lake" + i + "InTSS", self, self.ResID, noHeader=True 247 | ), 248 | ) 249 | setattr( 250 | self, 251 | "Lake" + i + "OutTSS", 252 | pcrm.TimeoutputTimeseries( 253 | "Lake" + i + "OutTSS", self, self.ResID, noHeader=True 254 | ), 255 | ) 256 | setattr( 257 | self, 258 | "Lake" + i + "StorTSS", 259 | pcrm.TimeoutputTimeseries( 260 | "Lake" + i + "StorTSS", self, self.ResID, noHeader=True 261 | ), 262 | ) 263 | -------------------------------------------------------------------------------- /utilities/netcdf2PCraster.py: -------------------------------------------------------------------------------- 1 | # Tool to force the SPHY model with NetCDF files 2 | # Copyright (C) 2018-2019 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import subprocess 19 | import netCDF4 as nc 20 | import os 21 | import numpy as np 22 | # import sys 23 | # np.set_printoptions(threshold=sys.maxsize) 24 | import csv 25 | from scipy.interpolate import griddata 26 | from scipy import spatial 27 | from scipy.spatial import distance 28 | from pyproj import Proj, transform 29 | from math import * 30 | 31 | #-file cache to minimize/reduce opening/closing files 32 | filecache = dict() 33 | 34 | #-initial processes to determine the x and coordinates of the model grid and netcdf grid 35 | def netcdf2pcrInit(self, pcr, forcing): 36 | #-define input and ouput projections 37 | if getattr(self, forcing + 'InProj') == "rotated": 38 | inProj = Proj(init="epsg:4326") 39 | else: 40 | inProj = Proj(init = getattr(self, forcing + 'InProj')) 41 | outProj = Proj(init = getattr(self, forcing + 'OutProj')) 42 | 43 | #-get the attributes of cloneMap 44 | attributeClone = getMapAttributesALL(self.clonefile) 45 | cellsizeClone = attributeClone['cellsize'] 46 | rowsClone = attributeClone['rows'] 47 | colsClone = attributeClone['cols'] 48 | xULClone = attributeClone['xUL'] 49 | yULClone = attributeClone['yUL'] 50 | 51 | #-read netcdf file 52 | f = nc.Dataset(getattr(self, forcing + 'NC')) 53 | filecache[getattr(self, forcing + 'NC')] = f 54 | 55 | #-get coordinates of upper right and lower left corners of model grid 56 | xURClone = xULClone + cellsizeClone * colsClone 57 | yURClone = yULClone 58 | xLLClone = xULClone 59 | yLLClone = yULClone - cellsizeClone * rowsClone 60 | yLRClone = yLLClone 61 | xLRClone = xURClone 62 | 63 | #-transform coordinates to netcdf projection coordinates 64 | xULCloneInput,yULCloneInput = transform(outProj, inProj, xULClone, yULClone) 65 | xURCloneInput,yURCloneInput = transform(outProj, inProj, xURClone, yURClone) 66 | xLRCloneInput,yLRCloneInput = transform(outProj, inProj, xLRClone, yLRClone) 67 | xLLCloneInput,yLLCloneInput = transform(outProj, inProj, xLLClone, yLLClone) 68 | 69 | #-determine netcdf cell size and subset coordinates to model domain 70 | if getattr(self, forcing + 'InProj') == "rotated": 71 | #-get coordinates from netcdf file 72 | xrot = f.variables[getattr(self, forcing + 'VarX')][:] 73 | yrot = f.variables[getattr(self, forcing + 'VarY')][:] 74 | 75 | #-get coordinates of north pole 76 | npLat = f.variables[getattr(self, forcing + 'VarX')].grid_north_pole_latitude 77 | npLon = f.variables[getattr(self, forcing + 'VarX')].grid_north_pole_longitude 78 | 79 | #-transform x and y coordinates to grid 80 | xrot,yrot = np.meshgrid(xrot, yrot) 81 | 82 | #-transform rotated grid to lat,lon-coordinates 83 | xLatLon = xrot * 0 84 | yLatLon = yrot * 0 85 | for idx, row in enumerate(xrot): 86 | for idy, val in enumerate(row): 87 | x, y = rotated_grid_transform((xrot[idx, idy], yrot[idx, idy]), 2, (npLon, npLat)) 88 | xLatLon[idx, idy] = x 89 | yLatLon[idx, idy] = y 90 | 91 | #-transform x,y-coordinates to 2d array 92 | xyLatLon = [np.array(xLatLon).flatten(), np.array(yLatLon).flatten()] 93 | xyLatLon = list(map(list, zip(*xyLatLon))) 94 | 95 | #-function to find closest node from list of coordinates 96 | def closest_node(node, nodes): 97 | closest_index = distance.cdist([node], nodes).argmin() 98 | indices = np.where(np.ma.getdata(xLatLon) == nodes[closest_index][0]) 99 | indices = np.array(indices).flatten().astype('int32') 100 | return indices.tolist() 101 | 102 | #-get indices of corner points clone map from netcdf 103 | indicesUL = closest_node((xULCloneInput,yULCloneInput), xyLatLon) 104 | indicesLL = closest_node((xLLCloneInput,yLLCloneInput), xyLatLon) 105 | indicesUR = closest_node((xURCloneInput,yURCloneInput), xyLatLon) 106 | indicesLR = closest_node((xLRCloneInput,yLRCloneInput), xyLatLon) 107 | 108 | #-determine indices of the corners of netcdf grid corresponding to model grid (+ buffer) 109 | xyUL = max(min(indicesUL[0], indicesLL[0], indicesUR[0], indicesLR[0]) - 2, 0) 110 | xyLL = min(max(indicesUL[0], indicesLL[0], indicesUR[0], indicesLR[0]) + 2, xLatLon.shape[0] - 1) 111 | xyUR = max(min(indicesUL[1], indicesLL[1], indicesUR[1], indicesLR[1]) - 2, 0) 112 | xyLR = min(max(indicesUL[1], indicesLL[1], indicesUR[1], indicesLR[1]) + 2, xLatLon.shape[1] - 1) 113 | 114 | #-determine x,y-coordinates corresponding to model grid (+ buffer) from netcdf grid 115 | x = xLatLon[xyUL:(xyLL + 1), xyUR:(xyLR + 1)] 116 | y = yLatLon[xyUL:(xyLL + 1), xyUR:(xyLR + 1)] 117 | 118 | else: 119 | #-get cell size, number of rows and columns and upper left corner coordinates from netcdf grid 120 | cellsizeInput = f.variables[getattr(self, forcing + 'VarY')][1]- f.variables[getattr(self, forcing + 'VarY')][0] 121 | cellsizeInput = float(cellsizeInput) 122 | 123 | #-determine x-coordinates corresponding to model grid (+ buffer) from netcdf grid 124 | xIdxSta = np.argmin(abs(f.variables[getattr(self, forcing + 'VarX')][:] - (min(xULCloneInput, xLLCloneInput) - 2 * cellsizeInput))) 125 | xIdxEnd = np.argmin(abs(f.variables[getattr(self, forcing + 'VarX')][:] - (max(xURCloneInput, xLRCloneInput) + 2 * cellsizeInput))) 126 | x = f.variables[getattr(self, forcing + 'VarX')][xIdxSta:(xIdxEnd + 1)] 127 | 128 | #-determine y-coordinates corresponding to model grid (+ buffer) from netcdf grid 129 | yIdxEnd = np.argmin(abs(f.variables[getattr(self, forcing + 'VarY')][:] - (max(yULCloneInput, yURCloneInput) + 2 * cellsizeInput))) 130 | yIdxSta = np.argmin(abs(f.variables[getattr(self, forcing + 'VarY')][:] - (min(yLLCloneInput, yLRCloneInput) - 2 * cellsizeInput))) 131 | y = f.variables[getattr(self, forcing + 'VarY')][yIdxSta:(yIdxEnd + 1)] 132 | 133 | #-transform x and y coordinates to grid 134 | x,y = np.meshgrid(x, y) 135 | 136 | #-project x and y coordinates to model grid projection 137 | x,y = transform(inProj, outProj, x, y) 138 | 139 | #-transform x and y coordinates to arrays 140 | x = np.asarray(x).ravel() 141 | y = np.asarray(y).ravel() 142 | 143 | #-determine model grid x and y coordinates and save in grid 144 | xi = np.arange(xULClone + cellsizeClone * 0.5, (xULClone + cellsizeClone * 0.5) + colsClone * cellsizeClone, cellsizeClone) 145 | yi = np.arange((yULClone + cellsizeClone * 0.5) - rowsClone * cellsizeClone, yULClone + cellsizeClone * 0.5, cellsizeClone) 146 | yi = np.flipud(yi) 147 | xi,yi = np.meshgrid(xi,yi) 148 | 149 | #-determine x,y-coordinates of netcdf file and model domain and indices of netcdf corresponding to model domain 150 | setattr(self, forcing + 'x', x) 151 | setattr(self, forcing + 'y', y) 152 | setattr(self, forcing + 'xi', xi) 153 | setattr(self, forcing + 'yi', yi) 154 | if getattr(self, forcing + 'InProj') == "rotated": 155 | setattr(self, forcing + 'xyUL', xyUL) 156 | setattr(self, forcing + 'xyLL', xyLL) 157 | setattr(self, forcing + 'xyUR', xyUR) 158 | setattr(self, forcing + 'xyLR', xyLR) 159 | else: 160 | setattr(self, forcing + 'xIdxSta', xIdxSta) 161 | setattr(self, forcing + 'xIdxEnd', xIdxEnd) 162 | setattr(self, forcing + 'yIdxSta', yIdxSta) 163 | setattr(self, forcing + 'yIdxEnd', yIdxEnd) 164 | 165 | #-function to interpolate netcdf gridded data to model grid 166 | def netcdf2pcrDynamic(self, pcr, forcing): #ncFile, varName, dateInput, method, factor, x, y, xi, yi, xIdxSta, xIdxEnd, yIdxSta, yIdxEnd): 167 | #-read netcdf file 168 | f = nc.Dataset(getattr(self, forcing + 'NC')) 169 | filecache[getattr(self, forcing + 'NC')] = f 170 | 171 | #-get index from netcdf corresponding with current date 172 | idx = int(nc.date2index(self.curdate, f.variables['time'], select ='exact')) 173 | 174 | #-get raw netcdf gridded data from netcdf, transform to array and multiply with factor 175 | if getattr(self, forcing + 'InProj') == "rotated": 176 | z = f.variables[getattr(self, forcing + 'VarName')][idx, getattr(self, forcing + 'xyUL'):(getattr(self, forcing + 'xyLL') + 1), getattr(self, forcing + 'xyUR'):(getattr(self, forcing + 'xyLR') + 1)] 177 | else: 178 | z = f.variables[getattr(self, forcing + 'VarName')][idx, getattr(self, forcing + 'yIdxSta'):(getattr(self, forcing + 'yIdxEnd') + 1), getattr(self, forcing + 'xIdxSta'):(getattr(self, forcing + 'xIdxEnd') + 1)] 179 | z = np.asarray(z).ravel() 180 | with np.errstate(invalid='ignore'): # surpress error message when there are already nans in the z array 181 | z = np.where(z<=-9999, np.nan, z) * getattr(self, forcing + 'Factor') 182 | 183 | #-remove nans from arrays 184 | x = getattr(self, forcing + 'x')[~np.isnan(z)] 185 | y = getattr(self, forcing + 'y')[~np.isnan(z)] 186 | z = z[~np.isnan(z)] 187 | 188 | #-interpolate with method (linear or cubic) 189 | zi = griddata((x, y), z, (getattr(self, forcing + 'xi'), getattr(self, forcing + 'yi')), method=getattr(self, forcing + 'Method')) 190 | zi = np.where(np.isnan(zi), -9999, zi) 191 | 192 | #-convert to PCRaster Python map 193 | output = pcr.numpy2pcr(pcr.Scalar, zi, -9999) 194 | 195 | return output 196 | 197 | #-function to interpolate netcdf gridded data to model grid 198 | def netcdf2pcrTimeIdx(self, pcr, forcing): #ncFile, varName, dateInput, method, factor, x, y, xi, yi, xIdxSta, xIdxEnd, yIdxSta, yIdxEnd): 199 | #-read netcdf file 200 | f = nc.Dataset(getattr(self, forcing + 'NC')) 201 | filecache[getattr(self, forcing + 'NC')] = f 202 | 203 | #-get index from netcdf corresponding with current date 204 | setattr(self, forcing + 'TimeIdx', nc.date2index(self.curdate, f.variables['time'], select ='exact')) 205 | 206 | #-function to get map attributes from clone map 207 | def getMapAttributesALL(cloneMap): 208 | cOut,err = subprocess.Popen(str('mapattr -p %s ' %(cloneMap)), stdout=subprocess.PIPE, stderr=open(os.devnull), shell=True).communicate() 209 | cellsize = float(cOut.split()[7]) 210 | mapAttr = {'cellsize': float(cellsize) ,\ 211 | 'rows' : float(cOut.split()[3]) ,\ 212 | 'cols' : float(cOut.split()[5]) ,\ 213 | 'xUL' : float(cOut.split()[17]),\ 214 | 'yUL' : float(cOut.split()[19])} 215 | co = None; cOut = None; err = None 216 | del co; del cOut; del err 217 | return mapAttr 218 | 219 | #-function to read the config and 220 | def getConfigNetcdf(self, config, forcing, section): 221 | setattr(self, forcing + 'NC', config.get(section, forcing + 'Netcdf')) 222 | setattr(self, forcing + 'NetcdfInput', config.get(section, forcing + 'NetcdfInput').split(',')) 223 | netcdfInput = getattr(self, forcing + 'NetcdfInput') 224 | setattr(self, forcing + 'VarName', netcdfInput[0]) 225 | setattr(self, forcing + 'VarX', netcdfInput[1]) 226 | setattr(self, forcing + 'VarY', netcdfInput[2]) 227 | setattr(self, forcing + 'Method', netcdfInput[3]) 228 | setattr(self, forcing + 'Factor', float(netcdfInput[4])) 229 | setattr(self, forcing + 'InProj', netcdfInput[5]) 230 | setattr(self, forcing + 'OutProj', netcdfInput[6]) 231 | 232 | 233 | #-function to transform rotated lat-lon to regular lat-lon 234 | def rotated_grid_transform(grid_in, option, SP_coor): 235 | lon = grid_in[0] 236 | lat = grid_in[1] 237 | 238 | if option == 2: 239 | lon = -lon 240 | lat = -lat 241 | 242 | lon = (lon*pi)/180 # Convert degrees to radians 243 | lat = (lat*pi)/180 244 | 245 | SP_lon = SP_coor[0] 246 | SP_lat = SP_coor[1] 247 | 248 | theta = 90+SP_lat # Rotation around y-axis 249 | phi = SP_lon # Rotation around z-axis 250 | 251 | theta = (theta*pi)/180 252 | phi = (phi*pi)/180 # Convert degrees to radians 253 | 254 | x = cos(lon)*cos(lat) # Convert from spherical to cartesian coordinates 255 | y = sin(lon)*cos(lat) 256 | z = sin(lat) 257 | 258 | if option == 1: # Regular -> Rotated 259 | 260 | x_new = cos(theta)*cos(phi)*x + cos(theta)*sin(phi)*y + sin(theta)*z 261 | y_new = -sin(phi)*x + cos(phi)*y 262 | z_new = -sin(theta)*cos(phi)*x - sin(theta)*sin(phi)*y + cos(theta)*z 263 | 264 | else: # Rotated -> Regular 265 | 266 | phi = -phi 267 | theta = -theta 268 | 269 | x_new = cos(theta)*cos(phi)*x + sin(phi)*y + sin(theta)*cos(phi)*z 270 | y_new = -cos(theta)*sin(phi)*x + cos(phi)*y - sin(theta)*sin(phi)*z 271 | z_new = -sin(theta)*x + cos(theta)*z 272 | 273 | 274 | 275 | lon_new = atan2(y_new,x_new) # Convert cartesian back to spherical coordinates 276 | lat_new = asin(z_new) 277 | 278 | lon_new = (lon_new*180)/pi # Convert radians back to degrees 279 | lat_new = (lat_new*180)/pi 280 | 281 | if option == 1: # Regular -> Rotated 282 | lon_new = -lon_new 283 | lat_new = -lat_new 284 | 285 | return lon_new, lat_new 286 | -------------------------------------------------------------------------------- /modules/sediment_transport.py: -------------------------------------------------------------------------------- 1 | # Sediment transport module that determines sediment flux and sediment yield at the stations, 2 | # considering reservoir sedimentation when the reservoir module is used 3 | # Copyright (C) 2015-2019 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 4 | # Email: jeekhout@cebas.csic.es 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | #- Equations for simulating sediment transport 20 | print('Sediment transport module imported') 21 | 22 | #-Sediment transport capacity 23 | def TC(self, pcr, runoff): 24 | #-runoff discharge per unit width in m2/day 25 | q = (runoff/1000) * pcr.celllength() 26 | #-transport capacity calculation ton/day 27 | TC = self.TC_k * q**self.TC_beta * self.Slope**self.TC_gamma 28 | #-only apply TC to cells with runoff (>0) and in the channel (upstream area > upstream_km2) 29 | TC_upstream = pcr.ifthen(pcr.pcrand(self.Channel == 1, runoff > 0), TC) 30 | #-determine average transport capacity per subcatchment 31 | TCSubcatchment = pcr.areaaverage(TC_upstream, self.subcatchmentRes) 32 | #-set all other cells to 0 33 | TCSubcatchment = pcr.cover(TCSubcatchment, 0) 34 | return TC 35 | # return TCSubcatchment 36 | 37 | #-Sediment transport 38 | def SedTrans(self, pcr, np, sed, TC): 39 | #-determine sediment transport without reservoirs 40 | if self.ResFLAG == 0: 41 | #-rout sediment based on transport capacity 42 | sedimentFlux = pcr.accucapacityflux(self.FlowDir, sed, TC) 43 | sedimentYield = pcr.accucapacitystate(self.FlowDir, sed, TC) 44 | sedDep = sedimentYield 45 | 46 | #-determine sediment transport with reservoirs 47 | else: 48 | #-store sed in sedTrans to be used in routing algorithm 49 | sedTrans = sed 50 | 51 | #-initiate empty map to be used in for-loop 52 | sedimentYield = self.DEM * 0 53 | sedimentFlux = self.DEM * 0 54 | subFinished = self.DEM * 0 55 | sedDep = self.DEM * 0 56 | 57 | #-increase the transport capacity in the reservoir cells such that all sediment is transported towards the end of the reservoir 58 | TC = pcr.ifthenelse(pcr.scalar(self.SedReservoirs) > 0, 1e10, TC) 59 | 60 | #-Determine total soil erosion 61 | sedTotal = np.sum(pcr.pcr2numpy(sed, 0)) 62 | 63 | #-Only rout sediment when soil erosion > 0 64 | if (sedTotal > 0): 65 | #-loop through the catchments, rout sediment and determine sedimentation in reservoirs based on trapping efficiency 66 | for step in range(max(self.subcatchmentSteps)+1): #-for-loop through the steps 67 | #-determine the subcatchments for this step 68 | subcatchments = np.where(self.subcatchmentSteps == step)[0] 69 | 70 | #-rout sediment based on transport capacity 71 | sedTransCapFlux = pcr.accucapacityflux(self.FlowDir, sedTrans, TC) 72 | sedTransCapState = pcr.accucapacitystate(self.FlowDir, sedTrans, TC) 73 | 74 | #-initiate empty map to be used in for-loop 75 | stepBool = self.DEM * 0 76 | 77 | #-for-loop through the subcatchments per step 78 | for subcatchment in subcatchments: 79 | #-create boolean map with location of reservoir 80 | reservoirBool = pcr.scalar(pcr.ifthenelse(self.ResSedID == int(self.subcatchmentOrder[subcatchment]), pcr.scalar(1), pcr.scalar(0))) 81 | 82 | #-extract routed sediment value at the reservoir from sedTransCapFlux 83 | reservoirFluxTC = pcr.ifthen(reservoirBool == 1, sedTransCapFlux) 84 | 85 | #-store trapped sediment in sedimentYield (multiply routed sediment value with trapping efficiency to be stored in reservoir cell) 86 | sedimentYield = pcr.ifthenelse(reservoirBool == 1, reservoirFluxTC * self.TrappingEff, sedimentYield) 87 | 88 | #-update subFinished and give subcatchment cells value 1 89 | subFinished = pcr.ifthenelse(pcr.scalar(self.subcatchmentRes) == int(self.subcatchmentOrder[subcatchment]), pcr.scalar(1), subFinished) 90 | 91 | #-update sedTrans, set all subcatchment cells to 0 92 | sedTrans = pcr.ifthenelse(pcr.scalar(subFinished) == 1, 0, sedTrans) 93 | #-add reservoir outflow to cell downstream of reservoir (multiply routed sediment value with outflow efficiency) 94 | sedTrans = sedTrans + pcr.upstream(self.FlowDir, pcr.ifthenelse(reservoirBool == 1, reservoirFluxTC * self.OutflowEff, pcr.scalar(0))) 95 | 96 | #-create boolean map with location of reservoir 97 | stepBool = stepBool + pcr.scalar(pcr.ifthenelse(self.subcatchmentRes == int(self.subcatchmentOrder[subcatchment]), self.subcatchmentRes == int(self.subcatchmentOrder[subcatchment]), pcr.boolean(0))) 98 | 99 | # store sedTransCapFlux in sedimentFlux 100 | sedimentFlux = sedTransCapFlux * subFinished + sedimentFlux 101 | 102 | #-rout sediment based on transport capacity 103 | sedDep = sedDep + sedTransCapState * stepBool 104 | 105 | #-rout sediment based on transport capacity 106 | sedTransCapFlux = pcr.accucapacityflux(self.FlowDir, sedTrans, TC) 107 | 108 | # store sedTransCapFlux in sedimentFlux 109 | sedimentFlux = sedTransCapFlux * (1 - subFinished) + sedimentFlux 110 | 111 | return sedimentYield, sedDep, sedimentFlux 112 | 113 | 114 | #-init processes 115 | def init(self, pcr, config, csv, np): 116 | #-init processes when reservoir module is used 117 | if self.ResFLAG == 1: 118 | #-nominal map with reservoir IDs 119 | self.ResSedID = pcr.cover(self.ResID, 0) 120 | else: 121 | self.ResSedID = self.Locations 122 | 123 | #-determine upstream area map 124 | self.UpstreamArea = pcr.accuflux(self.FlowDir, 1) * pcr.cellarea() / 10**6 125 | 126 | #-determine upstream area smaller than upstream_km2 and define channel cells based on upstream area 127 | self.Upstream_km2 = config.getfloat('SEDIMENT_TRANS', 'upstream_km2') 128 | self.Channel = self.UpstreamArea > self.Upstream_km2 129 | 130 | #-determine average slope per stream based on stream order and averaged per subcatchment 131 | self.Basin = pcr.subcatchment(self.FlowDir, self.ResSedID) 132 | self.StreamOrder = pcr.streamorder(self.FlowDir) 133 | self.Streams = pcr.scalar(self.Channel) * pcr.scalar(self.Basin) * 10 + pcr.scalar(self.Channel) * pcr.scalar(self.StreamOrder) 134 | self.SlopeStreams = pcr.areaaverage(self.Slope, pcr.nominal(self.Streams)) 135 | self.SlopeStreams = pcr.ifthenelse(self.Channel == 1, self.SlopeStreams, self.Slope) 136 | 137 | #-read transport capacity parameters 138 | self.TC_beta = config.getfloat('SEDIMENT_TRANS', 'TC_beta') 139 | self.TC_gamma = config.getfloat('SEDIMENT_TRANS', 'TC_gamma') 140 | 141 | #-init processes when reservoir module is used 142 | if self.ResFLAG == 1: 143 | #-nominal map with reservoir IDs and extent 144 | if self.ETOpenWaterFLAG == 1: 145 | self.SedReservoirs = pcr.cover(self.openWaterNominal, 0) 146 | else: 147 | self.SedReservoirs = pcr.readmap(self.inpath + config.get('RESERVOIR', 'reservoirs')) 148 | self.SedReservoirs = pcr.cover(self.SedReservoirs, 0) 149 | 150 | #-read table with the trapping efficiency per reservoir 151 | self.TrapEffTab = self.inpath + config.get('SEDIMENT_TRANS', 'TrapEffTab') 152 | self.TrappingEff = pcr.cover(pcr.lookupscalar(self.TrapEffTab, self.ResSedID), 0) 153 | 154 | #-construct map where all cells have 1 and only the reservoir cells have trapping efficiency value obtained from the table 155 | self.OutflowEff = pcr.cover(1-pcr.lookupscalar(self.TrapEffTab, self.ResSedID), 1) 156 | 157 | #-determine subcatchment map 158 | self.subcatchmentRes = pcr.subcatchment(self.FlowDir, self.ResSedID) 159 | 160 | #-read reservoir order for sediment transport and add the values to self.subcatchmentOrder and self.subcatchmentSteps 161 | self.ResOrder = config.get('SEDIMENT_TRANS', 'ResOrder') 162 | self.subcatchmentOrder = [] 163 | self.subcatchmentSteps = [] 164 | 165 | #-loop through the rows of the text file 166 | with open(self.inpath + self.ResOrder, 'rt') as f: 167 | next(f) # skip headings 168 | reader = csv.reader(f, delimiter='\t') 169 | for row in reader: 170 | self.subcatchmentOrder = np.append(self.subcatchmentOrder, int(row[0])) 171 | self.subcatchmentOrder = self.subcatchmentOrder.astype(np.int) 172 | self.subcatchmentSteps = np.append(self.subcatchmentSteps, int(row[1])) 173 | self.subcatchmentSteps = self.subcatchmentSteps.astype(np.int) 174 | 175 | #-loop through the steps and define map with step per subcatchment 176 | self.subcatchmentStepsMap = self.DEM * 0 177 | for step in range(max(self.subcatchmentSteps)+1): 178 | #-determine the subcatchments for this step 179 | subcatchments = np.where(self.subcatchmentSteps == step)[0] 180 | 181 | #-for-loop through the subcatchments per step 182 | for subcatchment in subcatchments: 183 | #-update subFinished and give subcatchment cells value 1 184 | self.subcatchmentStepsMap = pcr.ifthenelse(pcr.scalar(self.subcatchmentRes) == int(self.subcatchmentOrder[subcatchment]), pcr.scalar(step + 1), self.subcatchmentStepsMap) 185 | #-set all subcatchments with value 0 to the maximum step 186 | self.subcatchmentStepsMap = pcr.ifthenelse(self.subcatchmentStepsMap == 0, int(max(self.subcatchmentSteps)+1), self.subcatchmentStepsMap) 187 | #-map with step value for stations that are not reservoirs 188 | self.LocationsNoResSteps = pcr.scalar(self.LocationsNoRes) * self.subcatchmentStepsMap 189 | 190 | #-determine roughness factor for mmf only 191 | if self.SedModel == 2: 192 | #-Read flag if channels should be excluded from the detachment by runoff calculation 193 | self.manningChannelsFLAG = config.getint('SEDIMENT_TRANS', 'manningChannelFLAG') 194 | 195 | #-read manning value for channels 196 | if self.manningChannelsFLAG == 1: 197 | self.manningChannel = config.getfloat('SEDIMENT_TRANS', 'manningChannel') 198 | 199 | #-Determine flow velocity for transport capacity calculation 200 | self.n_veg_TC = self.mmf.manningVegetation(self, pcr, self.d_TC, self.Diameter, self.NoElements) 201 | self.n_veg_TC = pcr.ifthenelse(self.NoVegetation == 1, 0, self.n_veg_TC) 202 | self.n_veg_TC = pcr.ifthenelse(self.NoErosion == 1, 0, self.n_veg_TC) 203 | self.n_veg_TC = pcr.ifthenelse(self.n_table > 0, self.n_table, self.n_veg_TC) 204 | self.n_TC = (self.n_soil**2 + self.n_veg_TC**2)**0.5 205 | #-set manning value of channels to predetermined value 206 | if self.manningChannelsFLAG == 1: 207 | self.n_TC = pcr.ifthenelse(self.Channel == 1, self.manningChannel, self.n_TC) 208 | self.v_TC = self.mmf.FlowVelocity(self, pcr, self.n_TC, self.d_TC) 209 | 210 | #-Determine flow velocity after harvest, manning for tilled conditions is used 211 | if self.harvest_FLAG: 212 | self.n_veg_TC_harvest = self.mmf.manningVegetation(self, pcr, self.d_field, self.Diameter_harvest, self.NoElements_harvest) 213 | self.n_veg_TC_harvest = pcr.ifthenelse(self.Tillage_harvest == 1, 0, self.n_veg_field_harvest) 214 | self.n_TC_harvest = (self.n_soil**2 + self.n_veg_TC_harvest**2)**0.5 215 | #-set manning value of channels to predetermined value 216 | if self.manningChannelsFLAG == 1: 217 | self.n_TC_harvest = pcr.ifthenelse(pcr.pcrand(self.Channel == 1, self.n_TC_harvest > 0), self.manningChannel, self.n_TC_harvest) 218 | self.v_TC_harvest = self.mmf.FlowVelocity(self, pcr, self.n_TC_harvest, self.d_TC) 219 | 220 | #-Determine flow velocity for bare soil conditions (reference conditions) 221 | self.v_b = self.mmf.FlowVelocity(self, pcr, self.n_bare, self.d_bare) 222 | 223 | #-Determine roughness factor for transport capacity calculation 224 | self.roughnessFactor = self.v_TC / self.v_b 225 | 226 | #-initial conditions sediment transport 227 | def initial(self, pcr, config): 228 | try: 229 | self.SYieldR = pcr.readmap(self.inpath + config.get('SEDIMENT_TRANS', 'Sed_init')) 230 | except: 231 | self.SYieldR = config.getfloat('SEDIMENT_TRANS', 'Sed_init') 232 | 233 | #-dynamic sediment transport processes musle 234 | def dynamic_musle(self, pcr): 235 | #-transport capacity 236 | TC = self.sediment_transport.TC(self, pcr, (Q * 3600 * 24) / pcr.cellarea() * 1000) 237 | 238 | #-report the transport capacity per subcatchment 239 | self.reporting.reporting(self, pcr, 'TC', TC) 240 | 241 | #-determine sediment yield at reservoirs 242 | tempvar = self.sediment_transport.SedTrans(self, pcr, np, sed, TC) 243 | sedimentYield = tempvar[0] 244 | sedDep = tempvar[1] 245 | 246 | #-report the deposition in channel cells 247 | self.reporting.reporting(self, pcr, 'SedDep', sedDep) 248 | 249 | #-report sediment yield in the reservoirs 250 | self.reporting.reporting(self, pcr, 'SYieldRA', sedimentYield) 251 | 252 | #-dynamic sediment transport processes mmf 253 | def dynamic_mmf(self, pcr, Runoff, np, G): 254 | #-change the flow factor for harvested areas to actual and tillage conditions 255 | if self.harvest_FLAG == 1: 256 | self.roughnessFactorUpdate = pcr.ifthenelse(self.Harvested == 1, self.v_TC_harvest / self.v_b, self.roughnessFactor) 257 | else: 258 | self.roughnessFactorUpdate = self.roughnessFactor 259 | 260 | #-determine transport capacity 261 | TC = self.mmf.TransportCapacity(self, pcr, self.roughnessFactorUpdate, self.RootClayMap + self.RootSiltMap + self.RootSandMap, Runoff) 262 | 263 | #-report the transport capacity 264 | self.reporting.reporting(self, pcr, 'TC', TC) 265 | 266 | #-determine sediment yield at stations 267 | sedYield, sedDep, sedFlux = self.sediment_transport.SedTrans(self, pcr, np, G * pcr.cellarea() / 1000, TC) 268 | 269 | #-report the sediment deposition by transport capacity (ton/day) 270 | self.reporting.reporting(self, pcr, 'SedDep', sedDep) 271 | 272 | #-report sediment yield in the stations (ton/day) 273 | self.reporting.reporting(self, pcr, 'SedYld', sedYield) 274 | 275 | #-report sediment flux in the stations (ton/day) 276 | self.reporting.reporting(self, pcr, 'SedFlux', sedFlux) -------------------------------------------------------------------------------- /modules/mmf.py: -------------------------------------------------------------------------------- 1 | # Soil erosion module using the Morgan-Morgan-Finney soil erosion model 2 | # Copyright (C) 2017-2019 Joris Eekhout / Spanish National Research Council (CEBAS-CSIC) 3 | # Email: jeekhout@cebas.csic.es 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | print('MMF module imported') 19 | 20 | #-Effective rainfall (Rf, mm) 21 | def RainEff(self, pcr, precip): 22 | Rf = precip * pcr.cos(self.Slope) 23 | return Rf 24 | 25 | #-Leaf drainage (LD; mm) 26 | def LeafDrain(self, pcr, Rf): 27 | LD = Rf * self.CC 28 | return LD 29 | 30 | #-Direct throughfall (DT; mm) 31 | def DirectThroughfall(self, pcr, Rf, LD): 32 | DT = Rf - LD 33 | return DT 34 | 35 | #-Kinetic energy of the direct throughfall (KE_DT; J/m2) 36 | def KineticEnergyDT(self, pcr, DT, PrecInt): 37 | # KE_DT = DT * (8.95 + 8.44 * pcr.log10(PrecInt)) # Marshall and Palmer (1948) 38 | # KE_DT = DT * (0.283 * (1 - 0.52 * pcr.exp(-0.042 * PrecInt))) * 100 # Van Dijk et al (2002) 39 | # KE_DT = DT * (0.384 * (1 - 0.54 * pcr.exp(-0.029 * PrecInt))) * 100 # Cerro et al (1998) 40 | # KE_DT = DT * (0.1418 * PrecInt**0.172) * 100 # Meshesha et al. (2016) 41 | KE_DT = DT * (0.29 * (1 - 0.72 * pcr.exp(-0.05 * PrecInt))) * 100 # Brown and Foster (1987) 42 | return KE_DT 43 | 44 | #-Kinetic energy of the leaf drainage (KE_LD; J/m2) 45 | def KineticEnergyLD(self, pcr, LD, PlantHeight): 46 | KE_LD = pcr.ifthenelse(PlantHeight < 0.15, 0, LD * (15.8 * PlantHeight**0.5 - 5.87)) 47 | return KE_LD 48 | 49 | #-Detachment of soil particles by raindrop impact (F; kg/m2) 50 | def DetachmentRaindrop(self, pcr, K, texture, KE): 51 | F = K * texture * pcr.max(0, 1 - (self.NoErosion + self.Cover)) * KE * 1e-3 52 | return F 53 | 54 | #-Detachment of soil particles by runoff (H; kg/m2) 55 | def DetachmentRunoff(self, pcr, DR, texture, Q): 56 | H = DR * texture * Q**1.5 * pcr.max(0, 1 - (self.NoErosion + self.Cover)) * pcr.sin(self.Slope)**(0.3) * 1e-3 57 | 58 | #-set values in channels to 0 in case channels should be excluded 59 | if self.exclChannelsFLAG == 1: 60 | H = H * self.Hillslope 61 | 62 | return H 63 | 64 | #-Manning for tilled conditions (manningTilled; s/m1/3) 65 | def ManningTillage(self, pcr): 66 | manningTilled = pcr.exp(-2.1132 + 0.0349 * self.RFR) 67 | return manningTilled 68 | 69 | #-Manning for vegetated conditions (manningVegetated; s/m1/3) 70 | def manningVegetation(self, pcr, waterDepth, diameter, noElements): 71 | manningVegetated = (waterDepth**(0.67)) / ((2 * 9.81) / (diameter * noElements))**0.5 72 | return manningVegetated 73 | 74 | #-Flow velocity based on manning (v; m/s) 75 | def FlowVelocity(self, pcr, manning, waterDepth): 76 | v = 1 / manning * waterDepth**(0.67) * pcr.ifthenelse(self.Slope == 0, 1e-5, self.Slope)**0.5 77 | return v 78 | 79 | #-Particle fall number (N_f; -) 80 | def ParticleFallNumber(self, pcr, delta, velocity, waterDepth): 81 | v_s = (float(1)/18 * (delta ** 2) * (self.rho_s - self.rho) * 9.81) / (self.eta) 82 | N_f = (pcr.celllength() / pcr.cos(self.Slope) * v_s) / (velocity * waterDepth) 83 | return N_f 84 | 85 | #-Percentage of the detached sediment that is deposited (DEP; %) 86 | def Deposition(self, pcr, N_f): 87 | DEP = pcr.min(100, 44.1 * N_f ** 0.29) 88 | return DEP 89 | 90 | #-Delivery of detached particles to runoff (G; kg/m2) 91 | def MaterialTransport(self, pcr, F, H, DEP): 92 | G = (F + H) * (1 - DEP / 100) 93 | D = (F + H) * DEP / 100 94 | return G, D 95 | 96 | #-Transport capacity of the runoff (TC; ton/ha) 97 | def TransportCapacity(self, pcr, roughnessFactor, texture, Q): 98 | q = (Q/1000) * pcr.celllength() #-runoff discharge per unit width in m2/day 99 | TC = roughnessFactor * q**self.TC_beta * self.SlopeStreams**self.TC_gamma #-determine transport capacity 100 | return TC 101 | 102 | #-init processes mmf 103 | def init(self, pcr, config): 104 | #-if pedotransfer functions are not used read the sand and clay maps 105 | if self.PedotransferFLAG == 0: 106 | self.RootSandMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootSandMap')) / 100 107 | self.RootClayMap = pcr.readmap(self.inpath + config.get('PEDOTRANSFER','RootClayMap')) / 100 108 | self.RootSiltMap = 1 - self.RootSandMap - self.RootClayMap 109 | 110 | #-read precipitation intensity map or float 111 | try: 112 | self.PrecInt = pcr.readmap(self.inpath + config.get('MMF', 'PrecInt')) 113 | except: 114 | self.PrecInt = config.getfloat('MMF', 'PrecInt') 115 | 116 | #-read flag if the canopy cover should be determined based on LAI 117 | self.CanopyCoverLAIFlag = config.getfloat('MMF', 'CanopyCoverLAIFlag') 118 | 119 | #-read table with MMF input parameters per landuse class 120 | pcr.setglobaloption('matrixtable') 121 | MMF_table = self.inpath + config.get('MMF', 'MMF_table') 122 | self.PlantHeight = pcr.lookupscalar(MMF_table, 1, self.LandUse) 123 | self.NoElements = pcr.lookupscalar(MMF_table, 2, self.LandUse) 124 | self.Diameter = pcr.lookupscalar(MMF_table, 3, self.LandUse) 125 | self.CC_table = pcr.lookupscalar(MMF_table, 4, self.LandUse) 126 | self.GC_table = pcr.lookupscalar(MMF_table, 5, self.LandUse) 127 | self.NoErosion = pcr.lookupscalar(MMF_table, 6, self.LandUse) 128 | self.Tillage = pcr.lookupscalar(MMF_table, 7, self.LandUse) 129 | self.n_table = pcr.lookupscalar(MMF_table, 8, self.LandUse) 130 | self.NoVegetation = pcr.lookupscalar(MMF_table, 9, self.LandUse) 131 | pcr.setglobaloption('columntable') 132 | 133 | #-nominal map with reservoir IDs and extent 134 | if self.ResFLAG == 1: 135 | if self.ETOpenWaterFLAG == 1: 136 | self.Reservoirs = pcr.ifthenelse(pcr.scalar(self.openWaterNominal) > 0, pcr.scalar(1), pcr.scalar(0)) 137 | self.Reservoirs = pcr.cover(self.Reservoirs, 0) 138 | else: 139 | self.Reservoirs = pcr.readmap(self.inpath + config.get('RESERVOIR', 'reservoirs')) 140 | self.NoErosion = pcr.min(self.NoErosion + pcr.scalar(self.Reservoirs), 1) 141 | 142 | #-read table with MMF input parameters per landuse class for the period after harvest 143 | self.harvest_FLAG = config.getfloat('MMF', 'harvestFLAG') 144 | pcr.setglobaloption('matrixtable') 145 | if self.harvest_FLAG: 146 | MMF_harvest_table = self.inpath + config.get('MMF', 'MMF_harvest') 147 | self.Sowing = pcr.lookupscalar(MMF_harvest_table, 1, self.LandUse) 148 | self.Harvest = pcr.lookupscalar(MMF_harvest_table, 2, self.LandUse) 149 | self.PlantHeight_harvest = pcr.lookupscalar(MMF_harvest_table, 3, self.LandUse) 150 | self.NoElements_harvest = pcr.lookupscalar(MMF_harvest_table, 4, self.LandUse) 151 | self.Diameter_harvest = pcr.lookupscalar(MMF_harvest_table, 5, self.LandUse) 152 | self.CC_harvest = pcr.lookupscalar(MMF_harvest_table, 6, self.LandUse) 153 | self.GC_harvest = pcr.lookupscalar(MMF_harvest_table, 7, self.LandUse) 154 | self.Tillage_harvest = pcr.lookupscalar(MMF_harvest_table, 8, self.LandUse) 155 | pcr.setglobaloption('columntable') 156 | 157 | #-read other model parameters 158 | self.K_c = config.getfloat('MMF', 'K_c') 159 | self.K_z = config.getfloat('MMF', 'K_z') 160 | self.K_s = config.getfloat('MMF', 'K_s') 161 | self.DR_c = config.getfloat('MMF', 'DR_c') 162 | self.DR_z = config.getfloat('MMF', 'DR_z') 163 | self.DR_s = config.getfloat('MMF', 'DR_s') 164 | self.deltaClay = config.getfloat('MMF', 'deltaClay') 165 | self.deltaSilt = config.getfloat('MMF', 'deltaSilt') 166 | self.deltaSand = config.getfloat('MMF', 'deltaSand') 167 | self.n_bare = config.getfloat('MMF', 'manning') 168 | self.d_bare = config.getfloat('MMF', 'depthBare') 169 | self.d_field = config.getfloat('MMF', 'depthInField') 170 | self.d_TC = config.getfloat('MMF', 'depthTC') 171 | self.RFR = config.getfloat('MMF', 'RFR') 172 | self.rho_s = config.getfloat('MMF', 'rho_s') 173 | self.rho = config.getfloat('MMF', 'rho') 174 | self.eta = config.getfloat('MMF', 'eta') 175 | 176 | #-Determine manning for soil and tilled conditions 177 | self.n_tilled = self.mmf.ManningTillage(self, pcr) 178 | self.n_soil = pcr.ifthenelse(self.Tillage == 1, self.n_tilled, self.n_bare) 179 | 180 | #-Determine flow velocity for in field deposition 181 | self.n_veg_field = self.mmf.manningVegetation(self, pcr, self.d_field, self.Diameter, self.NoElements) 182 | self.n_veg_field = pcr.ifthenelse(self.NoVegetation == 1, 0, self.n_veg_field) 183 | self.n_veg_field = pcr.ifthenelse(self.NoErosion == 1, 0, self.n_veg_field) 184 | self.n_veg_field = pcr.ifthenelse(self.n_table > 0, self.n_table, self.n_veg_field) 185 | self.n_field = (self.n_soil**2 + self.n_veg_field**2)**0.5 186 | self.v_field = self.mmf.FlowVelocity(self, pcr, self.n_field, self.d_field) 187 | 188 | #-Determine flow velocity after harvest 189 | if self.harvest_FLAG: 190 | self.n_veg_field_harvest = self.mmf.manningVegetation(self, pcr, self.d_field, self.Diameter_harvest, self.NoElements_harvest) 191 | self.n_veg_field_harvest = pcr.ifthenelse(self.Tillage_harvest == 1, 0, self.n_veg_field_harvest) 192 | self.n_field_harvest = (self.n_soil**2 + self.n_veg_field_harvest**2)**0.5 193 | self.v_field_harvest = self.mmf.FlowVelocity(self, pcr, self.n_field_harvest, self.d_field) 194 | 195 | 196 | #-dynamic processes 197 | def dynamic(self, pcr, Precip, Runoff): 198 | #-determine canopy cover from LAI 199 | if self.CanopyCoverLAIFlag == 1 and self.DynVegFLAG == 1: 200 | self.CC = pcr.min(1, self.LAI) 201 | else: 202 | self.CC = self.CC_table 203 | 204 | #-determine areas that have been harvested 205 | if self.harvest_FLAG: 206 | self.Harvested = self.Slope * 0 207 | self.Harvested = pcr.ifthenelse(self.Harvest < self.Sowing, pcr.ifthenelse(pcr.pcrand(self.Harvest < self.curdate.timetuple().tm_yday, self.Sowing > self.curdate.timetuple().tm_yday), 1, self.Harvested), self.Harvested) 208 | self.Harvested = pcr.ifthenelse(self.Harvest > self.Sowing, pcr.ifthenelse(pcr.pcror(self.curdate.timetuple().tm_yday > self.Harvest, self.curdate.timetuple().tm_yday < self.Sowing), 1, self.Harvested), self.Harvested) 209 | self.Harvested = pcr.ifthenelse(self.Harvest == 0, 0, self.Harvested) 210 | 211 | #-set canopy cover to value from MMF harvest table for months between harvest and sowing 212 | if self.CanopyCoverLAIFlag == 0 and self.harvest_FLAG: 213 | self.CC = pcr.ifthenelse(self.Harvested == 1, self.CC_harvest, self.CC_table) 214 | 215 | #-set ground cover to value from MMF harvest table for months between harvest and sowing 216 | if self.harvest_FLAG: 217 | self.GC = pcr.ifthenelse(self.Harvested == 1, self.GC_harvest, self.GC_table) 218 | else: 219 | self.GC = self.GC_table 220 | 221 | #-define cover as fraction of soil covered by ground cover and rock 222 | if self.SnowFLAG == 1: 223 | SCover = pcr.scalar(self.TotalSnowStore > 0) 224 | self.Cover = pcr.min(SCover + self.GC + self.RockFrac, 1) 225 | else: 226 | self.Cover = pcr.min(self.GC + self.RockFrac, 1) 227 | 228 | #-determine effective rainfall 229 | Rf = self.mmf.RainEff(self, pcr, Precip) 230 | 231 | #-determine leaf drainage 232 | LD = self.mmf.LeafDrain(self, pcr, Rf) 233 | 234 | #-determine direct throughfall 235 | DT = self.mmf.DirectThroughfall(self, pcr, Rf, LD) 236 | 237 | #-obtain precipitation intensity from direct throughfall and fraction of the rain in the highest intensity 238 | if self.InfilFLAG == 1: 239 | self.PrecInt = DT * self.Alpha 240 | 241 | #-determine kinetic energy of the direct throughfall 242 | KE_DT = self.mmf.KineticEnergyDT(self, pcr, DT, self.PrecInt) 243 | KE_DT = pcr.ifthenelse(DT == 0, 0, KE_DT) 244 | 245 | #-update plant height for months between harvest and sowing 246 | if self.harvest_FLAG: 247 | self.PlantHeightUpdate = pcr.ifthenelse(self.Harvested == 1, self.PlantHeight_harvest, self.PlantHeight) 248 | else: 249 | self.PlantHeightUpdate = self.PlantHeight 250 | 251 | #-determine kinetic energy of the leaf drainage 252 | KE_LD = self.mmf.KineticEnergyLD(self, pcr, LD, self.PlantHeightUpdate) 253 | 254 | #-determine total kinetic energy 255 | KE = KE_DT + KE_LD 256 | 257 | #-determine detachment of soil particles by raindrop impact 258 | F_c = self.mmf.DetachmentRaindrop(self, pcr, self.K_c, self.RootClayMap, KE) 259 | F_z = self.mmf.DetachmentRaindrop(self, pcr, self.K_z, self.RootSiltMap, KE) 260 | F_s = self.mmf.DetachmentRaindrop(self, pcr, self.K_s, self.RootSandMap, KE) 261 | F = F_c + F_z + F_s 262 | 263 | #-report detachment of soil particles by raindrop impact (ton / cell) 264 | self.reporting.reporting(self, pcr, 'DetRn', F * pcr.cellarea() / 1000) 265 | 266 | #-determine detachment of soil particles by runoff 267 | H_c = self.mmf.DetachmentRunoff(self, pcr, self.DR_c, self.RootClayMap, Runoff) 268 | H_z = self.mmf.DetachmentRunoff(self, pcr, self.DR_z, self.RootSiltMap, Runoff) 269 | H_s = self.mmf.DetachmentRunoff(self, pcr, self.DR_s, self.RootSandMap, Runoff) 270 | H = H_c + H_z + H_s 271 | 272 | #-report detachment of soil particles by runoff (ton / cell) 273 | self.reporting.reporting(self, pcr, 'DetRun', H * pcr.cellarea() / 1000) 274 | 275 | #-replace velocity for vegetated conditions for tilled soil conditions in case of harvested areas 276 | if self.harvest_FLAG: 277 | self.v_update = pcr.ifthenelse(self.Harvested == 1, self.v_field_harvest, self.v_field) 278 | else: 279 | self.v_update = self.v_field 280 | 281 | #-determine particle fall number 282 | N_f_c = self.mmf.ParticleFallNumber(self, pcr, self.deltaClay, self.v_update, self.d_field) 283 | N_f_z = self.mmf.ParticleFallNumber(self, pcr, self.deltaSilt, self.v_update, self.d_field) 284 | N_f_s = self.mmf.ParticleFallNumber(self, pcr, self.deltaSand, self.v_update, self.d_field) 285 | 286 | #-determine percentage of the detached sediment that is deposited within the cell of origin 287 | DEP_c = self.mmf.Deposition(self, pcr, N_f_c) 288 | DEP_z = self.mmf.Deposition(self, pcr, N_f_z) 289 | DEP_s = self.mmf.Deposition(self, pcr, N_f_s) 290 | 291 | #-determine delivery of detached particles to runoff and sediment that is deposited within the cell of origin 292 | tempvar = self.mmf.MaterialTransport(self, pcr, F_c, H_c, DEP_c) 293 | G_c = tempvar[0] 294 | D_c = tempvar[1] 295 | tempvar = self.mmf.MaterialTransport(self, pcr, F_z, H_z, DEP_z) 296 | G_z = tempvar[0] 297 | D_z = tempvar[1] 298 | tempvar = self.mmf.MaterialTransport(self, pcr, F_s, H_s, DEP_s) 299 | G_s = tempvar[0] 300 | D_s = tempvar[1] 301 | G = G_c + G_z + G_s 302 | D = D_c + D_z + D_s 303 | 304 | #-report in field deposition of detached particles (ton / cell) 305 | self.reporting.reporting(self, pcr, 'SDepFld', D * pcr.cellarea() / 1000) 306 | 307 | #-report sediment in transport (ton / cell) 308 | self.reporting.reporting(self, pcr, 'SedTrans', G * pcr.cellarea() / 1000) 309 | 310 | return G -------------------------------------------------------------------------------- /modules/advanced_routing.py: -------------------------------------------------------------------------------- 1 | # The Spatial Processes in HYdrology (SPHY) model: 2 | # A spatially distributed hydrological model 3 | # Copyright (C) 2013-2025 FutureWater 4 | # Email: sphy@futurewater.nl 5 | # 6 | # Authors (alphabetical order): 7 | # P. Droogers, J. Eekhout, A. Fernandez-Rodriguez, W. Immerzeel, S. Khanal, A. Lutz, T. Schults, G. Simons, W. Terink. 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | # Advanced routing that is used for reservoirs or lakes 23 | print("Advanced routing module for lakes and reservoirs imported") 24 | 25 | 26 | # -Function to rout the specific runoff 27 | def ROUT(self, pcr, rvolume, qold, qout, sres): 28 | # Calculate the discharge Q (m3/d) 29 | Q = pcr.accufractionflux(self.FlowDir, rvolume, self.QFRAC) 30 | # Re-calculate Q, based on qold en kx, and assign Qout for cells being lake/reservoir 31 | Q = pcr.ifthenelse( 32 | self.QFRAC == 0, qout, (1 - self.kx) * Q + (qold * 24 * 3600) * self.kx 33 | ) 34 | # Only calculate inflow for lake/reservoir cells 35 | Qin = pcr.ifthenelse(self.QFRAC == 0, pcr.upstream(self.FlowDir, Q), 0) 36 | sres = sres - qout + Qin 37 | Q = Q / (24 * 3600) # -only convert Q to m3/s 38 | return sres, Q, Qin 39 | 40 | 41 | # -init advanced routing processes 42 | def init(self, pcr, config): 43 | self.FlowDir = pcr.readmap(self.inpath + config.get("ROUTING", "flowdir")) 44 | try: 45 | self.kx = pcr.readmap(self.inpath + config.get("ROUTING", "kx")) 46 | except: 47 | self.kx = config.getfloat("ROUTING", "kx") 48 | 49 | 50 | # -initial conditions advanced routing 51 | def initial(self, pcr, config): 52 | # -initial routed total runoff 53 | try: 54 | self.QRAold = config.getfloat("ROUT_INIT", "QRA_init") 55 | except: 56 | try: 57 | self.QRAold = pcr.readmap(self.inpath + config.get("ROUT_INIT", "QRA_init")) 58 | except: 59 | self.QRAold = 0 60 | # -initial routed runoff for the individual components 61 | pars = ["RootR", "RootD", "Rain", "Snow", "Glac", "Base"] 62 | for i in pars: 63 | try: 64 | setattr( 65 | self, 66 | i + "RAold", 67 | pcr.readmap(self.inpath + config.get("ROUT_INIT", i + "RA_init")), 68 | ) 69 | setattr(self, i + "RA_FLAG", True) 70 | except: 71 | try: 72 | setattr(self, i + "RAold", config.getfloat("ROUT_INIT", i + "RA_init")) 73 | setattr(self, i + "RA_FLAG", True) 74 | except: 75 | setattr(self, i + "RA_FLAG", False) 76 | 77 | # -initial storage in lakes/reservoirs of individual flow components 78 | pars = ["RootRRA", "RootDRA", "RainRA", "SnowRA", "GlacRA", "BaseRA"] 79 | for i in pars: 80 | column = pars.index( 81 | i 82 | ) # identify column to be read from lake or reservoir table 83 | try: # -try to sum the storages read from the lake and reservoir tables if both thse modules are used 84 | setattr( 85 | self, 86 | i + "stor", 87 | ( 88 | pcr.cover( 89 | pcr.lookupscalar(LakeStor_Tab, column + 2, self.LakeID), 0 90 | ) 91 | + pcr.cover( 92 | pcr.lookupscalar(ResStor_Tab, column + 3, self.ResID), 0 93 | ) 94 | ) 95 | * 10**6, 96 | ) 97 | if eval("self." + i + "_FLAG"): 98 | setattr(self, i + "_FLAG", True) 99 | else: 100 | setattr(self, i + "_FLAG", False) 101 | except: 102 | try: # -try to read the storages from the lake table 103 | setattr( 104 | self, 105 | i + "stor", 106 | pcr.cover( 107 | pcr.lookupscalar(LakeStor_Tab, column + 2, self.LakeID), 0 108 | ) 109 | * 10**6, 110 | ) 111 | if eval("self." + i + "_FLAG"): 112 | setattr(self, i + "_FLAG", True) 113 | else: 114 | setattr(self, i + "_FLAG", False) 115 | except: # -try to read the storages from the reservoir table 116 | try: 117 | setattr( 118 | self, 119 | i + "stor", 120 | pcr.cover( 121 | pcr.lookupscalar(ResStor_Tab, column + 3, self.ResID), 0 122 | ) 123 | * 10**6, 124 | ) 125 | if eval("self." + i + "_FLAG"): 126 | setattr(self, i + "_FLAG", True) 127 | else: 128 | setattr(self, i + "_FLAG", False) 129 | except: 130 | setattr(self, i + "_FLAG", False) 131 | 132 | 133 | # -dynamic processes advanced routing 134 | def dynamic(self, pcr, pcrm, config, TotR, ETOpenWater, PrecipTot): 135 | # -Update storage in lakes/reservoirs (m3) with specific runoff 136 | self.StorRES = self.StorRES + pcr.ifthenelse( 137 | self.QFRAC == 0, 0.001 * pcr.cellarea() * TotR, 0 138 | ) 139 | OldStorage = self.StorRES 140 | # -Calculate lake/reservoir outflow volumes 141 | if self.LakeFLAG == 1 and self.ResFLAG == 1: 142 | tempvar = self.lakes.UpdateLakeHStore(self, pcr, pcrm) 143 | LakeLevel = tempvar[0] 144 | self.StorRES = tempvar[1] 145 | LakeQ = self.lakes.QLake(self, pcr, LakeLevel) 146 | ResQ = self.reservoirs.QRes(self, pcr) 147 | Qout = pcr.ifthenelse( 148 | self.ResID != 0, ResQ, pcr.ifthenelse(self.LakeID != 0, LakeQ, 0) 149 | ) 150 | elif self.LakeFLAG == 1: 151 | tempvar = self.lakes.UpdateLakeHStore(self, pcr, pcrm) 152 | LakeLevel = tempvar[0] 153 | self.StorRES = tempvar[1] 154 | Qout = self.lakes.QLake(self, pcr, LakeLevel) 155 | else: 156 | Qout = self.reservoirs.QRes(self, pcr) 157 | 158 | # -Calculate volume available for routing (=outflow lakes/reservoir + cell specific runoff) 159 | RunoffVolume = pcr.upstream(self.FlowDir, Qout) + pcr.ifthenelse( 160 | self.QFRAC == 0, 0, 0.001 * pcr.cellarea() * TotR 161 | ) 162 | # -Routing of total flow 163 | tempvar = self.advanced_routing.ROUT( 164 | self, pcr, RunoffVolume, self.QRAold, Qout, self.StorRES 165 | ) 166 | self.StorRES = tempvar[0] 167 | if self.ETOpenWaterFLAG == 1: 168 | # -determine actual evapotranspiration per reservoir in m3/day 169 | ETaRES = pcr.ifthenelse( 170 | self.StorRES > 0, 171 | pcr.min( 172 | ( 173 | pcr.areatotal( 174 | ETOpenWater * pcr.cellarea() * self.openWaterFrac, 175 | self.openWaterNominal, 176 | ) 177 | * 0.001 178 | ), 179 | self.StorRES, 180 | ), 181 | 0, 182 | ) 183 | # -Determine total precipitation as input for fraction of open water 184 | PrecipRES = pcr.ifthenelse( 185 | self.StorRES > 0, 186 | ( 187 | pcr.areatotal( 188 | PrecipTot * pcr.cellarea() * self.openWaterFrac, 189 | self.openWaterNominal, 190 | ) 191 | * 0.001 192 | ), 193 | 0, 194 | ) 195 | # -update storage by subtracting the actual evapotranspiration per reservoir 196 | self.StorRES = self.StorRES - ETaRES + PrecipRES 197 | Q = tempvar[1] 198 | Qin = tempvar[2] 199 | self.QRAold = Q 200 | self.reporting.reporting(self, pcr, "QallRAtot", Q) 201 | # -report flux in mm 202 | if self.mm_rep_FLAG == 1 and self.QTOT_mm_FLAG == 1: 203 | self.QTOTSubBasinTSS.sample( 204 | ((Q * 3600 * 24) / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir)) * 1000 205 | ) 206 | # -report lake and reservoir waterbalance 207 | if self.LakeFLAG == 1 and config.getint("REPORTING", "Lake_wbal") == 1: 208 | self.LakeInTSS.sample(Qin) 209 | self.LakeOutTSS.sample(Qout) 210 | self.LakeStorTSS.sample(self.StorRES) 211 | if self.ResFLAG == 1 and config.getint("REPORTING", "Res_wbal") == 1: 212 | self.ResInTSS.sample(Qin) 213 | self.ResOutTSS.sample(Qout) 214 | self.ResStorTSS.sample(self.StorRES) 215 | if self.ETOpenWaterFLAG: 216 | self.ResETaTSS.sample(ETaRES) 217 | self.ResInCalTSS.sample(Qin - ETaRES) 218 | 219 | # -Routing of individual contributers 220 | # -Snow routing 221 | if self.SnowRA_FLAG == 1 and self.SnowFLAG == 1: 222 | self.SnowRAstor = self.SnowRAstor + pcr.ifthenelse( 223 | self.QFRAC == 0, SnowR * 0.001 * pcr.cellarea(), 0 224 | ) 225 | cQfrac = pcr.cover(self.SnowRAstor / OldStorage, 0) 226 | cQout = cQfrac * Qout 227 | cRunoffVolume = pcr.upstream(self.FlowDir, cQout) + pcr.ifthenelse( 228 | self.QFRAC == 0, 0, 0.001 * pcr.cellarea() * SnowR 229 | ) 230 | tempvar = self.advanced_routing.ROUT( 231 | self, pcr, cRunoffVolume, self.SnowRAold, cQout, self.SnowRAstor 232 | ) 233 | self.SnowRAstor = tempvar[0] 234 | SnowRA = tempvar[1] 235 | cQin = tempvar[2] 236 | self.SnowRAold = SnowRA 237 | self.reporting.reporting(self, pcr, "SnowRAtot", SnowRA) 238 | if self.mm_rep_FLAG == 1 and self.QSNOW_mm_FLAG == 1: 239 | self.QSNOWSubBasinTSS.sample( 240 | ( 241 | (SnowRA * 3600 * 24) 242 | / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir) 243 | ) 244 | * 1000 245 | ) 246 | # -report lake and reservoir waterbalance 247 | if self.LakeFLAG == 1 and config.getint("REPORTING", "Lake_wbal") == 1: 248 | self.LakeSnowInTSS.sample(cQin) 249 | self.LakeSnowOutTSS.sample(cQout) 250 | self.LakeSnowStorTSS.sample(self.SnowRAstor) 251 | if self.ResFLAG == 1 and config.getint("REPORTING", "Res_wbal") == 1: 252 | self.ResSnowInTSS.sample(cQin) 253 | self.ResSnowOutTSS.sample(cQout) 254 | self.ResSnowStorTSS.sample(self.SnowRAstor) 255 | # -Rain routing 256 | if self.RainRA_FLAG == 1: 257 | self.RainRAstor = self.RainRAstor + pcr.ifthenelse( 258 | self.QFRAC == 0, RainR * 0.001 * pcr.cellarea(), 0 259 | ) 260 | cQfrac = pcr.cover(self.RainRAstor / OldStorage, 0) 261 | cQout = cQfrac * Qout 262 | cRunoffVolume = pcr.upstream(self.FlowDir, cQout) + pcr.ifthenelse( 263 | self.QFRAC == 0, 0, 0.001 * pcr.cellarea() * RainR 264 | ) 265 | tempvar = self.advanced_routing.ROUT( 266 | self, pcr, cRunoffVolume, self.RainRAold, cQout, self.RainRAstor 267 | ) 268 | self.RainRAstor = tempvar[0] 269 | RainRA = tempvar[1] 270 | cQin = tempvar[2] 271 | self.RainRAold = RainRA 272 | self.reporting.reporting(self, pcr, "RainRAtot", RainRA) 273 | if self.mm_rep_FLAG == 1 and self.QRAIN_mm_FLAG == 1: 274 | self.QRAINSubBasinTSS.sample( 275 | ( 276 | (RainRA * 3600 * 24) 277 | / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir) 278 | ) 279 | * 1000 280 | ) 281 | # -report lake and reservoir waterbalance 282 | if self.LakeFLAG == 1 and config.getint("REPORTING", "Lake_wbal") == 1: 283 | self.LakeRainInTSS.sample(cQin) 284 | self.LakeRainOutTSS.sample(cQout) 285 | self.LakeRainStorTSS.sample(self.RainRAstor) 286 | if self.ResFLAG == 1 and config.getint("REPORTING", "Res_wbal") == 1: 287 | self.ResRainInTSS.sample(cQin) 288 | self.ResRainOutTSS.sample(cQout) 289 | self.ResRainStorTSS.sample(self.RainRAstor) 290 | # -Glacier routing 291 | if self.GlacRA_FLAG == 1 and self.GlacFLAG == 1: 292 | self.GlacRAstor = self.GlacRAstor + pcr.ifthenelse( 293 | self.QFRAC == 0, GlacR * 0.001 * pcr.cellarea(), 0 294 | ) 295 | cQfrac = pcr.cover(self.GlacRAstor / OldStorage, 0) 296 | cQout = cQfrac * Qout 297 | cRunoffVolume = pcr.upstream(self.FlowDir, cQout) + pcr.ifthenelse( 298 | self.QFRAC == 0, 0, 0.001 * pcr.cellarea() * GlacR 299 | ) 300 | tempvar = self.advanced_routing.ROUT( 301 | self, pcr, cRunoffVolume, self.GlacRAold, cQout, self.GlacRAstor 302 | ) 303 | self.GlacRAstor = tempvar[0] 304 | GlacRA = tempvar[1] 305 | cQin = tempvar[2] 306 | self.GlacRAold = GlacRA 307 | self.reporting.reporting(self, pcr, "GlacRAtot", GlacRA) 308 | if self.mm_rep_FLAG == 1 and self.QGLAC_mm_FLAG == 1: 309 | self.QGLACSubBasinTSS.sample( 310 | ( 311 | (GlacRA * 3600 * 24) 312 | / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir) 313 | ) 314 | * 1000 315 | ) 316 | # -report lake and reservoir waterbalance 317 | if self.LakeFLAG == 1 and config.getint("REPORTING", "Lake_wbal") == 1: 318 | self.LakeGlacInTSS.sample(cQin) 319 | self.LakeGlacOutTSS.sample(cQout) 320 | self.LakeGlacStorTSS.sample(self.GlacRAstor) 321 | if self.ResFLAG == 1 and config.getint("REPORTING", "Res_wbal") == 1: 322 | self.ResGlacInTSS.sample(cQin) 323 | self.ResGlacOutTSS.sample(cQout) 324 | self.ResGlacStorTSS.sample(self.GlacRAstor) 325 | # -Baseflow routing 326 | if self.BaseRA_FLAG == 1: 327 | self.BaseRAstor = self.BaseRAstor + pcr.ifthenelse( 328 | self.QFRAC == 0, self.BaseR * 0.001 * pcr.cellarea(), 0 329 | ) 330 | cQfrac = pcr.cover(self.BaseRAstor / OldStorage, 0) 331 | cQout = cQfrac * Qout 332 | cRunoffVolume = pcr.upstream(self.FlowDir, cQout) + pcr.ifthenelse( 333 | self.QFRAC == 0, 0, 0.001 * pcr.cellarea() * self.BaseR 334 | ) 335 | tempvar = self.routing.ROUT( 336 | self, pcr, cRunoffVolume, self.BaseRAold, cQout, self.BaseRAstor 337 | ) 338 | self.BaseRAstor = tempvar[0] 339 | BaseRA = tempvar[1] 340 | cQin = tempvar[2] 341 | self.BaseRAold = BaseRA 342 | self.reporting.reporting(self, pcr, "BaseRAtot", BaseRA) 343 | if self.mm_rep_FLAG == 1 and self.QBASE_mm_FLAG == 1: 344 | self.QBASESubBasinTSS.sample( 345 | ( 346 | (BaseRA * 3600 * 24) 347 | / pcr.catchmenttotal(pcr.cellarea(), self.FlowDir) 348 | ) 349 | * 1000 350 | ) 351 | # -report lake and reservoir waterbalance 352 | if self.LakeFLAG == 1 and config.getint("REPORTING", "Lake_wbal") == 1: 353 | self.LakeBaseInTSS.sample(cQin) 354 | self.LakeBaseOutTSS.sample(cQout) 355 | self.LakeBaseStorTSS.sample(self.BaseRAstor) 356 | if self.ResFLAG == 1 and config.getint("REPORTING", "Res_wbal") == 1: 357 | self.ResBaseInTSS.sample(cQin) 358 | self.ResBaseOutTSS.sample(cQout) 359 | self.ResBaseStorTSS.sample(self.BaseRAstor) 360 | return Q 361 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | --------------------------------------------------------------------------------