├── docs ├── _static │ ├── .keep │ ├── theme-deltares.css │ ├── deltares.svg │ ├── deltares-white.svg │ └── enabling-delta-life.svg ├── history.rst ├── contributing.rst ├── minimal_example.rst ├── index.rst ├── usage.rst ├── modules.rst ├── Makefile ├── make.bat ├── examples │ ├── minimal_example.py │ └── retrieve_parallel_to_netcdf.py └── conf.py ├── MANIFEST.in ├── .bumpversion.cfg ├── .editorconfig ├── .github ├── ISSUE_TEMPLATE.md └── workflows │ ├── pypi-upload.yml │ ├── pytest.yml │ └── sphinx-docs.yml ├── ddlpy ├── __init__.py ├── cli.py ├── utils.py ├── endpoints.json ├── waterinfo.py └── ddlpy.py ├── tests ├── test_waterinfo.py ├── test_utils.py ├── bulk.json ├── test_endpoints.py ├── test_cli.py ├── NVT_WATHTE_SCHE_20200507.csv └── test_ddlpy.py ├── .gitignore ├── pyproject.toml ├── Makefile ├── README.md ├── CONTRIBUTING.rst ├── HISTORY.rst └── LICENSE /docs/_static/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/minimal_example.rst: -------------------------------------------------------------------------------- 1 | Minimal example 2 | =============== 3 | 4 | .. literalinclude:: examples/minimal_example.py 5 | :language: python 6 | :linenos: 7 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. mdinclude:: ../README.md 2 | 3 | .. toctree:: 4 | :titlesonly: 5 | :hidden: 6 | 7 | usage 8 | modules 9 | contributing 10 | history -------------------------------------------------------------------------------- /docs/_static/theme-deltares.css: -------------------------------------------------------------------------------- 1 | /* enlarge deltares & github icon size; only works with local/url svg files; not with fa icons */ 2 | img.icon-link-image { 3 | height: 2.5em !important; 4 | } -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | =========== 3 | 4 | .. toctree:: 5 | :titlesonly: 6 | :hidden: 7 | :maxdepth: 2 8 | 9 | notebooks/measurements.ipynb 10 | notebooks/waterinfo.ipynb 11 | minimal_example.rst 12 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CONTRIBUTING.rst 2 | include HISTORY.rst 3 | include LICENSE 4 | include README.md 5 | 6 | include ddlpy/endpoints.json 7 | 8 | recursive-include tests * 9 | recursive-exclude * __pycache__ 10 | recursive-exclude * *.py[co] 11 | 12 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 13 | -------------------------------------------------------------------------------- /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.10.1 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:pyproject.toml] 7 | search = version = "{current_version}" 8 | replace = version = "{new_version}" 9 | 10 | [bumpversion:file:ddlpy/__init__.py] 11 | search = __version__ = "{current_version}" 12 | replace = __version__ = "{new_version}" 13 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | Modules 2 | ========= 3 | 4 | ddlpy.cli module 5 | ---------------- 6 | 7 | .. automodule:: ddlpy.cli 8 | :members: 9 | :undoc-members: 10 | :show-inheritance: 11 | 12 | 13 | ddlpy module 14 | --------------- 15 | 16 | .. automodule:: ddlpy 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | :member-order: bysource 21 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * ddlpy version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ```python 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /ddlpy/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Top-level package for Data Distributie Laag. Service from Rijkswaterstaat for distributing water quantity data..""" 4 | 5 | __version__ = "0.10.1" 6 | 7 | from ddlpy.ddlpy import locations 8 | from ddlpy.ddlpy import ( 9 | measurements, 10 | measurements_latest, 11 | measurements_available, 12 | measurements_amount, 13 | ) 14 | from ddlpy.utils import simplify_dataframe, dataframe_to_xarray 15 | 16 | __all__ = [ 17 | "locations", 18 | "measurements", 19 | "measurements_latest", 20 | "measurements_available", 21 | "measurements_amount", 22 | "simplify_dataframe", 23 | "dataframe_to_xarray", 24 | ] 25 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = ddlpy 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /.github/workflows/pypi-upload.yml: -------------------------------------------------------------------------------- 1 | name: pypi-upload 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-python@v5 14 | with: 15 | python-version: '3.11' 16 | - name: Install dependencies 17 | run: | 18 | python -m pip install --upgrade pip 19 | python -m pip install -e .[dev] 20 | - name: Build and publish 21 | env: 22 | TWINE_USERNAME: __token__ 23 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 24 | run: | 25 | python -m build 26 | twine check dist/* 27 | twine upload dist/* 28 | -------------------------------------------------------------------------------- /tests/test_waterinfo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Mar 12 15:33:59 2024 4 | 5 | @author: veenstra 6 | """ 7 | 8 | from ddlpy.waterinfo import waterinfo_read 9 | import os 10 | 11 | dir_tests = os.path.dirname(os.path.abspath(__file__)) 12 | 13 | 14 | def test_waterinfo_read(): 15 | # example in May, during DST 16 | f = os.path.join(dir_tests, "20200608_069_20200507.csv") 17 | g = os.path.join(dir_tests, "NVT_WATHTE_SCHE_20200507.csv") 18 | 19 | dxf_list = waterinfo_read(f, block=False) 20 | dxg_list = waterinfo_read(g, block=False) 21 | 22 | dxf0 = dxf_list[0] 23 | dxg0 = dxg_list[0] 24 | assert "time" in dxf0.variables 25 | assert "data" in dxf0.variables 26 | assert "time" in dxg0.variables 27 | assert "data" in dxg0.variables 28 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=python -msphinx 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=ddlpy 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The Sphinx module was not found. Make sure you have Sphinx installed, 20 | echo.then set the SPHINXBUILD environment variable to point to the full 21 | echo.path of the 'sphinx-build' executable. Alternatively you may add the 22 | echo.Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /.github/workflows/pytest.yml: -------------------------------------------------------------------------------- 1 | name: pytest 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | jobs: 12 | build: 13 | 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | # we assume it also works for inbetween versions 18 | python-version: ["3.9", "3.12", "3.14"] 19 | os: [ubuntu-latest, windows-latest, macos-latest] 20 | runs-on: ${{ matrix.os }} 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Set up Python 25 | uses: actions/setup-python@v5 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | python -m pip install -e .[dev,netcdf] 32 | - name: list env contents 33 | run: | 34 | pip list 35 | - name: Lint with flake8 36 | run: | 37 | flake8 . --max-line-length=88 --extend-ignore=E501 --exclude=docs/examples 38 | - name: Test with pytest 39 | run: | 40 | pytest --cov=ddlpy --cov-report xml --cov-report term 41 | - uses: codecov/codecov-action@v4 42 | env: 43 | CODECOV_TOKEN: ${{secrets.CODECOV_TOKEN}} 44 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Tests for `utils` package.""" 5 | 6 | from ddlpy.utils import date_series 7 | import datetime 8 | 9 | 10 | def test_date_series(): 11 | """Sample pytest test function with the pytest fixture as an argument.""" 12 | # from bs4 import BeautifulSoup 13 | # assert 'GitHub' in BeautifulSoup(response.content).title.string 14 | start = datetime.datetime(2018, 1, 1) 15 | end = datetime.datetime(2018, 3, 1) 16 | result = date_series(start, end) 17 | expected = [ 18 | (datetime.datetime(2018, 1, 1, 0, 0), datetime.datetime(2018, 2, 1, 0, 0)), 19 | (datetime.datetime(2018, 2, 1, 0, 0), datetime.datetime(2018, 3, 1, 0, 0)), 20 | ] 21 | assert result == expected 22 | 23 | start = datetime.datetime(2017, 11, 15) 24 | end = datetime.datetime(2018, 3, 5) 25 | result = date_series(start, end) 26 | expected = [ 27 | (datetime.datetime(2017, 11, 15, 0, 0), datetime.datetime(2017, 12, 15, 0, 0)), 28 | (datetime.datetime(2017, 12, 15, 0, 0), datetime.datetime(2018, 1, 15, 0, 0)), 29 | (datetime.datetime(2018, 1, 15, 0, 0), datetime.datetime(2018, 2, 15, 0, 0)), 30 | (datetime.datetime(2018, 2, 15, 0, 0), datetime.datetime(2018, 3, 5, 0, 0)), 31 | ] 32 | assert result == expected 33 | -------------------------------------------------------------------------------- /.github/workflows/sphinx-docs.yml: -------------------------------------------------------------------------------- 1 | name: sphinx-docs 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | 7 | permissions: 8 | contents: read 9 | pages: write 10 | id-token: write 11 | 12 | jobs: 13 | build: 14 | runs-on: windows-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-python@v5 18 | with: 19 | python-version: '3.11' 20 | - name: install pandoc 21 | # pip install is not seen somehow, so via choco 22 | run: | 23 | choco install pandoc 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | python -m pip install -e .[docs] 28 | - name: Sphinx build 29 | run: | 30 | sphinx-build docs docs/_build 31 | - uses: actions/upload-pages-artifact@v3 32 | with: 33 | path: docs/_build/ 34 | 35 | # Deploy the artifact to GitHub pages. 36 | # This is a separate job so that only actions/deploy-pages has the necessary permissions. 37 | deploy: 38 | needs: build 39 | runs-on: ubuntu-latest 40 | permissions: 41 | pages: write 42 | id-token: write 43 | environment: 44 | name: github-pages 45 | url: ${{ steps.deployment.outputs.page_url }} 46 | steps: 47 | - id: deployment 48 | uses: actions/deploy-pages@v4 -------------------------------------------------------------------------------- /docs/examples/minimal_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a minimal example on how to retrieve data from the DDL with ddlpy. 3 | """ 4 | 5 | import ddlpy 6 | import datetime as dt 7 | 8 | # enabling debug logging so we can see what happens in the background 9 | import logging 10 | logging.basicConfig() 11 | logging.getLogger("ddlpy").setLevel(logging.DEBUG) 12 | 13 | # get the dataframe with locations and their available parameters 14 | locations = ddlpy.locations() 15 | 16 | # Filter the locations dataframe with the desired parameters and stations. 17 | bool_stations = locations.index.isin(["ijmuiden.buitenhaven", "dantziggat.zuid", "hoekvanholland", "ameland.nes"]) 18 | # meting/astronomisch/verwachting 19 | bool_procestype = locations["ProcesType"].isin(["meting"]) 20 | # waterlevel/waterhoogte (WATHTE) 21 | bool_grootheid = locations["Grootheid.Code"].isin(["WATHTE"]) 22 | # timeseries ("") versus extremes (GETETM2/GETETMSL2/GETETBRKD2/GETETBRKDMSL2) 23 | bool_groepering = locations["Groepering.Code"].isin([""]) 24 | # vertical reference (NAP/MSL) 25 | bool_hoedanigheid = locations["Hoedanigheid.Code"].isin(["NAP"]) 26 | selected = locations.loc[ 27 | bool_procestype 28 | & bool_stations 29 | & bool_grootheid 30 | & bool_groepering 31 | & bool_hoedanigheid 32 | ] 33 | 34 | start_date = dt.datetime(2023, 1, 1) 35 | end_date = dt.datetime(2023, 1, 15) 36 | 37 | # provide a single row of the locations dataframe to ddlpy.measurements 38 | measurements = ddlpy.measurements(selected.iloc[0], start_date=start_date, end_date=end_date) 39 | 40 | if not measurements.empty: 41 | print("Data was found in RWS Waterwebservices/DDL") 42 | measurements.plot(y="Meetwaarde.Waarde_Numeriek", linewidth=0.8) 43 | else: 44 | print("No Data!") 45 | -------------------------------------------------------------------------------- /docs/_static/deltares.svg: -------------------------------------------------------------------------------- 1 | Artboard 1 -------------------------------------------------------------------------------- /docs/_static/deltares-white.svg: -------------------------------------------------------------------------------- 1 | Artboard 1 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # README.rst is generated from README.md, see Makefile 2 | README.rst 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # dotenv 89 | .env 90 | 91 | # virtualenv 92 | .venv 93 | venv/ 94 | ENV/ 95 | # Environments 96 | .env 97 | .venv 98 | env/ 99 | venv/ 100 | ENV/ 101 | env.bak/ 102 | venv.bak/ 103 | 104 | # Spyder project settings 105 | .spyderproject 106 | .spyproject 107 | 108 | # Rope project settings 109 | .ropeproject 110 | 111 | # mkdocs documentation 112 | /site 113 | 114 | # mypy 115 | .mypy_cache/ 116 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=64.0.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "rws-ddlpy" 7 | version = "0.10.1" 8 | maintainers = [ 9 | { name = "Fedor Baart", email = "fedor.baart@deltares.nl"}, 10 | { name = "Jelmer Veenstra", email = "jelmer.veenstra@deltares.nl"}, 11 | ] 12 | description = "Service from Rijkswaterstaat for distributing water quantity data." 13 | readme = "README.md" 14 | keywords = ["ddlpy"] 15 | license = "GPL-3.0" 16 | license-files = ["LICENSE"] 17 | requires-python = ">=3.9" 18 | dependencies = [ 19 | #numpy 1.21 is EOL since june 2023 20 | "numpy>=1.22", 21 | "pandas", 22 | "python-dateutil>=2.8", 23 | "pytz", 24 | "tqdm", 25 | "click", 26 | "requests", 27 | "platformdirs", # to create cache dir 28 | ] 29 | classifiers = [ 30 | "Development Status :: 3 - Alpha", 31 | "Intended Audience :: Developers", 32 | "Intended Audience :: Science/Research", 33 | "Operating System :: OS Independent", 34 | "Natural Language :: English", 35 | "Programming Language :: Python", 36 | "Programming Language :: Python :: 3", 37 | "Programming Language :: Python :: 3.9", 38 | "Programming Language :: Python :: 3.10", 39 | "Programming Language :: Python :: 3.11", 40 | "Programming Language :: Python :: 3.12", 41 | "Programming Language :: Python :: 3.13", 42 | "Programming Language :: Python :: 3.14", 43 | ] 44 | 45 | [project.urls] 46 | Home = "https://github.com/deltares/ddlpy" 47 | Code = "https://github.com/deltares/ddlpy" 48 | Issues = "https://github.com/deltares/ddlpy/issues" 49 | 50 | [project.optional-dependencies] 51 | dev = [ 52 | "bump2version>=0.5.11", 53 | "flake8", 54 | "pytest>=3.8.2", 55 | "pytest-cov", 56 | "twine", 57 | "build", 58 | "flake8>=3.5.0", 59 | "tox>=3.5.2", 60 | "twine>=1.12.1", 61 | ] 62 | docs = [ 63 | "sphinx>=1.8.1", 64 | "sphinx_mdinclude", 65 | "nbsphinx", 66 | "pydata-sphinx-theme", 67 | #"pandoc", # installed with choco on github 68 | ] 69 | examples = [ 70 | "jupyter", 71 | "notebook", 72 | "matplotlib", 73 | ] 74 | netcdf = [ 75 | "xarray", 76 | "h5netcdf", 77 | ] 78 | 79 | [project.scripts] 80 | ddlpy = "ddlpy.cli:cli" 81 | 82 | [tool.setuptools] 83 | packages = ["ddlpy"] 84 | 85 | [tool.pytest.ini_options] 86 | testpaths = ["tests"] 87 | addopts = "--durations=0" 88 | filterwarnings = [ 89 | "error", 90 | ] 91 | 92 | [tool.flake8] 93 | exclude = "docs" 94 | -------------------------------------------------------------------------------- /tests/bulk.json: -------------------------------------------------------------------------------- 1 | { 2 | "Zoekvraag": { 3 | "AquoMetadataLijst": [ 4 | { 5 | "Grootheid": { 6 | "Code": "H1/3" 7 | }, 8 | "Eenheid": { 9 | "Code": "cm" 10 | } 11 | }, 12 | { 13 | "Compartiment": { 14 | "Code": "OW" 15 | }, 16 | "Eenheid": { 17 | "Code": "%" 18 | }, 19 | "Grootheid": { 20 | "Code": "VERDGGD" 21 | }, 22 | "Parameter": { 23 | "Code": "O2" 24 | } 25 | }, 26 | { 27 | "Compartiment": { 28 | "Code": "OW" 29 | }, 30 | "Eenheid": { 31 | "Code": "mg/l" 32 | }, 33 | "Parameter": { 34 | "Code": "O2" 35 | } 36 | } 37 | ], 38 | "LocatieLijst": [ 39 | { 40 | "X": 742469.913149676, 41 | "Y": 5940708.14824459, 42 | "Code": "HUIBGOT" 43 | }, 44 | { 45 | "X": 595875.376191307, 46 | "Y" : 5790952.82210343, 47 | "Code": 48 | "NOORDWK2" 49 | }, 50 | { 51 | "X": 571670.054611366, 52 | "Y" : 5822651.05560318, 53 | "Code": "IJMDMNTSPS" 54 | } 55 | ], 56 | "Periode": { 57 | "Begindatumtijd" : "2009-01-01T00:00:00.000+01:00", 58 | "Einddatumtijd" : "2011-12-31T23:59:59.999+01:00" 59 | } 60 | }, 61 | "Email_succes": { 62 | "From": "info@rws.nl", 63 | "To": "fedor.baart@deltares.nl", 64 | "Subject": "Aanvraag bestand waarnemingen test", 65 | "Body": "Uw bestand met waarnemingen kunt u downloaden via {link_bestand}." 66 | }, 67 | "Email_fout": { 68 | "From": "info@rws.nl", 69 | "To": "aanvrager@rws.nl", 70 | "Subject": "Aanvraag niet gelukt test", 71 | "Body" : "Uw aanvraag voor het bestand met waarnemingen is mislukt." 72 | }, 73 | "Email_bevestiging": { 74 | "From": "info@rws.nl", 75 | "To": "aanvrager@rws.nl", 76 | "Subject" : "Bevestiging van aanvraag test", 77 | "Body":"Uw aanvraag is ontvangen. U ontvangt binnen 24 uur een e-mail met daarin een link voor het downloaden van de aanvraag." 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | 4 | define BROWSER_PYSCRIPT 5 | import os, webbrowser, sys 6 | 7 | try: 8 | from urllib import pathname2url 9 | except: 10 | from urllib.request import pathname2url 11 | 12 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 13 | endef 14 | export BROWSER_PYSCRIPT 15 | 16 | define PRINT_HELP_PYSCRIPT 17 | import re, sys 18 | 19 | for line in sys.stdin: 20 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 21 | if match: 22 | target, help = match.groups() 23 | print("%-20s %s" % (target, help)) 24 | endef 25 | export PRINT_HELP_PYSCRIPT 26 | 27 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 28 | 29 | help: 30 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 31 | 32 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 33 | 34 | clean-build: ## remove build artifacts 35 | rm -fr build/ 36 | rm -fr dist/ 37 | rm -fr .eggs/ 38 | rm -f README.rst 39 | find . -name '*.egg-info' -exec rm -fr {} + 40 | find . -name '*.egg' -exec rm -f {} + 41 | 42 | clean-pyc: ## remove Python file artifacts 43 | find . -name '*.pyc' -exec rm -f {} + 44 | find . -name '*.pyo' -exec rm -f {} + 45 | find . -name '*~' -exec rm -f {} + 46 | find . -name '__pycache__' -exec rm -fr {} + 47 | 48 | clean-test: ## remove test and coverage artifacts 49 | rm -fr .tox/ 50 | rm -f .coverage 51 | rm -fr htmlcov/ 52 | rm -fr .pytest_cache 53 | 54 | lint: ## check style with flake8 55 | flake8 ddlpy tests 56 | 57 | test: ## run tests quickly with the default Python 58 | py.test 59 | 60 | test-all: ## run tests on every Python version with tox 61 | tox 62 | 63 | coverage: ## check code coverage quickly with the default Python 64 | coverage run --source ddlpy -m pytest 65 | coverage report -m 66 | coverage html 67 | $(BROWSER) htmlcov/index.html 68 | 69 | README.rst: README.md 70 | pandoc --from=markdown --to=rst --output=README.rst README.md 71 | 72 | docs: README.rst ## generate Sphinx HTML documentation, including API docs 73 | rm -f docs/ddlpy.rst 74 | rm -f docs/modules.rst 75 | sphinx-apidoc -o docs/ ddlpy 76 | $(MAKE) -C docs clean 77 | $(MAKE) -C docs html 78 | $(BROWSER) docs/_build/html/index.html 79 | 80 | servedocs: docs ## compile the docs watching for changes 81 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 82 | 83 | release: dist ## package and upload a release 84 | twine upload dist/* 85 | 86 | dist: clean ## builds source and wheel package 87 | python setup.py sdist 88 | python setup.py bdist_wheel 89 | ls -l dist 90 | 91 | install: clean ## install the package to the active Python's site-packages 92 | python setup.py install 93 | -------------------------------------------------------------------------------- /tests/test_endpoints.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Tests for `ddlpy` package.""" 5 | 6 | import pytest 7 | import requests 8 | import ddlpy 9 | 10 | 11 | @pytest.fixture(scope="session") 12 | def endpoints(): 13 | """ 14 | Get the endpoints from the api 15 | """ 16 | endpoints = ddlpy.ddlpy.ENDPOINTS 17 | return endpoints 18 | 19 | 20 | @pytest.fixture 21 | def collect_catalogue_resp(endpoints): 22 | endpoint = endpoints["collect_catalogue"] 23 | resp = requests.post(endpoint["url"], json=endpoint["request"]) 24 | return resp 25 | 26 | 27 | def test_collect_catalogue(collect_catalogue_resp): 28 | assert collect_catalogue_resp.status_code == 200 29 | 30 | 31 | @pytest.fixture 32 | def collect_observations_resp(endpoints): 33 | endpoint = endpoints["collect_observations"] 34 | request = endpoint["request"] 35 | resp = requests.post(endpoint["url"], json=request) 36 | return resp 37 | 38 | 39 | def test_collect_observations(collect_observations_resp): 40 | assert collect_observations_resp.status_code == 200 41 | 42 | 43 | @pytest.fixture 44 | def collect_latest_observations_resp(endpoints): 45 | endpoint = endpoints["collect_latest_observations"] 46 | request = endpoint["request"] 47 | resp = requests.post(endpoint["url"], json=request) 48 | return resp 49 | 50 | 51 | def test_collect_latest_observations(collect_latest_observations_resp): 52 | assert collect_latest_observations_resp.status_code == 200 53 | 54 | 55 | @pytest.fixture 56 | def check_observations_available_resp(endpoints): 57 | endpoint = endpoints["check_observations_available"] 58 | resp = requests.post(endpoint["url"], json=endpoint["request"]) 59 | return resp 60 | 61 | 62 | def test_check_observations_available(check_observations_available_resp): 63 | assert check_observations_available_resp.status_code == 200 64 | 65 | 66 | @pytest.fixture 67 | def collect_number_of_observations_resp(endpoints): 68 | endpoint = endpoints["collect_number_of_observations"] 69 | resp = requests.post(endpoint["url"], json=endpoint["request"]) 70 | return resp 71 | 72 | 73 | def test_collect_number_of_observations(collect_number_of_observations_resp): 74 | assert collect_number_of_observations_resp.status_code == 200 75 | 76 | 77 | # TODO: AanvragenBulkWaarnemingen not present in new WaterWebservices 78 | # https://github.com/Deltares/ddlpy/issues/145 79 | # https://github.com/Rijkswaterstaat/WaterWebservices/issues/15 80 | # @pytest.fixture 81 | # def request_bulk_observations_resp(endpoints): 82 | # endpoint = endpoints['request_bulk_observations'] 83 | # resp = requests.post(endpoint['url'], json=endpoint['request']) 84 | # return resp 85 | 86 | # def test_request_bulk_observations(request_bulk_observations_resp): 87 | # assert request_bulk_observations_resp.status_code == 200 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![pypi-image](https://img.shields.io/pypi/v/rws-ddlpy.svg)](https://pypi.python.org/pypi/rws-ddlpy) 2 | [![pytest](https://github.com/Deltares/ddlpy/actions/workflows/pytest.yml/badge.svg?branch=main)](https://github.com/Deltares/ddlpy/actions/workflows/pytest.yml) 3 | [![codecov](https://img.shields.io/codecov/c/github/deltares/ddlpy.svg?style=flat-square)](https://app.codecov.io/gh/deltares/ddlpy?displayType=list) 4 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=Deltares_ddlpy&metric=alert_status)](https://sonarcloud.io/summary/overall?id=Deltares_ddlpy) 5 | [![Supported versions](https://img.shields.io/pypi/pyversions/rws-ddlpy.svg)](https://pypi.org/project/rws-ddlpy) 6 | [![Downloads](https://img.shields.io/pypi/dm/rws-ddlpy.svg)](https://pypistats.org/packages/rws-ddlpy) 7 | 8 | # ddlpy 9 | 10 | (D)ata (D)istributie (L)aag is a service from Rijkswaterstaat for distributing water quantity data, more information is available at https://rijkswaterstaatdata.nl/waterdata. This package provides an API for Python and includes easy filtering of available data and stations, convenient conversion to pandas and xarray objects, automatic chunking of large data requests, error handling and much more nifty features. See also https://github.com/wstolte/rwsapi for the R API. 11 | 12 | # Install 13 | 14 | Install the latest ddlpy PyPI release with (extra dependencies between `[]` are optional): 15 | 16 | pip install rws-ddlpy[netcdf,examples] 17 | 18 | # Examples 19 | 20 | Documentation: 21 | 22 | In the examples/notebooks folders you will find the following examples to get you started: 23 | 24 | * [minimal_example.py](https://github.com/Deltares/ddlpy/blob/main/docs/examples/minimal_example.py) -> minimal code to retrieve data. 25 | 26 | * [retrieve_parallel_to_netcdf.py](https://github.com/Deltares/ddlpy/blob/main/docs/examples/retrieve_parallel_to_netcdf.py) -> Code to retrieve a bulk of observations and write to netcdf files for each station. 27 | 28 | * [measurements.ipynb](https://github.com/Deltares/ddlpy/blob/main/docs/notebooks/measurements.ipynb) -> interactive notebook to subset/inspect locations and download/plot measurements 29 | 30 | * [waterinfo.ipynb](https://github.com/Deltares/ddlpy/blob/main/docs/notebooks/waterinfo.ipynb) -> interactive notebook to read csv's obained from waterinfo.rws.nl 31 | 32 | 33 | # Run ddlpy from console 34 | 35 | With `ddlpy locations` you can generate a (subsetted) locations.json file, for instance: 36 | 37 | ddlpy locations --quantity WATHTE --station hoekvanholland 38 | 39 | With `ddlpy measurements` you can obtain measurements for locations/parameters in an existing locations.json, for instance: 40 | 41 | ddlpy measurements 2023-01-01 2023-01-03 42 | 43 | 44 | # Something broke? 45 | 46 | First check the [status of the DDL](https://rijkswaterstaatdata.nl/waterdata/#hfd2f5e23-5092-4169-9f36-41e9734e7d87) (at the *Updates* section). If you found an issue in the data or with the Waterwebservices, please [start a discussion at the Waterwebservices github](https://github.com/Rijkswaterstaat/WaterWebservices/discussions). If you have a suggestion or found a bug in ddlpy, please [create a issue at the ddlpy Github](https://github.com/Deltares/ddlpy/issues). 47 | -------------------------------------------------------------------------------- /docs/_static/enabling-delta-life.svg: -------------------------------------------------------------------------------- 1 | Artboard 1 -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every little bit 8 | helps, and credit will always be given. 9 | 10 | 11 | Report Bugs 12 | ----------- 13 | 14 | Report bugs at https://github.com/deltares/ddlpy/issues. 15 | 16 | If you are reporting a bug, please include: 17 | 18 | * Your operating system name and version. 19 | * Any details about your local setup that might be helpful in troubleshooting. 20 | * Detailed steps to reproduce the bug. 21 | 22 | 23 | Get Started! 24 | ------------ 25 | 26 | Ready to contribute? Here's how to set up `ddlpy` for local development. 27 | 28 | 1. Fork the `ddlpy` repo on GitHub. 29 | 2. Clone your fork locally:: 30 | 31 | $ git clone git@github.com:your_name_here/ddlpy.git 32 | 33 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 34 | 35 | $ mkvirtualenv ddlpy 36 | $ cd ddlpy/ 37 | $ python setup.py develop 38 | 39 | 4. Create a branch for local development:: 40 | 41 | $ git checkout -b name-of-your-bugfix-or-feature 42 | 43 | Now you can make your changes locally. 44 | 45 | 5. When you're done making changes, check that your changes pass flake8 and the 46 | tests, including testing other Python versions with tox:: 47 | 48 | $ flake8 ddlpy tests 49 | $ python setup.py test or py.test 50 | $ tox 51 | 52 | To get flake8 and tox, just pip install them into your virtualenv. 53 | 54 | 6. Commit your changes and push your branch to GitHub:: 55 | 56 | $ git add . 57 | $ git commit -m "Your detailed description of your changes." 58 | $ git push origin name-of-your-bugfix-or-feature 59 | 60 | 7. Submit a pull request through the GitHub website. 61 | 62 | 63 | Testing 64 | ------- 65 | 66 | To run all the tests:: 67 | 68 | $ pytest 69 | 70 | 71 | To run a subset of tests:: 72 | 73 | $ pytest tests/test_ddlpy.py 74 | 75 | 76 | Generate documentation 77 | ---------------------- 78 | 79 | To generate the documentation:: 80 | 81 | $ sphinx-build docs docs/_build 82 | 83 | 84 | Create release 85 | -------------- 86 | 87 | - make sure the ``main`` branch is up to date (check pytest warnings, important issues solved, all pullrequests and branches closed) 88 | - create and checkout branch for release 89 | - bump the versionnumber with ``bumpversion minor`` 90 | - update heading (including date) in ``HISTORY.rst`` 91 | - run testbank 92 | - local check with: ``python -m build`` and ``twine check dist/*`` 93 | - commit+push to branch and merge PR 94 | - copy the ddlpy version from pyproject.toml (e.g. ``0.3.0``) 95 | - create a new release at https://github.com/Deltares/ddlpy/releases/new 96 | - click ``choose a tag`` and type v+versionnumber (e.g. ``v0.3.0``), click ``create new tag on publish`` 97 | - set the release title to the tagname (e.g. ``v0.3.0``) 98 | - click ``Generate release notes`` and replace the ``What's Changed`` info by a tagged link to ``HISTORY.rst`` 99 | - if all is set, click ``Publish release`` 100 | - a release is created and published on PyPI by the github action 101 | - post-release: commit+push ``bumpversion patch`` and ``UNRELEASED`` header in ``HISTORY.rst`` to distinguish between release and dev version 102 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Mar 13 07:44:47 2024 4 | 5 | @author: veenstra 6 | """ 7 | 8 | import os 9 | from click.testing import CliRunner 10 | from ddlpy import cli 11 | import importlib 12 | from packaging.version import Version 13 | 14 | 15 | def test_command_line_interface(tmp_path): 16 | """Test the CLI.""" 17 | os.chdir(tmp_path) 18 | 19 | runner = CliRunner() 20 | 21 | # running ddlpy without commands shows help 22 | result = runner.invoke(cli.cli) 23 | assert "Show this message and exit." in result.output 24 | click_version = Version(importlib.metadata.version("click")) 25 | # TODO: require click>=8.2.0 after dropping support for Python 3.8 and 3.9 26 | if click_version >= Version("8.2.0"): 27 | assert result.exit_code == 2 28 | else: 29 | assert result.exit_code == 0 30 | assert "Show this message and exit." in result.output 31 | 32 | # running ddlpy with help command shows help 33 | help_result = runner.invoke(cli.cli, ["--help"]) 34 | assert help_result.exit_code == 0 35 | assert "Show this message and exit." in help_result.output 36 | 37 | # running ddlpy-measurements without first running ddlpy-locations fails 38 | measurements_command = "measurements 2023-01-01 2023-01-03" 39 | measurements_result = runner.invoke(cli.cli, measurements_command.split()) 40 | assert measurements_result.exit_code == 1 41 | assert "locations.json file not found" in str(measurements_result.exception) 42 | 43 | # run ddlpy-locations 44 | locations_command = 'locations --procestype astronomisch --grootheid-code WATHTE --station hoekvanholland --groepering-code ""' 45 | # replace empty string representation ('""') with empty string ("") 46 | locations_command_split = locations_command.split() 47 | locations_command_split = ["" if x == '""' else x for x in locations_command_split] 48 | locations_result = runner.invoke(cli.cli, locations_command_split) 49 | assert locations_result.exit_code == 0 50 | file_locs = "locations.json" 51 | assert os.path.exists(file_locs) 52 | 53 | file_meas = "hoekvanholland_astronomisch_OW_cm_WATHTE__NAP_NVT_NVT.csv" 54 | 55 | # running ddlpy-measurements for period without data succeeds but gives no datafile 56 | measurements_command = "measurements 2050-01-01 2050-01-03" 57 | measurements_result = runner.invoke(cli.cli, measurements_command.split()) 58 | assert measurements_result.exit_code == 0 59 | assert not os.path.exists(file_meas) 60 | assert ( 61 | "No data available for station hoekvanholland in the requested period" 62 | in measurements_result.output 63 | ) 64 | 65 | # running ddlpy-measurements for a period with data succeeds and gives a datafile 66 | measurements_command = "measurements 2023-01-01 2023-01-03" 67 | measurements_result = runner.invoke(cli.cli, measurements_command.split()) 68 | assert measurements_result.exit_code == 0 69 | assert os.path.exists(file_meas) 70 | assert ( 71 | "Data for station hoekvanholland were retrieved" in measurements_result.output 72 | ) 73 | 74 | # running ddlpy-measurements in verbose mode to add test coverage 75 | measurements_command = "--verbose measurements 2023-01-01 2023-01-03" 76 | measurements_result = runner.invoke(cli.cli, measurements_command.split()) 77 | assert measurements_result.exit_code == 0 78 | assert os.path.exists(file_meas) 79 | -------------------------------------------------------------------------------- /docs/examples/retrieve_parallel_to_netcdf.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script gets data from ddl on multiple cores and generates a netcdf file per location and station. 3 | 4 | """ 5 | 6 | import ddlpy 7 | import datetime as dt 8 | import matplotlib.pyplot as plt 9 | plt.close("all") 10 | import xarray as xr 11 | import os 12 | from concurrent.futures import ProcessPoolExecutor 13 | import glob 14 | 15 | # enabling debug logging so we can see what happens in the background 16 | import logging 17 | logging.basicConfig() 18 | logging.getLogger("ddlpy").setLevel(logging.DEBUG) 19 | 20 | 21 | def get_data(location, start_date, end_date, dir_output, overwrite=True): 22 | station_id = location.name 23 | station_messageid = location["Locatie_MessageID"] 24 | filename = os.path.join(dir_output, f"{station_id}-{station_messageid}.nc") 25 | 26 | if os.path.isfile(filename) and overwrite is False: 27 | print("{station_id}: netcdf file already exists and overwrite=False, skipping") 28 | return 29 | 30 | measurements = ddlpy.measurements(location, start_date=start_date, end_date=end_date) 31 | 32 | if measurements.empty: 33 | print(f"{station_id}: no measurements found") 34 | return 35 | 36 | print(f"{station_id}: writing retrieved data to netcdf file") 37 | 38 | # convert to xarray: constant columns are converted to attributes to save disk space 39 | # except the columns in always_preserve 40 | always_preserve = [ 41 | "WaarnemingMetadata.Statuswaarde", 42 | "WaarnemingMetadata.Kwaliteitswaardecode", 43 | "WaardeBepalingsMethode.Code", 44 | "Meetwaarde.Waarde_Numeriek", 45 | ] 46 | ds = ddlpy.dataframe_to_xarray(measurements, always_preserve=always_preserve) 47 | 48 | # write to netcdf file. NETCDF3_CLASSIC or NETCDF4_CLASSIC automatically converts 49 | # variables of dtype = 1: 23 | level = logging.DEBUG 24 | logging.basicConfig(level=level) 25 | return 0 26 | 27 | 28 | # Define a command 29 | # Each command has options which are read from the console. 30 | @cli.command() 31 | @click.option( 32 | "--output", 33 | help="the locations json filename that will be created", 34 | default="locations.json", 35 | ) 36 | @click.option("--station", help="Station codes, e.g. HOEKVHLD", multiple=True) 37 | @click.option( 38 | "--procestype", 39 | help="Procestype, e.g. meting, astronomisch, verwachting", 40 | multiple=True, 41 | ) 42 | @click.option("--grootheid-code", help="Grootheid code, e.g. WATHTE", multiple=True) 43 | @click.option("--groepering-code", help="Groepering code, e.g. NVT", multiple=True) 44 | @click.option("--hoedanigheid-code", help="Hoedanigheid code, e.g. NAP", multiple=True) 45 | @click.option("--eenheid-code", help="Eenheid code, e.g. cm", multiple=True) 46 | @click.option("--parameter-code", help="Parameter code", multiple=True) 47 | @click.option("--compartiment-code", help="Compartiment code, e.g. OW", multiple=True) 48 | @click.option("--typering-code", help="Typering code, e.g. GETETTPE", multiple=True) 49 | def locations( 50 | output, 51 | station, 52 | procestype, 53 | grootheid_code, 54 | groepering_code, 55 | hoedanigheid_code, 56 | eenheid_code, 57 | parameter_code, 58 | compartiment_code, 59 | typering_code, 60 | ): 61 | """ 62 | Subset locations dataframe based on input codes and write locations.json. 63 | 64 | """ 65 | locations_df = ddlpy.locations() 66 | 67 | stations = station 68 | quantities = { 69 | "ProcesType": list(procestype), 70 | "Grootheid.Code": list(grootheid_code), 71 | "Groepering.Code": list(groepering_code), 72 | "Hoedanigheid.Code": list(hoedanigheid_code), 73 | "Eenheid.Code": list(eenheid_code), 74 | "Parameter.Code": list(parameter_code), 75 | "Compartiment.Code": list(compartiment_code), 76 | "Typering.Code": list(typering_code), 77 | } 78 | 79 | selected = locations_df.copy() 80 | 81 | if stations: 82 | selected = selected[selected.index.isin(stations)] 83 | 84 | for q in quantities.keys(): 85 | if len(quantities[q]) != 0: 86 | selected = selected[selected[q].isin(quantities[q])] 87 | 88 | selected.reset_index(inplace=True) 89 | 90 | output = output.split(".")[0] # make sure that extension is always json 91 | selected.to_json(output + ".json", orient="records") 92 | 93 | 94 | # Another command to get the measurements from locations 95 | @cli.command() 96 | @click.argument( 97 | "start-date", 98 | ) 99 | @click.argument( 100 | "end-date", 101 | ) 102 | @click.option( 103 | "--locations", 104 | default="locations.json", 105 | help="file in json or parquet format containing locations and codes", 106 | ) 107 | def measurements(locations, start_date, end_date): 108 | """ 109 | Obtain measurements from file with locations and codes. 110 | The arguments start_date and end_date should be formatted 111 | like "YYYY-MM-DD" or something else that `pandas.Timestamp` understands. 112 | """ 113 | if not os.path.exists(locations): 114 | raise FileNotFoundError( 115 | 'locations.json file not found. First run "ddlpy locations"' 116 | ) 117 | locations_df = pd.read_json(locations, orient="records") 118 | 119 | for irow, selected in locations_df.iterrows(): # goes through rows in table 120 | measurements = ddlpy.measurements( 121 | selected, start_date=start_date, end_date=end_date 122 | ) 123 | 124 | if len(measurements) > 0: 125 | print( 126 | "Data for station %s were retrieved from Waterwebservices" 127 | % selected["Code"] 128 | ) 129 | station = selected["Code"] 130 | pt = selected["ProcesType"] 131 | cc = selected["Compartiment.Code"] 132 | ec = selected["Eenheid.Code"] 133 | gc = selected["Grootheid.Code"] 134 | grc = selected["Groepering.Code"] 135 | hc = selected["Hoedanigheid.Code"] 136 | pc = selected["Parameter.Code"] 137 | tc = selected["Typering.Code"] 138 | 139 | measurements.to_csv( 140 | "%s_%s_%s_%s_%s_%s_%s_%s_%s.csv" 141 | % (station, pt, cc, ec, gc, grc, hc, pc, tc) 142 | ) 143 | else: 144 | print( 145 | "No data available for station %s in the requested period" 146 | % selected["Code"] 147 | ) 148 | 149 | 150 | if __name__ == "__main__": 151 | sys.exit(cli()) # pragma: no cover 152 | -------------------------------------------------------------------------------- /ddlpy/utils.py: -------------------------------------------------------------------------------- 1 | import dateutil.rrule 2 | import itertools 3 | import pandas as pd 4 | import numpy as np 5 | 6 | 7 | def date_series(start, end, freq=dateutil.rrule.MONTHLY): 8 | """return a list of start and end date over the timespan start[->end following the frequency rule""" 9 | 10 | def pairwise(it): 11 | """return all sequential pairs""" 12 | # loop over the iterator twice. 13 | # tee it so we don't consume it twice 14 | it0, it1 = itertools.tee(it) 15 | i0 = itertools.islice(it0, None) 16 | i1 = itertools.islice(it1, 1, None) 17 | # merge to a list of pairs 18 | return zip(i0, i1) 19 | 20 | # go over the rrule, also include the end, return consequitive pairs 21 | result = list( 22 | pairwise( 23 | list(dateutil.rrule.rrule(dtstart=start, until=end, freq=freq)) + [end] 24 | ) 25 | ) 26 | # remove last one if empty (first of month until first of month) 27 | if len(result) > 1 and result[-1][0] == result[-1][1]: 28 | # remove it 29 | del result[-1] 30 | return result 31 | 32 | 33 | def simplify_dataframe(df: pd.DataFrame, always_preserve=[]): 34 | """ 35 | Drop columns with constant values from the dataframe and collect them 36 | in a dictionary which is added as attrs of the dataframe. 37 | The column Meetwaarde.Waarde_Alfanumeriek is also dropped if it is a duplicate of 38 | Meetwaarde.Waarde_Numeriek. 39 | The column names passed in `always_preserve` are preserved even if they are constant. 40 | """ 41 | 42 | # define which columns are constant 43 | bool_constant = (df == df.iloc[0]).all(axis=0) 44 | 45 | # drop Waarde_Alfanumeriek if duplicate of Waarde_Numeriek 46 | str_num = "Meetwaarde.Waarde_Numeriek" 47 | str_alf = "Meetwaarde.Waarde_Alfanumeriek" 48 | if str_num in df.columns and str_alf in df.columns: 49 | df_num = df[str_num] 50 | df_alf = df[str_alf].astype(float) 51 | if np.allclose(df_num, df_alf, equal_nan=True): 52 | bool_constant[str_alf] = True 53 | 54 | # preserve some columns (even if their values are constant) by setting them as not constant 55 | for colname in always_preserve: 56 | if colname not in df.columns: 57 | raise ValueError(f"column '{colname}' not present in dataframe") 58 | bool_constant[colname] = False 59 | 60 | # constant columns are flattened and converted to dict of attrs 61 | df_attrs = df.loc[:, bool_constant].iloc[0].to_dict() 62 | 63 | # varying columns are kept in output dataframe 64 | df_simple = df.loc[:, ~bool_constant].copy() 65 | 66 | # attach as attrs to dataframe 67 | df_simple.attrs = df_attrs 68 | 69 | return df_simple 70 | 71 | 72 | def code_description_attrs_from_dataframe(df: pd.DataFrame): 73 | # create var_attrs_dict 74 | colname_code_list = df.columns[df.columns.str.contains(".Code")] 75 | colname_oms_list = df.columns[df.columns.str.contains(".Omschrijving")] 76 | var_attrs_dict = {} 77 | for colname_code, colname_oms in zip(colname_code_list, colname_oms_list): 78 | meas_twocol = df[[colname_code, colname_oms]].drop_duplicates() 79 | attr_dict = meas_twocol.set_index(colname_code)[colname_oms].to_dict() 80 | # drop empty attribute names/keys since these are not supported when writing to netcdf file 81 | if "" in attr_dict.keys(): 82 | attr_dict.pop("") 83 | var_attrs_dict[colname_code] = attr_dict 84 | return var_attrs_dict 85 | 86 | 87 | def dataframe_to_xarray(df: pd.DataFrame, always_preserve=[]): 88 | """ 89 | Converts the measurement dataframe to a xarray dataset. The dataframe is first 90 | simplified with `simplify_dataframe()` to minimize the size of the netcdf dataset on 91 | disk. 92 | 93 | The timestamps are converted to UTC since xarray does not support non-UTC timestamps. 94 | These can be converted to different timezones after loading the netcdf and converting 95 | to a pandas dataframe with df.index.tz_convert(). 96 | 97 | Furthermore, all ".Omschrijving" variables are dropped and the information is added 98 | as attributes to the Code variables. 99 | 100 | When writing the dataset to disk with ds.to_netcdf() it is recommended to use 101 | `format="NETCDF3_CLASSIC"` or `format="NETCDF4_CLASSIC"` since this automatically 102 | converts variables of dtype > ds = waterinfo_read('x.csv',tzone='UTC+1') 35 | >> df = ds.to_dataframe() 36 | >> df.head() 37 | 38 | """ 39 | # TODO: update this function to the new Waterwebservices or remove from ddlpy 40 | # https://github.com/Deltares/ddlpy/issues/173 41 | if block: 42 | raise DeprecationWarning( 43 | "ddlpy.waterinfo_read() is not maintained. You can still use it by passing " 44 | "the argument `block=False`. Please also create an issue on the ddlpy " 45 | "github to let us know you are using it." 46 | ) 47 | 48 | dfall = pd.read_csv(f, delimiter=";", encoding=encoding) 49 | 50 | if "WAARNEMINGDATUM" in dfall.keys(): 51 | variablecolumn = "GROOTHEID_ CODE" 52 | tzone = 1 53 | 54 | dfall = dfall.loc[dfall["KWALITEITSOORDEEL_CODE"] == "Normale waarde"] 55 | 56 | elif "Datum" in dfall.keys(): 57 | variablecolumn = "Parameter" 58 | tzone = "CET" 59 | 60 | variables = list(set(dfall[variablecolumn])) 61 | 62 | ds = [] 63 | 64 | for variable in variables: 65 | 66 | df = dfall[dfall[variablecolumn] == variable] 67 | 68 | print(len(df), " rows for variable: ", variable) 69 | 70 | if "WAARNEMINGDATUM" in df.keys(): 71 | # MONSTER_IDENTIFICATIE;MEETPUNT_IDENTIFICATIE;TYPERING_OMSCHRIJVING;TYPERING_CODE;GROOTHEID_OMSCHRIJVING;GROOTHEID_ CODE;PARAMETER_OMSCHRIJVING;PARAMETER_ CODE;EENHEID_CODE;HOEDANIGHEID_OMSCHRIJVING;HOEDANIGHEID_CODE;COMPARTIMENT_OMSCHRIJVING;COMPARTIMENT_CODE;WAARDEBEWERKINGSMETHODE_OMSCHRIJVING;WAARDEBEWERKINGSMETHODE_CODE;WAARDEBEPALINGSMETHODE_OMSCHRIJVING;WAARDEBEPALINGSMETHODE_CODE;BEMONSTERINGSSOORT_OMSCHRIJVING;BEMONSTERINGSSOORT_CODE;WAARNEMINGDATUM;WAARNEMINGTIJD;LIMIETSYMBOOL;NUMERIEKEWAARDE;ALFANUMERIEKEWAARDE;KWALITEITSOORDEEL_CODE;STATUSWAARDE;OPDRACHTGEVENDE_INSTANTIE;MEETAPPARAAT_OMSCHRIJVING;MEETAPPARAAT_CODE;BEMONSTERINGSAPPARAAT_OMSCHRIJVING;BEMONSTERINGSAPPARAAT_CODE;PLAATSBEPALINGSAPPARAAT_OMSCHRIJVING;PLAATSBEPALINGSAPPARAAT_CODE;BEMONSTERINGSHOOGTE;REFERENTIEVLAK;EPSG;X;Y;ORGAAN_OMSCHRIJVING;ORGAAN_CODE;TAXON_NAME 72 | # ;Scheveningen;;;Waterhoogte berekend;WATHTBRKD;;;cm;t.o.v. Normaal Amsterdams Peil;NAP;Oppervlaktewater;OW;;;Astronomische waterhoogte mbv harmonische analyse;other:F012;;;01-05-2020;00:00:00;;-44;;Normale waarde;Ongecontroleerd;RIKZMON_WAT;;;;;;;-999999999;NVT;25831;586550,994420996;5772806,43069697;;; 73 | 74 | t = [ 75 | datetime.strptime(t, "%d-%m-%Y%H:%M:%S") 76 | for t in df["WAARNEMINGDATUM"] + df["WAARNEMINGTIJD"] 77 | ] 78 | 79 | data = df["NUMERIEKEWAARDE"] / 1.0 80 | 81 | key_units = "EENHEID_CODE" 82 | 83 | keys2meta = [ 84 | "MEETPUNT_IDENTIFICATIE", 85 | "GROOTHEID_OMSCHRIJVING", 86 | "GROOTHEID_ CODE", 87 | "EENHEID_CODE", 88 | "HOEDANIGHEID_OMSCHRIJVING", 89 | "HOEDANIGHEID_CODE", 90 | "COMPARTIMENT_CODE", 91 | "COMPARTIMENT_OMSCHRIJVING", 92 | "WAARDEBEPALINGSMETHODE_CODE", 93 | "WAARDEBEPALINGSMETHODE_OMSCHRIJVING", 94 | "KWALITEITSOORDEEL_CODE", 95 | "STATUSWAARDE", 96 | "OPDRACHTGEVENDE_INSTANTIE", 97 | "EPSG", 98 | "X", 99 | "Y", 100 | ] 101 | 102 | elif "Datum" in df.keys(): 103 | # Datum;Tijd;Parameter;Locatie;Meting;Verwachting;Astronomisch getijden;Eenheid;Bemonsteringshoogte;Referentievlak; 104 | # 5-5-2020;21:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Den Helder;-1;;;cm;-999999999;NAP; 105 | 106 | # handle trailing ; 107 | df = df.loc[:, ~df.columns.str.contains("^Unnamed")] 108 | 109 | # parse time 110 | t = [ 111 | datetime.strptime(t, "%d-%m-%Y%H:%M:%S") 112 | for t in df["Datum"] + df["Tijd"] 113 | ] 114 | 115 | data = df["Meting"] 116 | key_units = "Eenheid" 117 | 118 | keys2meta = [ 119 | "Parameter", 120 | "Locatie", 121 | "Eenheid", 122 | "Bemonsteringshoogte", 123 | "Referentievlak", 124 | ] 125 | 126 | else: 127 | print("Unknown file header.") 128 | raise 129 | 130 | if isinstance(tzone, type("a")): 131 | # does not apply DST t = [t1.replace(tzinfo=pytz.timezone(tzone)).astimezone(pytz.timezone('UTC')) for t1 in t] 132 | t = [t1 - pytz.timezone("CET").utcoffset(t1) for t1 in t] 133 | else: 134 | t = [t1 - timedelta(seconds=3600) * tzone for t1 in t] 135 | t = [t1.replace(tzinfo=None) for t1 in t] # make datetime64 again 136 | 137 | # The array values in a DataArray have a single (homogeneous) data type. 138 | # To work with heterogeneous or structured data types in xarray, use coordinates, 139 | # or put separate DataArray objects in a single Dataset (see below). 140 | # ds2 = xr.DataArray(data, coords=[t], dims=['time']) 141 | 142 | d = xr.Dataset({"data": (("time"), data)}, {"time": t}) # make datetime64 again 143 | 144 | d.attrs["file.name"] = f 145 | d.attrs["file.encoding"] = encoding 146 | d.attrs["file.original_columns"] = df.keys() 147 | d.attrs["file.original_timezone"] = tzone 148 | 149 | # unit conversoin to SI 150 | # LUT = {'in':['cm'],'out':['m'],'f':[0.01]} 151 | 152 | for key in keys2meta: 153 | value = set(df[key]) 154 | if len(value) == 1: 155 | d["data"].attrs[key] = list(value)[0] 156 | else: 157 | d["data"].attrs[key] = value 158 | 159 | d["data"].attrs["units"] = d["data"].attrs[key_units] 160 | 161 | if tzone: 162 | d["time"].attrs["timezone"] = "UTC" 163 | 164 | ds.append(d) 165 | 166 | if len(ds) == 0: 167 | raise ValueError("no data available in file") 168 | 169 | return ds 170 | -------------------------------------------------------------------------------- /tests/NVT_WATHTE_SCHE_20200507.csv: -------------------------------------------------------------------------------- 1 | Datum;Tijd;Parameter;Locatie;Meting;Verwachting;Astronomisch getijden;Eenheid;Bemonsteringshoogte;Referentievlak; 2 | 7-5-2020;00:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-69;;;cm;-999999999;NVT; 3 | 7-5-2020;00:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-68;;;cm;-999999999;NVT; 4 | 7-5-2020;00:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-67;;;cm;-999999999;NVT; 5 | 7-5-2020;00:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-65;;;cm;-999999999;NVT; 6 | 7-5-2020;00:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-63;;;cm;-999999999;NVT; 7 | 7-5-2020;00:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-62;;;cm;-999999999;NVT; 8 | 7-5-2020;01:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-60;;;cm;-999999999;NVT; 9 | 7-5-2020;01:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-58;;;cm;-999999999;NVT; 10 | 7-5-2020;01:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-55;;;cm;-999999999;NVT; 11 | 7-5-2020;01:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-51;;;cm;-999999999;NVT; 12 | 7-5-2020;01:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-45;;;cm;-999999999;NVT; 13 | 7-5-2020;01:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-37;;;cm;-999999999;NVT; 14 | 7-5-2020;02:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-26;;;cm;-999999999;NVT; 15 | 7-5-2020;02:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-11;;;cm;-999999999;NVT; 16 | 7-5-2020;02:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;8;;;cm;-999999999;NVT; 17 | 7-5-2020;02:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;26;;;cm;-999999999;NVT; 18 | 7-5-2020;02:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;43;;;cm;-999999999;NVT; 19 | 7-5-2020;02:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;58;;;cm;-999999999;NVT; 20 | 7-5-2020;03:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;73;;;cm;-999999999;NVT; 21 | 7-5-2020;03:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;84;;;cm;-999999999;NVT; 22 | 7-5-2020;03:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;92;;;cm;-999999999;NVT; 23 | 7-5-2020;03:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;97;;;cm;-999999999;NVT; 24 | 7-5-2020;03:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;100;;;cm;-999999999;NVT; 25 | 7-5-2020;03:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;100;;;cm;-999999999;NVT; 26 | 7-5-2020;04:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;96;;;cm;-999999999;NVT; 27 | 7-5-2020;04:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;93;;;cm;-999999999;NVT; 28 | 7-5-2020;04:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;88;;;cm;-999999999;NVT; 29 | 7-5-2020;04:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;84;;;cm;-999999999;NVT; 30 | 7-5-2020;04:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;78;;;cm;-999999999;NVT; 31 | 7-5-2020;04:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;73;;;cm;-999999999;NVT; 32 | 7-5-2020;05:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;66;;;cm;-999999999;NVT; 33 | 7-5-2020;05:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;60;;;cm;-999999999;NVT; 34 | 7-5-2020;05:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;53;;;cm;-999999999;NVT; 35 | 7-5-2020;05:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;46;;;cm;-999999999;NVT; 36 | 7-5-2020;05:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;39;;;cm;-999999999;NVT; 37 | 7-5-2020;05:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;30;;;cm;-999999999;NVT; 38 | 7-5-2020;06:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;21;;;cm;-999999999;NVT; 39 | 7-5-2020;06:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;10;;;cm;-999999999;NVT; 40 | 7-5-2020;06:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;0;;;cm;-999999999;NVT; 41 | 7-5-2020;06:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-11;;;cm;-999999999;NVT; 42 | 7-5-2020;06:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-21;;;cm;-999999999;NVT; 43 | 7-5-2020;06:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-31;;;cm;-999999999;NVT; 44 | 7-5-2020;07:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-41;;;cm;-999999999;NVT; 45 | 7-5-2020;07:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-49;;;cm;-999999999;NVT; 46 | 7-5-2020;07:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-58;;;cm;-999999999;NVT; 47 | 7-5-2020;07:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-66;;;cm;-999999999;NVT; 48 | 7-5-2020;07:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-73;;;cm;-999999999;NVT; 49 | 7-5-2020;07:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-78;;;cm;-999999999;NVT; 50 | 7-5-2020;08:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-80;;;cm;-999999999;NVT; 51 | 7-5-2020;08:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-79;;;cm;-999999999;NVT; 52 | 7-5-2020;08:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-78;;;cm;-999999999;NVT; 53 | 7-5-2020;08:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-76;;;cm;-999999999;NVT; 54 | 7-5-2020;08:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-73;;;cm;-999999999;NVT; 55 | 7-5-2020;08:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-68;;;cm;-999999999;NVT; 56 | 7-5-2020;09:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-63;;;cm;-999999999;NVT; 57 | 7-5-2020;09:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-60;;;cm;-999999999;NVT; 58 | 7-5-2020;09:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-57;;;cm;-999999999;NVT; 59 | 7-5-2020;09:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-58;;;cm;-999999999;NVT; 60 | 7-5-2020;09:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-58;;;cm;-999999999;NVT; 61 | 7-5-2020;09:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-60;;;cm;-999999999;NVT; 62 | 7-5-2020;10:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-62;;;cm;-999999999;NVT; 63 | 7-5-2020;10:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-67;;;cm;-999999999;NVT; 64 | 7-5-2020;10:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-68;;;cm;-999999999;NVT; 65 | 7-5-2020;10:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-72;;;cm;-999999999;NVT; 66 | 7-5-2020;10:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-77;;;cm;-999999999;NVT; 67 | 7-5-2020;10:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-81;;;cm;-999999999;NVT; 68 | 7-5-2020;11:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-85;;;cm;-999999999;NVT; 69 | 7-5-2020;11:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-86;;;cm;-999999999;NVT; 70 | 7-5-2020;11:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-90;;;cm;-999999999;NVT; 71 | 7-5-2020;11:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-90;;;cm;-999999999;NVT; 72 | 7-5-2020;11:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-91;;;cm;-999999999;NVT; 73 | 7-5-2020;11:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-91;;;cm;-999999999;NVT; 74 | 7-5-2020;12:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-89;;;cm;-999999999;NVT; 75 | 7-5-2020;12:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-88;;;cm;-999999999;NVT; 76 | 7-5-2020;12:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-86;;;cm;-999999999;NVT; 77 | 7-5-2020;12:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-83;;;cm;-999999999;NVT; 78 | 7-5-2020;12:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-80;;;cm;-999999999;NVT; 79 | 7-5-2020;12:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-78;;;cm;-999999999;NVT; 80 | 7-5-2020;13:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-75;;;cm;-999999999;NVT; 81 | 7-5-2020;13:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-71;;;cm;-999999999;NVT; 82 | 7-5-2020;13:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-66;;;cm;-999999999;NVT; 83 | 7-5-2020;13:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-59;;;cm;-999999999;NVT; 84 | 7-5-2020;13:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-53;;;cm;-999999999;NVT; 85 | 7-5-2020;13:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-44;;;cm;-999999999;NVT; 86 | 7-5-2020;14:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-35;;;cm;-999999999;NVT; 87 | 7-5-2020;14:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-23;;;cm;-999999999;NVT; 88 | 7-5-2020;14:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-6;;;cm;-999999999;NVT; 89 | 7-5-2020;14:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;14;;;cm;-999999999;NVT; 90 | 7-5-2020;14:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;36;;;cm;-999999999;NVT; 91 | 7-5-2020;14:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;57;;;cm;-999999999;NVT; 92 | 7-5-2020;15:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;75;;;cm;-999999999;NVT; 93 | 7-5-2020;15:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;89;;;cm;-999999999;NVT; 94 | 7-5-2020;15:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;102;;;cm;-999999999;NVT; 95 | 7-5-2020;15:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;111;;;cm;-999999999;NVT; 96 | 7-5-2020;15:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;117;;;cm;-999999999;NVT; 97 | 7-5-2020;15:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;120;;;cm;-999999999;NVT; 98 | 7-5-2020;16:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;119;;;cm;-999999999;NVT; 99 | 7-5-2020;16:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;117;;;cm;-999999999;NVT; 100 | 7-5-2020;16:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;113;;;cm;-999999999;NVT; 101 | 7-5-2020;16:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;109;;;cm;-999999999;NVT; 102 | 7-5-2020;16:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;105;;;cm;-999999999;NVT; 103 | 7-5-2020;16:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;101;;;cm;-999999999;NVT; 104 | 7-5-2020;17:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;98;;;cm;-999999999;NVT; 105 | 7-5-2020;17:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;92;;;cm;-999999999;NVT; 106 | 7-5-2020;17:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;88;;;cm;-999999999;NVT; 107 | 7-5-2020;17:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;84;;;cm;-999999999;NVT; 108 | 7-5-2020;17:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;78;;;cm;-999999999;NVT; 109 | 7-5-2020;17:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;71;;;cm;-999999999;NVT; 110 | 7-5-2020;18:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;65;;;cm;-999999999;NVT; 111 | 7-5-2020;18:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;57;;;cm;-999999999;NVT; 112 | 7-5-2020;18:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;49;;;cm;-999999999;NVT; 113 | 7-5-2020;18:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;39;;;cm;-999999999;NVT; 114 | 7-5-2020;18:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;29;;;cm;-999999999;NVT; 115 | 7-5-2020;18:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;21;;;cm;-999999999;NVT; 116 | 7-5-2020;19:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;12;;;cm;-999999999;NVT; 117 | 7-5-2020;19:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;3;;;cm;-999999999;NVT; 118 | 7-5-2020;19:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-8;;;cm;-999999999;NVT; 119 | 7-5-2020;19:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-18;;;cm;-999999999;NVT; 120 | 7-5-2020;19:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-25;;;cm;-999999999;NVT; 121 | 7-5-2020;19:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-33;;;cm;-999999999;NVT; 122 | 7-5-2020;20:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-39;;;cm;-999999999;NVT; 123 | 7-5-2020;20:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-42;;;cm;-999999999;NVT; 124 | 7-5-2020;20:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-47;;;cm;-999999999;NVT; 125 | 7-5-2020;20:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-44;;;cm;-999999999;NVT; 126 | 7-5-2020;20:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-45;;;cm;-999999999;NVT; 127 | 7-5-2020;20:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-41;;;cm;-999999999;NVT; 128 | 7-5-2020;21:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-40;;;cm;-999999999;NVT; 129 | 7-5-2020;21:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-35;;;cm;-999999999;NVT; 130 | 7-5-2020;21:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-35;;;cm;-999999999;NVT; 131 | 7-5-2020;21:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-34;;;cm;-999999999;NVT; 132 | 7-5-2020;21:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-35;;;cm;-999999999;NVT; 133 | 7-5-2020;21:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-37;;;cm;-999999999;NVT; 134 | 7-5-2020;22:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-40;;;cm;-999999999;NVT; 135 | 7-5-2020;22:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-44;;;cm;-999999999;NVT; 136 | 7-5-2020;22:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-46;;;cm;-999999999;NVT; 137 | 7-5-2020;22:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-50;;;cm;-999999999;NVT; 138 | 7-5-2020;22:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-54;;;cm;-999999999;NVT; 139 | 7-5-2020;22:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-57;;;cm;-999999999;NVT; 140 | 7-5-2020;23:00:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-62;;;cm;-999999999;NVT; 141 | 7-5-2020;23:10:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-64;;;cm;-999999999;NVT; 142 | 7-5-2020;23:20:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-68;;;cm;-999999999;NVT; 143 | 7-5-2020;23:30:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-70;;;cm;-999999999;NVT; 144 | 7-5-2020;23:40:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-69;;;cm;-999999999;NVT; 145 | 7-5-2020;23:50:00;Waterhoogte Oppervlaktewater t.o.v. Normaal Amsterdams Peil in cm;Scheveningen;-72;;;cm;-999999999;NVT; 146 | -------------------------------------------------------------------------------- /ddlpy/ddlpy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Main module.""" 4 | import os 5 | import json 6 | import pathlib 7 | import logging 8 | import requests 9 | import pandas as pd 10 | import pytz 11 | import tqdm 12 | import dateutil 13 | import numpy as np 14 | import platformdirs 15 | 16 | from .utils import date_series 17 | 18 | BASE_URL = "https://waterwebservices.rijkswaterstaat.nl/" 19 | ENDPOINTS_PATH = pathlib.Path(__file__).with_name("endpoints.json") 20 | logger = logging.getLogger(__name__) 21 | 22 | with ENDPOINTS_PATH.open() as f: 23 | ENDPOINTS = json.load(f) 24 | 25 | 26 | class NoDataError(ValueError): 27 | pass 28 | 29 | 30 | def _send_post_request(url, request, timeout=None): 31 | logger.debug("Requesting at {} with request: {}".format(url, json.dumps(request))) 32 | resp = requests.post(url, json=request, timeout=timeout) 33 | 34 | if not resp.ok: 35 | # in case of for instance 36 | # resp.status_code: 400, resp.reason: Bad Request, resp.text: {"Succesvol":false,"Foutmelding":"Het maximaal aantal waarnemingen (160000) is overschreden. Beperk uw request.","WaarnemingenLijst":[]} 37 | # resp.status_code: 500, resp.reason: Internal Server Error 38 | raise IOError(f"{resp.status_code} {resp.reason}: {resp.text}") 39 | 40 | if resp.status_code == 204: 41 | # "204 No Content" is raised here, but catched in ddlpy.ddlpy.measurements() so the process can continue. 42 | raise NoDataError(f"{resp.status_code} {resp.reason}: {resp.text}") 43 | 44 | result = resp.json() 45 | return result 46 | 47 | 48 | def catalog(catalog_filter=None): 49 | endpoint = ENDPOINTS["collect_catalogue"] 50 | 51 | if catalog_filter is None: 52 | # use the default request from endpoints.json 53 | request = endpoint["request"] 54 | else: 55 | assert isinstance(catalog_filter, list) 56 | request = {"CatalogusFilter": {x: True for x in catalog_filter}} 57 | 58 | result = _send_post_request(endpoint["url"], request, timeout=None) 59 | 60 | return result 61 | 62 | 63 | def get_catalogfile_cache(catalog_filter): 64 | # create cache dir like %USERPROFILE%/AppData/Local/ddlpy/Cache 65 | cachedir = os.path.join(platformdirs.user_cache_dir(), "ddlpy", "Cache") 66 | os.makedirs(cachedir, exist_ok=True) 67 | catalogfile = os.path.join(cachedir, "locations_default_catalog_filter.json") 68 | 69 | # only allow to load catalog from cache if the default catalog_filter was used, 70 | # if the cachefile is present and if it is less than 4 hours old 71 | use_cache = False 72 | if catalog_filter is None and os.path.exists(catalogfile): 73 | cache_mtime = os.path.getmtime(catalogfile) 74 | cache_mtime_dt = pd.Timestamp.fromtimestamp(cache_mtime) 75 | tdiff_hours = (pd.Timestamp.now() - cache_mtime_dt).total_seconds() / 3600 76 | if tdiff_hours < 4: 77 | use_cache = True 78 | return catalogfile, use_cache 79 | 80 | 81 | def retrieve_or_load_catalog(catalog_filter: list = None): 82 | catalogfile, use_cache = get_catalogfile_cache(catalog_filter=catalog_filter) 83 | 84 | # load or retrieve the catalog 85 | if use_cache: 86 | logger.info("Loading Waterwebservices catalog from cache") 87 | with open(catalogfile, "r") as f: 88 | result = json.load(f) 89 | else: 90 | logger.info("Retrieving Waterwebservices catalog, this can take 30 seconds") 91 | result = catalog(catalog_filter=catalog_filter) 92 | if catalog_filter is None: 93 | # only write the catalogfile if the default catalog_filter was used 94 | with open(catalogfile, "w") as f: 95 | json.dump(result, f) 96 | return result 97 | 98 | 99 | def locations(catalog_filter: list = None) -> pd.DataFrame: 100 | """ 101 | Get station information from DDL (metadata from Catalogue). It conains all metadata 102 | regarding stations. The catalog is locally cached for maximum 4 hours, corresponding 103 | to the update frequency of the Waterwebservices catalog. If you want to avoid using 104 | the cache, pass a valid `catalog_filter` or delete the caching file manually. 105 | 106 | Parameters 107 | ---------- 108 | catalog_filter : list, optional 109 | list of catalogs to pass on to OphalenCatalogus CatalogusFilter, 110 | if None the list form endpoints.json is retrieved. The cache cannot be used when 111 | passing anything other than None. The default is None. 112 | 113 | Returns 114 | ------- 115 | pd.DataFrame 116 | DataFrame with a combination of available locations and measurements. 117 | 118 | """ 119 | 120 | result = retrieve_or_load_catalog(catalog_filter=catalog_filter) 121 | 122 | df_locations = pd.DataFrame(result["LocatieLijst"]) 123 | 124 | df_metadata = pd.json_normalize(result["AquoMetadataLijst"]) 125 | 126 | df_metadata_location = pd.DataFrame(result["AquoMetadataLocatieLijst"]) 127 | 128 | merged = ( 129 | df_metadata_location.set_index("Locatie_MessageID") 130 | .join(df_locations.set_index("Locatie_MessageID"), how="inner") 131 | .reset_index() 132 | ) 133 | merged = merged.set_index("AquoMetaData_MessageID").join( 134 | df_metadata.set_index("AquoMetadata_MessageID") 135 | ) 136 | # set station id as index 137 | return merged.set_index("Code") 138 | 139 | 140 | def _check_convert_dates(start_date, end_date, return_str=True): 141 | start_date = pd.Timestamp(start_date) 142 | end_date = pd.Timestamp(end_date) 143 | 144 | # check if timezones are the same 145 | assert start_date.tz == end_date.tz 146 | 147 | # set UTC timezone if tz is None 148 | if start_date.tz is None: 149 | start_date = pytz.UTC.localize(start_date) 150 | if end_date.tz is None: 151 | end_date = pytz.UTC.localize(end_date) 152 | 153 | if start_date > end_date: 154 | raise ValueError(f"start_date {start_date} is larger than end_date {end_date}") 155 | 156 | if return_str: 157 | start_date_str = start_date.isoformat(timespec="milliseconds") 158 | end_date_str = end_date.isoformat(timespec="milliseconds") 159 | return start_date_str, end_date_str 160 | else: 161 | return start_date, end_date 162 | 163 | 164 | def _get_request_dicts(location): 165 | 166 | # generate aquometadata dict from location "*.Code" values 167 | key_list = [x.replace(".Code", "") for x in location.index if x.endswith(".Code")] 168 | aquometadata_dict = {key: {"Code": location[f"{key}.Code"]} for key in key_list} 169 | # additional code required for ProcesType since this does not adhere to the 170 | # Code/Omschrijving convention. 171 | if "ProcesType" in location.index: 172 | aquometadata_dict["ProcesType"] = location["ProcesType"] 173 | 174 | # generate location dict from relevant values 175 | locatie_dict = { 176 | # assert code is used as index 177 | "Code": location.get("Code", location.name), 178 | } 179 | 180 | request_dicts = {"AquoMetadata": aquometadata_dict, "Locatie": locatie_dict} 181 | return request_dicts 182 | 183 | 184 | def measurements_available( 185 | location: pd.Series, start_date: (str, pd.Timestamp), end_date: (str, pd.Timestamp) 186 | ) -> bool: 187 | """ 188 | Checks if there are measurements available for a location in the requested period. 189 | 190 | Parameters 191 | ---------- 192 | location : pd.Series 193 | Single row of the `ddlpy.locations()` DataFrame. 194 | start_date : (str,pd.Timestamp) 195 | The start date of the requested period. 196 | end_date : (str,pd.Timestamp) 197 | The end date of the requested period. 198 | 199 | Returns 200 | ------- 201 | bool 202 | Whether there are measurements available or not. 203 | 204 | """ 205 | endpoint = ENDPOINTS["check_observations_available"] 206 | 207 | start_date_str, end_date_str = _check_convert_dates( 208 | start_date, end_date, return_str=True 209 | ) 210 | 211 | request_dicts = _get_request_dicts(location) 212 | 213 | request = { 214 | "AquoMetadataLijst": [request_dicts["AquoMetadata"]], 215 | "LocatieLijst": [request_dicts["Locatie"]], 216 | "Periode": {"Begindatumtijd": start_date_str, "Einddatumtijd": end_date_str}, 217 | } 218 | 219 | result = _send_post_request(endpoint["url"], request, timeout=5) 220 | 221 | # continue if request was successful 222 | logger.debug("Got response: {}".format(result)) 223 | if result["WaarnemingenAanwezig"] == "true": 224 | return True 225 | else: 226 | return False 227 | 228 | 229 | def measurements_amount( 230 | location: pd.Series, 231 | start_date: (str, pd.Timestamp), 232 | end_date: (str, pd.Timestamp), 233 | period: str = "Jaar", 234 | ) -> pd.DataFrame: 235 | """ 236 | Retrieves the amount of measurements available for a location for the requested period. 237 | 238 | Parameters 239 | ---------- 240 | location : pd.Series 241 | Single row of the `ddlpy.locations()` DataFrame. 242 | start_date : (str,pd.Timestamp) 243 | The start date of the requested period. 244 | end_date : (str,pd.Timestamp) 245 | The end date of the requested period. 246 | period : str, optional 247 | "Jaar", "Maand" or "Dag". The default is "Jaar". 248 | 249 | Returns 250 | ------- 251 | df_amount : pd.DataFrame 252 | A DataFrame with the number of mesurements (AantalMetingen) per period (Groeperingsperiode). 253 | 254 | """ 255 | # TODO: there are probably more Groeperingsperiodes accepted by ddl, but not supported by ddlpy yet 256 | accepted_period = ["Jaar", "Maand", "Dag"] 257 | if period not in accepted_period: 258 | raise ValueError(f"period should be one of {accepted_period}, not '{period}'") 259 | 260 | endpoint = ENDPOINTS["collect_number_of_observations"] 261 | 262 | start_date_str, end_date_str = _check_convert_dates( 263 | start_date, end_date, return_str=True 264 | ) 265 | 266 | request_dicts = _get_request_dicts(location) 267 | 268 | request = { 269 | "AquoMetadataLijst": [request_dicts["AquoMetadata"]], 270 | "LocatieLijst": [request_dicts["Locatie"]], 271 | "Groeperingsperiode": period, 272 | "Periode": {"Begindatumtijd": start_date_str, "Einddatumtijd": end_date_str}, 273 | } 274 | 275 | result = _send_post_request(endpoint["url"], request, timeout=None) 276 | 277 | # continue if request was successful 278 | df_list = [] 279 | for one in result["AantalWaarnemingenPerPeriodeLijst"]: 280 | df = pd.json_normalize(one["AantalMetingenPerPeriodeLijst"]) 281 | 282 | # combine columns to a period string 283 | df["Groeperingsperiode"] = df["Groeperingsperiode.Jaarnummer"].apply( 284 | lambda x: f"{x:04d}" 285 | ) 286 | if period in ["Maand", "Dag"]: 287 | df["Groeperingsperiode"] = ( 288 | df["Groeperingsperiode"] 289 | + "-" 290 | + df["Groeperingsperiode.Maandnummer"].apply(lambda x: f"{x:02d}") 291 | ) 292 | if period in ["Dag"]: 293 | df["Groeperingsperiode"] = ( 294 | df["Groeperingsperiode"] 295 | + "-" 296 | + df["Groeperingsperiode.Dag"].apply(lambda x: f"{x:02d}") 297 | ) 298 | 299 | # select columns from dataframe and append to list 300 | df = df.set_index("Groeperingsperiode") 301 | df = df[["AantalMetingen"]] 302 | df_list.append(df) 303 | 304 | if len(df_list) == 0: 305 | raise NoDataError("no measurements available returned") 306 | 307 | # concatenate and sum duplicated index 308 | df_amount = pd.concat(df_list).sort_index() 309 | df_amount = df_amount.groupby(df_amount.index).sum() 310 | return df_amount 311 | 312 | 313 | def _combine_waarnemingenlijst(result, location): 314 | assert "WaarnemingenLijst" in result 315 | 316 | # flatten the datastructure 317 | rows = [] 318 | for waarneming in result["WaarnemingenLijst"]: 319 | for row in waarneming["MetingenLijst"]: 320 | # metadata is a list of 1 value, flatten it 321 | new_row = {} 322 | for key, value in row["WaarnemingMetadata"].items(): 323 | new_key = "WaarnemingMetadata." + key 324 | new_row[new_key] = value 325 | 326 | # add remaining data 327 | for key, val in row.items(): 328 | if key == "WaarnemingMetadata": 329 | continue 330 | new_row[key] = val 331 | 332 | # add metadata 333 | for key, val in waarneming["AquoMetadata"].items(): 334 | if isinstance(val, dict) and "Code" in val and "Omschrijving" in val: 335 | # some values have a code/omschrijving pair, flatten them 336 | new_key = key + ".Code" 337 | new_val = val["Code"] 338 | new_row[new_key] = new_val 339 | 340 | new_key = key + ".Omschrijving" 341 | new_val = val["Omschrijving"] 342 | new_row[new_key] = new_val 343 | else: 344 | new_row[key] = val 345 | rows.append(new_row) 346 | # normalize and return 347 | df = pd.json_normalize(rows) 348 | 349 | # add other info 350 | df["Code"] = location.get("Code", location.name) 351 | 352 | for name in [ 353 | "Coordinatenstelsel", 354 | "Naam", 355 | "Lon", 356 | "Lat", 357 | ]: 358 | df[name] = location[name] 359 | 360 | # set NA value 361 | colname_qc = "WaarnemingMetadata.Kwaliteitswaardecode" 362 | colname_num = "Meetwaarde.Waarde_Numeriek" 363 | colname_alf = "Meetwaarde.Waarde_Alfanumeriek" 364 | if colname_qc in df.columns: 365 | bool_nan = df[colname_qc] == "99" 366 | if colname_num in df.columns: 367 | df.loc[bool_nan, colname_num] = np.nan 368 | if colname_alf in df.columns: 369 | # float("NaN") translates to nan 370 | df.loc[bool_nan, colname_alf] = "NaN" 371 | 372 | df["time"] = pd.to_datetime(df["Tijdstip"], format="ISO8601") 373 | df = df.set_index("time") 374 | 375 | return df 376 | 377 | 378 | def _measurements_slice(location, start_date, end_date): 379 | """get measurements for location, for the period start_date, end_date, use measurements instead""" 380 | endpoint = ENDPOINTS["collect_observations"] 381 | 382 | start_date_str, end_date_str = _check_convert_dates( 383 | start_date, end_date, return_str=True 384 | ) 385 | 386 | request_dicts = _get_request_dicts(location) 387 | 388 | request = { 389 | "AquoPlusWaarnemingMetadata": {"AquoMetadata": request_dicts["AquoMetadata"]}, 390 | "Locatie": request_dicts["Locatie"], 391 | "Periode": {"Begindatumtijd": start_date_str, "Einddatumtijd": end_date_str}, 392 | } 393 | 394 | result = _send_post_request(endpoint["url"], request, timeout=None) 395 | 396 | df = _combine_waarnemingenlijst(result, location) 397 | return df 398 | 399 | 400 | def _clean_dataframe(measurements): 401 | len_raw = len(measurements) 402 | # drop duplicate rows (preserves e.g. different Grootheden/Groeperingen at same timestep) 403 | measurements = measurements.drop_duplicates() 404 | 405 | # remove Tijdstip column, has to be done after drop_duplicates to avoid too much to be dropped 406 | measurements = measurements.drop("Tijdstip", axis=1) 407 | 408 | # sort dataframe on time, ddl returns non-sorted data 409 | measurements = measurements.sort_index() 410 | ndropped = len_raw - len(measurements) 411 | logger.debug(f"{ndropped} duplicated values dropped") 412 | return measurements 413 | 414 | 415 | def measurements( 416 | location: pd.Series, 417 | start_date: (str, pd.Timestamp), 418 | end_date: (str, pd.Timestamp), 419 | freq: int = dateutil.rrule.MONTHLY, 420 | clean_df: bool = True, 421 | ): 422 | """ 423 | Returns measurements for the given location and requested period. 424 | 425 | Parameters 426 | ---------- 427 | location : pd.Series 428 | Single row of the `ddlpy.locations()` DataFrame. 429 | start_date : str, pd.Timestamp 430 | Start of the retrieval period. 431 | end_date : str, pd.Timestamp 432 | End of the retrieval period. 433 | freq : int, dateutil.rrule.MONTHLY, dateutil.rrule.YEARLY, etc., optional 434 | The frequency in which to divide the requested period (e.g. yearly or monthly). 435 | Can also be None, in which case the entire dataset will be retrieved at once. 436 | Please note that 10-minute measurements can often not be downloaded in yearly (or larger) chunks 437 | since the DDL limits the responses to 157681 values and several stations have duplicated timesteps. 438 | In that case the query will fail with an error or timeout or just return an empty result (as if there was no data). 439 | In that case, the user should fallback to monthly chunks. 440 | This is significantly slower but it is also much more robust. The default is dateutil.rrule.MONTHLY. 441 | clean_df : bool, optional 442 | Whether to sort the dataframe and remove duplicate rows. The default is True. 443 | 444 | Returns 445 | ------- 446 | measurements : pd.DataFrame 447 | DataFrame with measurements. 448 | """ 449 | 450 | if isinstance(location, pd.DataFrame): 451 | raise TypeError( 452 | "The provided location is a pandas.DataFrame, but should be a pandas.Series, " 453 | "supply only one location/row instead, for instance by doing 'location.iloc[0]'" 454 | ) 455 | 456 | start_date, end_date = _check_convert_dates(start_date, end_date, return_str=False) 457 | 458 | measurements = [] 459 | 460 | if freq is None: 461 | date_series_iterator = tqdm.tqdm([(start_date, end_date)]) 462 | else: 463 | date_series_iterator = tqdm.tqdm(date_series(start_date, end_date, freq=freq)) 464 | 465 | for start_date_i, end_date_i in date_series_iterator: 466 | try: 467 | measurement = _measurements_slice( 468 | location, start_date=start_date_i, end_date=end_date_i 469 | ) 470 | measurements.append(measurement) 471 | except NoDataError: 472 | continue 473 | 474 | if len(measurements) == 0: 475 | # return empty dataframe in case of no data 476 | logger.debug("no data found for this station and time extent") 477 | return pd.DataFrame() 478 | 479 | measurements = pd.concat(measurements) 480 | 481 | if clean_df: 482 | measurements = _clean_dataframe(measurements) 483 | 484 | return measurements 485 | 486 | 487 | def measurements_latest(location: pd.Series) -> pd.DataFrame: 488 | """ 489 | Returns the latest available measurement for the given location. 490 | 491 | Parameters 492 | ---------- 493 | location : pd.Series 494 | Single row of the `ddlpy.locations()` DataFrame. 495 | 496 | Returns 497 | ------- 498 | df : pd.DataFrame 499 | DataFrame with measurements. 500 | 501 | """ 502 | endpoint = ENDPOINTS["collect_latest_observations"] 503 | 504 | request_dicts = _get_request_dicts(location) 505 | 506 | request = { 507 | "AquoPlusWaarnemingMetadataLijst": [ 508 | {"AquoMetadata": request_dicts["AquoMetadata"]} 509 | ], 510 | "LocatieLijst": [request_dicts["Locatie"]], 511 | } 512 | 513 | result = _send_post_request(endpoint["url"], request, timeout=5) 514 | 515 | # continue if request was successful 516 | df = _combine_waarnemingenlijst(result, location) 517 | return df 518 | -------------------------------------------------------------------------------- /tests/test_ddlpy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Tests for `ddlpy` package.""" 5 | import datetime as dt 6 | import pandas as pd 7 | import pytest 8 | import ddlpy 9 | import dateutil 10 | import numpy as np 11 | from ddlpy.ddlpy import _send_post_request, NoDataError, get_catalogfile_cache 12 | 13 | DTYPES_NONSTRING = { 14 | "Locatie_MessageID": np.int64, 15 | "AquoMetadata_MessageID": np.int64, 16 | "Meetwaarde.Waarde_Numeriek": np.float64, 17 | "Lon": np.float64, 18 | "Lat": np.float64, 19 | } 20 | 21 | 22 | @pytest.fixture(scope="session") 23 | def endpoints(): 24 | """ 25 | Get the endpoints from the api 26 | """ 27 | endpoints = ddlpy.ddlpy.ENDPOINTS 28 | return endpoints 29 | 30 | 31 | @pytest.fixture(scope="session") 32 | def locations(): 33 | """return all locations""" 34 | locations = ddlpy.locations() 35 | return locations 36 | 37 | 38 | @pytest.fixture(scope="session") 39 | def location(locations): 40 | """return sample location""" 41 | bool_grootheid = locations["Grootheid.Code"] == "WATHTE" 42 | bool_groepering = locations["Groepering.Code"] == "" 43 | bool_procestype = locations["ProcesType"] == "meting" 44 | location = locations[bool_grootheid & bool_groepering & bool_procestype].loc[ 45 | "denhelder.marsdiep" 46 | ] 47 | return location 48 | 49 | 50 | @pytest.fixture(scope="session") 51 | def measurements(location): 52 | """measurements for a location""" 53 | start_date = dt.datetime(1953, 1, 1) 54 | end_date = dt.datetime(1953, 4, 1) 55 | measurements = ddlpy.measurements( 56 | location, start_date=start_date, end_date=end_date 57 | ) 58 | return measurements 59 | 60 | 61 | def test_send_post_request_errors_wrongapi(): 62 | url = "https://ddapi20-waterwebservices.rijkswaterstaat.nl/ONLINEWAARNEMINGENSERVICES/OphalenCatalogus" 63 | with pytest.raises(IOError) as e: 64 | _send_post_request(url, request=None) 65 | assert "404 Not Found" in str(e.value) 66 | assert "No endpoint POST /ONLINEWAARNEMINGENSERVICES/OphalenCatalogus." in str( 67 | e.value 68 | ) 69 | 70 | 71 | def test_send_post_request_errors_ophalencatalogus(endpoints): 72 | endpoint = endpoints["collect_catalogue"] 73 | url = endpoint["url"] 74 | 75 | request_empty = {} 76 | with pytest.raises(IOError) as e: 77 | _send_post_request(url, request=request_empty) 78 | assert "400 Bad Request" in str(e.value) 79 | assert ( 80 | "Het ophalen van de catalogus is mislukt, geen catalogusFilter opgegeven" 81 | in str(e.value) 82 | ) 83 | 84 | # TODO: this should result in an error by ddapi 85 | # https://github.com/Rijkswaterstaat/WaterWebservices/issues/18 86 | request_incorrectkeys = { 87 | "CatalogusFilter": { 88 | # 'Eenheden': True, 'Grootheden': True, 'Hoedanigheden': True, 89 | # 'Groeperingen': True, 'Parameters': True, 'Compartimenten': True, 90 | "ProcesTypes": True, 91 | "BioTaxonType": True, 92 | "ProcesType": True, 93 | "BioTaxonTypes": True, # both incorrect in new ddapi 94 | } 95 | } 96 | result = _send_post_request(url, request=request_incorrectkeys) 97 | assert result["Succesvol"] 98 | assert result["AquoMetadataLijst"] == [] 99 | assert result["AquoMetadataLocatieLijst"] == [] 100 | assert result["LocatieLijst"] == [] 101 | assert result["StatuswaardeLijst"] == [ 102 | "Ongecontroleerd", 103 | "Gecontroleerd", 104 | "Definitief", 105 | ] 106 | 107 | 108 | def test_send_post_request_errors_ophalenwaarnemingen(endpoints): 109 | endpoint = endpoints["collect_observations"] 110 | url = endpoint["url"] 111 | request_valid = endpoint["request"] 112 | 113 | request_empty = {} 114 | with pytest.raises(IOError) as e: 115 | _send_post_request(url, request=request_empty) 116 | assert "400 Bad Request" in str(e.value) 117 | assert "Er moet een periode worden meegegeven als: Periode" in str(e.value) 118 | assert "Er moet een locatie worden meegegeven als: Locatie" in str(e.value) 119 | assert ( 120 | "Er moet een AquoPlusObservationMetadata worden meegegeven onder: AquoPlusWaarnemingMetadata" 121 | in str(e.value) 122 | ) 123 | 124 | request_empty_aquoplus = dict(request_valid) 125 | request_empty_aquoplus["AquoPlusWaarnemingMetadata"] = {} 126 | with pytest.raises(IOError) as e: 127 | _send_post_request(url, request=request_empty_aquoplus) 128 | assert '400 Bad Request: {"aquoPlusObservationMetadata.aquoMetadata":' in str( 129 | e.value 130 | ) 131 | 132 | request_invalid_locatie = dict(request_valid) 133 | request_invalid_locatie["Locatie"] = {"Code": "nonexistent"} 134 | with pytest.raises(NoDataError) as e: 135 | _send_post_request(url, request=request_invalid_locatie) 136 | assert "204 No Content:" in str(e.value) 137 | 138 | request_invalid_periode_order = dict(request_valid) 139 | request_invalid_periode_order["Periode"] = { 140 | "Begindatumtijd": "2020-01-01T00:00:00.000+00:00", 141 | "Einddatumtijd": "2015-01-02T00:00:00.000+00:00", 142 | } 143 | with pytest.raises(IOError) as e: 144 | _send_post_request(url, request=request_invalid_periode_order) 145 | assert ( 146 | '400 Bad Request: {"period":"De startdatum mag niet na de einddatum zijn onder: Periode."}' 147 | in str(e.value) 148 | ) 149 | 150 | # TODO: this error is not properly handled by ddapi20 151 | # https://github.com/Rijkswaterstaat/WaterWebservices/issues/19 152 | request_invalid_periode_format = dict(request_valid) 153 | request_invalid_periode_format["Periode"] = { 154 | "Begindatumtijd": "2015-01-01T00:00:00.000", 155 | "Einddatumtijd": "2015-01-02T00:00:00.000+00:00", 156 | } 157 | with pytest.raises(IOError) as e: 158 | _send_post_request(url, request=request_invalid_periode_format) 159 | assert "500 Internal Server Error: Onverwachte fout opgetreden" in str(e.value) 160 | 161 | request_invalid_periode_wrongkeys = dict(request_valid) 162 | request_invalid_periode_wrongkeys["Periode"] = { 163 | "Begindatum": "2015-01-01T00:00:00.000+00:00", 164 | "Einddatum": "2015-01-02T00:00:00.000+00:00", 165 | } 166 | with pytest.raises(IOError) as e: 167 | _send_post_request(url, request=request_invalid_periode_wrongkeys) 168 | assert '400 Bad Request: {"period.endDateTime":' in str(e.value) 169 | 170 | # TODO: succesful=false is duplicate of resp.ok=False 171 | # https://github.com/Rijkswaterstaat/WaterWebservices/issues/14 172 | request_toolarge = dict(request_valid) 173 | request_toolarge["Periode"] = { 174 | "Begindatumtijd": "2015-01-01T00:00:00.000+00:00", 175 | "Einddatumtijd": "2020-01-01T00:00:00.000+00:00", 176 | } 177 | with pytest.raises(IOError) as e: 178 | _send_post_request(url, request=request_toolarge) 179 | assert "400 Bad Request:" in str(e.value) 180 | assert '"Succesvol":false' in str(e.value) 181 | assert ( 182 | '"Foutmelding":"Het maximaal aantal waarnemingen (160000) is overschreden. Beperk uw request."' 183 | in str(e.value) 184 | ) 185 | assert '"WaarnemingenLijst":[]' in str(e.value) 186 | 187 | request_nodata = dict(request_valid) 188 | request_nodata["Periode"] = { 189 | "Begindatumtijd": "2180-01-01T00:00:00.000+00:00", 190 | "Einddatumtijd": "2180-01-02T00:00:00.000+00:00", 191 | } 192 | with pytest.raises(NoDataError) as e: 193 | _send_post_request(url, request=request_nodata) 194 | assert "204 No Content:" in str(e.value) 195 | 196 | 197 | def test_get_catalogfile_cache(): 198 | catalogfile, use_cache = get_catalogfile_cache(catalog_filter=None) 199 | assert use_cache is True 200 | 201 | catalogfile, use_cache = get_catalogfile_cache(catalog_filter=[]) 202 | assert use_cache is False 203 | 204 | 205 | def test_nodataerror(location): 206 | """ 207 | Test whether a request that returns no data is indeed properly catched also when not 208 | calling _send_post_request() directly. The response for measurements_slice() is 209 | identical. The response for measurements_amount() is different because resp.ok=True 210 | and returns an empty list that is later catched in measurements_amount(). 211 | """ 212 | start_date = dt.datetime(2180, 1, 1) 213 | end_date = dt.datetime(2180, 4, 1) 214 | # same response as testing _send_post_request 215 | with pytest.raises(NoDataError) as e: 216 | # ddlpy.measurements() catches NoDataError, so we have to test it with _measurements_slice 217 | _ = ddlpy.ddlpy._measurements_slice( 218 | location, start_date=start_date, end_date=end_date 219 | ) 220 | assert "204 No Content: " in str(e.value) 221 | # different response than testing _send_post_request, since empty result will also raise NoDataError 222 | with pytest.raises(NoDataError) as e: 223 | _ = ddlpy.ddlpy.measurements_amount( 224 | location, start_date=start_date, end_date=end_date 225 | ) 226 | assert "no measurements available returned" in str(e.value) 227 | 228 | 229 | def test_locations(locations): 230 | # check if index is station code 231 | assert locations.index.name == "Code" 232 | assert isinstance(locations.index, pd.Index) 233 | assert isinstance(locations.index[0], str) 234 | 235 | # check presence of columns 236 | expected_columns = [ 237 | "Locatie_MessageID", 238 | "Lat", 239 | "Lon", 240 | "Coordinatenstelsel", 241 | "Naam", 242 | "Omschrijving", 243 | "Parameter_Wat_Omschrijving", 244 | "ProcesType", 245 | "Compartiment.Code", 246 | "Compartiment.Omschrijving", 247 | "Grootheid.Code", 248 | "Grootheid.Omschrijving", 249 | "Eenheid.Code", 250 | "Eenheid.Omschrijving", 251 | "Hoedanigheid.Code", 252 | "Hoedanigheid.Omschrijving", 253 | "Parameter.Code", 254 | "Parameter.Omschrijving", 255 | "BioTaxon.Code", 256 | "BioTaxon.Omschrijving", 257 | "Orgaan.Code", 258 | "Orgaan.Omschrijving", 259 | "Groepering.Code", 260 | "Groepering.Omschrijving", 261 | "Typering.Code", 262 | "Typering.Omschrijving", 263 | "WaardeBewerkingsMethode.Code", 264 | "WaardeBewerkingsMethode.Omschrijving", 265 | ] 266 | for colname in expected_columns: 267 | assert colname in locations.columns 268 | 269 | # the number of columns depend on the catalog filter in endpoints.json 270 | assert locations.shape[1] == len(expected_columns) 271 | # the number of rows is the number of stations, so will change over time 272 | assert locations.shape[0] > 1 273 | 274 | # check whether first values of all columns have the expected dtype 275 | for colname in locations.columns: 276 | if colname in DTYPES_NONSTRING.keys(): 277 | expected_dtype = DTYPES_NONSTRING[colname] 278 | else: 279 | expected_dtype = str 280 | assert isinstance(locations[colname].iloc[0], expected_dtype) 281 | 282 | # check whether all dtypes are the same for entire column 283 | for colname in locations.columns: 284 | column_unique_dtypes = locations[colname].apply(type).drop_duplicates() 285 | assert len(column_unique_dtypes) == 1 286 | 287 | 288 | def test_locations_extended(): 289 | catalog_filter = [ 290 | "Compartimenten", 291 | "Eenheden", 292 | "Grootheden", 293 | "Hoedanigheden", 294 | "Groeperingen", 295 | "MeetApparaten", 296 | "Typeringen", 297 | "WaardeBepalingsmethoden", 298 | "Parameters", 299 | ] 300 | locations_extended = ddlpy.locations(catalog_filter=catalog_filter) 301 | # the number of columns depend on the provided catalog_filter 302 | assert locations_extended.shape[1] == 25 303 | # the number of rows is the number of stations, so will change over time 304 | assert locations_extended.shape[0] > 1 305 | 306 | 307 | def test_measurements(measurements): 308 | # check if index is time and check dtype 309 | assert measurements.index.name == "time" 310 | assert isinstance(measurements.index, pd.DatetimeIndex) 311 | assert isinstance(measurements.index[0], pd.Timestamp) 312 | 313 | # check presence of columns, skipping all but one *.Omschrijving and *.Code columns 314 | expected_columns = [ 315 | "WaarnemingMetadata.Statuswaarde", 316 | "WaarnemingMetadata.Bemonsteringshoogte", 317 | "WaarnemingMetadata.Referentievlak", 318 | "WaarnemingMetadata.OpdrachtgevendeInstantie", 319 | "WaarnemingMetadata.Kwaliteitswaardecode", 320 | "Parameter_Wat_Omschrijving", 321 | "ProcesType", 322 | "Meetwaarde.Waarde_Alfanumeriek", 323 | "Meetwaarde.Waarde_Numeriek", 324 | "Code", 325 | "Coordinatenstelsel", 326 | "Naam", 327 | "Lon", 328 | "Lat", 329 | "Grootheid.Code", 330 | "Grootheid.Omschrijving", 331 | ] 332 | for colname in expected_columns: 333 | assert colname in measurements.columns 334 | 335 | # check the shape of the dataframe 336 | assert measurements.shape[1] == len(expected_columns) + 32 337 | assert measurements.shape[0] > 1 338 | 339 | # check whether first values of all columns have the expected dtype 340 | for colname in measurements.columns: 341 | if colname in DTYPES_NONSTRING.keys(): 342 | expected_dtype = DTYPES_NONSTRING[colname] 343 | else: 344 | expected_dtype = str 345 | assert isinstance(measurements[colname].iloc[0], expected_dtype) 346 | 347 | # check whether all dtypes are the same for entire column 348 | for colname in measurements.columns: 349 | column_unique_dtypes = measurements[colname].apply(type).drop_duplicates() 350 | assert len(column_unique_dtypes) == 1 351 | 352 | # check whether the filtering was passed properly 353 | assert set(measurements["ProcesType"].unique()) == {"meting"} 354 | 355 | 356 | def test_measurements_invalid_to_nan(locations): 357 | bool_grootheid = locations["Grootheid.Code"] == "WATHTE" 358 | bool_groepering = locations["Groepering.Code"] == "" 359 | bool_procestype = locations["ProcesType"] == "meting" 360 | location = locations[bool_grootheid & bool_groepering & bool_procestype].loc["a12"] 361 | 362 | start_date = dt.datetime(2009, 1, 1) 363 | end_date = dt.datetime(2009, 4, 1) 364 | measurements = ddlpy.measurements( 365 | location, start_date=start_date, end_date=end_date 366 | ) 367 | qc = measurements["WaarnemingMetadata.Kwaliteitswaardecode"] 368 | num = measurements["Meetwaarde.Waarde_Numeriek"] 369 | alf = measurements["Meetwaarde.Waarde_Alfanumeriek"] 370 | alf_num = alf.astype(float) 371 | 372 | assert "99" in qc.tolist() # there are invalid values in the dataframe 373 | assert num.max() < 1000 # but the 999999999.0 have been replaced with nan 374 | assert num.isnull().any() 375 | assert alf_num.max() < 1000 # but the 999999999.0 have been replaced with nan 376 | assert alf_num.isnull().any() 377 | assert np.allclose(num, alf_num, equal_nan=True) 378 | 379 | 380 | def test_measurements_freq_yearly(location, measurements): 381 | start_date = dt.datetime(1953, 1, 1) 382 | end_date = dt.datetime(1953, 4, 1) 383 | measurements_yearly = ddlpy.measurements( 384 | location, start_date=start_date, end_date=end_date, freq=dateutil.rrule.YEARLY 385 | ) 386 | assert measurements.shape == measurements_yearly.shape 387 | 388 | 389 | def test_measurements_freq_none(location, measurements): 390 | start_date = dt.datetime(1953, 1, 1) 391 | end_date = dt.datetime(1953, 4, 1) 392 | measurements_monthly = ddlpy.measurements( 393 | location, start_date=start_date, end_date=end_date, freq=None 394 | ) 395 | assert measurements.shape == measurements_monthly.shape 396 | 397 | 398 | def test_measurements_available(location): 399 | start_date = dt.datetime(1953, 1, 1) 400 | end_date = dt.datetime(1953, 4, 1) 401 | data_present = ddlpy.measurements_available( 402 | location, start_date=start_date, end_date=end_date 403 | ) 404 | assert data_present is True 405 | 406 | 407 | def test_measurements_available_false(location): 408 | # request period for which data is not available 409 | start_date = dt.datetime(2050, 1, 1) 410 | end_date = dt.datetime(2050, 4, 1) 411 | data_present = ddlpy.measurements_available( 412 | location, start_date=start_date, end_date=end_date 413 | ) 414 | assert data_present is False 415 | 416 | 417 | def test_measurements_amount(location): 418 | start_date = dt.datetime(1953, 1, 1) 419 | end_date = dt.datetime(1953, 4, 5) 420 | data_amount_dag = ddlpy.measurements_amount( 421 | location, start_date=start_date, end_date=end_date, period="Dag" 422 | ) 423 | assert data_amount_dag.shape[0] > 50 424 | assert data_amount_dag.index.str.len()[0] == 10 425 | data_amount_maand = ddlpy.measurements_amount( 426 | location, start_date=start_date, end_date=end_date, period="Maand" 427 | ) 428 | assert data_amount_maand.shape[0] == 4 429 | assert data_amount_maand.index.str.len()[0] == 7 430 | data_amount_jaar = ddlpy.measurements_amount( 431 | location, start_date=start_date, end_date=end_date, period="Jaar" 432 | ) 433 | assert data_amount_jaar.shape[0] == 1 434 | assert data_amount_jaar.index.str.len()[0] == 4 435 | 436 | 437 | def test_measurements_amount_invalidperiod(location): 438 | start_date = dt.datetime(1953, 1, 1) 439 | end_date = dt.datetime(1953, 4, 5) 440 | with pytest.raises(ValueError) as e: 441 | _ = ddlpy.measurements_amount( 442 | location, start_date=start_date, end_date=end_date, period="invalid" 443 | ) 444 | assert "period should be one of ['Jaar', 'Maand', 'Dag']" in str(e.value) 445 | 446 | 447 | def test_measurements_amount_multipleblocks(location): 448 | # in 1993 the WaardeBepalingsmethode changes from 449 | # other:F001 (Rekenkundig gemiddelde waarde over vorige 10 minuten) to 450 | # other:F007 (Rekenkundig gemiddelde waarde over vorige 5 en volgende 5 minuten) 451 | date_min = "1990-01-01" 452 | date_max = "1995-01-01" 453 | # if we pass one row to the measurements function you can get all the measurements 454 | df_amount = ddlpy.measurements_amount(location, date_min, date_max) 455 | 456 | index_expected = np.array(["1990", "1991", "1992", "1993", "1994", "1995"]) 457 | values_expected = np.array([52554, 52560, 52704, 52560, 52560, 7]) 458 | assert (df_amount.index == index_expected).all() 459 | assert (df_amount["AantalMetingen"].values == values_expected).all() 460 | 461 | 462 | def test_measurements_latest(location): 463 | """measurements for a location""" 464 | latest = ddlpy.measurements_latest(location) 465 | assert latest.shape[0] > 1 466 | 467 | 468 | def test_measurements_empty(location): 469 | """measurements for a location""" 470 | start_date = dt.datetime(2153, 1, 1) 471 | end_date = dt.datetime(2153, 1, 2) 472 | measurements = ddlpy.measurements( 473 | location, start_date=start_date, end_date=end_date 474 | ) 475 | assert measurements.empty 476 | 477 | 478 | def test_measurements_typerror(locations): 479 | start_date = dt.datetime(1953, 1, 1) 480 | end_date = dt.datetime(1953, 4, 1) 481 | with pytest.raises(TypeError) as e: 482 | _ = ddlpy.measurements(locations, start_date=start_date, end_date=end_date) 483 | assert ( 484 | "The provided location is a pandas.DataFrame, but should be a pandas.Series" 485 | in str(e.value) 486 | ) 487 | 488 | 489 | def test_measurements_noindex(location): 490 | # pandas dataframe with Code as column instead of index 491 | locations_noindex = pd.DataFrame(location).T 492 | locations_noindex.index.name = "Code" 493 | locations_noindex = locations_noindex.reset_index(drop=False) 494 | 495 | # normal subsetting and retrieving 496 | location_sel = locations_noindex.iloc[0] 497 | start_date = dt.datetime(1953, 1, 1) 498 | end_date = dt.datetime(1953, 4, 1) 499 | measurements = ddlpy.measurements( 500 | location_sel, start_date=start_date, end_date=end_date 501 | ) 502 | assert measurements.shape[0] > 1 503 | 504 | 505 | def test_measurements_long(location): 506 | """measurements for a location""" 507 | start_date = dt.datetime(1951, 11, 1) 508 | end_date = dt.datetime(1953, 4, 1) 509 | measurements = ddlpy.measurements( 510 | location, start_date=start_date, end_date=end_date 511 | ) 512 | assert measurements.shape[0] > 1 513 | 514 | 515 | def test_measurements_sorted(measurements): 516 | """https://github.com/deltares/ddlpy/issues/27""" 517 | 518 | # restore Tijdstip column to avoid error on removal 519 | measurements = measurements.copy() 520 | measurements["Tijdstip"] = measurements.index 521 | # sort dataframe on values so it will not be sorted on time 522 | meas_wrongorder = measurements.sort_values("Meetwaarde.Waarde_Numeriek") 523 | assert meas_wrongorder.index.is_monotonic_increasing is False 524 | meas_clean = ddlpy.ddlpy._clean_dataframe(meas_wrongorder) 525 | assert meas_clean.index.is_monotonic_increasing is True 526 | # assert meas_clean.index.duplicated().sum() == 0 527 | 528 | # check wheter indexes are DatetimeIndex 529 | assert isinstance(meas_wrongorder.index, pd.DatetimeIndex) 530 | assert isinstance(meas_clean.index, pd.DatetimeIndex) 531 | 532 | 533 | def test_measurements_duplicated(measurements): 534 | """ 535 | WALSODN 2010 contains all values three times, ddlpy drops duplicates 536 | https://github.com/deltares/ddlpy/issues/24 537 | 538 | Tijdstip column and length assertion of meas_clean are important 539 | to prevent too much duplicates removal https://github.com/deltares/ddlpy/issues/53 540 | """ 541 | # restore Tijdstip column to avoid too much duplicates removal 542 | measurements = measurements.copy() 543 | measurements["Tijdstip"] = measurements.index 544 | 545 | # deliberately duplicate values in a measurements dataframe 546 | meas_duplicated = pd.concat([measurements, measurements, measurements], axis=0) 547 | meas_clean = ddlpy.ddlpy._clean_dataframe(meas_duplicated) 548 | assert len(meas_duplicated) == 3024 549 | assert len(meas_clean) == len(measurements) == 1008 550 | 551 | # check wheter indexes are DatetimeIndex 552 | assert isinstance(meas_duplicated.index, pd.DatetimeIndex) 553 | assert isinstance(meas_clean.index, pd.DatetimeIndex) 554 | 555 | 556 | def test_measurements_timezone_behaviour(location): 557 | start_date = "2015-01-01 00:00:00 +01:00" 558 | end_date = "2015-01-03 00:00:00 +01:00" 559 | measurements = ddlpy.measurements( 560 | location, start_date=start_date, end_date=end_date 561 | ) 562 | assert str(measurements.index[0].tz) == "UTC+01:00" 563 | assert measurements.index[0] == pd.Timestamp(start_date) 564 | assert measurements.index[-1] == pd.Timestamp(end_date) 565 | 566 | data_amount_dag = ddlpy.measurements_amount( 567 | location, start_date=start_date, end_date=end_date, period="Dag" 568 | ) 569 | # when retrieving with tzone +01:00 we expect 1 value on 2015-01-03 570 | assert np.allclose(data_amount_dag["AantalMetingen"].values, [144, 144, 1]) 571 | 572 | start_date = "2015-01-01" 573 | end_date = "2015-01-03" 574 | measurements = ddlpy.measurements( 575 | location, start_date=start_date, end_date=end_date 576 | ) 577 | assert str(measurements.index[0].tz) == "UTC+01:00" 578 | assert measurements.index[0] == pd.Timestamp(start_date).tz_localize( 579 | "UTC" 580 | ).tz_convert("UTC+01:00") 581 | assert measurements.index[-1] == pd.Timestamp(end_date).tz_localize( 582 | "UTC" 583 | ).tz_convert("UTC+01:00") 584 | 585 | data_amount_dag = ddlpy.measurements_amount( 586 | location, start_date=start_date, end_date=end_date, period="Dag" 587 | ) 588 | # when retrieving with tzone +00:00 we expect 7 values on 2015-01-03 589 | assert np.allclose(data_amount_dag["AantalMetingen"].values, [138, 144, 7]) 590 | 591 | 592 | datetype_list = ["string", "pd.Timestamp", "dt.datetime", "mixed"] 593 | 594 | 595 | @pytest.mark.parametrize("datetype", datetype_list) 596 | def test_check_convert_dates(datetype): 597 | if datetype == "string": 598 | start_date = "1953-01-01" 599 | end_date = "1953-04-01" 600 | elif datetype == "pd.Timestamp": 601 | start_date = pd.Timestamp("1953-01-01") 602 | end_date = pd.Timestamp("1953-04-01") 603 | elif datetype == "dt.datetime": 604 | start_date = dt.datetime(1953, 1, 1) 605 | end_date = dt.datetime(1953, 4, 1) 606 | elif datetype == "mixed": 607 | start_date = "1953-01-01" 608 | end_date = dt.datetime(1953, 4, 1) 609 | 610 | # assert output 611 | start_date_out, end_date_out = ddlpy.ddlpy._check_convert_dates( 612 | start_date, end_date 613 | ) 614 | assert start_date_out == "1953-01-01T00:00:00.000+00:00" 615 | assert end_date_out == "1953-04-01T00:00:00.000+00:00" 616 | 617 | 618 | def test_check_convert_wrongorder(): 619 | start_date = "1953-01-01" 620 | end_date = "1953-04-01" 621 | 622 | # assert output 623 | with pytest.raises(ValueError): 624 | _, _ = ddlpy.ddlpy._check_convert_dates(end_date, start_date) 625 | 626 | 627 | def test_simplify_dataframe(measurements): 628 | """ 629 | should be in test_utils.py 630 | """ 631 | assert len(measurements.columns) == 48 632 | meas_simple = ddlpy.simplify_dataframe(measurements) 633 | assert hasattr(meas_simple, "attrs") 634 | # TODO: the below should be 47 and 1, but there are still RIKZ_WAT instances in 635 | # OpdrachtgevendeInstantie column, which is different from RIKZMON_WAT 636 | # this also probably partly causes the 96 duplicated timestamps 637 | # https://github.com/Rijkswaterstaat/WaterWebservices/issues/16 638 | assert len(meas_simple.attrs) == 46 639 | assert len(meas_simple.columns) == 2 640 | expected_columns = [ 641 | "WaarnemingMetadata.OpdrachtgevendeInstantie", 642 | "Meetwaarde.Waarde_Numeriek", 643 | ] 644 | assert set(meas_simple.columns) == set(expected_columns) 645 | 646 | 647 | def test_simplify_dataframe_always_preserve(measurements): 648 | """ 649 | should be in test_utils.py 650 | """ 651 | assert len(measurements.columns) == 48 652 | always_preserve = [ 653 | "WaarnemingMetadata.Statuswaarde", 654 | "WaarnemingMetadata.OpdrachtgevendeInstantie", 655 | "WaarnemingMetadata.Kwaliteitswaardecode", 656 | "Groepering.Code", 657 | "BemonsteringsApparaat.Code", 658 | "Meetwaarde.Waarde_Numeriek", 659 | ] 660 | meas_simple = ddlpy.simplify_dataframe( 661 | measurements, always_preserve=always_preserve 662 | ) 663 | assert hasattr(meas_simple, "attrs") 664 | assert len(meas_simple.attrs) == 42 665 | assert len(meas_simple.columns) == 6 666 | expected_columns = [ 667 | "WaarnemingMetadata.Statuswaarde", 668 | "WaarnemingMetadata.OpdrachtgevendeInstantie", 669 | "WaarnemingMetadata.Kwaliteitswaardecode", 670 | "Groepering.Code", 671 | "BemonsteringsApparaat.Code", 672 | "Meetwaarde.Waarde_Numeriek", 673 | ] 674 | assert set(meas_simple.columns) == set(expected_columns) 675 | 676 | 677 | def test_simplify_dataframe_always_preserve_invalid_key(measurements): 678 | """ 679 | should be in test_utils.py 680 | """ 681 | assert len(measurements.columns) == 48 682 | always_preserve = ["invalid_key"] 683 | with pytest.raises(ValueError) as e: 684 | _ = ddlpy.simplify_dataframe(measurements, always_preserve=always_preserve) 685 | assert "column 'invalid_key' not present in dataframe" in str(e.value) 686 | 687 | 688 | def test_simplify_dataframe_alfanumeriek_with_nan_dropped(locations): 689 | bool_grootheid = locations["Grootheid.Code"] == "WATHTE" 690 | bool_groepering = locations["Groepering.Code"] == "" 691 | bool_procestype = locations["ProcesType"] == "meting" 692 | location = locations[bool_grootheid & bool_groepering & bool_procestype].loc["a12"] 693 | 694 | start_date = dt.datetime(2009, 1, 1) 695 | end_date = dt.datetime(2009, 4, 1) 696 | measurements = ddlpy.measurements( 697 | location, start_date=start_date, end_date=end_date 698 | ) 699 | meas_simple = ddlpy.simplify_dataframe(df=measurements) 700 | expected_columns = [ 701 | "WaarnemingMetadata.Kwaliteitswaardecode", 702 | "Meetwaarde.Waarde_Numeriek", 703 | ] 704 | assert set(meas_simple.columns) == set(expected_columns) 705 | 706 | 707 | def test_dataframe_to_xarray(measurements): 708 | """ 709 | should be in test_utils.py 710 | """ 711 | always_preserve = [ 712 | "WaarnemingMetadata.Statuswaarde", 713 | "WaarnemingMetadata.Kwaliteitswaardecode", 714 | "MeetApparaat.Code", 715 | "WaardeBepalingsMethode.Code", 716 | "Meetwaarde.Waarde_Numeriek", 717 | ] 718 | ds_clean = ddlpy.dataframe_to_xarray( 719 | df=measurements, 720 | always_preserve=always_preserve, 721 | ) 722 | 723 | non_constant_columns = [ 724 | "WaarnemingMetadata.OpdrachtgevendeInstantie", 725 | "Meetwaarde.Waarde_Numeriek", 726 | ] 727 | 728 | preserved = always_preserve + non_constant_columns 729 | 730 | for varname in measurements.columns: 731 | # check if all varnames in always_preserve and non-constant columns are indeed preserved as variables 732 | if varname in preserved: 733 | assert varname in ds_clean.data_vars 734 | assert varname not in ds_clean.attrs.keys() 735 | else: 736 | assert varname not in ds_clean.data_vars 737 | assert varname in ds_clean.attrs.keys() 738 | varname_oms = varname.replace(".Code", ".Omschrijving") 739 | assert varname_oms in ds_clean.attrs.keys() 740 | 741 | # check if times and timezone are correct 742 | refdate_utc = measurements.tz_convert(None).index[0] 743 | ds_firsttime = ds_clean.time.to_pandas().iloc[0] 744 | assert refdate_utc == ds_firsttime 745 | assert ds_firsttime.tz is None 746 | 747 | 748 | def test_dataframe_to_xarray_drop_omschrijving(measurements): 749 | """ 750 | in case of non-unique Code/Omschrijving pairs, the Omschrijving variable should be 751 | dropped also. The information it contains is added as attrs to the Code value. 752 | """ 753 | # make MeetApparaat non-unique 754 | measurements.loc["1953-01-01 02:40:00+01:00", "MeetApparaat.Code"] = "newcode" 755 | measurements.loc["1953-01-01 02:40:00+01:00", "MeetApparaat.Omschrijving"] = ( 756 | "newoms" 757 | ) 758 | 759 | always_preserve = [ 760 | "WaarnemingMetadata.Statuswaarde", 761 | "WaarnemingMetadata.Kwaliteitswaardecode", 762 | "WaardeBepalingsMethode.Code", 763 | "Meetwaarde.Waarde_Numeriek", 764 | ] 765 | 766 | ds = ddlpy.dataframe_to_xarray(measurements, always_preserve=always_preserve) 767 | for varn in ds.data_vars: 768 | assert not varn.endswith(".Omschrijving") 769 | 770 | expected_attrs = {"newcode": "newoms", "10272": "other:Vlotterniveaumeter"} 771 | assert ds["MeetApparaat.Code"].attrs == expected_attrs 772 | 773 | 774 | def test_code_description_attrs_from_dataframe_prevent_empty(measurements): 775 | """ 776 | should be in test_utils.py 777 | https://github.com/Deltares/ddlpy/issues/156 778 | """ 779 | assert "" in measurements["Groepering.Code"].unique() 780 | attr_dict = ddlpy.utils.code_description_attrs_from_dataframe(measurements) 781 | for attr_key_value_pairs in attr_dict.values(): 782 | assert "" not in attr_key_value_pairs.keys() 783 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Service from Rijkswaterstaat for distributing water quantity data. 5 | Copyright (C) 2019 Fedor Baart 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | You should also get your employer (if you work as a programmer) or school, 654 | if any, to sign a "copyright disclaimer" for the program, if necessary. 655 | For more information on this, and how to apply and follow the GNU GPL, see 656 | . 657 | along with this program. If not, see . 658 | 659 | Also add information on how to contact you by electronic and paper mail. 660 | 661 | If the program does terminal interaction, make it output a short 662 | notice like this when it starts in an interactive mode: 663 | 664 | Copyright (C) 665 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 666 | This is free software, and you are welcome to redistribute it 667 | under certain conditions; type `show c' for details. 668 | 669 | The hypothetical commands `show w' and `show c' should show the appropriate 670 | parts of the General Public License. Of course, your program's commands 671 | might be different; for a GUI interface, you would use an "about box". 672 | 673 | You should also get your employer (if you work as a programmer) or school, 674 | if any, to sign a "copyright disclaimer" for the program, if necessary. 675 | For more information on this, and how to apply and follow the GNU GPL, see 676 | . 677 | 678 | The GNU General Public License does not permit incorporating your program 679 | into proprietary programs. If your program is a subroutine library, you 680 | may consider it more useful to permit linking proprietary applications with 681 | the library. If this is what you want to do, use the GNU Lesser General 682 | Public License instead of this License. But first, please read 683 | . 684 | --------------------------------------------------------------------------------