├── .gitignore ├── pytopkapi ├── __version.py ├── tests │ ├── test_data │ │ ├── mask.flt │ │ ├── cell_down.npy │ │ ├── flow_dir.flt │ │ ├── mask.hdr │ │ └── flow_dir.hdr │ ├── test_continuity │ │ ├── d8 │ │ │ ├── rainfall.h5 │ │ │ ├── evapotranspiration.h5 │ │ │ ├── global_param.dat │ │ │ └── cell_param.dat │ │ ├── lieb │ │ │ ├── rainfall.h5 │ │ │ ├── evapotranspiration.h5 │ │ │ ├── global_param.dat │ │ │ └── cell_param.dat │ │ ├── 4cells │ │ │ ├── rainfall.h5 │ │ │ ├── evapotranspiration.h5 │ │ │ ├── global_parameters.dat │ │ │ └── cell_parameters.dat │ │ ├── D8.ini │ │ ├── 4cells.ini │ │ ├── lieb.ini │ │ └── continuity_tests.py │ ├── test_parameter_utils.py │ └── test_infiltration.py ├── parameter_utils │ ├── __init__.py │ ├── common.py │ ├── map_param.py │ └── GIS_treatment.py ├── results_analysis │ ├── __init__.py │ ├── plot_Qsim_Qobs_Rain.py │ └── plot_soil_moisture_maps.py ├── __init__.py ├── interpolation.py ├── arcfltgrid.py ├── infiltration.py ├── evap.py ├── fluxes.py └── utils.py ├── docs ├── TOPKAPI_Manual.doc ├── source │ ├── _static │ │ ├── logo.png │ │ ├── sponsor-logos.png │ │ ├── figures │ │ │ ├── ext-flows.png │ │ │ ├── flow-rain.png │ │ │ ├── plot-ini.png │ │ │ ├── cell-params.png │ │ │ ├── sim-results.png │ │ │ ├── topkapi-ini.png │ │ │ ├── field_SWI_0006.png │ │ │ ├── global-params.png │ │ │ ├── soil-moisture-ini.png │ │ │ ├── sub-catchment-layout.png │ │ │ └── forcing-vars-HDFExplorer.png │ │ ├── logo.svg │ │ └── sphinxdoc.css │ ├── gitwash │ │ ├── branch_list.png │ │ ├── pull_button.png │ │ ├── forking_button.png │ │ ├── branch_list_compare.png │ │ ├── git_development.rst │ │ ├── index.rst │ │ ├── git_intro.rst │ │ ├── git_install.rst │ │ ├── dot2_dot3.rst │ │ ├── following_latest.rst │ │ ├── forking_hell.rst │ │ ├── git_resources.rst │ │ ├── set_up_fork.rst │ │ ├── configure_git.rst │ │ ├── git_links.inc │ │ ├── patching.rst │ │ └── development_workflow.rst │ ├── contents.rst │ ├── developer.rst │ ├── bugs.rst │ ├── contact.rst │ ├── api.rst │ ├── _templates │ │ ├── layout.html │ │ └── index.html │ ├── install.rst │ ├── intro.rst │ └── conf.py ├── HOWTO_RELEASE.rst ├── Makefile └── infiltration-changes.txt ├── example_simulation ├── forcing_variables │ ├── ET.h5 │ ├── rainfields.h5 │ ├── external_lesotho_flows.dat │ └── C8H020_6h_Obs_Example.dat ├── parameter_files │ └── global_param.dat ├── run_example.py ├── plot-flow-precip.ini ├── plot-soil-moisture-maps.ini ├── coordinate-system.txt └── model-simulation.ini ├── scripts ├── grassrc_national ├── extract-tertiary.py ├── grass-processing.ini ├── run-grass-script └── process-catchment ├── testing.txt ├── conda-env.yaml ├── RELEASE-NOTES ├── LICENSE ├── create_distributions.py ├── README.md ├── setup.py └── change_log /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | docs/build 3 | *.pyc 4 | -------------------------------------------------------------------------------- /pytopkapi/__version.py: -------------------------------------------------------------------------------- 1 | version = 'dev-notbuilt' 2 | git_revision = 'dev-notbuilt' 3 | -------------------------------------------------------------------------------- /docs/TOPKAPI_Manual.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/TOPKAPI_Manual.doc -------------------------------------------------------------------------------- /docs/source/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/logo.png -------------------------------------------------------------------------------- /pytopkapi/tests/test_data/mask.flt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_data/mask.flt -------------------------------------------------------------------------------- /docs/source/gitwash/branch_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/gitwash/branch_list.png -------------------------------------------------------------------------------- /docs/source/gitwash/pull_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/gitwash/pull_button.png -------------------------------------------------------------------------------- /pytopkapi/parameter_utils/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sub-package with tools for the preparation of parameter files. 3 | """ 4 | -------------------------------------------------------------------------------- /docs/source/_static/sponsor-logos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/sponsor-logos.png -------------------------------------------------------------------------------- /docs/source/gitwash/forking_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/gitwash/forking_button.png -------------------------------------------------------------------------------- /pytopkapi/tests/test_data/cell_down.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_data/cell_down.npy -------------------------------------------------------------------------------- /pytopkapi/tests/test_data/flow_dir.flt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_data/flow_dir.flt -------------------------------------------------------------------------------- /docs/source/_static/figures/ext-flows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/ext-flows.png -------------------------------------------------------------------------------- /docs/source/_static/figures/flow-rain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/flow-rain.png -------------------------------------------------------------------------------- /docs/source/_static/figures/plot-ini.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/plot-ini.png -------------------------------------------------------------------------------- /docs/source/_static/figures/cell-params.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/cell-params.png -------------------------------------------------------------------------------- /docs/source/_static/figures/sim-results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/sim-results.png -------------------------------------------------------------------------------- /docs/source/_static/figures/topkapi-ini.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/topkapi-ini.png -------------------------------------------------------------------------------- /docs/source/gitwash/branch_list_compare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/gitwash/branch_list_compare.png -------------------------------------------------------------------------------- /example_simulation/forcing_variables/ET.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/example_simulation/forcing_variables/ET.h5 -------------------------------------------------------------------------------- /docs/source/_static/figures/field_SWI_0006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/field_SWI_0006.png -------------------------------------------------------------------------------- /docs/source/_static/figures/global-params.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/global-params.png -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/d8/rainfall.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/d8/rainfall.h5 -------------------------------------------------------------------------------- /docs/source/_static/figures/soil-moisture-ini.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/soil-moisture-ini.png -------------------------------------------------------------------------------- /pytopkapi/results_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sub-package with tools for the analysis of results. 3 | """ 4 | from .sim_result_tools import * 5 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/lieb/rainfall.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/lieb/rainfall.h5 -------------------------------------------------------------------------------- /example_simulation/forcing_variables/rainfields.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/example_simulation/forcing_variables/rainfields.h5 -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/4cells/rainfall.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/4cells/rainfall.h5 -------------------------------------------------------------------------------- /scripts/grassrc_national: -------------------------------------------------------------------------------- 1 | GISDBASE: /home/scott/Data/grassdata 2 | LOCATION_NAME: pytopkapi_sa 3 | MAPSET: work 4 | MONITOR: x0 5 | GRASS_GUI: text 6 | -------------------------------------------------------------------------------- /docs/source/_static/figures/sub-catchment-layout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/sub-catchment-layout.png -------------------------------------------------------------------------------- /docs/source/_static/figures/forcing-vars-HDFExplorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/docs/source/_static/figures/forcing-vars-HDFExplorer.png -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/d8/evapotranspiration.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/d8/evapotranspiration.h5 -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/lieb/evapotranspiration.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/lieb/evapotranspiration.h5 -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/4cells/evapotranspiration.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahg/PyTOPKAPI/HEAD/pytopkapi/tests/test_continuity/4cells/evapotranspiration.h5 -------------------------------------------------------------------------------- /testing.txt: -------------------------------------------------------------------------------- 1 | The package can be tested by running `nosetests` from this 2 | directory. This will test the code of the current source tree (*not* 3 | the installed version of PyTOPKAPI). 4 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/4cells/global_parameters.dat: -------------------------------------------------------------------------------- 1 | X Dt Alpha_s Alpha_o Alpha_c A_thres W_min W_max 2 | 1000 3600 3 1.66666667 1.66666667 1000000 1 10 3 | -------------------------------------------------------------------------------- /example_simulation/parameter_files/global_param.dat: -------------------------------------------------------------------------------- 1 | X Dt Alpha_s Alpha_o Alpha_c A_thres W_min W_max 2 | 1000 21600 2.5 1.66666667 1.66666667 25000000 5.0 40.0 -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/d8/global_param.dat: -------------------------------------------------------------------------------- 1 | X Dt Alpha_s Alpha_o Alpha_c A_thres W_min W_max 2 | 1000 21600 2.5 1.66666667 1.66666667 25000000 5.0 40.0 -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/lieb/global_param.dat: -------------------------------------------------------------------------------- 1 | X Dt Alpha_s Alpha_o Alpha_c A_thres W_min W_max 2 | 1000 21600 2.5 1.66666667 1.66666667 25000000 5.0 40.0 -------------------------------------------------------------------------------- /pytopkapi/tests/test_data/mask.hdr: -------------------------------------------------------------------------------- 1 | ncols 84 2 | nrows 78 3 | xllcorner 698672.75236927 4 | yllcorner 7132972.0124861 5 | cellsize 30 6 | NODATA_value -9999 7 | byteorder LSBFIRST 8 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_data/flow_dir.hdr: -------------------------------------------------------------------------------- 1 | ncols 84 2 | nrows 78 3 | xllcorner 698672.75236927 4 | yllcorner 7132972.0124861 5 | cellsize 30 6 | NODATA_value -9999 7 | byteorder LSBFIRST 8 | -------------------------------------------------------------------------------- /conda-env.yaml: -------------------------------------------------------------------------------- 1 | name: pytopkapi-0.5.x 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - python=3 6 | - numpy 7 | - scipy 8 | - h5py 9 | - gdal 10 | - networkx 11 | - tqdm 12 | - matplotlib 13 | - pandas 14 | - nose 15 | -------------------------------------------------------------------------------- /docs/source/gitwash/git_development.rst: -------------------------------------------------------------------------------- 1 | .. _git-development: 2 | 3 | ===================== 4 | Git for development 5 | ===================== 6 | 7 | Contents: 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | forking_hell 13 | set_up_fork 14 | configure_git 15 | development_workflow 16 | 17 | -------------------------------------------------------------------------------- /docs/source/gitwash/index.rst: -------------------------------------------------------------------------------- 1 | .. _using-git: 2 | 3 | Working with *PyTOPKAPI* source code 4 | ====================================== 5 | 6 | Contents: 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | git_intro 12 | git_install 13 | following_latest 14 | patching 15 | git_development 16 | git_resources 17 | 18 | 19 | -------------------------------------------------------------------------------- /RELEASE-NOTES: -------------------------------------------------------------------------------- 1 | Version 0.4.x release highlights 2 | -------------------------------- 3 | 4 | - PyTOPKAPI now targets Python 3 5 | 6 | - Experimental multi-core parallel processing mode 7 | 8 | - Infiltration layer based on Green-Ampt 9 | 10 | - Semi-automated parameter file generation tools using GRASS GIS 11 | 12 | - Numerous improvements and bug fixes 13 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/4cells/cell_parameters.dat: -------------------------------------------------------------------------------- 1 | 0 1 4 0 0 0 0.09 0 0.5 0.001 0.04 0.45 0.1 0.03 1 2.4 0 0 1 146.600006 0.322 2 | 1 1 3 1 1000 0 0.08 0.08 0.75 0.001 0.05 0.5 0.2 0.04 2 2.4 0 0.001 1 146.600006 0.322 3 | 2 1 2 1 1000 0 0.07 0.07 1 0.001 0.06 0.55 0.3 0.05 3 2.4 0 0.001 1 146.600006 0.322 4 | 3 1 1 1 1000 0 0.05 0.05 1.25 0.001 0.07 0.6 0.4 0.06 -99 2.4 0 0.001 1 146.600006 0.322 5 | -------------------------------------------------------------------------------- /docs/source/contents.rst: -------------------------------------------------------------------------------- 1 | .. _contents: 2 | 3 | ================================ 4 | PyTOPKAPI documentation contents 5 | ================================ 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | 10 | intro 11 | install 12 | tutorial 13 | api 14 | bugs 15 | developer 16 | 17 | Indices and tables 18 | ================== 19 | 20 | * :ref:`genindex` 21 | * :ref:`modindex` 22 | * :ref:`search` 23 | -------------------------------------------------------------------------------- /docs/source/developer.rst: -------------------------------------------------------------------------------- 1 | .. _developer: 2 | 3 | =================== 4 | Developer Resources 5 | =================== 6 | 7 | This section contains information that is useful for contributing to 8 | the PyTOPKAPI development effort. At present the notes in this section 9 | are produced using the fantastic `gitwash 10 | `_ tool from Matthew Brett. 11 | 12 | .. toctree:: 13 | :maxdepth: 2 14 | 15 | gitwash/index 16 | -------------------------------------------------------------------------------- /docs/source/bugs.rst: -------------------------------------------------------------------------------- 1 | .. _bugs: 2 | 3 | =========== 4 | Bug Reports 5 | =========== 6 | 7 | The best place to file bug reports is at the `Bug Tracker 8 | `_, this requires a free 9 | `Github `_ account. 10 | 11 | Please ensure that bug reports clearly describe the bug and if 12 | possible provide a simple script that can reproduce the problem. If in 13 | doubt start a discussion on the `mailing list `_. 14 | -------------------------------------------------------------------------------- /docs/source/contact.rst: -------------------------------------------------------------------------------- 1 | .. _contact: 2 | 3 | ======= 4 | Contact 5 | ======= 6 | 7 | User support and development discussion takes place on the official 8 | `mailing list `_. If you 9 | have a Google account, just sign in and join the group. 10 | 11 | It is also possible to join the group without a Google account, simply 12 | send an e-mail to `[Groupname]+subscribe@googlegroups.com` from the 13 | e-mail account you wish to use, be sure to replace `[Groupname]` with 14 | `pytopkapi`. 15 | -------------------------------------------------------------------------------- /docs/HOWTO_RELEASE.rst: -------------------------------------------------------------------------------- 1 | ================================ 2 | Notes on producing a new release 3 | ================================ 4 | 5 | * Create a release branch off the develop branch, following the model 6 | proposed in http://nvie.com/posts/a-successful-git-branching-model/ 7 | 8 | * Generate appropriate source and Windows binary distributions and 9 | upload to the Github download page. 10 | 11 | * Be sure to register the release on PyPI using `python setup.py 12 | register` - requires authentication. 13 | 14 | * Announce release on mailing list. 15 | -------------------------------------------------------------------------------- /scripts/extract-tertiary.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import grass.script as grass 3 | 4 | catch_id = 'C83' 5 | 6 | # create catchment mask 7 | grass.run_command('v.extract', 8 | flags = '-o', 9 | input = 'wr2005_catchments', 10 | output = '%s_py' % catch_id, 11 | where="TERTIARY = '%s'" % catch_id) 12 | 13 | grass.run_command('v.dissolve', 14 | flags = '-o', 15 | input = '%s_py' % catch_id, 16 | output = '%s_dissolve_py' % catch_id, 17 | column='TERTIARY') 18 | -------------------------------------------------------------------------------- /scripts/grass-processing.ini: -------------------------------------------------------------------------------- 1 | # This config file describes the contents of a GRASS GIS location and 2 | # contains some parameters for processing catchments using GRASS 3 | # tools. 4 | 5 | [parameters] 6 | catchment_id=lieb 7 | buffer_range=5000 8 | 9 | [GIS_layers] 10 | catchment_boundary=lieb_subcatch 11 | DEM=srtm_dem 12 | surface_slope=srtm_slope 13 | manning_overland=manning_overland 14 | soil_depth=soil_depth 15 | sat_moisture_content=sat_moisture_content 16 | residual_moisture_content=residual_moisture_content 17 | hydraulic_conductivity=hydraulic_conductivity 18 | pore_size_index=pore_size 19 | bubbling_pressure=bubbling_pressure 20 | -------------------------------------------------------------------------------- /docs/source/gitwash/git_intro.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | Introduction 3 | ============== 4 | 5 | These pages describe a git_ and github_ workflow for the PyTOPKAPI_ 6 | project. 7 | 8 | There are several different workflows here, for different ways of 9 | working with *PyTOPKAPI*. 10 | 11 | This is not a comprehensive git_ reference, it's just a workflow for our 12 | own project. It's tailored to the github_ hosting service. You may well 13 | find better or quicker ways of getting stuff done with git_, but these 14 | should get you started. 15 | 16 | For general resources for learning git_ see :ref:`git-resources`. 17 | 18 | .. include:: git_links.inc 19 | -------------------------------------------------------------------------------- /example_simulation/run_example.py: -------------------------------------------------------------------------------- 1 | import pytopkapi 2 | from pytopkapi.results_analysis import plot_Qsim_Qobs_Rain, \ 3 | plot_soil_moisture_maps 4 | 5 | if __name__ == '__main__': 6 | # Run a model simulation using the configuration in 7 | # model-simulation.ini 8 | pytopkapi.run('model-simulation.ini') 9 | 10 | # Plot the simulation results (rainfall-runoff graphics) using the 11 | # config in plot-flow-precip.ini 12 | plot_Qsim_Qobs_Rain.run('plot-flow-precip.ini') 13 | 14 | 15 | # Plot the simulation results (soil moisture maps) using the config in 16 | # plot-soil-moisture-maps.ini 17 | plot_soil_moisture_maps.run('plot-soil-moisture-maps.ini') 18 | -------------------------------------------------------------------------------- /docs/source/gitwash/git_install.rst: -------------------------------------------------------------------------------- 1 | .. _install-git: 2 | 3 | ============= 4 | Install git 5 | ============= 6 | 7 | Overview 8 | ======== 9 | 10 | ================ ============= 11 | Debian / Ubuntu ``sudo apt-get install git-core`` 12 | Fedora ``sudo yum install git-core`` 13 | Windows Download and install msysGit_ 14 | OS X Use the git-osx-installer_ 15 | ================ ============= 16 | 17 | In detail 18 | ========= 19 | 20 | See the git_ page for the most recent information. 21 | 22 | Have a look at the github_ install help pages available from `github help`_ 23 | 24 | There are good instructions here: http://book.git-scm.com/2_installing_git.html 25 | 26 | .. include:: git_links.inc 27 | -------------------------------------------------------------------------------- /example_simulation/plot-flow-precip.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the options for creating a plot of the results (rainfall 3 | # runoff graphic). Paths may be specified relative to the location of the 4 | # script reading this file or in absolute terms. At this stage a '/' must be 5 | # used as the directory separator (even on Windows) 6 | 7 | [files] 8 | file_Qsim = results/Example_simulation_results.h5 9 | file_Qobs = forcing_variables/C8H020_6h_Obs_Example.dat 10 | file_rain = forcing_variables/rainfields.h5 11 | image_out = results/Example_simulation_Qsim_Qobs_P_color.png 12 | 13 | [groups] 14 | group_name = sample_event 15 | 16 | [flags] 17 | Qobs = True 18 | Pobs = True 19 | nash = False 20 | -------------------------------------------------------------------------------- /example_simulation/plot-soil-moisture-maps.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the options for creating a plot of the results (soil 3 | # moisture maps). Paths may be specified relative to the location of the script 4 | # reading this file or in absolute terms. At this stage a '/' must be used as 5 | # the directory separator (even on Windows) 6 | 7 | [files] 8 | file_global_param=parameter_files/global_param.dat 9 | file_cell_param=parameter_files/cell_param.dat 10 | file_sim=results/Example_simulation_results.h5 11 | 12 | [paths] 13 | path_out=results 14 | 15 | [calib_params] 16 | fac_L=1. 17 | fac_Ks=60.0 18 | fac_n_o=1.0 19 | fac_n_c=1.7 20 | 21 | [flags] 22 | t1=1 23 | t2=20 24 | variable=4 25 | -------------------------------------------------------------------------------- /docs/source/gitwash/dot2_dot3.rst: -------------------------------------------------------------------------------- 1 | .. _dot2-dot3: 2 | 3 | ======================================== 4 | Two and three dots in difference specs 5 | ======================================== 6 | 7 | Thanks to Yarik Halchenko for this explanation. 8 | 9 | Imagine a series of commits A, B, C, D... Imagine that there are two 10 | branches, *topic* and *master*. You branched *topic* off *master* when 11 | *master* was at commit 'E'. The graph of the commits looks like this:: 12 | 13 | 14 | A---B---C topic 15 | / 16 | D---E---F---G master 17 | 18 | Then:: 19 | 20 | git diff master..topic 21 | 22 | will output the difference from G to C (i.e. with effects of F and G), 23 | while:: 24 | 25 | git diff master...topic 26 | 27 | would output just differences in the topic branch (i.e. only A, B, and 28 | C). 29 | -------------------------------------------------------------------------------- /docs/source/api.rst: -------------------------------------------------------------------------------- 1 | =========================== 2 | PyTOPKAPI API Documentation 3 | =========================== 4 | 5 | Main module 6 | =========== 7 | 8 | .. automodule:: pytopkapi.model 9 | :members: 10 | 11 | ODE module 12 | ========== 13 | 14 | .. automodule:: pytopkapi.ode 15 | :members: solve_storage_eq, qas, RKF 16 | :undoc-members: 17 | 18 | Fluxes module 19 | ============= 20 | .. automodule:: pytopkapi.fluxes 21 | :members: 22 | 23 | Evaporation module 24 | ================== 25 | .. automodule:: pytopkapi.evap 26 | :members: 27 | 28 | Pretreatment module 29 | =================== 30 | .. automodule:: pytopkapi.pretreatment 31 | :members: 32 | 33 | Utils module 34 | ============ 35 | .. automodule:: pytopkapi.utils 36 | :members: 37 | 38 | Arcfltgrid module 39 | ================= 40 | .. automodule:: pytopkapi.arcfltgrid 41 | :members: 42 | 43 | -------------------------------------------------------------------------------- /pytopkapi/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | PyTOPKAPI is a BSD licensed Python package implementing the TOPKAPI 3 | Hydrological model (Liu and Todini, 2002). The model is a 4 | physically-based and fully distributed hydrological model, which has 5 | already been successfully applied in several countries around the 6 | world (Liu and Todini, 2002; Bartholomes and Todini, 2005; Liu et al., 7 | 2005; Martina et al., 2006; Vischel et al., 2008, Sinclair and Pegram, 8 | 2010). 9 | 10 | """ 11 | 12 | try: 13 | from .__dev_version import version as __version__ 14 | from .__dev_version import git_revision as __git_revision__ 15 | except ImportError: 16 | from .__version import version as __version__ 17 | from .__version import git_revision as __git_revision__ 18 | 19 | from . import model 20 | from .model import * 21 | from . import results_analysis 22 | from .results_analysis import * 23 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/D8.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the model configuration. Paths may be specified relative 3 | # to the location of the script reading this file or in absolute terms. 4 | # At this stage a '/' must be used as the directory separator (even on Windows) 5 | 6 | [input_files] 7 | file_global_param = d8/global_param.dat 8 | file_cell_param = d8/cell_param.dat 9 | file_rain = d8/rainfall.h5 10 | file_ET = d8/evapotranspiration.h5 11 | 12 | [output_files] 13 | file_out = d8/simulation.h5 14 | append_output = False 15 | 16 | [groups] 17 | group_name = test_event 18 | 19 | [external_flow] 20 | external_flow = False 21 | 22 | [numerical_options] 23 | solve_s = 0 24 | solve_o = 0 25 | solve_c = 0 26 | only_channel_output = False 27 | 28 | [calib_params] 29 | fac_L = 1.0 30 | fac_Ks = 1.0 31 | fac_n_o = 1.0 32 | fac_n_c = 1.0 33 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/4cells.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the model configuration. Paths may be specified relative 3 | # to the location of the script reading this file or in absolute terms. 4 | # At this stage a '/' must be used as the directory separator (even on Windows) 5 | 6 | [input_files] 7 | file_global_param=4cells/global_parameters.dat 8 | file_cell_param=4cells/cell_parameters.dat 9 | file_rain=4cells/rainfall.h5 10 | file_ET=4cells/evapotranspiration.h5 11 | 12 | [output_files] 13 | file_out=4cells/simulation_results.h5 14 | append_output=False 15 | 16 | [groups] 17 | group_name=4cells 18 | 19 | [external_flow] 20 | external_flow=False 21 | 22 | [numerical_options] 23 | solve_s=0 24 | solve_o=0 25 | solve_c=0 26 | only_channel_output=False 27 | 28 | [calib_params] 29 | fac_L=1.0 30 | fac_Ks=1.0 31 | fac_n_o=1.0 32 | fac_n_c=1.0 33 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/lieb.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the model configuration. Paths may be specified relative 3 | # to the location of the script reading this file or in absolute terms. 4 | # At this stage a '/' must be used as the directory separator (even on Windows) 5 | 6 | [input_files] 7 | file_global_param = lieb/global_param.dat 8 | file_cell_param = lieb/cell_param.dat 9 | file_rain = lieb/rainfall.h5 10 | file_ET = lieb/evapotranspiration.h5 11 | 12 | [output_files] 13 | file_out = lieb/simulation.h5 14 | append_output = False 15 | 16 | [groups] 17 | group_name = sample_event 18 | 19 | [external_flow] 20 | external_flow = False 21 | 22 | [numerical_options] 23 | solve_s = 0 24 | solve_o = 0 25 | solve_c = 0 26 | only_channel_output = False 27 | 28 | [calib_params] 29 | fac_L = 1.0 30 | fac_Ks = 1.0 31 | fac_n_o = 1.0 32 | fac_n_c = 1.0 33 | -------------------------------------------------------------------------------- /docs/source/gitwash/following_latest.rst: -------------------------------------------------------------------------------- 1 | .. _following-latest: 2 | 3 | ============================= 4 | Following the latest source 5 | ============================= 6 | 7 | These are the instructions if you just want to follow the latest 8 | *PyTOPKAPI* source, but you don't need to do any development for now. 9 | 10 | The steps are: 11 | 12 | * :ref:`install-git` 13 | * get local copy of the git repository from github_ 14 | * update local copy from time to time 15 | 16 | Get the local copy of the code 17 | ============================== 18 | 19 | From the command line:: 20 | 21 | git clone git://github.com/sahg/PyTOPKAPI.git 22 | 23 | You now have a copy of the code tree in the new ``PyTOPKAPI`` directory. 24 | 25 | Updating the code 26 | ================= 27 | 28 | From time to time you may want to pull down the latest code. Do this with:: 29 | 30 | cd PyTOPKAPI 31 | git pull 32 | 33 | The tree in ``PyTOPKAPI`` will now have the latest changes from the initial 34 | repository. 35 | 36 | .. include:: git_links.inc 37 | -------------------------------------------------------------------------------- /example_simulation/coordinate-system.txt: -------------------------------------------------------------------------------- 1 | The coordinate system used in this example is Transverse Mercator, based on 2 | the Clarke 1880 ellipsoid. Conversion to and from this coordinate system can 3 | be achieved using many tools. This file contains the WKT and proj.4 strings 4 | defining the projection. 5 | 6 | Proj.4: 7 | 8 | '+proj=tmerc +lon_0=31 +a=6378249.145 +rf=293.465' 9 | 10 | e.g. 11 | 12 | >>> from pyproj import Proj 13 | >>> lons = an array/list of lons 14 | >>> lats = an array/list of lats 15 | >>> p = Proj('+proj=tmerc +lon_0=31 +a=6378249.145 +rf=293.465') 16 | >>> X, Y = p(lons, lats) 17 | 18 | WKT: 19 | 20 | PROJCS["Clarke_1880_RGS_Transverse_Mercator",GEOGCS["GCS_Clarke_1880_RGS",DATUM["D_Clarke_1880_RGS",SPHEROID["Clarke_1880_RGS",6378249.145,293.465]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",31.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]] -------------------------------------------------------------------------------- /pytopkapi/parameter_utils/common.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | def parameter_file_to_dataframe(param_fname): 5 | column_labels = ['cell_label', 6 | 'X', 7 | 'Y', 8 | 'lambda', 9 | 'Xc', 10 | 'dam', 11 | 'tan_beta', 12 | 'tan_beta_channel', 13 | 'L', 14 | 'Ks', 15 | 'theta_r', 16 | 'theta_s', 17 | 'n_o', 18 | 'n_c', 19 | 'cell_down', 20 | 'pVs_t0', 21 | 'ar_Vo_t0', 22 | 'Qc_t0', 23 | 'Kc', 24 | 'psi_b', 25 | 'lambda'] 26 | 27 | params = np.loadtxt(param_fname) 28 | 29 | params = pd.DataFrame(params[:, 1:], 30 | index=params[:, 0], columns=column_labels[1:]) 31 | 32 | return params 33 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_continuity/d8/cell_param.dat: -------------------------------------------------------------------------------- 1 | 0 -2.60E+005 -3.07E+006 1 1000 0 3.99E-003 4.76E-005 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 3.50E-002 -9999 5.00E+001 0 0 1 332.350006 0.1495 2 | 1 -2.61E+005 -3.07E+006 1 1000 0 1.52E-003 4.76E-005 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 3.50E-002 0 5.00E+001 0 0 1 332.350006 0.1495 3 | 2 -2.61E+005 -3.07E+006 0 1000 0 8.40E-003 3.00E-003 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 0 1 5.00E+001 0 0 1 332.350006 0.1495 4 | 3 -2.62E+005 -3.07E+006 0 1000 0 2.57E-003 1.00E-003 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 0 2 5.00E+001 0 0 1 332.350006 0.1495 5 | 4 -2.60E+005 -3.07E+006 1 1414.21 0 6.08E-003 2.00E-003 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 3.50E-002 1 5.00E+001 0 0 1 332.350006 0.1495 6 | 5 -2.62E+005 -3.07E+006 0 1000 0 1.00E-003 4.76E-005 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 0 4 5.00E+001 0 0 1 332.350006 0.1495 7 | 6 -2.61E+005 -3.07E+006 0 1000 0 5.81E-003 5.00E-004 6.70E-001 6.06E-005 4.10E-002 4.35E-001 4.00E-002 0 5 5.00E+001 0 0 1 332.350006 0.1495 8 | -------------------------------------------------------------------------------- /example_simulation/model-simulation.ini: -------------------------------------------------------------------------------- 1 | # This ini files describes the locations of the model input and output files 2 | # and controls some of the model configuration. Paths may be specified relative 3 | # to the location of the script reading this file or in absolute terms. At 4 | # this stage a '/' must be used as the directory separator (even on Windows) 5 | 6 | [input_files] 7 | file_global_param=parameter_files/global_param.dat 8 | file_cell_param=parameter_files/cell_param.dat 9 | file_rain=forcing_variables/rainfields.h5 10 | file_ET=forcing_variables/ET.h5 11 | 12 | [output_files] 13 | file_out=results/Example_simulation_results.h5 14 | append_output=False 15 | 16 | [groups] 17 | group_name=sample_event 18 | 19 | [external_flow] 20 | external_flow=True 21 | Xexternal_flow=-256314.83 22 | Yexternal_flow=-3149857.34 23 | file_Qexternal_flow=forcing_variables/external_lesotho_flows.dat 24 | 25 | [numerical_options] 26 | solve_s=1 27 | solve_o=1 28 | solve_c=1 29 | only_channel_output=False 30 | 31 | [calib_params] 32 | fac_L=1. 33 | fac_Ks=60.0 34 | fac_n_o=1.0 35 | fac_n_c=1.7 36 | -------------------------------------------------------------------------------- /docs/source/gitwash/forking_hell.rst: -------------------------------------------------------------------------------- 1 | .. _forking: 2 | 3 | ========================================== 4 | Making your own copy (fork) of PyTOPKAPI 5 | ========================================== 6 | 7 | You need to do this only once. The instructions here are very similar 8 | to the instructions at http://help.github.com/forking/ - please see that 9 | page for more detail. We're repeating some of it here just to give the 10 | specifics for the PyTOPKAPI_ project, and to suggest some default names. 11 | 12 | Set up and configure a github_ account 13 | ====================================== 14 | 15 | If you don't have a github_ account, go to the github_ page, and make one. 16 | 17 | You then need to configure your account to allow write access - see the 18 | ``Generating SSH keys`` help on `github help`_. 19 | 20 | Create your own forked copy of PyTOPKAPI_ 21 | ========================================= 22 | 23 | #. Log into your github_ account. 24 | #. Go to the PyTOPKAPI_ github home at `PyTOPKAPI github`_. 25 | #. Click on the *fork* button: 26 | 27 | .. image:: forking_button.png 28 | 29 | Now, after a short pause and some 'Hardcore forking action', you 30 | should find yourself at the home page for your own forked copy of PyTOPKAPI_. 31 | 32 | .. include:: git_links.inc 33 | 34 | -------------------------------------------------------------------------------- /docs/source/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "basic/layout.html" %} 2 | 3 | {% block rootrellink %} 4 |
  • Home
  • 5 |
  • Search
  • 6 | {% endblock %} 7 | 8 | 9 | {% block relbar1 %} 10 | 11 |
    12 | 13 | pyTOPKAPI
15 | logo 16 | 17 | Sponsor logos 19 | 20 |
    21 | {{ super() }} 22 | {% endblock %} 23 | 24 | {# put the sidebar before the body #} 25 | {% block sidebar1 %}{{ sidebar() }}{% endblock %} 26 | {% block sidebar2 %}{% endblock %} 27 | 28 | {% block footer %} 29 |

    30 | Creative Commons License 31 | Copyright {{ copyright }} 32 |
    33 | {%- if last_updated %} 34 | Last updated on {{ last_updated }} 35 | {%- endif %} 36 | {%- if show_sphinx %} 37 | | Created using Sphinx 38 | {%- endif %} 39 |

    40 | {% endblock %} 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2007-2017, PyTOPKAPI Developers. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above 12 | copyright notice, this list of conditions and the following 13 | disclaimer in the documentation and/or other materials provided 14 | with the distribution. 15 | 16 | * Neither the name of the PyTOPKAPI Developers nor the names of 17 | any contributors may be used to endorse or promote products 18 | derived from this software without specific prior written 19 | permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /create_distributions.py: -------------------------------------------------------------------------------- 1 | """Script to automate the creation of Windows and Linux source distributions. 2 | 3 | The TOPKAPI_example directory is also copied and the .svn directories stripped 4 | to make a clean distribution. The manual is included in MSWord format for now 5 | because this is how it's stored in SVN. 6 | 7 | This script currently relies on Linux tools and will only work on a Linux 8 | system. 9 | 10 | """ 11 | import os 12 | import shutil 13 | 14 | # Linux shell command to strip .svn directories 15 | command = 'find . -name .svn -type d -print0 | xargs -0 rm -rf' 16 | 17 | def make_distro(dist_path, ex_path, add_files): 18 | path = os.path.join(dist_path, ex_path) 19 | 20 | if os.path.isdir(dist_path): 21 | for root, dirs, files in os.walk(dist_path, topdown=False): 22 | for name in files: 23 | os.remove(os.path.join(root, name)) 24 | for name in dirs: 25 | os.rmdir(os.path.join(root, name)) 26 | else: 27 | os.mkdir(dist_path) 28 | 29 | shutil.copytree(ex_path, path) 30 | curr_dir = os.getcwd() 31 | os.chdir(path) 32 | os.system(command) 33 | os.chdir(curr_dir) 34 | 35 | for fname in add_files: 36 | shutil.copy(fname, dist_path) 37 | 38 | if __name__ == "__main__": 39 | # build source distributions 40 | os.system('python setup.py sdist --formats=gztar,zip --force-manifest') 41 | 42 | # make Linux distribution 43 | dist_path = 'TOPKAPI_linux' 44 | ex_path = 'TOPKAPI_Example' 45 | linux_files = ['dist/TOPKAPI-0.2dev.tar.gz', 'docs/TOPKAPI_Manual.doc'] 46 | 47 | make_distro(dist_path, ex_path, linux_files) 48 | 49 | # make Windows distribution 50 | dist_path = 'TOPKAPI_windows' 51 | ex_path = 'TOPKAPI_Example' 52 | windows_files = ['dist/TOPKAPI-0.2dev.zip', 'docs/TOPKAPI_Manual.doc'] 53 | 54 | make_distro(dist_path, ex_path, windows_files) 55 | -------------------------------------------------------------------------------- /docs/source/gitwash/git_resources.rst: -------------------------------------------------------------------------------- 1 | .. _git-resources: 2 | 3 | ================ 4 | git_ resources 5 | ================ 6 | 7 | Tutorials and summaries 8 | ======================= 9 | 10 | * `github help`_ has an excellent series of how-to guides. 11 | * `learn.github`_ has an excellent series of tutorials 12 | * The `pro git book`_ is a good in-depth book on git. 13 | * A `git cheat sheet`_ is a page giving summaries of common commands. 14 | * The `git user manual`_ 15 | * The `git tutorial`_ 16 | * The `git community book`_ 17 | * `git ready`_ - a nice series of tutorials 18 | * `git casts`_ - video snippets giving git how-tos. 19 | * `git magic`_ - extended introduction with intermediate detail 20 | * Our own :ref:`git-foundation`. 21 | * Fernando Perez' git page - `Fernando's git page`_ - many links and tips 22 | * A good but technical page on `git concepts`_ 23 | * The `git parable`_ is an easy read explaining the concepts behind git. 24 | * `git svn crash course`_: git_ for those of us used to subversion_ 25 | 26 | Advanced git workflow 27 | ===================== 28 | 29 | There are many ways of working with git_; here are some posts on the 30 | rules of thumb that other projects have come up with: 31 | 32 | * Linus Torvalds on `git management`_ 33 | * Linus Torvalds on `linux git workflow`_ . Summary; use the git tools 34 | to make the history of your edits as clean as possible; merge from 35 | upstream edits as little as possible in branches where you are doing 36 | active development. 37 | 38 | Manual pages online 39 | =================== 40 | 41 | You can get these on your own machine with (e.g) ``git help push`` or 42 | (same thing) ``git push --help``, but, for convenience, here are the 43 | online manual pages for some common commands: 44 | 45 | * `git add`_ 46 | * `git branch`_ 47 | * `git checkout`_ 48 | * `git clone`_ 49 | * `git commit`_ 50 | * `git config`_ 51 | * `git diff`_ 52 | * `git log`_ 53 | * `git pull`_ 54 | * `git push`_ 55 | * `git remote`_ 56 | * `git status`_ 57 | 58 | .. include:: git_links.inc 59 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_parameter_utils.py: -------------------------------------------------------------------------------- 1 | """Tests for the parameter_utils sub-package. 2 | 3 | """ 4 | import numpy as np 5 | import networkx as nx 6 | from osgeo import gdal 7 | 8 | from pytopkapi.parameter_utils.create_file import cell_connectivity 9 | from pytopkapi.parameter_utils.create_file import _make_strahler_dicts 10 | from pytopkapi.parameter_utils.create_file import strahler_stream_order 11 | 12 | def test_strahler_simple(): 13 | nodes = np.arange(5) 14 | edges = [(4,3), (3,1), (2,1), (1,0)] 15 | 16 | G = nx.DiGraph() 17 | G.add_nodes_from(nodes) 18 | G.add_edges_from(edges) 19 | 20 | stream_orders = {} 21 | 22 | nodes_per_arc, arcs_per_node = _make_strahler_dicts(G) 23 | strahler_stream_order(0, 1, nodes_per_arc, arcs_per_node, stream_orders) 24 | 25 | solution = {0 : 2, 1 : 1, 2 : 1, 3 : 1} 26 | assert(stream_orders == solution) 27 | 28 | def test_strahler_complex(): 29 | nodes = np.arange(14) 30 | edges = [(13,11), (12,11), (11,9), (10,9), 31 | (9,1), (1,0), (8,6), (7,6), (6,4), (5,4), (4,2), (3,2), (2,1)] 32 | 33 | G = nx.DiGraph() 34 | G.add_nodes_from(nodes) 35 | G.add_edges_from(edges) 36 | 37 | stream_orders = {} 38 | 39 | nodes_per_arc, arcs_per_node = _make_strahler_dicts(G) 40 | strahler_stream_order(0, 1, nodes_per_arc, arcs_per_node, stream_orders) 41 | 42 | solution = {0: 3, 1: 2, 2: 1, 3: 2, 4: 1, 43 | 5: 2, 6: 1, 7: 1, 8: 2, 9: 1, 10: 2, 11: 1, 12: 1} 44 | assert(stream_orders == solution) 45 | 46 | def test_outlet_on_boundary(): 47 | """Catchment outlet on the flow direction raster boundary should 48 | be properly handled. 49 | 50 | Github issue #7 (https://github.com/sahg/PyTOPKAPI/issues/7) 51 | 52 | """ 53 | dset = gdal.Open('pytopkapi/tests/test_data/flow_dir.flt') 54 | flowdir = dset.ReadAsArray() 55 | 56 | dset = gdal.Open('pytopkapi/tests/test_data/mask.flt') 57 | mask = dset.ReadAsArray() 58 | 59 | cell_down = cell_connectivity(flowdir, mask, source='ArcGIS') 60 | 61 | cell_down_expected = np.load('pytopkapi/tests/test_data/cell_down.npy') 62 | 63 | assert(np.all(cell_down == cell_down_expected)) 64 | -------------------------------------------------------------------------------- /docs/source/install.rst: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | =================================== 4 | PyTOPKAPI installation instructions 5 | =================================== 6 | 7 | Download 8 | -------- 9 | 10 | PyTOPKAPI source releases and a 32-bit Windows installer can be 11 | downloaded from http://github.com/sahg/PyTOPKAPI/downloads 12 | 13 | Prerequisites 14 | ------------- 15 | 16 | Before using the PyTOPKAPI package, you will need a working Python 17 | installation on your computer. Python can be obtained from 18 | http://www.python.org if it is not already present on your system. In 19 | addition, the model depends on a number of 3rd party Python packages, 20 | these are: `NumPy `_, `SciPy 21 | `_ and `PyTables 22 | `_. All of the 3rd party packages must be 23 | installed and working on your system for PyTOPKAPI to work correctly. 24 | 25 | In order to produce plots in the tutorial and to use the tools in the 26 | `results_analysis` sub-package, there is an additional optional 27 | dependency. Users wishing to produce plots using these tools must also 28 | install `Matplotlib `_. 29 | 30 | Windows Binary Installer 31 | ------------------------ 32 | 33 | Simply double-click the installer and follow the instructions. 34 | 35 | Source Install 36 | -------------- 37 | 38 | The PyTOPKAPI package currently consists of pure Python code and does 39 | not require any extension modules to be built, so installation from 40 | source is straightforward on all popular operating systems. Windows 41 | users who have installed PyTOPKAPI using the binary installer do not 42 | need to perform a source install. 43 | 44 | Once the prerequisite Python packages have been successfully 45 | installed, PyTOPKAPI can be installed by issuing the following command 46 | at the system command line:: 47 | 48 | $ python setup.py install 49 | 50 | If this fails, you'll need to check that the `python` executable is on 51 | your system path. 52 | 53 | Next steps 54 | ---------- 55 | 56 | Once installed a basic test of the installation can be made in the 57 | Python interpreter:: 58 | 59 | >>> import pytopkapi 60 | >>> print pytopkapi.__version__ 61 | 62 | New users should then follow the basic :ref:`tutorial `. 63 | -------------------------------------------------------------------------------- /docs/source/gitwash/set_up_fork.rst: -------------------------------------------------------------------------------- 1 | .. _set-up-fork: 2 | 3 | ================== 4 | Set up your fork 5 | ================== 6 | 7 | First you follow the instructions for :ref:`forking`. 8 | 9 | Overview 10 | ======== 11 | 12 | :: 13 | 14 | git clone git@github.com:your-user-name/PyTOPKAPI.git 15 | cd PyTOPKAPI 16 | git remote add upstream git://github.com/sahg/PyTOPKAPI.git 17 | 18 | In detail 19 | ========= 20 | 21 | Clone your fork 22 | --------------- 23 | 24 | #. Clone your fork to the local computer with ``git clone 25 | git@github.com:your-user-name/PyTOPKAPI.git`` 26 | #. Investigate. Change directory to your new repo: ``cd PyTOPKAPI``. Then 27 | ``git branch -a`` to show you all branches. You'll get something 28 | like:: 29 | 30 | * master 31 | remotes/origin/master 32 | 33 | This tells you that you are currently on the ``master`` branch, and 34 | that you also have a ``remote`` connection to ``origin/master``. 35 | What remote repository is ``remote/origin``? Try ``git remote -v`` to 36 | see the URLs for the remote. They will point to your github_ fork. 37 | 38 | Now you want to connect to the upstream `PyTOPKAPI github`_ repository, so 39 | you can merge in changes from trunk. 40 | 41 | .. _linking-to-upstream: 42 | 43 | Linking your repository to the upstream repo 44 | -------------------------------------------- 45 | 46 | :: 47 | 48 | cd PyTOPKAPI 49 | git remote add upstream git://github.com/sahg/PyTOPKAPI.git 50 | 51 | ``upstream`` here is just the arbitrary name we're using to refer to the 52 | main PyTOPKAPI_ repository at `PyTOPKAPI github`_. 53 | 54 | Note that we've used ``git://`` for the URL rather than ``git@``. The 55 | ``git://`` URL is read only. This means we that we can't accidentally 56 | (or deliberately) write to the upstream repo, and we are only going to 57 | use it to merge into our own code. 58 | 59 | Just for your own satisfaction, show yourself that you now have a new 60 | 'remote', with ``git remote -v show``, giving you something like:: 61 | 62 | upstream git://github.com/sahg/PyTOPKAPI.git (fetch) 63 | upstream git://github.com/sahg/PyTOPKAPI.git (push) 64 | origin git@github.com:your-user-name/PyTOPKAPI.git (fetch) 65 | origin git@github.com:your-user-name/PyTOPKAPI.git (push) 66 | 67 | .. include:: git_links.inc 68 | 69 | -------------------------------------------------------------------------------- /docs/source/_templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | {% set title = 'Overview' %} 3 | {% block body %} 4 |

    5 | PyTOPKAPI is 6 | a BSD 7 | licensed Python library implementing the TOPKAPI Hydrological 8 | model (Liu and Todini, 2002). The model is a physically-based and 9 | fully distributed hydrological model, which has already been 10 | successfully applied in several countries around the world (Liu 11 | and Todini, 2002; Bartholomes and Todini, 2005; Liu et al., 2005; 12 | Martina et al., 2006; Vischel et al., 2008, Sinclair and Pegram, 13 | 2010). 14 |

    15 | 16 |

    17 | The main strengths of the TOPKAPI model are: 18 |

    19 | 20 |
      21 |
    • The physical basis of the equations,
    • 22 |
    • the fine-scale representation of the spatial catchment 23 | features,
    • 24 |
    • the parsimonious parametrisation linked to field/catchment 25 | information,
    • 26 |
    • the good computation time performance,
    • 27 |
    • the modularity of the processes,
    • 28 |
    • the ease of use.
    • 29 |
    30 | 31 |

    32 | These and the good results obtained in modelling the river 33 | discharges of Liebenbergsvlei catchment, make the TOPKAPI model a 34 | promising tool for hydrological modelling of catchments in South 35 | Africa and around the world. 36 |

    37 | 38 |
    39 | 40 |

    Note

    41 |

    42 | PyTOPKAPI is under active development and the public interface 43 | (API) is not yet considered stable. However, the model is 44 | already usable and we would welcome feedback from users and 45 | collaborators as we work to stabilize the API and make the model 46 | more robust. 47 |

    48 |
    49 | 50 | 65 | 66 | {% endblock %} 67 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | 9 | # Internal variables. 10 | PAPEROPT_a4 = -D latex_paper_size=a4 11 | PAPEROPT_letter = -D latex_paper_size=letter 12 | ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 13 | 14 | .PHONY: help clean html web pickle htmlhelp latex changes linkcheck 15 | 16 | help: 17 | @echo "Please use \`make ' where is one of" 18 | @echo " html to make standalone HTML files" 19 | @echo " pickle to make pickle files" 20 | @echo " json to make JSON files" 21 | @echo " htmlhelp to make HTML files and a HTML help project" 22 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 23 | @echo " changes to make an overview over all changed/added/deprecated items" 24 | @echo " linkcheck to check all external links for integrity" 25 | 26 | clean: 27 | -rm -rf build/* 28 | 29 | html: 30 | mkdir -p build/html build/doctrees 31 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html 32 | @echo 33 | @echo "Build finished. The HTML pages are in build/html." 34 | 35 | pickle: 36 | mkdir -p build/pickle build/doctrees 37 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle 38 | @echo 39 | @echo "Build finished; now you can process the pickle files." 40 | 41 | web: pickle 42 | 43 | json: 44 | mkdir -p build/json build/doctrees 45 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json 46 | @echo 47 | @echo "Build finished; now you can process the JSON files." 48 | 49 | htmlhelp: 50 | mkdir -p build/htmlhelp build/doctrees 51 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp 52 | @echo 53 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 54 | ".hhp project file in build/htmlhelp." 55 | 56 | latex: 57 | mkdir -p build/latex build/doctrees 58 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex 59 | @echo 60 | @echo "Build finished; the LaTeX files are in build/latex." 61 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 62 | "run these through (pdf)latex." 63 | 64 | changes: 65 | mkdir -p build/changes build/doctrees 66 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes 67 | @echo 68 | @echo "The overview file is in build/changes." 69 | 70 | linkcheck: 71 | mkdir -p build/linkcheck build/doctrees 72 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck 73 | @echo 74 | @echo "Link check complete; look for any errors in the above output " \ 75 | "or in build/linkcheck/output.txt." 76 | -------------------------------------------------------------------------------- /pytopkapi/interpolation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import rpy 3 | from rpy import r 4 | 5 | from pytopkapi import arcfltgrid 6 | 7 | def krige_to_grid(grid_fname, obs_x, obs_y, obs_data, vgm_par): 8 | """Interpolate point data onto a grid using Kriging. 9 | 10 | Interpolate point data onto a regular rectangular grid of square cells using 11 | Kriging with a predefined semi-variogram. The observed data locations must 12 | be specified in the same projection and coordinate system as the grid, which 13 | is defined in an ArcGIS raster file. 14 | 15 | Parameters 16 | ---------- 17 | grid_fname : string 18 | Filename of an ArcGIS float grid raster defining the required grid to 19 | Krige onto. All cells are included regardless of their value. 20 | obs_x : array_like 21 | The x coordinates of the observation locations. 22 | obs_y : array_like 23 | The y coordinates of the observation locations. 24 | obs_data : array_like 25 | The data values at the observation locations. 26 | vgm : dict 27 | A dictionary describing the semi-variogram model. Required keys are: 28 | 'model' can be one of {'Lin', 'Exp', 'Sph', 'Gau'} 29 | 'nugget' must be a scalar 30 | 'range' must be a scalar 31 | 'sill' must be a scalar 32 | 33 | Returns 34 | ------- 35 | kriged_est : 2darray 36 | A 2D array containing the Kriged estimates at each point on the 37 | specified rectangular grid. 38 | 39 | Notes 40 | ----- 41 | This function requires that R, RPy and the R gstat library are correctly 42 | installed. 43 | 44 | """ 45 | grid, headers = arcfltgrid.read(grid_fname) 46 | cols = headers[0] 47 | rows = headers[1] 48 | x0 = headers[2] 49 | y0 = headers[3] 50 | cell_size = headers[4] 51 | # TO DO: adjust x0, y0 by 0.5*cell_size if llcorner.. 52 | 53 | # define the grid (pixel centre's) 54 | xt, yt = np.meshgrid(np.linspace(x0, x0 + (cols-1)*cell_size, num=cols), 55 | np.linspace(y0 + (rows-1)*cell_size, y0, num=rows)) 56 | 57 | xt = xt.flatten() 58 | yt = yt.flatten() 59 | 60 | # Krige using gstat via RPy 61 | r.library('gstat') 62 | rpy.set_default_mode(rpy.NO_CONVERSION) 63 | 64 | obs_frame = r.data_frame(x=obs_x, y=obs_y, data=obs_data) 65 | target_grid = r.data_frame(x=xt, y=yt) 66 | 67 | v = r.vgm(vgm_par['sill'], vgm_par['model'], 68 | vgm_par['range'], vgm_par['nugget']) 69 | 70 | result = r.krige(r('data ~ 1'), r('~ x + y'), 71 | obs_frame, target_grid, model=v) 72 | 73 | rpy.set_default_mode(rpy.BASIC_CONVERSION) 74 | 75 | result = result.as_py() 76 | 77 | kriged_est = np.array(result['var1.pred']) 78 | kriged_est = kriged_est.reshape(rows, cols) 79 | 80 | return kriged_est 81 | -------------------------------------------------------------------------------- /pytopkapi/arcfltgrid.py: -------------------------------------------------------------------------------- 1 | """Utilities for reading and plotting ArcGIS binary files. 2 | 3 | This module contains some simple functions to make it easier 4 | to read and plot the data contained in the binary grid files 5 | produced by ArcGIS. 6 | 7 | """ 8 | import sys 9 | import numpy as np 10 | from numpy import ma 11 | 12 | 13 | def read_bin(fname): 14 | """Read data from a ArcGIS binary file into an array. 15 | 16 | Read the data from a binary file created by ArcGIS into 17 | a Numpy array. The file is expected to be in binary format 18 | with floating point precision. e.g. ".flt" extension. 19 | 20 | """ 21 | 22 | f = open(fname, "rb") 23 | raw = f.read() 24 | f.close() 25 | data = np.fromstring(raw, 'f') 26 | if sys.byteorder == 'big': 27 | data = data.byteswap() 28 | 29 | return data 30 | 31 | def read(bingrid_name): 32 | """Read the data field and headers from an ArcGIS binary grid 33 | 34 | This function reads the header and data from the ArcGIS binary 35 | data files produced by the "Raster to Float" tool in ArcGIS 9.1 36 | 37 | """ 38 | 39 | if bingrid_name[-4:] == '.flt': 40 | hdr_name = bingrid_name[:-4] 41 | bin_name = bingrid_name 42 | else: 43 | hdr_name = bingrid_name 44 | bin_name = bingrid_name + '.flt' 45 | 46 | li_headers=read_headers(hdr_name) 47 | 48 | rows = li_headers[1] 49 | cols = li_headers[0] 50 | 51 | a = read_bin(bin_name) 52 | 53 | a = a.reshape(rows, cols) 54 | 55 | return a, li_headers 56 | 57 | def read_headers(bingrid_name): 58 | """Read the ascii headers of the ArcGIS binary grid file 59 | 60 | The headers have the following format: 61 | 62 | ncols 62 63 | nrows 121 64 | xllcorner -288595.47161281 65 | yllcorner -3158065.5722693 66 | cellsize 1000 67 | NODATA_value -9999 68 | byteorder LSBFIRST 69 | """ 70 | 71 | hdr_name = bingrid_name + '.hdr' 72 | f=open(hdr_name,'r') 73 | tab_read=f.readlines() 74 | f.close() 75 | 76 | li_headers=[] 77 | i=-1 78 | for line in tab_read: 79 | i=i+1 80 | donnees=line.split() 81 | if i<6: 82 | li_headers.append(float(donnees[1])) 83 | else: 84 | li_headers.append(donnees[1]) 85 | 86 | return li_headers 87 | 88 | def plot(bin_name, fig_name, title='Raster Plot'): 89 | """Create a plot of the data in an ArcGIS binary file.""" 90 | import matplotlib.pyplot as plt 91 | 92 | a, headers = read(bin_name) 93 | 94 | a_mask = ma.masked_where(a < 0, a) 95 | plt.imshow(a_mask, interpolation='nearest') 96 | plt.colorbar() 97 | plt.title(title) 98 | plt.savefig(fig_name) 99 | plt.close() 100 | -------------------------------------------------------------------------------- /pytopkapi/tests/test_infiltration.py: -------------------------------------------------------------------------------- 1 | """Tests for the infiltration module 2 | 3 | """ 4 | import numpy as np 5 | from scipy.optimize import fsolve 6 | 7 | from pytopkapi.infiltration import _green_ampt_cum_eq 8 | from pytopkapi.infiltration import green_ampt_cum_infiltration 9 | 10 | def test_basic_green_ampt(): 11 | """Test the Green-Ampt infiltration solution 12 | 13 | This test solves Example 4.3.1 pg 116 from Chow et al. 1988, 14 | 'Applied Hydrology' 15 | 16 | """ 17 | psi = 16.7 18 | eff_theta = 0.486 19 | eff_sat = 0.3 20 | K = 0.65 21 | dt = 1 22 | 23 | dtheta = (1 - eff_sat)*eff_theta 24 | 25 | F = K*dt # initial guess 26 | soln, infodict, ierr, mesg = fsolve(_green_ampt_cum_eq, F, 27 | args=(0, psi, 28 | dtheta, K, dt), 29 | full_output=True) 30 | cum_infil = soln[0] 31 | 32 | assert np.allclose(cum_infil, [3.16721373]) 33 | 34 | def test_cum_green_ampt_variable_rainfall(): 35 | """Test Green-Ampt with variable rainfall inputs 36 | 37 | This test solves Example 5.4.1 pg 144 from Chow et al., 1988, 38 | 'Applied Hydrology' 39 | 40 | """ 41 | psi = 11.01 42 | eff_theta = 0.412 43 | eff_sat = 0.4 44 | K = 1.09 45 | dt = 10/60.0 46 | rain = np.array([0.18, 47 | 0.21, 48 | 0.26, 49 | 0.32, 50 | 0.37, 51 | 0.43, 52 | 0.64, 53 | 1.14, 54 | 3.18, 55 | 1.65, 56 | 0.81, 57 | 0.52, 58 | 0.42, 59 | 0.36, 60 | 0.28, 61 | 0.24, 62 | 0.19, 63 | 0.17]) 64 | 65 | expected = np.array([0, 66 | 0.17999999999999999, 67 | 0.39000000000000001, 68 | 0.65000000000000002, 69 | 0.96999999999999997, 70 | 1.3399999999999999, 71 | 1.7699999999999998, 72 | 2.2010980254004107, 73 | 2.5894006663182325, 74 | 2.9497199417670243, 75 | 3.2899523056814881, 76 | 3.6148926600284406, 77 | 3.9277082030903774, 78 | 4.2306187029814302, 79 | 4.5252501037735513, 80 | 4.8052501037735516, 81 | 5.0452501037735518, 82 | 5.2352501037735522, 83 | 5.4052501037735521]) 84 | 85 | cum_rain = np.concatenate(([0], np.cumsum(rain))) 86 | 87 | F = [0] 88 | Ft = 0.0 89 | for r in rain/dt: 90 | Ft = green_ampt_cum_infiltration(r, psi, 91 | eff_theta, eff_sat, K, dt, Ft) 92 | F.append(Ft) 93 | 94 | assert(np.allclose(F, expected)) 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![PyTOPKAPI logo](http://sahg.github.io/PyTOPKAPI/static/logo.png) 2 | 3 | PyTOPKAPI is a BSD licensed Python library implementing the TOPKAPI 4 | Hydrological model (Liu and Todini, 2002). The model is a 5 | physically-based and fully distributed hydrological model, which has 6 | already been successfully applied in several countries around the 7 | world (e.g. Liu and Todini, 2002; Bartholomes and Todini, 2005; Liu et 8 | al., 2005; Martina et al., 2006; Vischel et al., 2008a/b). 9 | 10 | Install 11 | ------- 12 | 13 | Download the latest release 14 | [![DOI](https://zenodo.org/badge/689231.svg)](https://zenodo.org/badge/latestdoi/689231) 15 | Alternatively available on 16 | [Github](https://github.com/sahg/PyTOPKAPI/releases) 17 | 18 | The PyTOPKAPI package currently consists of pure Python code and does 19 | not require any extension modules to be built. However, the model 20 | depends on a number of 3rd party Python packages with compiled code 21 | linking to external libraries. These are most easily managed using the 22 | conda package manager from 23 | [Anaconda](https://docs.continuum.io/anaconda/). 24 | 25 | Once Anaconda is installed, a conda environment with the pre-requisite 26 | Python packages can be created and activated [this should be done from 27 | the root of the unpacked PyTOPKAPI archive]: 28 | 29 | $ conda env create -f conda-env.yaml 30 | $ source activate pytopkapi-0.4.x 31 | 32 | PyTOPKAPI can be installed into the conda environment using pip [note 33 | the 'dot' at the end, which refers to the current directory]: 34 | 35 | $ pip install --upgrade . 36 | 37 | The package tests can be run as follows: 38 | 39 | $ nosetests 40 | 41 | An example simulation can be run from the *example_simulation* 42 | directory: 43 | 44 | $ cd example_simulation 45 | $ python run_example.py 46 | 47 | Documentation 48 | ------------- 49 | 50 | The most recent documentation for PyTOPKAPI can be found at 51 | http://sahg.github.io/PyTOPKAPI/ 52 | 53 | 54 | Citation 55 | -------- 56 | 57 | Latest release: 58 | 59 | [![DOI](https://zenodo.org/badge/689231.svg)](https://zenodo.org/badge/latestdoi/689231) 60 | 61 | Selected publications: 62 | 63 | Sinclair S. and Pegram G.G.S., (2010), "A comparison of ASCAT and 64 | modeled soil moisture over South Africa, using TOPKAPI in land surface 65 | mode", Hydrol. Earth Syst. Sci., 14, 613-626. [Full Text via 66 | CrossRef](http://dx.doi.org/10.5194/hess-14-613-2010) 67 | 68 | Sinclair S. and Pegram G.G.S., (2013), "A sensitivity assessment of 69 | the TOPKAPI model with an added infiltration module", J. Hydrol., 479, 70 | 100-112. [Full Text via 71 | CrossRef](http://dx.doi.org/10.1016/j.jhydrol.2012.11.061) 72 | 73 | Vischel T., Pegram G.G.S., Sinclair S. and Parak M., (2008a), 74 | "Implementation of the TOPKAPI model in South Africa: Initial results 75 | from the Liebenbergsvlei catchment", Water SA, 34(3), 1-12. [Full 76 | Text](http://hdl.handle.net/10520/EJC116536) 77 | 78 | Vischel T., Pegram G.G.S., Sinclair S., Wagner W. and Bartsch A., 79 | (2008b), "Comparison of soil moisture fields estimated by catchment 80 | modelling and remote sensing: a case study in South Africa", 81 | Hydrol. Earth Syst. Sci., 12, 751-767. [Full Text via 82 | CrossRef](http://dx.doi.org/10.5194/hess-12-751-2008) -------------------------------------------------------------------------------- /scripts/run-grass-script: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | """Wrapper script to set-up proper environment to run GRASS 4 | 5 | Before importing the grass package, the correct environment variables 6 | must be set. This script sets up the environment for a Linux system, 7 | according to the specified GRASSRC file (or the default GRASSRC if not 8 | specified) then calls the processing script in a subprocess. 9 | 10 | """ 11 | import os 12 | import warnings 13 | import optparse 14 | import subprocess 15 | 16 | from pytopkapi.utils import exec_command 17 | 18 | def prepend_env_var(key, val): 19 | """Prepend `val` to an environment variable 20 | 21 | A new variable is created if `key` doesn't exist, otherwise `val` 22 | is prepended to the existing environment variable. 23 | 24 | Parameters 25 | ---------- 26 | key : string 27 | The name of the environment variable 28 | val : string 29 | The value to prepend 30 | 31 | """ 32 | if key in os.environ.keys(): 33 | old_val = os.environ[key] 34 | 35 | os.environ[key] = ':'.join([val, old_val]) 36 | else: 37 | os.environ[key] = val 38 | 39 | def find_gisbase(): 40 | """Find the value of the GISBASE environ variable on Linux 41 | 42 | A bit hackish, but seems to work for now.. 43 | 44 | """ 45 | gscript = subprocess.check_output(['which', 'grass']).strip('\n') 46 | 47 | fp = open(gscript, 'r') 48 | for line in fp: 49 | if 'GISBASE=' in line: 50 | gis_base = line.split('=')[1] 51 | fp.close() 52 | 53 | return gis_base.strip() # remove line-endings 54 | 55 | def main(): 56 | """Runs program and handles command line options""" 57 | 58 | parser = optparse.OptionParser(description="""Set up proper environment for GRASS and run the specified script in a sub-process""", 59 | prog='run-grass-script', 60 | version='0.1', 61 | usage='%prog