├── .github ├── ISSUE_TEMPLATE │ └── issue.md └── workflows │ ├── dev.yml │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── ecmwf └── opendata │ ├── __init__.py │ ├── bufr.py │ ├── client.py │ ├── date.py │ ├── grib.py │ └── urls.py ├── examples └── aifs-ens-earthkit.ipynb ├── pytest.ini ├── setup.py ├── tests ├── requirements.txt ├── test_aifs_ens.py ├── test_date.py ├── test_examples.py ├── test_latest.py ├── test_opendata.py ├── test_request.py ├── test_sources.py └── test_stream.py ├── tools ├── .gitignore ├── README ├── check-index.py ├── crawl.py ├── get-all.py ├── param-units.py ├── parse.py ├── possible.py ├── requirements.txt ├── upload.py └── upload.sh └── tox.ini /.github/ISSUE_TEMPLATE/issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue 3 | about: Report an issue with ecmwf-opendata 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Please note that comments on this platform are not monitored by ECMWF. The open data is provided on a best effort basis, without further support from ECMWF. However, users are free to discuss their experiences and issues related to the software tool, and propose clean merge requests with appropriate testing and documentation. If you do require support or assistance, we encourage you to create a support request in the ECMWF Support Portal. Thank you for your understanding and for your contribution to our community. 11 | -------------------------------------------------------------------------------- /.github/workflows/dev.yml: -------------------------------------------------------------------------------- 1 | name: Dev test 2 | 3 | on: 4 | workflow_dispatch: {} 5 | 6 | jobs: 7 | checks: 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | platform: ["ubuntu-latest", "macos-latest"] 12 | python-version: ["3.9", "3.10", "3.11" ] 13 | 14 | name: Python ${{ matrix.python-version }} on ${{ matrix.platform }} 15 | runs-on: ${{ matrix.platform }} 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | 24 | - name: Install 25 | run: | 26 | pip install pytest 27 | pip install -e . 28 | pip install -r tests/requirements.txt 29 | pip freeze 30 | 31 | - name: Tests 32 | run: pytest tests/test_examples.py 33 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | push: {} 8 | release: 9 | types: [ created ] 10 | 11 | jobs: 12 | quality: 13 | name: Code QA 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - run: pip install black flake8 isort 18 | - run: black --version 19 | - run: isort --version 20 | - run: flake8 --version 21 | - run: isort --check . 22 | - run: black --check . 23 | - run: flake8 . 24 | 25 | checks: 26 | if: ${{ github.event_name == 'release' }} 27 | 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | platform: [ "ubuntu-latest", "macos-latest" ] 32 | python-version: [ "3.9", "3.10", "3.11" ] 33 | 34 | name: Python ${{ matrix.python-version }} on ${{ matrix.platform }} 35 | runs-on: ${{ matrix.platform }} 36 | needs: quality 37 | 38 | steps: 39 | - uses: actions/checkout@v2 40 | 41 | - uses: actions/setup-python@v2 42 | with: 43 | python-version: ${{ matrix.python-version }} 44 | 45 | - name: Install 46 | run: | 47 | pip install pytest 48 | pip install -e . 49 | pip install -r tests/requirements.txt 50 | pip freeze 51 | 52 | - name: Tests 53 | run: env SOURCES_TO_TEST=ecmwf pytest 54 | 55 | deploy: 56 | 57 | if: ${{ github.event_name == 'release' }} 58 | runs-on: ubuntu-latest 59 | needs: checks 60 | 61 | steps: 62 | - uses: actions/checkout@v2 63 | 64 | - name: Set up Python 65 | uses: actions/setup-python@v2 66 | with: 67 | python-version: '3.10' 68 | 69 | - name: Check that tag version matches code version 70 | run: | 71 | tag=${GITHUB_REF#refs/tags/} 72 | version=$(python setup.py --version) 73 | echo 'tag='$tag 74 | echo "version file="$version 75 | test "$tag" == "$version" 76 | 77 | - name: Install dependencies 78 | run: | 79 | python -m pip install --upgrade pip 80 | pip install build twine 81 | - name: Build and publish 82 | env: 83 | TWINE_USERNAME: __token__ 84 | TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} 85 | run: | 86 | python -m build 87 | twine upload dist/* 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,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 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Other 132 | *.swp 133 | test.py 134 | .vscode/ 135 | target 136 | data 137 | *.grib 138 | *.grib2 139 | ? 140 | *.download 141 | *.index 142 | *.out 143 | *.1 144 | test.* 145 | *.bufr 146 | done 147 | *.raw 148 | ?.* 149 | TODO 150 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ecmwf-opendata 2 | 3 | `ecmwf-opendata` is a package to simplify the download of ECMWF [open data](https://www.ecmwf.int/en/forecasts/datasets/open-data). It implements a request-based interface to the dataset using ECMWF's MARS language to select meteorological fields, similar to the existing [ecmwf-api-client](https://github.com/ecmwf/ecmwf-api-client) Python package. 4 | 5 | A collection of Jupyter Notebooks that make use of that package is available [here](https://github.com/ecmwf/notebook-examples/tree/master/opencharts). 6 | 7 | ## Installation 8 | 9 | The `ecmwf-opendata` Python package can be installed from PyPI with: 10 | 11 | ```$ pip install ecmwf-opendata``` 12 | 13 | ## Usage 14 | The example below will download the latest available 10-day forecast for the *mean sea level pressure* (`msl`) into a local file called `data.grib2`: 15 | 16 | ```python 17 | from ecmwf.opendata import Client 18 | 19 | client = Client() 20 | 21 | client.retrieve( 22 | step=240, 23 | type="fc", 24 | param="msl", 25 | target="data.grib2", 26 | ) 27 | ``` 28 | 29 | > ❗ **NOTE:** This package is designed for users that want to download a subset of the whole dataset. If you plan to download a large percentage of each data file, it may be more efficient to download whole files and filter out the data you want locally. See the documentation on the [file naming convention](https://confluence.ecmwf.int/display/DAC/ECMWF+open+data%3A+real-time+forecasts+from+IFS+and+AIFS) for more information. Alternatively, you can use this tool to download whole files by only specifying `date`, `time`, `step`, `stream` and `type`. Please be aware that all data for a full day is in the order of 726 GiB. 30 | 31 | 32 | ## Options 33 | 34 | The constructor of the client object takes the following options: 35 | 36 | ```python 37 | client = Client( 38 | source="ecmwf", 39 | model="ifs", 40 | resol="0p25", 41 | preserve_request_order=False, 42 | infer_stream_keyword=True, 43 | ) 44 | ``` 45 | 46 | where: 47 | 48 | - `source` is either the name of server to contact or a fully qualified URL. Possible values are `ecmwf` to access ECMWF's servers, `aws` for data hosted by Amazon Web Services or `azure` to access data hosted on Microsoft's Azure. Default is `ecmwf`. 49 | 50 | - `model` is the name of the model that produced the data. Use `ifs` for the physics-driven model, `aifs-single` for the data-driven model, and `aifs-ens` for the ensemble data-driven model. Default is `ifs`. 51 | 52 | - `resol` specifies the resolution of the data. Default is `0p25` for 0.25 degree resolution, and is the only resolution that is currently available. 53 | 54 | - `preserve_request_order`. If this flag is set to `True`, the library will attempt to write the retrieved data into the target file in the order specified by the request. For example, if the request specifies `param=[2t,msl]` the library will ensure that the field `2t` is first in the target file, while with `param=[msl,2t]`, the field `msl` will be first. This also works across different keywords: `...,levelist=[500,100],param=[z,t],...` will produce different output to `...,param=[z,t],levelist=[500,100],...` 55 | If the flag is set to `False`, the library will sort the request to minimise the number of HTTP requests made to the server, leading to faster download speeds. Default is `False`. 56 | 57 | - `infer_stream_keyword`. The `stream` keyword represents the ECMWF forecasting system that creates the data. Setting it properly requires knowledge of how ECMWF runs its operations. If this boolean is set to `True`, the library will try to infer the correct value for the `stream` keyword based on the rest of the request. Default is `True` if model is `ifs`. 58 | 59 | > ⚠️ **NOTE:** It is recommended **not** to set the `preserve_request_order` flag to `True` when downloading a large number of fields as this will add extra load on the servers. 60 | 61 | ## Methods 62 | 63 | > `Client.retrieve()` 64 | 65 | The `Client.retrieve()` method takes request as input and will retrieve the corresponding data from the server and write them in the user's target file. 66 | 67 | A request is a list of keyword/value pairs used to select the desired data. It is possible to specify a list of values for a given keyword. 68 | 69 | The request can either be specified as a dictionary: 70 | 71 | ```python 72 | from ecmwf.opendata import Client 73 | 74 | client = Client(source="ecmwf") 75 | 76 | request = { 77 | "time": 0, 78 | "type": "fc", 79 | "step": 24, 80 | "param": ["2t", "msl"], 81 | } 82 | 83 | client.retrieve(request, "data.grib2") 84 | 85 | # or: 86 | 87 | client.retrieve( 88 | request=request, 89 | target="data.grib2", 90 | ) 91 | ``` 92 | 93 | or directly as arguments to the `retrieve()` method: 94 | 95 | ```python 96 | from ecmwf.opendata import Client 97 | 98 | client = Client(source="ecmwf") 99 | 100 | client.retrieve( 101 | time=0, 102 | type="fc", 103 | step=24, 104 | param=["2t", "msl"], 105 | target="data.grib2", 106 | ) 107 | ``` 108 | 109 | The `date` and `time` keyword are used to select the date and time of the forecast run (see [Date and time](#date-and-time) below). If `date` or both `date` and `time` are not specified, the library will query the server for the most recent matching data. The `date` and `time` of the downloaded forecast is returned by the `retrieve()` method. 110 | 111 | ```python 112 | from ecmwf.opendata import Client 113 | 114 | client = Client(source="ecmwf") 115 | 116 | result = client.retrieve( 117 | type="fc", 118 | step=24, 119 | param=["2t", "msl"], 120 | target="data.grib2", 121 | ) 122 | 123 | print(result.datetime) 124 | ``` 125 | 126 | may print `2022-01-23 00:00:00`. 127 | 128 | > `Client.download()` 129 | 130 | The `Client.download()` method takes the same parameters as the `Client.retrieve()` method, but will download the whole data files from the server, ignoring keywords like `param`, `levelist` or `number`. 131 | 132 | The example below will download all field from the latest time step 24, ignoring the keyword `param`: 133 | 134 | ```python 135 | from ecmwf.opendata import Client 136 | 137 | client = Client(source="ecmwf") 138 | 139 | client.download( 140 | param="msl", 141 | type="fc", 142 | step=24, 143 | target="data.grib2", 144 | ) 145 | 146 | ``` 147 | 148 | > `Client.latest()` 149 | 150 | The `Client.latest()` method takes the same parameters as the `Client.retrieve()` method, and returns the date of the most recent matching forecast without downloading the data: 151 | 152 | ```python 153 | from ecmwf.opendata import Client 154 | 155 | client = Client(source="ecmwf") 156 | 157 | print(client.latest( 158 | type="fc", 159 | step=24, 160 | param=["2t", "msl"], 161 | target="data.grib2", 162 | )) 163 | ``` 164 | 165 | may print `2022-01-23 00:00:00`. 166 | 167 | > ⏰ **NOTE**: The data is available between 7 and 9 hours after the forecast starting date and time, depending on the forecasting system and the time step specified. 168 | 169 | ## Request keywords 170 | 171 | The supported keywords are: 172 | 173 | - `type`: the type of data (compulsory, defaults to `fc`). 174 | - `stream`: the forecast system (optional if unambiguous, compulsory otherwise). See the `infer_stream_keyword` [above](#options). 175 | - `date`: the date at which the forecast starts. 176 | - `time`: the time at which the forecast starts. 177 | - `step`: the forecast time step in hours, or `fcmonth`, the time step in months for the seasonal forecast (compulsory, default to `0` and `1`, respectively). 178 | 179 | and (all optional, with no defaults): 180 | 181 | - `param`: the meteorological parameters, such as wind, pressure or humidity. 182 | - `levtype`: select between single level parameters and parameters on pressure levels. 183 | - `levelist`: the list of pressure levels when relevant. 184 | - `number`: the list of ensemble member numbers when relevant. 185 | 186 | The keywords in the first list are used to identify which file to access, while the second list is used to identify which parts of the files need to be actually downloaded. Some HTTP servers are able to return multiple parts of a file, while other can only return a single part from a file. In the latter case, the library may perform many HTTP requests to the server. If you wish to download whole files, only provide keywords from the first list. 187 | 188 | ### Date and time 189 | 190 | The date and time parameters refer to the starting time of the forecast. All date and time are expressed in UTC. 191 | 192 | There are several ways to specify the date and time in a request. 193 | 194 | Date can be specified using strings, numbers and Python `datetime.datetime` or `datetime.date` objects: 195 | 196 | ```python 197 | ... 198 | date='20220125', 199 | time=12, 200 | ... 201 | date='2022-01-25', 202 | time=12, 203 | ... 204 | date='2022-01-25 12:00:00', 205 | ... 206 | date=20220125, 207 | time=12, 208 | ... 209 | date=datetime.datetime(2022, 1, 25, 12, 0, 0), 210 | ... 211 | date=datetime.date(2022, 1, 25), 212 | time=12, 213 | ... 214 | ``` 215 | 216 | Dates can also be given as a number less than or equal to zero. In this case, it is equivalent to the current UTC date minus the given number of days: 217 | 218 | ```python 219 | ... 220 | date=0, # today 221 | date=-1, # yesterday 222 | date=-2, # the day before yesterday 223 | ... 224 | ``` 225 | 226 | The keyword `time` can be given as a string or an integer, or a Python `datetime.time` object. All values of time below are equivalent: 227 | 228 | ```python 229 | ... 230 | time=12, 231 | ... 232 | time=1200, 233 | ... 234 | time='12', 235 | ... 236 | time='1200', 237 | ... 238 | time=datetime.time(12), 239 | ... 240 | ``` 241 | 242 | | List of valid values for time | 243 | | ----------------------------- | 244 | | 0, 6, 12 and 18 | 245 | 246 | If `time` is not specified, the time is extracted from the date. 247 | 248 | ```python 249 | ... 250 | date='2022-01-25 12:00:00', 251 | ... 252 | ``` 253 | 254 | is equivalent to: 255 | 256 | ```python 257 | ... 258 | date='2022-01-25', 259 | time=12, 260 | ... 261 | ``` 262 | 263 | If the `time` keyword is specified, it overrides any time given in the request. 264 | 265 | ```python 266 | ... 267 | date='2022-01-25 12:00:00', 268 | time=18, 269 | ... 270 | ``` 271 | 272 | is equivalent to: 273 | 274 | ```python 275 | ... 276 | date='2022-01-25', 277 | time=18, 278 | ... 279 | ``` 280 | 281 | As stated before, if `date` or both `date` and `time` are not specified, the library will query the server for the most recent matching data. The `date` and `time` of the downloaded forecast is returned by the `retrieve()` method: 282 | 283 | Example without the `date` keyword: 284 | 285 | ```python 286 | from ecmwf.opendata import Client 287 | 288 | client = Client(source="ecmwf") 289 | 290 | result = client.retrieve( 291 | time=12, 292 | type="fc", 293 | param="2t", 294 | step="24", 295 | target="data.grib2", 296 | ) 297 | 298 | print(result.datetime) 299 | 300 | ``` 301 | 302 | will print `2022-01-22 12:00:00` if run in the morning of 2022-01-23. 303 | 304 | Example without the `date` and `time` keywords: 305 | 306 | ```python 307 | from ecmwf.opendata import Client 308 | 309 | client = Client(source="ecmwf") 310 | 311 | result = client.retrieve( 312 | type="fc", 313 | param="2t", 314 | step="24", 315 | target="data.grib2", 316 | ) 317 | 318 | print(result.datetime) 319 | 320 | ``` 321 | 322 | will print `2022-01-23 00:00:00` if run in the morning of 2022-01-23. 323 | 324 | ### Stream and type 325 | 326 | ECMWF runs several forecasting systems: 327 | 328 | - [HRES](https://confluence.ecmwf.int/display/FUG/HRES+-+High-Resolution+Forecast): High Resolution Forecast. 329 | - [ENS](https://confluence.ecmwf.int/display/FUG/ENS+-+Ensemble+Forecasts): Ensemble Forecasts. 330 | - [SEAS](https://confluence.ecmwf.int/display/FUG/Long-Range+%28Seasonal%29+Forecast): Long-Range (Seasonal) Forecast. 331 | 332 | Each of these forecasts also produces several types of products, that are referred to using the keywords 333 | `stream` and `type`. 334 | 335 | > Valid values for `type` are: 336 | 337 | HRES: 338 | 339 | - `fc`: Forecast. 340 | 341 | ENS: 342 | 343 | - `cf`: Control forecast. 344 | - `pf`: Perturbed forecast. 345 | - `em`: Ensemble mean. 346 | - `es`: Ensemble standard deviation. 347 | - `ep`: Probabilities. 348 | 349 | > Valid values for `stream` are: 350 | 351 | - `oper`: Atmospheric fields from HRES - 00 UTC and 12 UTC. 352 | - `wave`: Ocean wave fields from HRES - 00 UTC and 12 UTC. 353 | - `enfo`: Atmospheric fields from ENS. 354 | - `waef`: Ocean wave fields from ENS. 355 | - `scda`: Atmospheric fields from HRES - 06 UTC and 18 UTC. 356 | - `scwv`: Ocean wave fields from HRES - 06 UTC and 18 UTC. 357 | 358 | > 📌 **NOTE**: if the client's flag [`infer_stream_keyword`](#options) is set to `True`, the library will infer the stream from the `type` and `time`. In that case, you just need to specify `stream=wave` to access ocean wave products, and don't provide a value for `stream` in other cases. 359 | 360 | ### Time steps 361 | 362 | To select a time step, use the `step` keyword: 363 | 364 | ```python 365 | ... 366 | step=24, 367 | ... 368 | step=[24, 48], 369 | ... 370 | ``` 371 | 372 | | Forecasting system | Time | List of time steps | 373 | | -------- | ---- | ------------------ | 374 | | HRES | 00 and 12 | 0 to 144 by 3, 144 to 240 by 6 | 375 | | ENS | 00 and 12 | 0 to 144 by 3, 144 to 360 by 6 | 376 | | HRES | 06 and 18 | 0 to 90 by 3 | 377 | | ENS | 06 and 18 | 0 to 144 by 3 | 378 | | Probabilities - Instantaneous weather events | 00 and 12 | 0 to 360 by 12 | 379 | | Probabilities - Daily weather events | 00 and 12 | 0-24 to 336-360 by 12 | 380 | 381 | > 📌 **NOTE**: Not specifying `step` will return all available time steps. 382 | 383 | ### Parameters and levels 384 | 385 | To select a parameter, use the `param` keyword: 386 | 387 | ```python 388 | ... 389 | param="msl", 390 | ... 391 | param=["2t", "msl"] 392 | ... 393 | ``` 394 | 395 | for pressure level parameters, use the `levelist` keyword: 396 | 397 | ```python 398 | ... 399 | param="t", 400 | levelist=850, 401 | ... 402 | param=["u", "v"], 403 | levelist=[1000, 850, 500], 404 | ... 405 | ``` 406 | 407 | > 📌 **NOTE**: Not specifying `levelist` will return all available levels, and not specifying `param` will return all available parameters. 408 | 409 | | List of pressure levels (hPa) | 410 | | ----------------------------- | 411 | | 1000, 925, 850, 700, 500, 300, 250, 200 and 50 | 412 | 413 | 414 | Below is the list of all parameters: 415 | 416 | > Atmospheric fields on pressure levels 417 | 418 | | Parameter | Description | Units | 419 | | --------- | ----------- | ----- | 420 | | d | Divergence | s-1 | 421 | | gh | Geopotential height | gpm | 422 | | q | Specific humidity | kg kg-1 | 423 | | r | Relative humidity | % | 424 | | t | Temperature | K | 425 | | u | U component of wind | m s-1 | 426 | | v | V component of wind | m s-1 | 427 | | vo | Vorticity (relative) | s-1 | 428 | 429 | > Atmospheric fields on a single level 430 | 431 | | Parameter | Description | Units | 432 | | --------- | ----------- | ----- | 433 | | 10u | 10 metre U wind component | m s-1 | 434 | | 10v | 10 metre V wind component | m s-1 | 435 | | 2t | 2 metre temperature | K | 436 | | msl | Mean sea level pressure | Pa | 437 | | ro | Runoff | m | 438 | | skt | Skin temperature | K | 439 | | sp | Surface pressure | Pa | 440 | | st | Soil Temperature | K | 441 | | stl1 | Soil temperature level 1 | K | 442 | | tcwv | Total column vertically-integrated water vapour | kg m-2 | 443 | | tp | Total Precipitation | m | 444 | 445 | > Ocean waves fields 446 | 447 | | Parameter | Description | Units | 448 | | --------- | ----------- | ----- | 449 | | mp2 | Mean zero-crossing wave period | s | 450 | | mwd | Mean wave direction | Degree true | 451 | | mwp | Mean wave period | s | 452 | | pp1d | Peak wave period | s | 453 | | swh | Significant height of combined wind waves and swell | m | 454 | 455 | > Ensemble mean and standard deviation - pressure levels 456 | 457 | | Parameter | Description | Units | Levels | 458 | | --------- | ----------- | ----- | ------ | 459 | | gh | Geopotential height | gpm | 300, 500, 1000 | 460 | | t | Temperature | K | 250, 500, 850 | 461 | | ws | Wind speed | m s-1 | 250, 850 | 462 | 463 | > Ensemble mean and standard deviation - single level 464 | 465 | | Parameter | Description | Units | 466 | | --------- | ----------- | ----- | 467 | | msl | Mean sea level pressure | Pa | 468 | 469 | > Instantaneous weather events - atmospheric fields - 850 hPa 470 | 471 | | Parameter | Description | Units | 472 | | --------- | ----------- | ----- | 473 | | ptsa_gt_1p5stdev | Probability of temperature standardized anomaly greater than 1.5 standard deviation | % | 474 | | ptsa_gt_1stdev | Probability of temperature standardized anomaly greater than 1 standard deviation | % | 475 | | ptsa_gt_2stdev | Probability of temperature standardized anomaly greater than 2 standard deviation | % | 476 | | ptsa_lt_1p5stdev | Probability of temperature standardized anomaly less than -1.5 standard deviation | % | 477 | | ptsa_lt_1stdev | Probability of temperature standardized anomaly less than -1 standard deviation | % | 478 | | ptsa_lt_2stdev | Probability of temperature standardized anomaly less than -2 standard deviation | % | 479 | 480 | > Daily weather events - atmospheric fields - single level 481 | 482 | | Parameter | Description | Units | 483 | | --------- | ----------- | ----- | 484 | | 10fgg10 | 10 metre wind gust of at least 10 m/s | % | 485 | | 10fgg15 | 10 metre wind gust of at least 15 m/s | % | 486 | | 10fgg25 | 10 metre wind gust of at least 25 m/s | % | 487 | | tpg1 | Total precipitation of at least 1 mm | % | 488 | | tpg10 | Total precipitation of at least 10 mm | % | 489 | | tpg100 | Total precipitation of at least 100 mm | % | 490 | | tpg20 | Total precipitation of at least 20 mm | % | 491 | | tpg25 | Total precipitation of at least 25 mm | % | 492 | | tpg5 | Total precipitation of at least 5 mm | % | 493 | | tpg50 | Total precipitation of at least 50 mm | % | 494 | 495 | > Instantaneous weather events - ocean waves fields 496 | 497 | | Parameter | Description | Units | 498 | | --------- | ----------- | ----- | 499 | | swhg2 | Significant wave height of at least 2 m | % | 500 | | swhg4 | Significant wave height of at least 4 m | % | 501 | | swhg6 | Significant wave height of at least 6 m | % | 502 | | swhg8 | Significant wave height of at least 8 m | % | 503 | 504 | ### Ensemble numbers 505 | 506 | You can select individual members of the ensemble forecast use the keyword `number`. 507 | 508 | ```python 509 | ... 510 | stream="enfo", 511 | step=24, 512 | param="msl", 513 | number=1, 514 | ... 515 | stream="enfo", 516 | step=24, 517 | param="msl", 518 | number=[1, 10, 20], 519 | ... 520 | ``` 521 | 522 | | List of ensemble numbers | 523 | | ----------------------------- | 524 | | 1 to 50 | 525 | 526 | > 📌 **NOTE**: Not specifying `number` will return all ensemble forecast members. 527 | 528 | ## Examples 529 | 530 | ### Download a single surface parameter at a single forecast step from ECMWF's 00UTC HRES forecast 531 | 532 | ```python 533 | from ecmwf.opendata import Client 534 | 535 | client = Client(source="ecmwf") 536 | 537 | client.retrieve( 538 | time=0, 539 | stream="oper", 540 | type="fc", 541 | step=24, 542 | param="2t", 543 | target="data.grib2", 544 | ) 545 | ``` 546 | 547 | ### Download the tropical cyclone tracks from ECMWF's 00UTC HRES forecast 548 | 549 | ```python 550 | from ecmwf.opendata import Client 551 | 552 | client = Client(source="ecmwf") 553 | 554 | client.retrieve( 555 | time=0, 556 | stream="oper", 557 | type="tf", 558 | step=240, 559 | target="data.bufr", 560 | ) 561 | ``` 562 | 563 | - The downloaded data are encoded in BUFR edition 4 564 | - For the HRES Tropical Cyclone tracks at time=06 and time=18 use: 565 | 566 | ```python 567 | ... 568 | step = 90, 569 | ... 570 | ``` 571 | 572 | > ❗ **NOTE:** Tropical cyclone tracks products are only available when there are tropical cyclones observed or forecast. 573 | 574 | ### Download a single surface parameter at a single forecast step for all ensemble members from ECMWF's 12UTC 00UTC ENS forecast 575 | 576 | ```python 577 | from ecmwf.opendata import Client 578 | 579 | client = Client(source="ecmwf") 580 | 581 | client.retrieve( 582 | time=0, 583 | stream="enfo", 584 | type="pf", 585 | param="msl", 586 | target="data.grib2", 587 | ) 588 | ``` 589 | 590 | - To download a single ensemble member, use the `number` keyword: `number=1`. 591 | - All of the odd numbered ensemble members use `number=[num for num in range(1,51,2)]`. 592 | - To download the control member, use `type="cf"`. 593 | 594 | 595 | ### Download a single surface parameter at a single forecast step for all ensemble members from ECMWF's 12UTC 00UTC AIFS-ENS forecast 596 | 597 | ```python 598 | from ecmwf.opendata import Client 599 | 600 | client = Client(source="ecmwf", model="aifs-ens") 601 | 602 | client.retrieve( 603 | time=0, 604 | stream="enfo", 605 | type="pf", 606 | param="msl", 607 | target="data.grib2", 608 | ) 609 | ``` 610 | 611 | - To download a single ensemble member, use the `number` keyword: `number=1`. 612 | - All of the odd numbered ensemble members use `number=[num for num in range(1,51,2)]`. 613 | - To download the control member, use `type="cf"`. 614 | 615 | ### Download the Tropical Cyclone tracks from ECMWF's 00UTC ENS forecast 616 | 617 | The Tropical Cyclone tracks are identified by the keyword `type="tf"`. 618 | 619 | ```python 620 | from ecmwf.opendata import Client 621 | 622 | client = Client(source="ecmwf") 623 | 624 | client.retrieve( 625 | time=0, 626 | stream="enfo", 627 | type="tf", 628 | step=240, 629 | target="data.bufr", 630 | ) 631 | ``` 632 | 633 | - The downloaded data are encoded in BUFR edition 4 634 | - For the ENS Tropical Cyclone tracks at time=06 and time=18 replace `step=240` with `step=144`. 635 | 636 | ### Download the ensemble mean and standard deviation for all parameters at a single forecast step from ECMWF's 00UTC ENS forecast 637 | 638 | The ensemble mean and standard deviation are identified by the keywords `type="em"`: 639 | 640 | ```python 641 | from ecmwf.opendata import Client 642 | 643 | client = Client(source="ecmwf") 644 | 645 | client.retrieve( 646 | time=0, 647 | stream="enfo", 648 | type="em", 649 | step=24, 650 | target="data.grib2", 651 | ) 652 | ``` 653 | 654 | and `type="es"`, respectively: 655 | 656 | ```python 657 | from ecmwf.opendata import Client 658 | 659 | client = Client(source="ecmwf") 660 | 661 | client.retrieve( 662 | time=0, 663 | stream="enfo", 664 | type="es", 665 | step=24, 666 | target="data.grib2", 667 | ) 668 | 669 | ``` 670 | 671 | ### Download the ensemble probability products 672 | 673 | The ensemble probability products are identified by the keyword `type="ep"`. The probability products are available only for `time=00` and `time=12`. 674 | 675 | Two different products are available. 676 | 677 | #### Probabilities - Instantaneous weather events - Pressure levels 678 | 679 | The probability of temperature standardized anomalies at a constant 680 | pressure level of 850hPa are available at 12 hourly forecast steps. 681 | 682 | ```python 683 | from ecmwf.opendata import Client 684 | 685 | client = Client(source="ecmwf") 686 | 687 | client.retrieve( 688 | time=0, 689 | stream="enfo", 690 | type="ep", 691 | step=[i for i in range(12, 361, 12)], 692 | levelist=850, 693 | param=[ 694 | "ptsa_gt_1stdev", 695 | "ptsa_gt_1p5stdev", 696 | "ptsa_gt_2stdev", 697 | "ptsa_lt_1stdev", 698 | "ptsa_lt_1p5stdev", 699 | "ptsa_lt_2stdev", 700 | ], 701 | target="data.grib2", 702 | ) 703 | ``` 704 | 705 | #### Probabilities - Daily weather events - Single level 706 | 707 | The probabilities of total precipitation and wind gusts exceeding specified thresholds in a 24 hour period are available for step ranges 0-24 to 336-360 by 12​​. These are specified in the retrieval request using, e.g.: `step=["0-24", "12-36", "24-48"]`. 708 | 709 | ```python 710 | from ecmwf.opendata import Client 711 | 712 | client = Client(source="ecmwf") 713 | 714 | steps = [f"{12 * i}-{ 12 * i + 24}" for i in range(29)] 715 | 716 | client.retrieve( 717 | time=0, 718 | stream="enfo", 719 | type="ep", 720 | step=steps, 721 | param=["tpg1", "tpg5", "10fgg10"], 722 | target="data.grib2", 723 | ) 724 | ``` 725 | 726 | ### ECMWF open data license 727 | 728 | By downloading data from the ECMWF open data dataset, you agree to the terms: Attribution 4.0 International (CC BY 4.0). If you do not agree with such terms, do not download the data. Visit [this page](https://apps.ecmwf.int/datasets/licences/general/) for more information. 729 | 730 | ### License 731 | 732 | [Apache License 2.0](LICENSE) In applying this licence, ECMWF does not waive the privileges and immunities 733 | granted to it by virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. 734 | -------------------------------------------------------------------------------- /ecmwf/opendata/__init__.py: -------------------------------------------------------------------------------- 1 | # (C) Copyright 2021 ECMWF. 2 | # 3 | # This software is licensed under the terms of the Apache Licence Version 2.0 4 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 5 | # In applying this licence, ECMWF does not waive the privileges and immunities 6 | # granted to it by virtue of its status as an intergovernmental organisation 7 | # nor does it submit to any jurisdiction. 8 | # 9 | 10 | 11 | from .client import Client 12 | 13 | __version__ = "0.3.23" 14 | 15 | __all__ = ["Client"] 16 | -------------------------------------------------------------------------------- /ecmwf/opendata/bufr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | 11 | """ 12 | For testing 13 | """ 14 | 15 | from eccodes import codes_bufr_new_from_file, codes_release 16 | 17 | 18 | def count_bufrs(path): 19 | count = 0 20 | with open(path, "rb") as f: 21 | while True: 22 | handle = codes_bufr_new_from_file(f, headers_only=True) 23 | if handle is None: 24 | return count 25 | count += 1 26 | codes_release(handle) 27 | -------------------------------------------------------------------------------- /ecmwf/opendata/client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | 11 | import datetime 12 | import itertools 13 | import json 14 | import logging 15 | import os 16 | from collections import defaultdict 17 | 18 | import requests 19 | from multiurl import download, robust 20 | 21 | from .date import ( 22 | canonical_time, 23 | end_step, 24 | expand_date, 25 | expand_list, 26 | expand_time, 27 | full_date, 28 | ) 29 | from .urls import URLS 30 | 31 | LOG = logging.getLogger(__name__) 32 | 33 | HOURLY_PATTERN = ( 34 | "{_url}/{_yyyymmdd}/{_H}z/{model}/{resol}/{_stream}/" 35 | "{_yyyymmddHHMMSS}-{step}h-{_stream}-{type}.{_extension}" 36 | ) 37 | 38 | MONTHLY_PATTERN = ( 39 | "{_url}/{_yyyymmdd}/{_H}z/{model}/{resol}/{_stream}/" 40 | "{_yyyymmddHHMMSS}-{fcmonth}m-{_stream}-{type}.{_extension}" 41 | ) 42 | 43 | PATTERNS = {"mmsa": MONTHLY_PATTERN} 44 | EXTENSIONS = {"tf": "bufr"} 45 | 46 | ONCE = set() 47 | 48 | _ATTRIBUTION_SHOWN = False # module-level guard to avoid spamming 49 | 50 | 51 | def _show_attribution_message(): 52 | global _ATTRIBUTION_SHOWN 53 | if not _ATTRIBUTION_SHOWN: 54 | print( 55 | "By downloading data from the ECMWF open data dataset, you agree to " 56 | "the terms: Attribution 4.0 International (CC BY 4.0). Please " 57 | "attribute ECMWF when downloading this data." 58 | ) 59 | _ATTRIBUTION_SHOWN = True 60 | 61 | 62 | def warning_once(*args, did_you_mean=None): 63 | if repr(args) in ONCE: 64 | return 65 | 66 | LOG.warning(*args) 67 | 68 | ONCE.add(repr(args)) 69 | 70 | if did_you_mean: 71 | (words, vocabulary) = did_you_mean 72 | 73 | def levenshtein(a, b): 74 | if len(a) == 0: 75 | return len(b) 76 | 77 | if len(b) == 0: 78 | return len(a) 79 | 80 | if a[0].lower() == b[0].lower(): 81 | return levenshtein(a[1:], b[1:]) 82 | 83 | return 1 + min( 84 | [ 85 | levenshtein(a[1:], b[1:]), 86 | levenshtein(a[1:], b), 87 | levenshtein(a, b[1:]), 88 | ] 89 | ) 90 | 91 | if not isinstance(words, (list, tuple)): 92 | words = [words] 93 | 94 | for word in words: 95 | distance, best = min((levenshtein(word, w), w) for w in vocabulary) 96 | if distance < min(len(word), len(best)): 97 | LOG.warning( 98 | "Did you mean %r instead of %r?", 99 | best, 100 | word, 101 | ) 102 | 103 | 104 | class Result: 105 | def __init__(self, urls, target, dates, for_urls, for_index): 106 | self.urls = urls 107 | self.target = target 108 | if len(dates) == 1: 109 | self.datetime = dates[0] 110 | else: 111 | self.datetime = dates 112 | self.for_urls = for_urls 113 | self.for_index = for_index 114 | 115 | 116 | class Client: 117 | def __init__( 118 | self, 119 | source="ecmwf", 120 | model="ifs", 121 | resol="0p25", 122 | beta=False, # to access experimental data 123 | preserve_request_order=False, 124 | infer_stream_keyword=True, 125 | debug=False, 126 | verify=True, 127 | ): 128 | self._url = None 129 | self.source = source 130 | self.model = model 131 | self.resol = resol 132 | self.beta = beta 133 | self.preserve_request_order = preserve_request_order 134 | self.infer_stream_keyword = infer_stream_keyword 135 | self.session = requests.Session() 136 | self.verify = verify 137 | 138 | if debug: 139 | logging.basicConfig(level=logging.DEBUG) 140 | 141 | @property 142 | def url(self): 143 | if self._url is None: 144 | if self.source.startswith("http://") or self.source.startswith("https://"): 145 | self._url = self.source 146 | else: 147 | if self.source not in URLS: 148 | warning_once( 149 | "Unknown source %r. Known sources are %r", 150 | self.source, 151 | list(URLS.keys()), 152 | did_you_mean=(self.source, list(URLS.keys())), 153 | ) 154 | raise ValueError("Unknown source %r" % (self.source,)) 155 | self._url = URLS[self.source] 156 | 157 | return self._url 158 | 159 | def retrieve(self, request=None, target=None, **kwargs): 160 | result = self._get_urls(request, target=target, use_index=True, **kwargs) 161 | result.size = download( 162 | result.urls, 163 | target=result.target, 164 | verify=self.verify, 165 | session=self.session, 166 | ) 167 | _show_attribution_message() 168 | return result 169 | 170 | def download(self, request=None, target=None, **kwargs): 171 | result = self._get_urls(request, target=target, use_index=False, **kwargs) 172 | result.size = download( 173 | result.urls, 174 | target=result.target, 175 | verify=self.verify, 176 | session=self.session, 177 | ) 178 | _show_attribution_message() 179 | return result 180 | 181 | def latest(self, request=None, **kwargs): 182 | if request is None: 183 | params = dict(**kwargs) 184 | else: 185 | params = dict(**request) 186 | 187 | if "time" not in params: 188 | delta = datetime.timedelta(hours=6) 189 | else: 190 | delta = datetime.timedelta(days=1) 191 | 192 | date = full_date(0, params.get("time", 18)) 193 | 194 | stop = date - datetime.timedelta(days=2) 195 | 196 | while date > stop: 197 | result = self._get_urls( 198 | request=None, 199 | use_index=False, 200 | date=date, 201 | **params, 202 | ) 203 | codes = [ 204 | robust(self.session.head)(url, verify=self.verify).status_code 205 | for url in result.urls 206 | ] 207 | if len(codes) > 0 and all(c == 200 for c in codes): 208 | return date 209 | date -= delta 210 | 211 | raise ValueError("Cannot establish latest date for %r" % (result.for_urls,)) 212 | 213 | def _get_urls(self, request=None, use_index=None, target=None, **kwargs): 214 | assert use_index in (True, False) 215 | if request is None: 216 | params = dict(**kwargs) 217 | else: 218 | params = dict(**request) 219 | 220 | if "date" not in params: 221 | params["date"] = self.latest(params) 222 | 223 | if target is None: 224 | target = params.pop("target", None) 225 | 226 | for_urls, for_index = self.prepare_request(params) 227 | 228 | for_urls["_url"] = [self.url] 229 | 230 | seen = set() 231 | data_urls = [] 232 | 233 | dates = set() 234 | 235 | for args in ( 236 | dict(zip(for_urls.keys(), x)) for x in itertools.product(*for_urls.values()) 237 | ): 238 | pattern = PATTERNS.get(args["stream"], HOURLY_PATTERN) 239 | date = full_date(args.pop("date", None), args.pop("time", None)) 240 | dates.add(date) 241 | args["_yyyymmdd"] = date.strftime("%Y%m%d") 242 | args["_H"] = date.strftime("%H") 243 | args["_yyyymmddHHMMSS"] = date.strftime("%Y%m%d%H%M%S") 244 | args["_extension"] = EXTENSIONS.get(args["type"], "grib2") 245 | args["_stream"] = self.patch_stream(args) 246 | 247 | if self.beta: 248 | # test data is put in an /experimental subdir after resol 249 | # it is not part of a mars request, so we inject it here 250 | args["resol"] += "/experimental" 251 | 252 | url = pattern.format(**args) 253 | 254 | if self.resol == "0p4-beta": 255 | url = url.replace("/ifs/", "/") 256 | 257 | if url not in seen: 258 | data_urls.append(url) 259 | seen.add(url) 260 | 261 | if for_index and use_index: 262 | data_urls = self.get_parts(data_urls, for_index) 263 | 264 | return Result( 265 | urls=data_urls, 266 | target=target, 267 | dates=sorted(dates), 268 | for_urls=for_urls, 269 | for_index=for_index, 270 | ) 271 | 272 | def get_parts(self, data_urls, for_index): 273 | count = len(for_index) 274 | result = [] 275 | line = None 276 | 277 | possible_values = defaultdict(set) 278 | 279 | for url in data_urls: 280 | base, _ = os.path.splitext(url) 281 | index_url = f"{base}.index" 282 | r = robust(self.session.get)(index_url, verify=self.verify) 283 | r.raise_for_status() 284 | 285 | parts = [] 286 | for line in r.iter_lines(): 287 | line = json.loads(line) 288 | matches = [] 289 | for i, (name, values) in enumerate(for_index.items()): 290 | idx = line.get(name) 291 | if idx is not None: 292 | possible_values[name].add(idx) 293 | if idx in values: 294 | if self.preserve_request_order: 295 | for j, v in enumerate(values): 296 | if v == idx: 297 | matches.append((i, j)) 298 | else: 299 | matches.append(line["_offset"]) 300 | 301 | if len(matches) == count: 302 | parts.append((tuple(matches), (line["_offset"], line["_length"]))) 303 | 304 | if parts: 305 | result.append((url, tuple(p[1] for p in sorted(parts)))) 306 | 307 | for name, values in for_index.items(): 308 | diff = set(values).difference(possible_values[name]) 309 | for d in diff: 310 | warning_once( 311 | "No index entries for %s=%s", 312 | name, 313 | d, 314 | did_you_mean=(d, possible_values[name]), 315 | ) 316 | 317 | if not result: 318 | raise ValueError("Cannot find index entries matching %r" % (for_index,)) 319 | 320 | return result 321 | 322 | def user_to_index(self, key, value, request, for_index): 323 | FOR_INDEX = { 324 | ("type", "ef"): ["cf", "pf"], 325 | } 326 | 327 | return FOR_INDEX.get((key, value), value) 328 | 329 | def user_to_url(self, key, value, request, for_urls, model): 330 | FOR_URL = { 331 | ("type", "cf"): "ef", 332 | ("type", "pf"): "ef", 333 | ("type", "em"): "ep", 334 | ("type", "es"): "ep", 335 | ("type", "fcmean"): "fc", 336 | ("stream", "mmsa"): "mmsf", 337 | } 338 | 339 | # If the model is aifs-ens, we need to map the type to pf/cf because aifs-ens does not currently use ef 340 | if model == "aifs-ens": 341 | FOR_URL[("type", "pf")] = "pf" 342 | FOR_URL[("type", "cf")] = "cf" 343 | 344 | if key == "step" and for_urls["type"] == ["ep"]: 345 | if end_step(value) <= 240: 346 | return "240" 347 | else: 348 | return "360" 349 | 350 | return FOR_URL.get((key, value), value) 351 | 352 | def prepare_request(self, request=None, **kwargs): 353 | if request is None: 354 | params = dict(**kwargs) 355 | else: 356 | params = dict(**request) 357 | 358 | # If model is in the retireve overwrite the client model 359 | # Warn user if client model does not match the model in retrieve 360 | if "model" in params: 361 | if self.model != params["model"]: 362 | warning_once( 363 | "Model %r does not match the client model %r, using model %r from retrieve", 364 | params["model"], 365 | self.model, 366 | params["model"], 367 | did_you_mean=(params["model"], self.model), 368 | ) 369 | model = params["model"] 370 | else: 371 | model = self.model 372 | 373 | if "class" in params: 374 | model = {"od": "ifs", "ai": "aifs-single", "aifs-ens": "aifs-ens"}[ 375 | params["class"] 376 | ] 377 | 378 | # Default stream for aifs-ens is enfo as this model only has ensemble forecasts 379 | if model == "aifs-ens": 380 | params["stream"] = "enfo" 381 | 382 | DEFAULTS_FC = dict( 383 | model=model, 384 | resol=self.resol, 385 | type="fc", 386 | stream="oper", 387 | step=0, 388 | fcmonth=1, 389 | ) 390 | 391 | DEFAULTS_EF = dict( 392 | model=model, 393 | resol=self.resol, 394 | type=["cf", "pf"], 395 | stream="enfo", 396 | step=0, 397 | fcmonth=1, 398 | ) 399 | 400 | DEFAULTS = { 401 | "enfo": DEFAULTS_EF, 402 | "waef": DEFAULTS_EF, 403 | } 404 | 405 | URL_COMPONENTS = ( 406 | "date", 407 | "time", 408 | "model", 409 | "resol", 410 | "stream", 411 | "type", # Must be before 'step' in that list 412 | "step", 413 | "fcmonth", 414 | ) 415 | 416 | INDEX_COMPONENTS = ( 417 | "param", 418 | "type", 419 | "step", 420 | "fcmonth", 421 | "number", 422 | "levelist", 423 | "levtype", 424 | ) 425 | 426 | CANONICAL = { 427 | "time": lambda x: str(canonical_time(x)), 428 | # "param": lambda x: str(x).lower(), 429 | # "type": lambda x: str(x).lower(), 430 | # "stream": lambda x: str(x).lower(), 431 | } 432 | 433 | EXPAND_LIST = { 434 | "date": expand_date, 435 | "time": expand_time, 436 | } 437 | 438 | OTHER_STEP = {"mmsa": "step"} 439 | 440 | POSPROCESSING = { 441 | "area", 442 | "grid", 443 | "rotation", 444 | "frame", 445 | "bitmap", 446 | "gaussian", 447 | "accuracy", 448 | "format", 449 | } 450 | 451 | POSSIBLE_VALUES = { 452 | "type": ["tf", "fc", "fcmean", "cf", "pf", "em", "ep", "es"], 453 | "stream": ["oper", "wave", "scda", "scwv", "enfo", "waef", "mmsa"], 454 | } 455 | 456 | defaults = DEFAULTS.get(params.get("stream"), DEFAULTS_FC) 457 | for key, value in defaults.items(): 458 | params.setdefault(key, value) 459 | 460 | params.pop("target", None) 461 | params.pop("class", None) 462 | 463 | params.pop(OTHER_STEP.get(params["stream"], "fcmonth"), None) 464 | 465 | postproc = POSPROCESSING.intersection(set(params.keys())) 466 | if postproc: 467 | warning_once("MARS post-processing keywords %r not supported", postproc) 468 | 469 | for_urls = defaultdict(list) 470 | for_index = defaultdict(list) 471 | ignored = set() 472 | 473 | def sorter(kv): 474 | a = kv[0] 475 | if a in URL_COMPONENTS: 476 | return URL_COMPONENTS.index(a) 477 | if a in INDEX_COMPONENTS: 478 | return INDEX_COMPONENTS.index(a) + len(URL_COMPONENTS) 479 | return len(URL_COMPONENTS) + len(INDEX_COMPONENTS) 480 | 481 | for k, v in sorted(params.items(), key=sorter): 482 | if isinstance(v, str): 483 | v = v.split("/") 484 | 485 | if not isinstance(v, (list, tuple)): 486 | v = [v] 487 | 488 | v = EXPAND_LIST.get(k, expand_list)(v) 489 | 490 | # Return canonical forms 491 | v = [CANONICAL.get(k, str)(x) for x in v] 492 | 493 | if k.startswith("_"): 494 | continue 495 | 496 | if k in POSSIBLE_VALUES: 497 | possible_values = POSSIBLE_VALUES[k] 498 | for value in v: 499 | if value not in possible_values: 500 | warning_once( 501 | "Unknown value %r for keyword %r", 502 | value, 503 | k, 504 | did_you_mean=(value, possible_values), 505 | ) 506 | 507 | if k in INDEX_COMPONENTS: 508 | for values in [self.user_to_index(k, x, params, for_index) for x in v]: 509 | if not isinstance(values, (list, tuple)): 510 | values = [values] 511 | for value in values: 512 | if value not in for_index[k]: 513 | for_index[k].append(value) 514 | 515 | if k in URL_COMPONENTS: 516 | for values in [ 517 | self.user_to_url(k, x, params, for_urls, model) for x in v 518 | ]: 519 | if not isinstance(values, (list, tuple)): 520 | values = [values] 521 | for value in values: 522 | if value not in for_urls[k]: 523 | for_urls[k].append(value) 524 | 525 | if ( 526 | k not in URL_COMPONENTS 527 | and k not in INDEX_COMPONENTS 528 | and k not in POSPROCESSING 529 | ): 530 | ignored.add(k) 531 | 532 | if ignored: 533 | warning_once( 534 | "The following keywords %r are ignored", 535 | ignored, 536 | did_you_mean=(list(ignored), URL_COMPONENTS + INDEX_COMPONENTS), 537 | ) 538 | 539 | if params.get("type") == "tf": 540 | for_index.clear() 541 | 542 | return (dict(**for_urls), dict(**for_index)) 543 | 544 | def patch_stream(self, args): 545 | URL_STREAM_MAPPING = { 546 | ("oper", "06"): "scda", 547 | ("oper", "18"): "scda", 548 | ("wave", "06"): "scwv", 549 | ("wave", "18"): "scwv", 550 | # 551 | ("oper", "ef"): "enfo", 552 | ("wave", "ef"): "waef", 553 | ("oper", "ep"): "enfo", 554 | ("wave", "ep"): "waef", 555 | ("scda", "ef"): "enfo", 556 | ("scwv", "ef"): "waef", 557 | ("scda", "ep"): "enfo", 558 | ("scwv", "ep"): "waef", 559 | } 560 | stream, time, type = args["stream"], args["_H"], args["type"] 561 | 562 | if not self.infer_stream_keyword or args["model"] == "aifs-single": 563 | return stream 564 | 565 | stream = URL_STREAM_MAPPING.get((stream, time), stream) 566 | stream = URL_STREAM_MAPPING.get((stream, type), stream) 567 | 568 | return stream 569 | -------------------------------------------------------------------------------- /ecmwf/opendata/date.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | import datetime 11 | import re 12 | 13 | VALID_DATE = re.compile(r"\d\d\d\d-\d\d-\d\d([T\s]\d\d:\d\d(:\d\d)?)?Z?") 14 | 15 | 16 | def end_step(p): 17 | if isinstance(p, str): 18 | return int(p.split("-")[-1]) 19 | return int(p) 20 | 21 | 22 | def canonical_time(time): 23 | if isinstance(time, datetime.time): 24 | assert datetime.time(time.hour) == time, time 25 | return time.hour 26 | time = int(time) 27 | if time >= 100: 28 | assert time % 100 == 0, time 29 | time //= 100 30 | return time 31 | 32 | 33 | def full_date(date, time=None): 34 | if isinstance(date, datetime.date) and not isinstance(date, datetime.datetime): 35 | date = datetime.datetime(date.year, date.month, date.day) 36 | 37 | if isinstance(date, int): 38 | if date <= 0: 39 | date = datetime.datetime.utcnow() + datetime.timedelta(days=date) 40 | date = datetime.datetime(date.year, date.month, date.day) 41 | else: 42 | date = datetime.datetime(date // 10000, date % 10000 // 100, date % 100) 43 | 44 | if isinstance(date, str): 45 | try: 46 | return full_date(int(date), time) 47 | except ValueError: 48 | pass 49 | 50 | if VALID_DATE.match(date): 51 | date = datetime.datetime.fromisoformat(date) 52 | 53 | if not isinstance(date, datetime.datetime): 54 | raise ValueError("Invalid date: {} ({})".format(date, type(date))) 55 | 56 | if time is not None: 57 | time = canonical_time(time) 58 | date = datetime.datetime(date.year, date.month, date.day, time, 0, 0) 59 | 60 | return date 61 | 62 | 63 | def _expandable(lst): 64 | if len(lst) not in (3, 5): 65 | return False 66 | 67 | if not isinstance(lst[1], str) or lst[1].lower() != "to": 68 | return False 69 | 70 | if len(lst) == 5 and (not isinstance(lst[3], str) or lst[3].lower() != "by"): 71 | return False 72 | 73 | return True 74 | 75 | 76 | def expand_list(lst): 77 | if not _expandable(lst): 78 | return lst 79 | 80 | start = int(lst[0]) 81 | end = int(lst[2]) 82 | by = 1 83 | 84 | if len(lst) == 5: 85 | by = int(lst[4]) 86 | 87 | assert start <= end and by > 0, (start, end, by) 88 | 89 | return list(range(start, end + by, by)) 90 | 91 | 92 | def expand_date(lst): 93 | if not _expandable(lst): 94 | return lst 95 | 96 | start = full_date(lst[0]) 97 | end = full_date(lst[2]) 98 | by = 1 99 | 100 | if len(lst) == 5: 101 | by = int(lst[4]) 102 | 103 | assert start <= end and by > 0, (start, end, by) 104 | 105 | result = [] 106 | by = datetime.timedelta(days=by) 107 | 108 | while start <= end: 109 | result.append(start.strftime("%Y%m%d")) 110 | start += by 111 | 112 | return result 113 | 114 | 115 | def expand_time(lst): 116 | if not _expandable(lst): 117 | return lst 118 | 119 | start = canonical_time(lst[0]) 120 | end = canonical_time(lst[2]) 121 | by = 6 122 | 123 | if len(lst) == 5: 124 | by = int(lst[4]) 125 | 126 | assert start <= end and by > 0, (start, end, by) 127 | 128 | return list(range(start, end + by, by)) 129 | -------------------------------------------------------------------------------- /ecmwf/opendata/grib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | 11 | """ 12 | For testing 13 | """ 14 | 15 | from eccodes import ( 16 | codes_get_long, 17 | codes_get_string, 18 | codes_grib_new_from_file, 19 | codes_keys_iterator_delete, 20 | codes_keys_iterator_get_name, 21 | codes_keys_iterator_new, 22 | codes_keys_iterator_next, 23 | codes_release, 24 | ) 25 | 26 | 27 | def grib_index(path): 28 | index = [] 29 | with open(path, "rb") as f: 30 | while True: 31 | handle = codes_grib_new_from_file(f, headers_only=True) 32 | if handle is None: 33 | return index 34 | try: 35 | keys = {} 36 | iter = codes_keys_iterator_new(handle, "mars") 37 | try: 38 | while codes_keys_iterator_next(iter): 39 | name = codes_keys_iterator_get_name(iter) 40 | if name.startswith("_"): 41 | continue 42 | value = codes_get_string(handle, name) 43 | keys[name] = value 44 | 45 | if "step" not in keys and "fcmonth" not in keys: 46 | if keys["stream"] in ("mmsa",): 47 | keys["fcmonth"] = str( 48 | (codes_get_long(handle, "endStep") + 48) // (24 * 30) 49 | ) 50 | 51 | finally: 52 | codes_keys_iterator_delete(iter) 53 | 54 | keys["param"] = codes_get_string(handle, "shortName") 55 | keys["_offset"] = codes_get_long(handle, "offset") 56 | keys["_length"] = codes_get_long(handle, "totalLength") 57 | 58 | index.append(keys) 59 | finally: 60 | codes_release(handle) 61 | 62 | 63 | def count_gribs(path): 64 | count = 0 65 | with open(path, "rb") as f: 66 | while True: 67 | handle = codes_grib_new_from_file(f, headers_only=True) 68 | if handle is None: 69 | return count 70 | count += 1 71 | codes_release(handle) 72 | -------------------------------------------------------------------------------- /ecmwf/opendata/urls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | 11 | import json 12 | import os 13 | 14 | DOT_ECMWF_OPENDATA = os.path.expanduser("~/.ecmwf-opendata") 15 | 16 | URLS = { 17 | "ecmwf": "https://data.ecmwf.int/forecasts", 18 | "azure": "https://ai4edataeuwest.blob.core.windows.net/ecmwf", 19 | "aws": "https://ecmwf-forecasts.s3.eu-central-1.amazonaws.com", 20 | "ecmwf-esuites": "https://xdiss.ecmwf.int/ecpds/home/opendata", 21 | } 22 | 23 | if os.path.exists(DOT_ECMWF_OPENDATA): 24 | with open(DOT_ECMWF_OPENDATA) as f: 25 | URLS.update(json.load(f)) 26 | 27 | if "ECMWF_OPENDATA_URLS" in os.environ: 28 | URLS.update(json.loads(os.environ["ECMWF_OPENDATA_URLS"])) 29 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts=-s --verbose 3 | testpaths = tests 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # (C) Copyright 2021 ECMWF. 3 | # 4 | # This software is licensed under the terms of the Apache Licence Version 2.0 5 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 6 | # In applying this licence, ECMWF does not waive the privileges and immunities 7 | # granted to it by virtue of its status as an intergovernmental organisation 8 | # nor does it submit to any jurisdiction. 9 | # 10 | 11 | 12 | import io 13 | import os 14 | 15 | import setuptools 16 | 17 | 18 | def read(fname): 19 | file_path = os.path.join(os.path.dirname(__file__), fname) 20 | return io.open(file_path, encoding="utf-8").read() 21 | 22 | 23 | version = None 24 | for line in read("ecmwf/opendata/__init__.py").split("\n"): 25 | if line.startswith("__version__"): 26 | version = line.split("=")[-1].strip()[1:-1] 27 | 28 | 29 | assert version 30 | 31 | 32 | setuptools.setup( 33 | name="ecmwf-opendata", 34 | version=version, 35 | description="A package to download ECMWF open data", 36 | long_description=read("README.md"), 37 | long_description_content_type="text/markdown", 38 | author="European Centre for Medium-Range Weather Forecasts (ECMWF)", 39 | author_email="software.support@ecmwf.int", 40 | license="Apache License Version 2.0", 41 | url="https://github.com/ecmwf/ecmwf-opendata", 42 | packages=setuptools.find_namespace_packages(include=["ecmwf.*"]), 43 | include_package_data=True, 44 | install_requires=["multiurl>=0.2.1"], 45 | zip_safe=True, 46 | keywords="tool", 47 | classifiers=[ 48 | "Development Status :: 3 - Alpha", 49 | "Intended Audience :: Developers", 50 | "License :: OSI Approved :: Apache Software License", 51 | "Programming Language :: Python :: 3", 52 | "Programming Language :: Python :: 3.7", 53 | "Programming Language :: Python :: 3.8", 54 | "Programming Language :: Python :: 3.9", 55 | "Programming Language :: Python :: 3.10", 56 | "Programming Language :: Python :: Implementation :: CPython", 57 | "Programming Language :: Python :: Implementation :: PyPy", 58 | "Operating System :: OS Independent", 59 | ], 60 | ) 61 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | freezegun 2 | ecmwflibs 3 | eccodes 4 | -------------------------------------------------------------------------------- /tests/test_aifs_ens.py: -------------------------------------------------------------------------------- 1 | from ecmwf.opendata import Client 2 | from ecmwf.opendata.grib import count_gribs 3 | 4 | 5 | def test_aifs_ens_1(): 6 | client = Client(source="ecmwf", model="aifs-ens") 7 | client.retrieve( 8 | date=-1, 9 | time=0, 10 | step=12, 11 | param="10u", 12 | target="data.grib", 13 | ) 14 | 15 | assert count_gribs("data.grib") == 51 16 | 17 | 18 | def test_aifs_ens_2(): 19 | client = Client(source="ecmwf", model="aifs-ens") 20 | client.retrieve( 21 | date=-1, 22 | time=0, 23 | step=12, 24 | type="cf", 25 | param="10u", 26 | target="data.grib", 27 | ) 28 | 29 | assert count_gribs("data.grib") == 1 30 | 31 | 32 | def test_aifs_ens_3(): 33 | client = Client(source="ecmwf", model="aifs-ens") 34 | client.retrieve( 35 | date=-1, 36 | time=0, 37 | step=12, 38 | type="pf", 39 | param="10u", 40 | target="data.grib", 41 | ) 42 | 43 | assert count_gribs("data.grib") == 50 44 | -------------------------------------------------------------------------------- /tests/test_date.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from freezegun import freeze_time 4 | 5 | from ecmwf.opendata.date import canonical_time, end_step, full_date 6 | 7 | 8 | @freeze_time("2022-01-21T13:21:34Z") 9 | def test_date_1(): 10 | assert full_date("20010101") == datetime.datetime(2001, 1, 1) 11 | assert full_date(20010101) == datetime.datetime(2001, 1, 1) 12 | assert full_date("2001-01-01") == datetime.datetime(2001, 1, 1) 13 | 14 | assert full_date(0) == datetime.datetime(2022, 1, 21) 15 | assert full_date(-10) == datetime.datetime(2022, 1, 11) 16 | 17 | assert full_date("20010101", 0) == datetime.datetime(2001, 1, 1) 18 | assert full_date(20010101, 0) == datetime.datetime(2001, 1, 1) 19 | assert full_date("2001-01-01", 0) == datetime.datetime(2001, 1, 1) 20 | 21 | assert full_date(0, 0) == datetime.datetime(2022, 1, 21) 22 | assert full_date(-10, 0) == datetime.datetime(2022, 1, 11) 23 | 24 | assert full_date("20010101", 12) == datetime.datetime(2001, 1, 1, 12) 25 | assert full_date(20010101, 12) == datetime.datetime(2001, 1, 1, 12) 26 | assert full_date("2001-01-01", 12) == datetime.datetime(2001, 1, 1, 12) 27 | 28 | assert full_date(0, 12) == datetime.datetime(2022, 1, 21, 12) 29 | assert full_date(-10, 12) == datetime.datetime(2022, 1, 11, 12) 30 | 31 | assert full_date("20010101", "18") == datetime.datetime(2001, 1, 1, 18) 32 | assert full_date(20010101, "18") == datetime.datetime(2001, 1, 1, 18) 33 | assert full_date("2001-01-01", "18") == datetime.datetime(2001, 1, 1, 18) 34 | 35 | assert full_date(0, "18") == datetime.datetime(2022, 1, 21, 18) 36 | assert full_date(-10, "18") == datetime.datetime(2022, 1, 11, 18) 37 | 38 | assert full_date("20010101", "06") == datetime.datetime(2001, 1, 1, 6) 39 | assert full_date(20010101, "06") == datetime.datetime(2001, 1, 1, 6) 40 | assert full_date("2001-01-01", "06") == datetime.datetime(2001, 1, 1, 6) 41 | 42 | assert full_date(0, "06") == datetime.datetime(2022, 1, 21, 6) 43 | assert full_date(-10, "06") == datetime.datetime(2022, 1, 11, 6) 44 | 45 | assert full_date("20010101", "0600") == datetime.datetime(2001, 1, 1, 6) 46 | assert full_date(20010101, "0600") == datetime.datetime(2001, 1, 1, 6) 47 | assert full_date("2001-01-01", "0600") == datetime.datetime(2001, 1, 1, 6) 48 | 49 | assert full_date(0, "0600") == datetime.datetime(2022, 1, 21, 6) 50 | assert full_date(-10, "0600") == datetime.datetime(2022, 1, 11, 6) 51 | 52 | assert full_date("20010101", "1200") == datetime.datetime(2001, 1, 1, 12) 53 | assert full_date(20010101, "1200") == datetime.datetime(2001, 1, 1, 12) 54 | assert full_date("2001-01-01", "1200") == datetime.datetime(2001, 1, 1, 12) 55 | 56 | assert full_date(0, "1200") == datetime.datetime(2022, 1, 21, 12) 57 | assert full_date(-10, "1200") == datetime.datetime(2022, 1, 11, 12) 58 | 59 | assert full_date("20010101", "18") == datetime.datetime(2001, 1, 1, 18) 60 | assert full_date(20010101, "18") == datetime.datetime(2001, 1, 1, 18) 61 | assert full_date("2001-01-01", "18") == datetime.datetime(2001, 1, 1, 18) 62 | 63 | assert full_date(0, "18") == datetime.datetime(2022, 1, 21, 18) 64 | assert full_date(-10, "18") == datetime.datetime(2022, 1, 11, 18) 65 | 66 | assert full_date("2022-01-25 12:00:00") == datetime.datetime(2022, 1, 25, 12) 67 | assert full_date("2022-01-25 12:00:00", "18") == datetime.datetime(2022, 1, 25, 18) 68 | assert full_date("2022-01-25T12:00:00") == datetime.datetime(2022, 1, 25, 12) 69 | 70 | 71 | def test_date_2(): 72 | assert full_date(datetime.datetime(2000, 1, 1, 6)) == datetime.datetime( 73 | 2000, 1, 1, 6 74 | ) 75 | assert full_date(datetime.datetime(2000, 1, 1, 6), 12) == datetime.datetime( 76 | 2000, 1, 1, 12 77 | ) 78 | assert full_date(datetime.date(2000, 1, 1)) == datetime.datetime(2000, 1, 1) 79 | assert full_date(datetime.date(2000, 1, 1), 12) == datetime.datetime(2000, 1, 1, 12) 80 | 81 | 82 | def test_time(): 83 | assert canonical_time(0) == 0 84 | assert canonical_time(6) == 6 85 | assert canonical_time(12) == 12 86 | assert canonical_time(18) == 18 87 | 88 | assert canonical_time("0") == 0 89 | assert canonical_time("6") == 6 90 | assert canonical_time("12") == 12 91 | assert canonical_time("18") == 18 92 | 93 | assert canonical_time("00") == 0 94 | assert canonical_time("06") == 6 95 | assert canonical_time("12") == 12 96 | assert canonical_time("18") == 18 97 | 98 | assert canonical_time(1200) == 12 99 | assert canonical_time(1800) == 18 100 | 101 | assert canonical_time("0000") == 0 102 | assert canonical_time("0600") == 6 103 | assert canonical_time("1200") == 12 104 | assert canonical_time("1800") == 18 105 | 106 | assert canonical_time(datetime.time(12)) == 12 107 | 108 | 109 | def test_step(): 110 | assert end_step(24) == 24 111 | assert end_step("24") == 24 112 | assert end_step("12-24") == 24 113 | -------------------------------------------------------------------------------- /tests/test_examples.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | import pytest 5 | 6 | README = os.path.realpath( 7 | os.path.join(os.path.dirname(os.path.dirname(__file__)), "README.md") 8 | ) 9 | 10 | 11 | def example_list(): 12 | examples = [] 13 | code = [] 14 | python = False 15 | 16 | with open(README, "rt", encoding="utf-8") as f: 17 | for line in f: 18 | if line.startswith("```python"): 19 | python = True 20 | continue 21 | if python and line.startswith("```"): 22 | if any("from ecmwf.opendata import Client" in c for c in code): 23 | examples.append(code) 24 | python = False 25 | code = [] 26 | continue 27 | if python: 28 | code.append(line) 29 | 30 | return sorted(examples) 31 | 32 | 33 | @pytest.mark.parametrize("example", example_list()) 34 | def xxx_test_example(example): 35 | code = "".join(example) 36 | try: 37 | exec(code, dict(__file__=README), {}) 38 | except Exception as e: 39 | print("===========", file=sys.stderr) 40 | print(code, file=sys.stderr) 41 | print("===========", file=sys.stderr) 42 | raise ValueError("Exception: %s\n%s" % (e, code)) 43 | 44 | 45 | if __name__ == "__main__": 46 | for e in example_list(): 47 | try: 48 | xxx_test_example(e) 49 | except Exception: 50 | pass 51 | -------------------------------------------------------------------------------- /tests/test_latest.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from freezegun import freeze_time 4 | 5 | from ecmwf.opendata import Client 6 | 7 | TEST_URL = "https://get.ecmwf.int/repository/ecmwf-opendata/testing" 8 | 9 | 10 | @freeze_time("2022-01-21t13:21:34Z") 11 | def test_utc(): 12 | assert datetime.datetime.utcnow() == datetime.datetime(2022, 1, 21, 13, 21, 34) 13 | 14 | 15 | @freeze_time("2022-01-21T13:21:34Z") 16 | def test_latest_00(): 17 | client = Client(TEST_URL) 18 | date = client.latest( 19 | time=0, 20 | step=48, 21 | stream="oper", 22 | type="fc", 23 | levtype="sfc", 24 | param="2t", 25 | target="data.grib", 26 | ) 27 | 28 | assert date == datetime.datetime(2022, 1, 20) 29 | 30 | 31 | @freeze_time("2022-01-21T13:21:34Z") 32 | def test_latest_06(): 33 | client = Client(TEST_URL) 34 | date = client.latest( 35 | time=6, 36 | step=48, 37 | type="fc", 38 | levtype="sfc", 39 | param="2t", 40 | target="data.grib", 41 | ) 42 | 43 | assert date == datetime.datetime(2022, 1, 20, 6) 44 | 45 | 46 | @freeze_time("2022-01-21T13:21:34Z") 47 | def test_latest_12(): 48 | client = Client(TEST_URL) 49 | date = client.latest( 50 | time=12, 51 | step=48, 52 | type="fc", 53 | levtype="sfc", 54 | param="2t", 55 | target="data.grib", 56 | ) 57 | 58 | assert date == datetime.datetime(2022, 1, 20, 12) 59 | 60 | 61 | @freeze_time("2022-01-20T13:21:34Z") 62 | def test_latest_18(): 63 | client = Client(TEST_URL) 64 | date = client.latest( 65 | time=18, 66 | step=48, 67 | type="fc", 68 | levtype="sfc", 69 | param="2t", 70 | target="data.grib", 71 | ) 72 | 73 | assert date == datetime.datetime(2022, 1, 19, 18) 74 | -------------------------------------------------------------------------------- /tests/test_opendata.py: -------------------------------------------------------------------------------- 1 | from freezegun import freeze_time 2 | 3 | from ecmwf.opendata import Client 4 | from ecmwf.opendata.bufr import count_bufrs 5 | from ecmwf.opendata.grib import count_gribs 6 | 7 | TEST_URL = "https://get.ecmwf.int/repository/ecmwf-opendata/testing" 8 | 9 | """ 10 | format=bufr, type=tf 11 | HH=00/12 12 | stream=enfo/oper, step=240h 13 | HH=06/18 14 | stream=enfo, step=144h 15 | stream=scda, step=90h 16 | 17 | format=grib2 18 | HH=00/12 19 | stream=enfo/waef 20 | type=ef, step=0h to 144h by 3h, 144h to 360h by 6h 21 | type=ep, step=240h/360h 22 | stream=oper, wave 23 | type=fc, step=0h to 144h by 3h, 144h to 360h by 6h 24 | HH=06/18 25 | stream=enfo/waef 26 | type=ef, step=0h to 144h by 3h 27 | stream= scda /scwv 28 | type=fc, step=0h to 90h by 3h 29 | HH=00 30 | stream=mmsf, type=fc, u=m, step=1m to 7m 31 | """ 32 | 33 | 34 | @freeze_time("2022-01-21t13:21:34z") 35 | def xxx_test_opendata_1(): 36 | client = Client(TEST_URL) 37 | client.retrieve( 38 | time=0, 39 | step=240, 40 | stream="oper", 41 | type="tf", 42 | levtype="sfc", 43 | param="tpg100", 44 | target="data.bufr", 45 | ) 46 | 47 | assert count_bufrs("data.bufr") > 0 48 | 49 | 50 | @freeze_time("2022-01-21t13:21:34z") 51 | def test_opendata_2(): 52 | client = Client(TEST_URL) 53 | client.retrieve( 54 | date=-1, 55 | time=0, 56 | step=12, 57 | stream="enfo", 58 | type="ef", 59 | levtype="sfc", 60 | param="10u", 61 | target="data.grib", 62 | ) 63 | 64 | assert count_gribs("data.grib") == 51 65 | 66 | 67 | @freeze_time("2022-01-21t13:21:34z") 68 | def test_opendata_3(): 69 | client = Client(TEST_URL) 70 | client.retrieve( 71 | date=-1, 72 | time=0, 73 | step=12, 74 | stream="enfo", 75 | type="cf", 76 | levtype="sfc", 77 | param="10u", 78 | target="data.grib", 79 | ) 80 | 81 | assert count_gribs("data.grib") == 1 82 | 83 | 84 | @freeze_time("2022-01-21t13:21:34z") 85 | def test_opendata_4(): 86 | client = Client(TEST_URL) 87 | client.retrieve( 88 | date=-1, 89 | time=0, 90 | step=12, 91 | stream="enfo", 92 | type="pf", 93 | levtype="sfc", 94 | param="10u", 95 | target="data.grib", 96 | ) 97 | 98 | assert count_gribs("data.grib") == 50 99 | 100 | 101 | @freeze_time("2022-01-21t13:21:34z") 102 | def xx_test_opendata_6(): 103 | client = Client(TEST_URL) 104 | client.retrieve( 105 | date=-1, 106 | time=0, 107 | type="tf", 108 | stream="enfo", 109 | step=240, 110 | target="data.bufr", 111 | ) 112 | 113 | with open("data.bufr", "rb") as f: 114 | assert f.read(4) == b"BUFR" 115 | -------------------------------------------------------------------------------- /tests/test_request.py: -------------------------------------------------------------------------------- 1 | from ecmwf.opendata import Client 2 | 3 | 4 | def test_request(): 5 | client = Client(preserve_request_order=True) 6 | 7 | for_urls, _ = client.prepare_request(step="0/to/120") 8 | 9 | assert for_urls["step"] == [str(s) for s in range(0, 121)] 10 | 11 | for_urls, _ = client.prepare_request(step="0/to/120/by/6") 12 | 13 | assert for_urls["step"] == [str(s) for s in range(0, 121, 6)] 14 | 15 | for_urls, _ = client.prepare_request(time="0/to/18") 16 | 17 | assert for_urls["time"] == [str(s) for s in range(0, 24, 6)] 18 | 19 | for_urls, _ = client.prepare_request(date="20000101/to/20000131") 20 | 21 | assert for_urls["date"] == [str(s) for s in range(20000101, 20000132)] 22 | 23 | for_urls, _ = client.prepare_request(date="20000101/to/20000131/by/7") 24 | 25 | assert for_urls["date"] == [str(s) for s in range(20000101, 20000132, 7)] 26 | 27 | 28 | if __name__ == "__main__": 29 | test_request() 30 | -------------------------------------------------------------------------------- /tests/test_sources.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pytest 4 | 5 | from ecmwf.opendata import Client 6 | from ecmwf.opendata.bufr import count_bufrs 7 | from ecmwf.opendata.grib import count_gribs 8 | 9 | SOURCES = os.getenv("SOURCES_TO_TEST", "ecmwf,azure,aws").split(",") 10 | 11 | 12 | @pytest.mark.parametrize("source", SOURCES) 13 | def test_sources_1(source): 14 | client = Client(source) 15 | 16 | client.retrieve( 17 | time=0, 18 | stream="oper", 19 | type="fc", 20 | step=24, 21 | param="2t", 22 | target="data.grib", 23 | ) 24 | 25 | assert count_gribs("data.grib") == 1 26 | 27 | 28 | @pytest.mark.parametrize("source", SOURCES) 29 | def xxx_test_sources_2(source): 30 | client = Client(source) 31 | client.retrieve( 32 | time=0, 33 | stream="oper", 34 | type="tf", 35 | step=240, 36 | target="data.bufr", 37 | ) 38 | 39 | assert count_gribs("data.grib") == 51 40 | 41 | 42 | @pytest.mark.parametrize("source", SOURCES) 43 | def test_sources_3(source): 44 | client = Client(source) 45 | client.retrieve( 46 | time=0, 47 | stream="enfo", 48 | type="pf", 49 | param="msl", 50 | target="data.grib", 51 | ) 52 | 53 | assert count_gribs("data.grib") == 50 54 | 55 | 56 | @pytest.mark.parametrize("source", SOURCES) 57 | def xxx_test_sources_4(source): 58 | client = Client(source) 59 | client.retrieve( 60 | time=0, 61 | stream="enfo", 62 | type="tf", 63 | step=240, 64 | target="data.bufr", 65 | ) 66 | 67 | assert count_bufrs("data.bufr") > 0 68 | 69 | 70 | @pytest.mark.parametrize("source", SOURCES) 71 | def test_sources_6(source): 72 | client = Client(source) 73 | client.retrieve( 74 | time=0, 75 | stream="enfo", 76 | type=["es", "em"], 77 | step=24, 78 | target="data.grib", 79 | ) 80 | assert count_gribs("data.grib") == 18 81 | -------------------------------------------------------------------------------- /tests/test_stream.py: -------------------------------------------------------------------------------- 1 | from ecmwf.opendata import Client 2 | 3 | 4 | def patch_stream(stream, time, type): 5 | client = Client(infer_stream_keyword=True) 6 | args = {"stream": stream, "_H": "%02d" % (time,), "type": type, "model": "ifs"} 7 | return client.patch_stream(args) 8 | 9 | 10 | def test_stream(): 11 | assert patch_stream("oper", 0, "fc") == "oper" 12 | assert patch_stream("oper", 6, "fc") == "scda" 13 | assert patch_stream("oper", 12, "fc") == "oper" 14 | assert patch_stream("oper", 18, "fc") == "scda" 15 | 16 | assert patch_stream("wave", 0, "fc") == "wave" 17 | assert patch_stream("wave", 6, "fc") == "scwv" 18 | assert patch_stream("wave", 12, "fc") == "wave" 19 | assert patch_stream("wave", 18, "fc") == "scwv" 20 | 21 | assert patch_stream("oper", 0, "ef") == "enfo" 22 | assert patch_stream("oper", 6, "ef") == "enfo" 23 | assert patch_stream("oper", 12, "ef") == "enfo" 24 | assert patch_stream("oper", 18, "ef") == "enfo" 25 | 26 | assert patch_stream("wave", 0, "ef") == "waef" 27 | assert patch_stream("wave", 6, "ef") == "waef" 28 | assert patch_stream("wave", 12, "ef") == "waef" 29 | assert patch_stream("wave", 18, "ef") == "waef" 30 | 31 | assert patch_stream("oper", 0, "ep") == "enfo" 32 | assert patch_stream("oper", 6, "ep") == "enfo" 33 | assert patch_stream("oper", 12, "ep") == "enfo" 34 | assert patch_stream("oper", 18, "ep") == "enfo" 35 | 36 | assert patch_stream("wave", 0, "ep") == "waef" 37 | assert patch_stream("wave", 6, "ep") == "waef" 38 | assert patch_stream("wave", 12, "ep") == "waef" 39 | assert patch_stream("wave", 18, "ep") == "waef" 40 | 41 | 42 | if __name__ == "__main__": 43 | test_stream() 44 | -------------------------------------------------------------------------------- /tools/.gitignore: -------------------------------------------------------------------------------- 1 | index.txt 2 | done.txt 3 | index.txt 4 | -------------------------------------------------------------------------------- /tools/README: -------------------------------------------------------------------------------- 1 | ./crawl.py > index.txt 2 | -------------------------------------------------------------------------------- /tools/check-index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import json 3 | 4 | import requests 5 | 6 | seen = {} 7 | x = {} 8 | c = [] 9 | OK = { 10 | ("enfo", "cf"): "ef", 11 | ("enfo", "pf"): "ef", 12 | ("waef", "cf"): "ef", 13 | ("waef", "pf"): "ef", 14 | ("enfo", "es"): "ep", 15 | ("enfo", "em"): "ep", 16 | ("enfo", "es", True): "240", 17 | ("waef", "es", True): "240", 18 | ("enfo", "em", True): "240", 19 | ("waef", "em", True): "240", 20 | ("enfo", "ep", True): "240", 21 | ("waef", "ep", True): "240", 22 | ("enfo", "es", False): "360", 23 | ("waef", "es", False): "360", 24 | ("enfo", "em", False): "360", 25 | ("waef", "em", False): "360", 26 | ("enfo", "ep", False): "360", 27 | ("waef", "ep", False): "360", 28 | "mmsa": "mmsf", 29 | ("mmsa", "fcmean"): "fc", 30 | } 31 | with open("index.txt") as f: 32 | for url in f: 33 | if "mmsf" in url: 34 | continue 35 | r = requests.get(url.strip()) 36 | r.raise_for_status() 37 | 38 | line = url.strip().split("/") 39 | 40 | line = line[7:] 41 | date = line[0] 42 | time = line[1][:-1] + "00" 43 | 44 | stream = line[3] 45 | line = line[4].split("-") 46 | assert line[0] == f"{date}{time}00" 47 | if line[1][-1] == "m": 48 | fcmonth = line[1][:-1] 49 | step = None 50 | else: 51 | step = line[1][:-1] 52 | fcmonth = None 53 | assert line[2] == stream 54 | type = line[-1].split(".")[0] 55 | 56 | print(url.strip()) 57 | for p in r.text.splitlines(): 58 | r = json.loads(p) 59 | ok = True 60 | ok = ok and r.get("date") == date 61 | ok = ok and r.get("time") == time 62 | 63 | rstep = r.get("step", "0").split("-")[-1] 64 | rstep = OK.get( 65 | (r.get("stream"), r.get("type"), int(rstep) <= 240), 66 | r.get("step"), 67 | ) 68 | 69 | ok = ok and rstep == step 70 | ok = ok and r.get("fcmonth") == fcmonth 71 | 72 | rstream = OK.get(r.get("stream"), r.get("stream")) 73 | ok = ok and rstream == stream 74 | 75 | rtype = OK.get((r.get("stream"), r.get("type")), r.get("type")) 76 | ok = ok and rtype == type 77 | 78 | if not ok: 79 | print(url.strip()) 80 | print("Mismatch:", r) 81 | 82 | for a, b, c in ( 83 | ("date", r.get("date"), date), 84 | ("time", r.get("time"), time), 85 | ("step", rstep, step), 86 | ("fcmonth", r.get("fcmonth"), fcmonth), 87 | ("stream", rstream, stream), 88 | ("type", rtype, type), 89 | ): 90 | if b != c: 91 | print("Mismatch: %r %r %r" % (a, b, c)) 92 | # assert False 93 | -------------------------------------------------------------------------------- /tools/crawl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from urllib.parse import urlparse 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | 7 | from ecmwf.opendata import Client 8 | 9 | url = urlparse(Client().url) 10 | top = url.scheme + "://" + url.netloc 11 | 12 | 13 | def crawl(url): 14 | print(f"{top}{url}") 15 | r = requests.get(f"{top}{url}") 16 | r.raise_for_status() 17 | soup = BeautifulSoup(r.text, "html.parser") 18 | for link in soup.find_all("a"): 19 | href = link.get("href") 20 | if href is not None and not url.startswith(href): 21 | if href.startswith("javascript:"): 22 | continue 23 | if href.endswith("/"): 24 | crawl(href) 25 | else: 26 | if href.endswith(".index"): 27 | print(f"{top}{href}") 28 | 29 | 30 | crawl(url.path + ("" if url.path.endswith("/") else "/")) 31 | -------------------------------------------------------------------------------- /tools/get-all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import random 4 | import traceback 5 | 6 | import eccodes 7 | import requests 8 | 9 | from ecmwf.opendata import Client 10 | 11 | client = Client() 12 | 13 | done = set() 14 | 15 | with open("done.txt") as f: 16 | for url in f: 17 | url = url.rstrip() 18 | done.add(url) 19 | 20 | ok = open("done.txt", "a") 21 | fail = open("fail.txt", "a") 22 | 23 | with open("index.txt") as f: 24 | for url in f: 25 | url = url.rstrip() 26 | if url in done: 27 | print(url, "DONE") 28 | continue 29 | print(url) 30 | # if "mmsf" in url: 31 | # continue 32 | r = requests.get(url) 33 | r.raise_for_status() 34 | 35 | try: 36 | lines = [] 37 | for line in r.text.splitlines(): 38 | line = json.loads(line) 39 | lines.append(line) 40 | 41 | random.shuffle(lines) 42 | 43 | for i, line in enumerate(lines): 44 | if i > 20: 45 | break 46 | line["target"] = "data" 47 | client.retrieve(line) 48 | with open("data", "rb") as g: 49 | h = eccodes.codes_new_from_file(g, eccodes.CODES_PRODUCT_GRIB) 50 | try: 51 | for k, v in line.items(): 52 | if k in ["target", "_length", "_offset"]: 53 | continue 54 | 55 | if k == "param": 56 | k = "shortName" 57 | w = eccodes.codes_get_string(h, k) 58 | assert v == w, (v, w) 59 | finally: 60 | eccodes.codes_release(h) 61 | 62 | print(url, file=ok) 63 | except Exception as e: 64 | print(traceback.format_exc()) 65 | print(url, e, file=fail) 66 | -------------------------------------------------------------------------------- /tools/param-units.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import sys 4 | from collections import defaultdict 5 | 6 | import eccodes 7 | import requests 8 | 9 | from ecmwf.opendata import Client 10 | 11 | client = Client() 12 | 13 | GROUPS = { 14 | ("oper", "fc", "pl"): "01 Atmospheric fields on pressure levels", 15 | ("scda", "fc", "pl"): "01 Atmospheric fields on pressure levels", 16 | ("enfo", "cf", "pl"): "01 Atmospheric fields on pressure levels", 17 | ("enfo", "pf", "pl"): "01 Atmospheric fields on pressure levels", 18 | ("oper", "fc", "sfc"): "02 Atmospheric fields on a single level", 19 | ("scda", "fc", "sfc"): "02 Atmospheric fields on a single level", 20 | ("enfo", "cf", "sfc"): "02 Atmospheric fields on a single level", 21 | ("enfo", "pf", "sfc"): "02 Atmospheric fields on a single level", 22 | ("wave", "fc", "sfc"): "03 Ocean waves fields", 23 | ("waef", "cf", "sfc"): "03 Ocean waves fields", 24 | ("waef", "pf", "sfc"): "03 Ocean waves fields", 25 | ("scwv", "fc", "sfc"): "03 Ocean waves fields", 26 | ("enfo", "em", "pl"): "04 Ensemble mean and standard deviation - pressure levels", 27 | ("enfo", "es", "pl"): "04 Ensemble mean and standard deviation - pressure levels", 28 | ("enfo", "em", "sfc"): "05 Ensemble mean and standard deviation - single level", 29 | ("enfo", "es", "sfc"): "05 Ensemble mean and standard deviation - single level", 30 | ( 31 | "enfo", 32 | "ep", 33 | "pl", 34 | ): "07 Instantaneous weather events - atmospheric fields - 850 hPa", 35 | ( 36 | "enfo", 37 | "ep", 38 | "sfc", 39 | ): "08 Daily weather events - atmospheric fields - single level", 40 | ("waef", "ep", "sfc"): "10 Instantaneous weather events - ocean waves fields", 41 | } 42 | 43 | groups = defaultdict(set) 44 | seen = set() 45 | 46 | with open("index.txt") as f: 47 | for j, url in enumerate(f): 48 | url = url.rstrip() 49 | 50 | if ( 51 | "240h" not in url 52 | and "360h" not in url 53 | and "90h" not in url 54 | and "1m" not in url 55 | ): 56 | continue 57 | 58 | print(url, file=sys.stderr) 59 | 60 | r = requests.get(url) 61 | r.raise_for_status() 62 | 63 | lines = [] 64 | for line in r.text.splitlines(): 65 | line = json.loads(line) 66 | lines.append(line) 67 | 68 | for i, line in enumerate(lines): 69 | key = tuple(line.get(x) for x in ("type", "stream", "levtype", "param")) 70 | if key in seen: 71 | continue 72 | 73 | seen.add(key) 74 | 75 | line["target"] = "data" 76 | print(line, file=sys.stderr) 77 | client.retrieve(line) 78 | with open("data", "rb") as g: 79 | h = eccodes.codes_new_from_file(g, eccodes.CODES_PRODUCT_GRIB) 80 | try: 81 | key = ( 82 | eccodes.codes_get_string(h, "stream"), 83 | eccodes.codes_get_string(h, "type"), 84 | eccodes.codes_get_string(h, "levtype"), 85 | ) 86 | groups[GROUPS[key]].add( 87 | ( 88 | eccodes.codes_get_string(h, "shortName"), 89 | eccodes.codes_get_string(h, "nameECMF").replace( 90 | "Geopotential Height", "Geopotential height" 91 | ), 92 | eccodes.codes_get_string(h, "units") 93 | .replace("**-1", "-1") 94 | .replace("**-2", "-2"), 95 | ) 96 | ) 97 | finally: 98 | eccodes.codes_release(h) 99 | 100 | 101 | x = {} 102 | 103 | for k, v in sorted(groups.items()): 104 | print() 105 | print(">", k[3:]) 106 | print() 107 | x = " | ".join(["Parameter", "Description", "Units"]) 108 | print("|", x, "|") 109 | x = " | ".join(["---------", "-----------", "-----"]) 110 | print("|", x, "|") 111 | for r in sorted(v): 112 | print("|", " | ".join(r), "|") 113 | 114 | with open("param.json", "w") as f: 115 | print(json.dumps(x, indent=4), file=f) 116 | -------------------------------------------------------------------------------- /tools/parse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from climetlab.utils.factorise import factorise 3 | 4 | seen = {} 5 | x = {} 6 | c = [] 7 | with open("list.txt") as f: 8 | for line in f: 9 | line = line.strip().split("/") 10 | if line[-1].endswith(".index"): 11 | continue 12 | line = line[6:] 13 | line.pop(1) 14 | line = [line[0]] + line[2].split("-")[1:] 15 | if tuple(line) in seen: 16 | continue 17 | seen[tuple(line)] = True 18 | c.append( 19 | dict( 20 | time=line[0], 21 | step=line[1][:-1], 22 | u=line[1][-1], 23 | stream=line[2], 24 | type=line[3].split(".")[0], 25 | format=line[3].split(".")[1], 26 | ) 27 | ) 28 | 29 | 30 | def compress(steps): 31 | if len(steps) < 3: 32 | return [str(s) for s in sorted(steps)] 33 | 34 | r = [] 35 | d = steps[1] - steps[0] 36 | start = steps[0] 37 | prev = steps[0] 38 | for s in steps[1:]: 39 | nd = s - prev 40 | if nd != d: 41 | r.append("%s-%s-%s" % (start, prev, d)) 42 | start = prev 43 | d = nd 44 | prev = s 45 | r.append("%s-%s-%s" % (start, prev, d)) 46 | return r 47 | 48 | 49 | p = [] 50 | for n in factorise(c).to_list(): 51 | n["step"] = compress(sorted(int(x) for x in n["step"])) 52 | p.append(n) 53 | 54 | print(factorise(p).tree()) 55 | -------------------------------------------------------------------------------- /tools/possible.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import traceback 4 | from collections import defaultdict 5 | 6 | import requests 7 | 8 | from ecmwf.opendata import Client 9 | 10 | client = Client() 11 | 12 | done = set() 13 | 14 | possible_values = defaultdict(set) 15 | 16 | with open("index.txt") as f: 17 | for url in f: 18 | try: 19 | url = url.rstrip() 20 | print(url) 21 | r = requests.get(url) 22 | r.raise_for_status() 23 | 24 | lines = [] 25 | for line in r.text.splitlines(): 26 | line = json.loads(line) 27 | for k, v in line.items(): 28 | if not k.startswith("_"): 29 | possible_values[k].add(v) 30 | 31 | except Exception: 32 | print(traceback.format_exc()) 33 | 34 | # print(possible_values) 35 | 36 | x = {} 37 | 38 | for k, v in possible_values.items(): 39 | x[k] = sorted(v) 40 | 41 | print(json.dumps(x, indent=4)) 42 | -------------------------------------------------------------------------------- /tools/requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | -------------------------------------------------------------------------------- /tools/upload.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import json 3 | import os 4 | import sys 5 | 6 | from nexus.toolkit import Authenticator, DownloadInstance, FileManager 7 | 8 | with open(os.path.expanduser("~/.nexus")) as f: 9 | config = json.load(f) 10 | 11 | authenticator = Authenticator.from_credentials( 12 | username=config["username"], 13 | password=config["password"], 14 | ) 15 | 16 | nexus = DownloadInstance( 17 | authenticator=authenticator, 18 | repository="ecmwf-opendata", 19 | ) 20 | 21 | file_manager = FileManager(nexus=nexus) 22 | 23 | file_manager.upload( 24 | local_path=sys.argv[1], 25 | remote_path=sys.argv[2], 26 | ) 27 | -------------------------------------------------------------------------------- /tools/upload.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # https://get.ecmwf.int/#browse/browse:ecmwf-opendata 3 | set -eau 4 | 5 | DATE1=20220119 6 | DATE2=20220120 7 | touch done 8 | 9 | for time in 00 06 12 18 10 | do 11 | DATE=$DATE2 12 | if [[ $time -gt 12 ]] 13 | then 14 | DATE=$DATE1 15 | fi 16 | for stream in oper wave scda scwv enfo waef 17 | do 18 | for type in fc ef ep # tf 19 | do 20 | ext=grib2 21 | if [[ $type == "tf" ]] 22 | then 23 | ext=bufr 24 | fi 25 | for step in $(seq 0 3 144) $(seq 150 6 360) 26 | do 27 | 28 | grep url done && continue 29 | 30 | url=$URL/$DATE/${time}z/0p4-beta/${stream}/${DATE}${time}0000-${step}h-$stream-$type.$ext 31 | code=$(curl --silent --head $url | head -1 | awk '{print $2;}') 32 | if [[ $code -eq 404 ]] 33 | then 34 | continue 35 | fi 36 | if [[ $code -ne 200 ]] 37 | then 38 | echo "Code $code" 39 | exit 1 40 | fi 41 | echo $url 42 | base=$(basename $url .grib2) 43 | data=$base.grib2 44 | index=$base.index 45 | curl --fail $url -o $data.raw 46 | ~/build/mir/bin/mir --grid=20/20 $data.raw $data 47 | ~/build/pgen/bin/pgen-create-index-file -i $data -o $index 48 | yes | ./upload.py $data /testing/$DATE/${time}z/0p4-beta/${stream}/ 49 | yes | ./upload.py $index /testing/$DATE/${time}z/0p4-beta/${stream}/ 50 | rm -f $data $index $data.raw 51 | echo $url >> done 52 | done 53 | done 54 | done 55 | done 56 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | ; See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#slices 4 | extend-ignore = E203 5 | [isort] 6 | profile=black 7 | --------------------------------------------------------------------------------