├── .github
└── workflows
│ ├── python-publish.yml
│ └── stalebot
├── .gitignore
├── .pre-commit-config.yaml
├── CITATION.cff
├── LICENSE
├── README.md
├── pyproject.toml
├── src
└── ai_models
│ ├── __init__.py
│ ├── __main__.py
│ ├── checkpoint.py
│ ├── inputs
│ ├── __init__.py
│ ├── base.py
│ ├── cds.py
│ ├── compute.py
│ ├── file.py
│ ├── interpolate.py
│ ├── mars.py
│ ├── opendata.py
│ ├── recenter.py
│ └── transform.py
│ ├── model.py
│ ├── outputs
│ └── __init__.py
│ ├── remote
│ ├── __init__.py
│ ├── api.py
│ ├── config.py
│ └── model.py
│ └── stepper.py
└── tests
├── requirements.txt
└── test_code.py
/.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 |
8 | push: {}
9 |
10 | release:
11 | types: [created]
12 |
13 | jobs:
14 | quality:
15 | name: Code QA
16 | runs-on: ubuntu-latest
17 | steps:
18 | # - run: sudo apt-get install -y pandoc # Needed by sphinx for notebooks
19 | - uses: actions/checkout@v4
20 | - uses: actions/setup-python@v5
21 | with:
22 | python-version: 3.x
23 | - uses: pre-commit/action@v3.0.1
24 | env:
25 | SKIP: no-commit-to-branch
26 |
27 |
28 | checks:
29 | strategy:
30 | fail-fast: false
31 | matrix:
32 | platform: ["ubuntu-latest", "macos-latest"]
33 | python-version: ["3.10"]
34 |
35 | name: Python ${{ matrix.python-version }} on ${{ matrix.platform }}
36 | runs-on: ${{ matrix.platform }}
37 |
38 | steps:
39 | - uses: actions/checkout@v4
40 |
41 | - uses: actions/setup-python@v2
42 | with:
43 | python-version: ${{ matrix.python-version }}
44 |
45 | - name: Install
46 | run: |
47 | python -m pip install --upgrade pip
48 | pip install pytest
49 | pip install -e .
50 | pip install -r tests/requirements.txt
51 | pip freeze
52 |
53 | - name: Tests
54 | run: pytest
55 |
56 | deploy:
57 |
58 | if: ${{ github.event_name == 'release' }}
59 | runs-on: ubuntu-latest
60 | needs: [checks, quality]
61 |
62 | steps:
63 | - uses: actions/checkout@v4
64 |
65 | - name: Set up Python
66 | uses: actions/setup-python@v2
67 | with:
68 | python-version: 3.x
69 |
70 | - name: Install dependencies
71 | run: |
72 | python -m pip install --upgrade pip
73 | pip install build wheel twine
74 | - name: Build and publish
75 | env:
76 | TWINE_USERNAME: __token__
77 | TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
78 | run: |
79 | python -m build
80 | twine upload dist/*
81 |
--------------------------------------------------------------------------------
/.github/workflows/stalebot:
--------------------------------------------------------------------------------
1 | name: 'Close stale issues and PR'
2 | on:
3 | schedule:
4 | - cron: '30 1 * * *'
5 |
6 | jobs:
7 | stale:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/stale@v9
11 | with:
12 | stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days.'
13 | close-issue-message: 'This issue was closed because it has been stalled for 10 days with no activity.'
14 | days-before-stale: 60
15 | days-before-close: 10
16 | days-before-pr-close: -1
17 |
--------------------------------------------------------------------------------
/.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 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
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 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
162 | *.grib
163 | *.onnx
164 | *.ckpt
165 | *.swp
166 | *.npy
167 | *.download
168 | ?
169 | ?.*
170 | foo
171 | bar
172 | *.grib
173 | *.nc
174 | *.npz
175 | *.json
176 | *.req
177 | dev/
178 | *.out
179 | _version.py
180 | *.tar
181 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 |
3 | # Empty notebookds
4 | - repo: local
5 | hooks:
6 | - id: clear-notebooks-output
7 | name: clear-notebooks-output
8 | files: tools/.*\.ipynb$
9 | stages: [commit]
10 | language: python
11 | entry: jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace
12 | additional_dependencies: [jupyter]
13 |
14 |
15 | - repo: https://github.com/pre-commit/pre-commit-hooks
16 | rev: v4.4.0
17 | hooks:
18 | - id: check-yaml # Check YAML files for syntax errors only
19 | args: [--unsafe, --allow-multiple-documents]
20 | - id: debug-statements # Check for debugger imports and py37+ breakpoint()
21 | - id: end-of-file-fixer # Ensure files end in a newline
22 | - id: trailing-whitespace # Trailing whitespace checker
23 | - id: no-commit-to-branch # Prevent committing to main / master
24 | - id: check-added-large-files # Check for large files added to git
25 | - id: check-merge-conflict # Check for files that contain merge conflict
26 |
27 | - repo: https://github.com/psf/black-pre-commit-mirror
28 | rev: 24.1.1
29 | hooks:
30 | - id: black
31 | args: [--line-length=120]
32 |
33 | - repo: https://github.com/pycqa/isort
34 | rev: 5.13.2
35 | hooks:
36 | - id: isort
37 | args:
38 | - -l 120
39 | - --force-single-line-imports
40 | - --profile black
41 |
42 |
43 | - repo: https://github.com/astral-sh/ruff-pre-commit
44 | rev: v0.3.0
45 | hooks:
46 | - id: ruff
47 | exclude: '(dev/.*|.*_)\.py$'
48 | args:
49 | - --line-length=120
50 | - --fix
51 | - --exit-non-zero-on-fix
52 | - --preview
53 |
54 | - repo: https://github.com/sphinx-contrib/sphinx-lint
55 | rev: v0.9.1
56 | hooks:
57 | - id: sphinx-lint
58 |
59 | # For now, we use it. But it does not support a lot of sphinx features
60 | - repo: https://github.com/dzhu/rstfmt
61 | rev: v0.0.14
62 | hooks:
63 | - id: rstfmt
64 |
65 | - repo: https://github.com/b8raoult/pre-commit-docconvert
66 | rev: "0.1.4"
67 | hooks:
68 | - id: docconvert
69 | args: ["numpy"]
70 |
--------------------------------------------------------------------------------
/CITATION.cff:
--------------------------------------------------------------------------------
1 | # This CITATION.cff file was generated with cffinit.
2 | # Visit https://bit.ly/cffinit to generate yours today!
3 |
4 | cff-version: 1.2.0
5 | title: ai-models
6 | message: >-
7 | If you use this software, please cite it using the
8 | metadata from this file.
9 | type: software
10 | authors:
11 | - given-names: Baudouin
12 | family-names: Raoult
13 | affiliation: ECMWF
14 | - given-names: Florian
15 | family-names: Pinault
16 | - given-names: Gert
17 | family-names: Mertes
18 | affiliation: ECMWF
19 | - given-names: Jesper Sören
20 | family-names: Dramsch
21 | affiliation: ECMWF
22 | orcid: 'https://orcid.org/0000-0001-8273-905X'
23 | - given-names: Harrison
24 | family-names: Cook
25 | affiliation: ECMWF
26 | orcid: 'https://orcid.org/0009-0009-3207-4876'
27 | - given-names: Matthew
28 | family-names: Chantry
29 | affiliation: ECMWF
30 | repository-code: 'https://github.com/ecmwf-lab/ai-models'
31 | abstract: >-
32 | ai-models is used to run AI-based weather forecasting
33 | models. These models need to be installed independently.
34 | keywords:
35 | - ai
36 | - weather forecasting
37 | license: Apache-2.0
38 |
--------------------------------------------------------------------------------
/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 | # ai-models
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | **DISCLAIMER**
22 |
23 | > \[!IMPORTANT\]
24 | > This project is **BETA** and will be **Experimental** for the foreseeable future.
25 | > Interfaces and functionality are likely to change, and the project itself may be scrapped.
26 | > **DO NOT** use this software in any project/software that is operational.
27 |
28 |
29 |
30 |
31 | The `ai-models` command is used to run AI-based weather forecasting models. These models need to be installed independently.
32 |
33 | ## Usage
34 |
35 | Although the source code `ai-models` and its plugins are available under open sources licences, some model weights may be available under a different licence. For example some models make their weights available under the CC-BY-NC-SA 4.0 license, which does not allow commercial use. For more informations, please check the license associated with each model on their main home page, that we link from each of the corresponding plugins.
36 |
37 | ## Prerequisites
38 |
39 | Before using the `ai-models` command, ensure you have the following prerequisites:
40 |
41 | - Python 3.10 (it may work with different versions, but it has been tested with 3.10 on Linux/MacOS).
42 | - An ECMWF and/or CDS account for accessing input data (see below for more details).
43 | - A computed with a GPU for optimal performance (strongly recommended).
44 |
45 | ## Installation
46 |
47 | To install the `ai-models` command, run the following command:
48 |
49 | ```bash
50 | pip install ai-models
51 | ```
52 |
53 | ## Available Models
54 |
55 | Currently, four models can be installed:
56 |
57 | ```bash
58 | pip install ai-models-panguweather
59 | pip install ai-models-fourcastnet
60 | pip install ai-models-graphcast # Install details at https://github.com/ecmwf-lab/ai-models-graphcast
61 | pip install ai-models-fourcastnetv2
62 | ```
63 |
64 | See [ai-models-panguweather](https://github.com/ecmwf-lab/ai-models-panguweather), [ai-models-fourcastnet](https://github.com/ecmwf-lab/ai-models-fourcastnet),
65 | [ai-models-fourcastnetv2](https://github.com/ecmwf-lab/ai-models-fourcastnetv2) and [ai-models-graphcast](https://github.com/ecmwf-lab/ai-models-graphcast) for more details about these models.
66 |
67 | ## Running the models
68 |
69 | To run model, make sure it has been installed, then simply run:
70 |
71 | ```bash
72 | ai-models
73 | ```
74 |
75 | Replace `` with the name of the specific AI model you want to run.
76 |
77 | By default, the model will be run for a 10-day lead time (240 hours), using yesterday's 12Z analysis from ECMWF's MARS archive.
78 |
79 | To produce a 15 days forecast, use the `--lead-time HOURS` option:
80 |
81 | ```bash
82 | ai-models --lead-time 360
83 | ```
84 |
85 | You can change the other defaults using the available command line options, as described below.
86 |
87 | ## Performances Considerations
88 |
89 | The AI models can run on a CPU; however, they perform significantly better on a GPU. A 10-day forecast can take several hours on a CPU but only around one minute on a modern GPU.
90 |
91 | :warning: **We strongly recommend running these models on a computer equipped with a GPU for optimal performance.**
92 |
93 | It you see the following message when running a model, it means that the ONNX runtime was not able to find a the CUDA libraries on your system:
94 | > [W:onnxruntime:Default, onnxruntime_pybind_state.cc:541 CreateExecutionProviderInstance] Failed to create CUDAExecutionProvider. Please reference to ensure all dependencies are met.
95 |
96 | To fix this issue, we suggest that you install `ai-models` in a [conda](https://docs.conda.io/en/latest/) environment and install the CUDA libraries in that environment. For example:
97 |
98 | ```bash
99 | conda create -n ai-models python=3.10
100 | conda activate ai-models
101 | conda install cudatoolkit
102 | pip install ai-models
103 | ...
104 | ```
105 |
106 | ## Assets
107 |
108 | The AI models rely on weights and other assets created during training. The first time you run a model, you will need to download the trained weights and any additional required assets.
109 |
110 | To download the assets before running a model, use the following command:
111 |
112 | ```bash
113 | ai-models --download-assets
114 | ```
115 |
116 | The assets will be downloaded if needed and stored in the current directory. You can provide a different directory to store the assets:
117 |
118 | ```bash
119 | ai-models --download-assets --assets
120 | ```
121 |
122 | Then, later on, simply use:
123 |
124 | ```bash
125 | ai-models --assets
126 | ```
127 |
128 | or
129 |
130 | ```bash
131 | export AI_MODELS_ASSETS=
132 | ai-models
133 | ```
134 |
135 | For better organisation of the assets directory, you can use the `--assets-sub-directory` option. This option will store the assets of each model in its own subdirectory within the specified assets directory.
136 |
137 | ## Input data
138 |
139 | The models require input data (initial conditions) to run. You can provide the input data using different sources, as described below:
140 |
141 | ### From MARS
142 |
143 | By default, `ai-models` use yesterday's 12Z analysis from ECMWF, fetched from the Centre's MARS archive using the [ECMWF WebAPI](https://www.ecmwf.int/en/computing/software/ecmwf-web-api). You will need an ECMWF account to access that service.
144 |
145 | To change the date or time, use the `--date` and `--time` options, respectively:
146 |
147 | ```bash
148 | ai-models --date YYYYMMDD --time HHMM
149 | ```
150 |
151 | ### From the CDS
152 |
153 | You can start the models using ERA5 (ECMWF Reanalysis version 5) data for the [Copernicus Climate Data Store (CDS)](https://cds.climate.copernicus.eu/). You will need to create an account on the CDS. The data will be downloaded using the [CDS API](https://cds.climate.copernicus.eu/api-how-to).
154 |
155 | To access the CDS, simply add `--input cds` on the command line. Please note that ERA5 data is added to the CDS with a delay, so you will also have to provide a date with `--date YYYYMMDD`.
156 |
157 | ```bash
158 | ai-models --input cds --date 20230110 --time 0000
159 | ```
160 |
161 | ### From a GRIB file
162 |
163 | If you have input data in the GRIB format, you can provide the file using the `--file` option:
164 |
165 | ```bash
166 | ai-models --file
167 | ```
168 |
169 | The GRIB file can contain more fields than the ones required by the model. The `ai-models` command will automatically select the necessary fields from the file.
170 |
171 | To find out the list of fields needed by a specific model as initial conditions, use the following command:
172 |
173 | ```bash
174 | ai-models --fields
175 | ```
176 |
177 | ## Output
178 |
179 | By default, the model output will be written in GRIB format in a file called `.grib`. You can change the file name with the option `--path `. If the path you specify contains placeholders between `{` and `}`, multiple files will be created based on the [eccodes](https://confluence.ecmwf.int/display/ECC) keys. For example:
180 |
181 | ```bash
182 | ai-models --path 'out-{step}.grib'
183 | ```
184 |
185 | This command will create a file for each forecasted time step.
186 |
187 | If you want to disable writing the output to a file, use the `--output none` option.
188 |
189 | ## Command line options
190 |
191 | It has the following options:
192 |
193 | - `--help`: Displays this help message.
194 | - `--models`: Lists all installed models.
195 | - `--debug`: Turns on debug mode. This will print additional information to the console.
196 |
197 | ### Input
198 |
199 | - `--input INPUT`: The input source for the model. This can be a `mars`, `cds` or `file`.
200 | - `--file FILE`: The specific file to use as input. This option will set `--source` to `file`.
201 |
202 | - `--date DATE`: The analysis date for the model. This defaults to yesterday.
203 | - `--time TIME`: The analysis time for the model. This defaults to 1200.
204 |
205 | ### Output
206 |
207 | - `--output OUTPUT`: The output destination for the model. Values are `file` or `none`.
208 | - `--path PATH`: The path to write the output of the model.
209 |
210 | ### Run
211 |
212 | - `--lead-time HOURS`: The number of hours to forecast. The default is 240 (10 days).
213 |
214 | ### Assets management
215 |
216 | - `--assets ASSETS`: Specifies the path to the directory containing the model assets. The default is the current directory, but you can override it by setting the `$AI_MODELS_ASSETS` environment variable.
217 | - `--assets-sub-directory`: Enables organising assets in `/` subdirectories.
218 | - `--download-assets`: Downloads the assets if they do not exist.
219 |
220 | ### Misc. options
221 |
222 | - `--fields`: Print the list of fields needed by a model as initial conditions.
223 | - `--expver EXPVER`: The experiment version of the model output.
224 | - `--class CLASS`: The 'class' metadata of the model output.
225 | - `--metadata KEY=VALUE`: Additional metadata metadata in the model output
226 |
227 | ## License
228 |
229 | ```
230 | Copyright 2022, European Centre for Medium Range Weather Forecasts.
231 |
232 | Licensed under the Apache License, Version 2.0 (the "License");
233 | you may not use this file except in compliance with the License.
234 | You may obtain a copy of the License at
235 |
236 | http://www.apache.org/licenses/LICENSE-2.0
237 |
238 | Unless required by applicable law or agreed to in writing, software
239 | distributed under the License is distributed on an "AS IS" BASIS,
240 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
241 | See the License for the specific language governing permissions and
242 | limitations under the License.
243 |
244 | In applying this licence, ECMWF does not waive the privileges and immunities
245 | granted to it by virtue of its status as an intergovernmental organisation
246 | nor does it submit to any jurisdiction.
247 | ```
248 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # (C) Copyright 2024 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 | # https://packaging.python.org/en/latest/guides/writing-pyproject-toml/
11 |
12 | [build-system]
13 | requires = ["setuptools>=60", "setuptools-scm>=8.0"]
14 |
15 | [project]
16 | description = "A package to run AI weather models."
17 | name = "ai-models"
18 |
19 | dynamic = ["version"]
20 | license = { file = "LICENSE" }
21 | requires-python = ">=3.9"
22 |
23 | authors = [
24 | { name = "European Centre for Medium-Range Weather Forecasts (ECMWF)", email = "software.support@ecmwf.int" },
25 | ]
26 |
27 | keywords = ["tools", "ai"]
28 |
29 | classifiers = [
30 | "Development Status :: 4 - Beta",
31 | "Intended Audience :: Developers",
32 | "License :: OSI Approved :: Apache Software License",
33 | "Programming Language :: Python :: 3",
34 | "Programming Language :: Python :: 3.9",
35 | "Programming Language :: Python :: 3.10",
36 | "Programming Language :: Python :: 3.11",
37 | "Programming Language :: Python :: Implementation :: CPython",
38 | "Programming Language :: Python :: Implementation :: PyPy",
39 | "Operating System :: OS Independent",
40 | ]
41 |
42 | dependencies = [
43 | "cdsapi",
44 | "earthkit-data>=0.11.3",
45 | "earthkit-meteo",
46 | "earthkit-regrid",
47 | "eccodes>=2.37",
48 | "ecmwf-api-client",
49 | "ecmwf-opendata",
50 | "entrypoints",
51 | "gputil",
52 | "multiurl",
53 | "numpy<2",
54 | "pyyaml",
55 | "requests",
56 | "tqdm",
57 | ]
58 |
59 |
60 | [project.urls]
61 | Homepage = "https://github.com/ecmwf-lab/ai-models/"
62 | Repository = "https://github.com/ecmwf-lab/ai-models/"
63 | Issues = "https://github.com/ecmwf-lab/ai-models/issues"
64 |
65 | [project.scripts]
66 | ai-models = "ai_models.__main__:main"
67 |
68 | [tool.setuptools_scm]
69 | version_file = "src/ai_models/_version.py"
70 |
71 | [project.entry-points."ai_models.input"]
72 | file = "ai_models.inputs.file:FileInput"
73 | mars = "ai_models.inputs.mars:MarsInput"
74 | cds = "ai_models.inputs.cds:CdsInput"
75 | ecmwf-open-data = "ai_models.inputs.opendata:OpenDataInput"
76 | opendata = "ai_models.inputs.opendata:OpenDataInput"
77 |
78 | [project.entry-points."ai_models.output"]
79 | file = "ai_models.outputs:FileOutput"
80 | none = "ai_models.outputs:NoneOutput"
81 |
--------------------------------------------------------------------------------
/src/ai_models/__init__.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | from ._version import __version__
9 |
--------------------------------------------------------------------------------
/src/ai_models/__main__.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import argparse
9 | import logging
10 | import os
11 | import shlex
12 | import sys
13 |
14 | import earthkit.data as ekd
15 |
16 | from .inputs import available_inputs
17 | from .model import Timer
18 | from .model import available_models
19 | from .model import load_model
20 | from .outputs import available_outputs
21 |
22 | ekd.settings.set("cache-policy", "user")
23 |
24 | LOG = logging.getLogger(__name__)
25 |
26 |
27 | def _main(argv):
28 | parser = argparse.ArgumentParser()
29 |
30 | # See https://github.com/pytorch/pytorch/issues/77764
31 | os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
32 |
33 | parser.add_argument(
34 | "--models",
35 | action="store_true",
36 | help="List models and exit",
37 | )
38 |
39 | parser.add_argument(
40 | "--debug",
41 | action="store_true",
42 | help="Turn on debug",
43 | )
44 |
45 | parser.add_argument(
46 | "-v",
47 | "--verbose",
48 | action="count",
49 | default=0,
50 | help="Increase verbosity",
51 | )
52 |
53 | parser.add_argument(
54 | "--retrieve-requests",
55 | help=("Print mars requests to stdout." "Use --requests-extra to extend or overide the requests. "),
56 | action="store_true",
57 | )
58 |
59 | parser.add_argument(
60 | "--archive-requests",
61 | help=("Save mars archive requests to FILE." "Use --requests-extra to extend or overide the requests. "),
62 | metavar="FILE",
63 | )
64 |
65 | parser.add_argument(
66 | "--requests-extra",
67 | help=("Extends the retrieve or archive requests with a list of key1=value1,key2=value."),
68 | )
69 |
70 | parser.add_argument(
71 | "--json",
72 | action="store_true",
73 | help=("Dump the requests in JSON format."),
74 | )
75 |
76 | parser.add_argument(
77 | "--retrieve-fields-type",
78 | help="Type of field to retrieve. To use with --retrieve-requests.",
79 | choices=["constants", "prognostics", "all"],
80 | default="all",
81 | )
82 |
83 | parser.add_argument(
84 | "--retrieve-only-one-date",
85 | help="Only retrieve the last date/time. To use with --retrieve-requests.",
86 | action="store_true",
87 | )
88 |
89 | parser.add_argument(
90 | "--dump-provenance",
91 | metavar="FILE",
92 | help=("Dump information for tracking provenance."),
93 | )
94 |
95 | parser.add_argument(
96 | "--input",
97 | default="mars",
98 | help="Source to use",
99 | choices=sorted(available_inputs()),
100 | )
101 |
102 | parser.add_argument(
103 | "--file",
104 | help="Source to use if source=file",
105 | )
106 |
107 | parser.add_argument(
108 | "--output",
109 | default="file",
110 | help="Where to output the results",
111 | choices=sorted(available_outputs()),
112 | )
113 |
114 | parser.add_argument(
115 | "--date",
116 | default="-1",
117 | help="For which analysis date to start the inference (default: yesterday)",
118 | )
119 |
120 | parser.add_argument(
121 | "--time",
122 | type=int,
123 | default=12,
124 | help="For which analysis time to start the inference (default: 12)",
125 | )
126 |
127 | parser.add_argument(
128 | "--assets",
129 | default=os.environ.get("AI_MODELS_ASSETS", "."),
130 | help="Path to directory containing the weights and other assets",
131 | )
132 |
133 | parser.add_argument(
134 | "--assets-sub-directory",
135 | help="Load assets from a subdirectory of --assets based on the name of the model.",
136 | action=argparse.BooleanOptionalAction,
137 | )
138 |
139 | parser.parse_args(["--no-assets-sub-directory"])
140 |
141 | parser.add_argument(
142 | "--assets-list",
143 | help="List the assets used by the model",
144 | action="store_true",
145 | )
146 |
147 | parser.add_argument(
148 | "--download-assets",
149 | help="Download assets if they do not exists.",
150 | action="store_true",
151 | )
152 |
153 | parser.add_argument(
154 | "--path",
155 | help="Path where to write the output of the model",
156 | )
157 |
158 | parser.add_argument(
159 | "--fields",
160 | help="Show the fields needed as input for the model",
161 | action="store_true",
162 | )
163 |
164 | parser.add_argument(
165 | "--expver",
166 | help="Set the experiment version of the model output. Has higher priority than --metadata.",
167 | )
168 |
169 | parser.add_argument(
170 | "--class",
171 | help="Set the 'class' metadata of the model output. Has higher priority than --metadata.",
172 | metavar="CLASS",
173 | dest="class_",
174 | )
175 |
176 | parser.add_argument(
177 | "--metadata",
178 | help="Set additional metadata metadata in the model output",
179 | metavar="KEY=VALUE",
180 | action="append",
181 | )
182 |
183 | parser.add_argument(
184 | "--num-threads",
185 | type=int,
186 | default=1,
187 | help="Number of threads. Only relevant for some models.",
188 | )
189 |
190 | parser.add_argument(
191 | "--lead-time",
192 | type=int,
193 | default=240,
194 | help="Length of forecast in hours.",
195 | )
196 |
197 | parser.add_argument(
198 | "--hindcast-reference-year",
199 | help="For encoding hincast-like outputs",
200 | )
201 |
202 | parser.add_argument(
203 | "--hindcast-reference-date",
204 | help="For encoding hincast-like outputs",
205 | )
206 |
207 | parser.add_argument(
208 | "--staging-dates",
209 | help="For encoding hincast-like outputs",
210 | )
211 |
212 | parser.add_argument(
213 | "--only-gpu",
214 | help="Fail if GPU is not available",
215 | action="store_true",
216 | )
217 |
218 | parser.add_argument(
219 | "--deterministic",
220 | help="Fail if GPU is not available",
221 | action="store_true",
222 | )
223 |
224 | # TODO: deprecate that option
225 | parser.add_argument(
226 | "--model-version",
227 | default="latest",
228 | help="Model version",
229 | )
230 |
231 | parser.add_argument(
232 | "--version",
233 | action="store_true",
234 | help="Print ai-models version and exit",
235 | )
236 |
237 | if all(arg not in ("--models", "--version") for arg in argv):
238 | parser.add_argument(
239 | "model",
240 | metavar="MODEL",
241 | choices=available_models() if "--remote" not in argv else None,
242 | help="The model to run",
243 | )
244 |
245 | parser.add_argument(
246 | "--remote",
247 | help="Enable remote execution, read url and token from ~/.config/ai-models/api.yaml",
248 | action="store_true",
249 | dest="remote_execution",
250 | default=(os.environ.get("AI_MODELS_REMOTE", "0") == "1"),
251 | )
252 |
253 | args, unknownargs = parser.parse_known_args(argv)
254 |
255 | if args.version:
256 | from ai_models import __version__
257 |
258 | print(__version__)
259 | sys.exit(0)
260 |
261 | del args.version
262 |
263 | if args.models:
264 | if args.remote_execution:
265 | from .remote import RemoteAPI
266 |
267 | api = RemoteAPI()
268 | models = api.models()
269 | if len(models) == 0:
270 | print(f"No remote models available on {api.url}")
271 | sys.exit(0)
272 | print(f"Models available on remote server {api.url}")
273 | else:
274 | models = available_models()
275 |
276 | for p in sorted(models):
277 | print(p)
278 | sys.exit(0)
279 |
280 | if args.assets_sub_directory:
281 | args.assets = os.path.join(args.assets, args.model)
282 |
283 | if args.path is None:
284 | args.path = f"{args.model}.grib"
285 |
286 | if args.file is not None:
287 | args.input = "file"
288 |
289 | if not args.fields and not args.retrieve_requests:
290 | logging.basicConfig(
291 | level="DEBUG" if args.debug else "INFO",
292 | format="%(asctime)s %(levelname)s %(message)s",
293 | )
294 |
295 | if args.metadata is None:
296 | args.metadata = []
297 |
298 | args.metadata = dict(kv.split("=") for kv in args.metadata)
299 |
300 | if args.expver is not None:
301 | args.metadata["expver"] = args.expver
302 |
303 | if args.class_ is not None:
304 | args.metadata["class"] = args.class_
305 |
306 | if args.requests_extra:
307 | if not args.retrieve_requests and not args.archive_requests:
308 | parser.error("You need to specify --retrieve-requests or --archive-requests")
309 |
310 | run(vars(args), unknownargs)
311 |
312 |
313 | def run(cfg: dict, model_args: list):
314 | if cfg["remote_execution"]:
315 | from .remote import RemoteModel
316 |
317 | model = RemoteModel(**cfg, model_args=model_args)
318 | else:
319 | model = load_model(cfg["model"], **cfg, model_args=model_args)
320 |
321 | if cfg["fields"]:
322 | model.print_fields()
323 | sys.exit(0)
324 |
325 | # This logic is a bit convoluted, but it is for backwards compatibility.
326 | if cfg["retrieve_requests"] or (cfg["requests_extra"] and not cfg["archive_requests"]):
327 | model.print_requests()
328 | sys.exit(0)
329 |
330 | if cfg["assets_list"]:
331 | model.print_assets_list()
332 | sys.exit(0)
333 |
334 | try:
335 | model.run()
336 | except FileNotFoundError as e:
337 | LOG.exception(e)
338 | LOG.error(
339 | "It is possible that some files required by %s are missing.",
340 | cfg["model"],
341 | )
342 | LOG.error("Rerun the command as:")
343 | LOG.error(
344 | " %s",
345 | shlex.join([sys.argv[0], "--download-assets"] + sys.argv[1:]),
346 | )
347 | sys.exit(1)
348 |
349 | model.finalise()
350 |
351 | if cfg["dump_provenance"]:
352 | with Timer("Collect provenance information"):
353 | with open(cfg["dump_provenance"], "w") as f:
354 | prov = model.provenance()
355 | import json # import here so it is not listed in provenance
356 |
357 | json.dump(prov, f, indent=4)
358 |
359 |
360 | def main():
361 | with Timer("Total time"):
362 | _main(sys.argv[1:])
363 |
364 |
365 | if __name__ == "__main__":
366 | main()
367 |
--------------------------------------------------------------------------------
/src/ai_models/checkpoint.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 | import os
10 | import pickle
11 | import zipfile
12 | from typing import Any
13 |
14 | LOG = logging.getLogger(__name__)
15 |
16 |
17 | class FakeStorage:
18 | def __init__(self):
19 | import torch
20 |
21 | self.dtype = torch.float32
22 | self._untyped_storage = torch.UntypedStorage(0)
23 |
24 |
25 | class UnpicklerWrapper(pickle.Unpickler):
26 | def __init__(self, file, **kwargs):
27 | super().__init__(file, **kwargs)
28 |
29 | def persistent_load(self, pid: Any) -> Any:
30 | return FakeStorage()
31 |
32 |
33 | def tidy(x):
34 | if isinstance(x, dict):
35 | return {k: tidy(v) for k, v in x.items()}
36 |
37 | if isinstance(x, list):
38 | return [tidy(v) for v in x]
39 |
40 | if isinstance(x, tuple):
41 | return tuple([tidy(v) for v in x])
42 |
43 | if x is None:
44 | return None
45 |
46 | if isinstance(x, (int, float, str, bool)):
47 | return x
48 |
49 | return x
50 |
51 |
52 | def peek(path):
53 | with zipfile.ZipFile(path, "r") as f:
54 | data_pkl = None
55 | for b in f.namelist():
56 | if os.path.basename(b) == "data.pkl":
57 | if data_pkl is not None:
58 | raise Exception(f"Found two data.pkl files in {path}: {data_pkl} and {b}")
59 | data_pkl = b
60 |
61 | LOG.info(f"Found data.pkl at {data_pkl}")
62 |
63 | with zipfile.ZipFile(path, "r") as f:
64 | unpickler = UnpicklerWrapper(f.open(data_pkl, "r"))
65 | x = tidy(unpickler.load())
66 | return tidy(x)
67 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/__init__.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 | from functools import cached_property
10 |
11 | import earthkit.data as ekd
12 | import earthkit.regrid as ekr
13 | import entrypoints
14 | from earthkit.data.indexing.fieldlist import FieldArray
15 |
16 | LOG = logging.getLogger(__name__)
17 |
18 |
19 | def get_input(name, *args, **kwargs):
20 | return available_inputs()[name].load()(*args, **kwargs)
21 |
22 |
23 | def available_inputs():
24 | result = {}
25 | for e in entrypoints.get_group_all("ai_models.input"):
26 | result[e.name] = e
27 | return result
28 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/base.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 | from functools import cached_property
10 |
11 | import earthkit.data as ekd
12 |
13 | LOG = logging.getLogger(__name__)
14 |
15 |
16 | class RequestBasedInput:
17 | def __init__(self, owner, **kwargs):
18 | self.owner = owner
19 |
20 | def _patch(self, **kargs):
21 | r = dict(**kargs)
22 | self.owner.patch_retrieve_request(r)
23 | return r
24 |
25 | @cached_property
26 | def fields_sfc(self):
27 | param = self.owner.param_sfc
28 | if not param:
29 | return ekd.from_source("empty")
30 |
31 | LOG.info(f"Loading surface fields from {self.WHERE}")
32 |
33 | return ekd.from_source(
34 | "multi",
35 | [
36 | self.sfc_load_source(
37 | **self._patch(
38 | date=date,
39 | time=time,
40 | param=param,
41 | grid=self.owner.grid,
42 | area=self.owner.area,
43 | **self.owner.retrieve,
44 | )
45 | )
46 | for date, time in self.owner.datetimes()
47 | ],
48 | )
49 |
50 | @cached_property
51 | def fields_pl(self):
52 | param, level = self.owner.param_level_pl
53 | if not (param and level):
54 | return ekd.from_source("empty")
55 |
56 | LOG.info(f"Loading pressure fields from {self.WHERE}")
57 | return ekd.from_source(
58 | "multi",
59 | [
60 | self.pl_load_source(
61 | **self._patch(
62 | date=date,
63 | time=time,
64 | param=param,
65 | level=level,
66 | grid=self.owner.grid,
67 | area=self.owner.area,
68 | )
69 | )
70 | for date, time in self.owner.datetimes()
71 | ],
72 | )
73 |
74 | @cached_property
75 | def fields_ml(self):
76 | param, level = self.owner.param_level_ml
77 | if not (param and level):
78 | return ekd.from_source("empty")
79 |
80 | LOG.info(f"Loading model fields from {self.WHERE}")
81 | return ekd.from_source(
82 | "multi",
83 | [
84 | self.ml_load_source(
85 | **self._patch(
86 | date=date,
87 | time=time,
88 | param=param,
89 | level=level,
90 | grid=self.owner.grid,
91 | area=self.owner.area,
92 | )
93 | )
94 | for date, time in self.owner.datetimes()
95 | ],
96 | )
97 |
98 | @cached_property
99 | def all_fields(self):
100 | return self.fields_sfc + self.fields_pl + self.fields_ml
101 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/cds.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | import earthkit.data as ekd
11 |
12 | from .base import RequestBasedInput
13 |
14 | LOG = logging.getLogger(__name__)
15 |
16 |
17 | class CdsInput(RequestBasedInput):
18 | WHERE = "CDS"
19 |
20 | def pl_load_source(self, **kwargs):
21 | kwargs["product_type"] = "reanalysis"
22 | return ekd.from_source("cds", "reanalysis-era5-pressure-levels", kwargs)
23 |
24 | def sfc_load_source(self, **kwargs):
25 | kwargs["product_type"] = "reanalysis"
26 | return ekd.from_source("cds", "reanalysis-era5-single-levels", kwargs)
27 |
28 | def ml_load_source(self, **kwargs):
29 | raise NotImplementedError("CDS does not support model levels")
30 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/compute.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | import earthkit.data as ekd
11 | import tqdm
12 | from earthkit.data.core.temporary import temp_file
13 | from earthkit.data.indexing.fieldlist import FieldArray
14 |
15 | LOG = logging.getLogger(__name__)
16 |
17 | G = 9.80665 # Same a pgen
18 |
19 |
20 | def make_z_from_gh(ds):
21 |
22 | tmp = temp_file()
23 |
24 | out = ekd.new_grib_output(tmp.path)
25 | other = []
26 |
27 | for f in tqdm.tqdm(ds, delay=0.5, desc="GH to Z", leave=False):
28 |
29 | if f.metadata("param") == "gh":
30 | out.write(f.to_numpy() * G, template=f, param="z")
31 | else:
32 | other.append(f)
33 |
34 | out.close()
35 |
36 | result = FieldArray(other) + ekd.from_source("file", tmp.path)
37 | result._tmp = tmp
38 |
39 | return result
40 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/file.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 | from functools import cached_property
10 |
11 | import earthkit.data as ekd
12 | import entrypoints
13 |
14 | LOG = logging.getLogger(__name__)
15 |
16 |
17 | class FileInput:
18 | def __init__(self, owner, file, **kwargs):
19 | self.file = file
20 | self.owner = owner
21 |
22 | @cached_property
23 | def fields_sfc(self):
24 | return self.all_fields.sel(levtype="sfc")
25 |
26 | @cached_property
27 | def fields_pl(self):
28 | return self.all_fields.sel(levtype="pl")
29 |
30 | @cached_property
31 | def fields_ml(self):
32 | return self.all_fields.sel(levtype="ml")
33 |
34 | @cached_property
35 | def all_fields(self):
36 | return ekd.from_source("file", self.file)
37 |
38 |
39 | def get_input(name, *args, **kwargs):
40 | return available_inputs()[name].load()(*args, **kwargs)
41 |
42 |
43 | def available_inputs():
44 | result = {}
45 | for e in entrypoints.get_group_all("ai_models.input"):
46 | result[e.name] = e
47 | return result
48 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/interpolate.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | import earthkit.data as ekd
11 | import earthkit.regrid as ekr
12 | import tqdm
13 | from earthkit.data.core.temporary import temp_file
14 |
15 | LOG = logging.getLogger(__name__)
16 |
17 |
18 | class Interpolate:
19 | def __init__(self, grid, source, metadata):
20 | self.grid = list(grid) if isinstance(grid, tuple) else grid
21 | self.source = list(source) if isinstance(source, tuple) else source
22 | self.metadata = metadata
23 |
24 | def __call__(self, ds):
25 | tmp = temp_file()
26 |
27 | out = ekd.new_grib_output(tmp.path)
28 |
29 | result = []
30 | for f in tqdm.tqdm(ds, delay=0.5, desc="Interpolating", leave=False):
31 | data = ekr.interpolate(f.to_numpy(), dict(grid=self.source), dict(grid=self.grid))
32 | out.write(data, template=f, **self.metadata)
33 |
34 | out.close()
35 |
36 | result = ekd.from_source("file", tmp.path)
37 | result._tmp = tmp
38 |
39 | print("Interpolated data", tmp.path)
40 |
41 | return result
42 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/mars.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | import earthkit.data as ekd
11 |
12 | from .base import RequestBasedInput
13 |
14 | LOG = logging.getLogger(__name__)
15 |
16 |
17 | class MarsInput(RequestBasedInput):
18 | WHERE = "MARS"
19 |
20 | def __init__(self, owner, **kwargs):
21 | self.owner = owner
22 |
23 | def pl_load_source(self, **kwargs):
24 | kwargs["levtype"] = "pl"
25 | logging.debug("load source mars %s", kwargs)
26 | return ekd.from_source("mars", kwargs)
27 |
28 | def sfc_load_source(self, **kwargs):
29 | kwargs["levtype"] = "sfc"
30 | logging.debug("load source mars %s", kwargs)
31 | return ekd.from_source("mars", kwargs)
32 |
33 | def ml_load_source(self, **kwargs):
34 | kwargs["levtype"] = "ml"
35 | logging.debug("load source mars %s", kwargs)
36 | return ekd.from_source("mars", kwargs)
37 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/opendata.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import itertools
9 | import logging
10 | import os
11 |
12 | import earthkit.data as ekd
13 | from earthkit.data.core.temporary import temp_file
14 | from earthkit.data.indexing.fieldlist import FieldArray
15 | from multiurl import download
16 |
17 | from .base import RequestBasedInput
18 | from .compute import make_z_from_gh
19 | from .interpolate import Interpolate
20 | from .recenter import recenter
21 | from .transform import NewMetadataField
22 |
23 | LOG = logging.getLogger(__name__)
24 |
25 | CONSTANTS = (
26 | "z",
27 | "sdor",
28 | "slor",
29 | )
30 |
31 | CONSTANTS_URL = "https://get.ecmwf.int/repository/test-data/ai-models/opendata/constants-{resol}.grib2"
32 |
33 | RESOLS = {
34 | (0.25, 0.25): ("0p25", (0.25, 0.25), False, False, {}),
35 | (0.1, 0.1): (
36 | "0p25",
37 | (0.25, 0.25),
38 | True,
39 | True,
40 | dict(
41 | longitudeOfLastGridPointInDegrees=359.9,
42 | iDirectionIncrementInDegrees=0.1,
43 | jDirectionIncrementInDegrees=0.1,
44 | Ni=3600,
45 | Nj=1801,
46 | ),
47 | ),
48 | # "N320": ("0p25", (0.25, 0.25), True, False, dict(gridType='reduced_gg')),
49 | # "O96": ("0p25", (0.25, 0.25), True, False, dict(gridType='reduced_gg', )),
50 | }
51 |
52 |
53 | def _identity(x):
54 | return x
55 |
56 |
57 | class OpenDataInput(RequestBasedInput):
58 | WHERE = "OPENDATA"
59 |
60 | def __init__(self, owner, **kwargs):
61 | self.owner = owner
62 |
63 | def _adjust(self, kwargs):
64 |
65 | kwargs.setdefault("step", 0)
66 |
67 | if "level" in kwargs:
68 | # OpenData uses levelist instead of level
69 | kwargs["levelist"] = kwargs.pop("level")
70 |
71 | if "area" in kwargs:
72 | kwargs.pop("area")
73 |
74 | grid = kwargs.pop("grid")
75 | if isinstance(grid, list):
76 | grid = tuple(grid)
77 |
78 | kwargs["resol"], source, interp, oversampling, metadata = RESOLS[grid]
79 | r = dict(**kwargs)
80 | r.update(self.owner.retrieve)
81 |
82 | if interp:
83 |
84 | logging.info("Interpolating input data from %s to %s.", source, grid)
85 | if oversampling:
86 | logging.warning("This will oversample the input data.")
87 | return Interpolate(grid, source, metadata)
88 | else:
89 | return _identity
90 |
91 | def pl_load_source(self, **kwargs):
92 |
93 | gh_to_z = _identity
94 | interpolate = self._adjust(kwargs)
95 |
96 | kwargs["levtype"] = "pl"
97 | request = kwargs.copy()
98 |
99 | param = [p.lower() for p in kwargs["param"]]
100 | assert isinstance(param, (list, tuple))
101 |
102 | if "z" in param:
103 | logging.warning("Parameter 'z' on pressure levels is not available in ECMWF open data, using 'gh' instead")
104 | param = list(param)
105 | param.remove("z")
106 | if "gh" not in param:
107 | param.append("gh")
108 | kwargs["param"] = param
109 | gh_to_z = make_z_from_gh
110 |
111 | logging.info("ecmwf-open-data %s", kwargs)
112 |
113 | opendata = recenter(ekd.from_source("ecmwf-open-data", **kwargs))
114 | opendata = gh_to_z(opendata)
115 | opendata = interpolate(opendata)
116 |
117 | return self.check_pl(opendata, request)
118 |
119 | def constants(self, constant_params, request, kwargs):
120 | if len(constant_params) == 1:
121 | logging.warning(
122 | f"Single level parameter '{constant_params[0]}' is"
123 | " not available in ECMWF open data, using constants.grib2 instead"
124 | )
125 | else:
126 | logging.warning(
127 | f"Single level parameters {constant_params} are"
128 | " not available in ECMWF open data, using constants.grib2 instead"
129 | )
130 |
131 | cachedir = os.path.expanduser("~/.cache/ai-models")
132 | constants_url = CONSTANTS_URL.format(resol=request["resol"])
133 | basename = os.path.basename(constants_url)
134 |
135 | if not os.path.exists(cachedir):
136 | os.makedirs(cachedir)
137 |
138 | path = os.path.join(cachedir, basename)
139 |
140 | if not os.path.exists(path):
141 | logging.info("Downloading %s to %s", constants_url, path)
142 | download(constants_url, path + ".tmp")
143 | os.rename(path + ".tmp", path)
144 |
145 | ds = ekd.from_source("file", path)
146 | ds = ds.sel(param=constant_params)
147 |
148 | tmp = temp_file()
149 |
150 | out = ekd.new_grib_output(tmp.path)
151 |
152 | for f in ds:
153 | out.write(
154 | f.to_numpy(),
155 | template=f,
156 | date=kwargs["date"],
157 | time=kwargs["time"],
158 | step=kwargs.get("step", 0),
159 | )
160 |
161 | out.close()
162 |
163 | result = ekd.from_source("file", tmp.path)
164 | result._tmp = tmp
165 |
166 | return result
167 |
168 | def sfc_load_source(self, **kwargs):
169 | interpolate = self._adjust(kwargs)
170 |
171 | kwargs["levtype"] = "sfc"
172 | request = kwargs.copy()
173 |
174 | param = [p.lower() for p in kwargs["param"]]
175 | assert isinstance(param, (list, tuple))
176 |
177 | constant_params = []
178 | param = list(param)
179 | for c in CONSTANTS:
180 | if c in param:
181 | param.remove(c)
182 | constant_params.append(c)
183 |
184 | if constant_params:
185 | constants = self.constants(constant_params, request, kwargs)
186 | else:
187 | constants = ekd.from_source("empty")
188 |
189 | kwargs["param"] = param
190 |
191 | opendata = recenter(ekd.from_source("ecmwf-open-data", **kwargs))
192 | opendata = opendata + constants
193 | opendata = interpolate(opendata)
194 |
195 | # Fix grib2/eccodes bug
196 |
197 | opendata = FieldArray([NewMetadataField(f, levelist=None) for f in opendata])
198 |
199 | return self.check_sfc(opendata, request)
200 |
201 | def ml_load_source(self, **kwargs):
202 | interpolate = self._adjust(kwargs)
203 | kwargs["levtype"] = "ml"
204 | request = kwargs.copy()
205 |
206 | opendata = recenter(ekd.from_source("ecmwf-open-data", **kwargs))
207 | opendata = interpolate(opendata)
208 |
209 | return self.check_ml(opendata, request)
210 |
211 | def check_pl(self, ds, request):
212 | self._check(ds, "PL", request, "param", "levelist")
213 | return ds
214 |
215 | def check_sfc(self, ds, request):
216 | self._check(ds, "SFC", request, "param")
217 | return ds
218 |
219 | def check_ml(self, ds, request):
220 | self._check(ds, "ML", request, "param", "levelist")
221 | return ds
222 |
223 | def _check(self, ds, what, request, *keys):
224 |
225 | def _(p):
226 | if len(p) == 1:
227 | return p[0]
228 |
229 | expected = set()
230 | for p in itertools.product(*[request[key] for key in keys]):
231 | expected.add(p)
232 |
233 | found = set()
234 | for f in ds:
235 | found.add(tuple(f.metadata(key) for key in keys))
236 |
237 | missing = expected - found
238 | if missing:
239 | missing = [_(p) for p in missing]
240 | if len(missing) == 1:
241 | raise ValueError(f"The following {what} parameter '{missing[0]}' is not available in ECMWF open data")
242 | raise ValueError(f"The following {what} parameters {missing} are not available in ECMWF open data")
243 |
244 | extra = found - expected
245 | if extra:
246 | extra = [_(p) for p in extra]
247 | if len(extra) == 1:
248 | raise ValueError(f"Unexpected {what} parameter '{extra[0]}' from ECMWF open data")
249 | raise ValueError(f"Unexpected {what} parameters {extra} from ECMWF open data")
250 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/recenter.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | import earthkit.data as ekd
11 | import numpy as np
12 | import tqdm
13 | from earthkit.data.core.temporary import temp_file
14 |
15 | LOG = logging.getLogger(__name__)
16 |
17 | CHECKED = set()
18 |
19 |
20 | def _init_recenter(ds, f):
21 |
22 | # For now, we only support the 0.25x0.25 grid from OPENDATA (centered on the greenwich meridian)
23 |
24 | latitudeOfFirstGridPointInDegrees = f.metadata("latitudeOfFirstGridPointInDegrees")
25 | longitudeOfFirstGridPointInDegrees = f.metadata("longitudeOfFirstGridPointInDegrees")
26 | latitudeOfLastGridPointInDegrees = f.metadata("latitudeOfLastGridPointInDegrees")
27 | longitudeOfLastGridPointInDegrees = f.metadata("longitudeOfLastGridPointInDegrees")
28 | iDirectionIncrementInDegrees = f.metadata("iDirectionIncrementInDegrees")
29 | jDirectionIncrementInDegrees = f.metadata("jDirectionIncrementInDegrees")
30 | scanningMode = f.metadata("scanningMode")
31 | Ni = f.metadata("Ni")
32 | Nj = f.metadata("Nj")
33 |
34 | assert scanningMode == 0
35 | assert latitudeOfFirstGridPointInDegrees == 90
36 | assert longitudeOfFirstGridPointInDegrees == 180
37 | assert latitudeOfLastGridPointInDegrees == -90
38 | assert longitudeOfLastGridPointInDegrees == 179.75
39 | assert iDirectionIncrementInDegrees == 0.25
40 | assert jDirectionIncrementInDegrees == 0.25
41 |
42 | assert Ni == 1440
43 | assert Nj == 721
44 |
45 | shape = (Nj, Ni)
46 | roll = -Ni // 2
47 | axis = 1
48 |
49 | key = (
50 | latitudeOfFirstGridPointInDegrees,
51 | longitudeOfFirstGridPointInDegrees,
52 | latitudeOfLastGridPointInDegrees,
53 | longitudeOfLastGridPointInDegrees,
54 | iDirectionIncrementInDegrees,
55 | jDirectionIncrementInDegrees,
56 | Ni,
57 | Nj,
58 | )
59 |
60 | ############################
61 |
62 | if key not in CHECKED:
63 | lon = ekd.from_source("forcings", ds, param=["longitude"], date=f.metadata("date"))[0]
64 | assert np.all(np.roll(lon.to_numpy(), roll, axis=axis)[:, 0] == 0)
65 | CHECKED.add(key)
66 |
67 | return (shape, roll, axis, dict(longitudeOfFirstGridPointInDegrees=0, longitudeOfLastGridPointInDegrees=359.75))
68 |
69 |
70 | def recenter(ds):
71 |
72 | tmp = temp_file()
73 |
74 | out = ekd.new_grib_output(tmp.path)
75 |
76 | for f in tqdm.tqdm(ds, delay=0.5, desc="Recentering", leave=False):
77 |
78 | shape, roll, axis, metadata = _init_recenter(ds, f)
79 |
80 | data = f.to_numpy()
81 | assert data.shape == shape, (data.shape, shape)
82 |
83 | data = np.roll(data, roll, axis=axis)
84 |
85 | out.write(data, template=f, **metadata)
86 |
87 | out.close()
88 |
89 | result = ekd.from_source("file", tmp.path)
90 | result._tmp = tmp
91 |
92 | return result
93 |
--------------------------------------------------------------------------------
/src/ai_models/inputs/transform.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 |
10 | LOG = logging.getLogger(__name__)
11 |
12 |
13 | class WrappedField:
14 | def __init__(self, field):
15 | self._field = field
16 |
17 | def __getattr__(self, name):
18 | return getattr(self._field, name)
19 |
20 | def __repr__(self) -> str:
21 | return repr(self._field)
22 |
23 |
24 | class NewDataField(WrappedField):
25 | def __init__(self, field, data):
26 | super().__init__(field)
27 | self._data = data
28 | self.shape = data.shape
29 |
30 | def to_numpy(self, flatten=False, dtype=None, index=None):
31 | data = self._data
32 | if dtype is not None:
33 | data = data.astype(dtype)
34 | if flatten:
35 | data = data.flatten()
36 | if index is not None:
37 | data = data[index]
38 | return data
39 |
40 |
41 | class NewMetadataField(WrappedField):
42 | def __init__(self, field, **kwargs):
43 | super().__init__(field)
44 | self._metadata = kwargs
45 |
46 | def metadata(self, *args, **kwargs):
47 | if len(args) == 1 and args[0] in self._metadata:
48 | return self._metadata[args[0]]
49 | return self._field.metadata(*args, **kwargs)
50 |
--------------------------------------------------------------------------------
/src/ai_models/model.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import base64
9 | import datetime
10 | import json
11 | import logging
12 | import os
13 | import sys
14 | import time
15 | from collections import defaultdict
16 | from functools import cached_property
17 |
18 | import earthkit.data as ekd
19 | import entrypoints
20 | import numpy as np
21 | from earthkit.data.utils.humanize import seconds
22 | from multiurl import download
23 |
24 | from .checkpoint import peek
25 | from .inputs import get_input
26 | from .outputs import get_output
27 | from .stepper import Stepper
28 |
29 | LOG = logging.getLogger(__name__)
30 |
31 |
32 | class Timer:
33 | def __init__(self, title):
34 | self.title = title
35 | self.start = time.time()
36 |
37 | def __enter__(self):
38 | return self
39 |
40 | def __exit__(self, *args):
41 | elapsed = time.time() - self.start
42 | LOG.info("%s: %s.", self.title, seconds(elapsed))
43 |
44 |
45 | class ArchiveCollector:
46 | UNIQUE = {"date", "hdate", "time", "referenceDate", "type", "stream", "expver"}
47 |
48 | def __init__(self) -> None:
49 | self.expect = 0
50 | self.request = defaultdict(set)
51 |
52 | def add(self, field):
53 | self.expect += 1
54 | for k, v in field.items():
55 | self.request[k].add(str(v))
56 | if k in self.UNIQUE:
57 | if len(self.request[k]) > 1:
58 | raise ValueError(f"Field {field} has different values for {k}: {self.request[k]}")
59 |
60 |
61 | class Model:
62 | lagged = False
63 | assets_extra_dir = None
64 | retrieve = {} # Extra parameters for retrieve
65 | version = 1 # To be overriden in subclasses
66 | grib_edition = 2 # Default GRIB edition
67 | grib_extra_metadata = {} # Extra metadata for grib files
68 |
69 | param_level_ml = ([], []) # param, level
70 | param_level_pl = ([], []) # param, level
71 | param_sfc = [] # param
72 |
73 | def __init__(self, input, output, download_assets, **kwargs):
74 | self.input = get_input(input, self, **kwargs)
75 | self.output = get_output(output, self, **kwargs)
76 |
77 | for k, v in kwargs.items():
78 | setattr(self, k, v)
79 |
80 | # We need to call it to initialise the default args
81 | args = self.parse_model_args(self.model_args)
82 | if args:
83 | for k, v in vars(args).items():
84 | setattr(self, k, v)
85 |
86 | if self.assets_sub_directory:
87 | if self.assets_extra_dir is not None:
88 | self.assets += self.assets_extra_dir
89 |
90 | LOG.debug("Asset directory is %s", self.assets)
91 |
92 | try:
93 | self.date = int(self.date)
94 | except ValueError:
95 | pass
96 |
97 | if download_assets:
98 | self.download_assets(**kwargs)
99 |
100 | self.archiving = defaultdict(ArchiveCollector)
101 | self.created = time.time()
102 |
103 | @cached_property
104 | def fields_pl(self):
105 | return self.input.fields_pl
106 |
107 | @cached_property
108 | def fields_ml(self):
109 | return self.input.fields_ml
110 |
111 | @cached_property
112 | def fields_sfc(self):
113 | return self.input.fields_sfc
114 |
115 | @cached_property
116 | def all_fields(self):
117 | return self.input.all_fields
118 |
119 | def write(self, *args, **kwargs):
120 | self.collect_archive_requests(
121 | self.output.write(*args, **kwargs, **self.grib_extra_metadata),
122 | )
123 |
124 | def collect_archive_requests(self, written):
125 | if self.archive_requests:
126 | handle, path = written
127 | if self.hindcast_reference_year or self.hindcast_reference_date:
128 | # The clone is necessary because the handle
129 | # does not return always return recently set keys
130 | handle = handle.clone()
131 |
132 | self.archiving[path].add(handle.as_namespace("mars"))
133 |
134 | def finalise(self):
135 | self.output.flush()
136 |
137 | if self.archive_requests:
138 | with open(self.archive_requests, "w") as f:
139 | json_requests = []
140 |
141 | for path, archive in self.archiving.items():
142 | request = dict(expect=archive.expect)
143 | if path is not None:
144 | request["source"] = f'"{path}"'
145 | request.update(archive.request)
146 | request.update(self._requests_extra)
147 |
148 | if self.json:
149 | json_requests.append(request)
150 | else:
151 | self._print_request("archive", request, file=f)
152 |
153 | if json_requests:
154 |
155 | def json_default(obj):
156 | if isinstance(obj, set):
157 | if len(obj) > 1:
158 | return sorted(list(obj))
159 | else:
160 | return obj.pop()
161 | raise TypeError
162 |
163 | print(
164 | json.dumps(json_requests, separators=(",", ":"), default=json_default, sort_keys=True),
165 | file=f,
166 | )
167 |
168 | def download_assets(self, **kwargs):
169 | for file in self.download_files:
170 | asset = os.path.realpath(os.path.join(self.assets, file))
171 | if not os.path.exists(asset):
172 | os.makedirs(os.path.dirname(asset), exist_ok=True)
173 | LOG.info("Downloading %s", asset)
174 | download(self.download_url.format(file=file), asset + ".download")
175 | os.rename(asset + ".download", asset)
176 |
177 | @property
178 | def asset_files(self, **kwargs):
179 | result = []
180 | for file in self.download_files:
181 | result.append(os.path.realpath(os.path.join(self.assets, file)))
182 | return result
183 |
184 | @cached_property
185 | def device(self):
186 | import torch
187 |
188 | device = "cpu"
189 |
190 | if torch.backends.mps.is_available() and torch.backends.mps.is_built():
191 | device = "mps"
192 |
193 | if torch.cuda.is_available() and torch.backends.cuda.is_built():
194 | device = "cuda"
195 |
196 | LOG.info(
197 | "Using device '%s'. The speed of inference depends greatly on the device.",
198 | device.upper(),
199 | )
200 |
201 | if self.only_gpu:
202 | if device == "cpu":
203 | raise RuntimeError("GPU is not available")
204 |
205 | return device
206 |
207 | def torch_deterministic_mode(self):
208 | import torch
209 |
210 | LOG.info("Setting deterministic mode for PyTorch")
211 | os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
212 |
213 | torch.backends.cudnn.benchmark = False
214 | torch.backends.cudnn.deterministic = True
215 | torch.use_deterministic_algorithms(True)
216 |
217 | @cached_property
218 | def providers(self):
219 | import onnxruntime as ort
220 |
221 | available_providers = ort.get_available_providers()
222 | providers = []
223 | for n in ["CUDAExecutionProvider", "CPUExecutionProvider"]:
224 | if n in available_providers:
225 | providers.append(n)
226 |
227 | LOG.info(
228 | "Using device '%s'. The speed of inference depends greatly on the device.",
229 | ort.get_device(),
230 | )
231 |
232 | if self.only_gpu:
233 | assert isinstance(ort.get_device(), str)
234 | if ort.get_device() == "CPU":
235 | raise RuntimeError("GPU is not available")
236 |
237 | providers = ["CUDAExecutionProvider"]
238 |
239 | LOG.info("ONNXRuntime providers: %s", providers)
240 |
241 | return providers
242 |
243 | def timer(self, title):
244 | return Timer(title)
245 |
246 | def stepper(self, step):
247 | # We assume that we call this method only once
248 | # just before the first iteration.
249 | elapsed = time.time() - self.created
250 | LOG.info("Model initialisation: %s", seconds(elapsed))
251 | return Stepper(step, self.lead_time)
252 |
253 | def _datetimes(self, dates):
254 | date = self.date
255 | assert isinstance(date, int)
256 | if date <= 0:
257 | date = datetime.datetime.utcnow() + datetime.timedelta(days=date)
258 | date = date.year * 10000 + date.month * 100 + date.day
259 |
260 | time = self.time
261 | assert isinstance(time, int)
262 | if time < 100:
263 | time *= 100
264 | # assert time in (0, 600, 1200, 1800), time
265 |
266 | lagged = self.lagged
267 | if not lagged:
268 | lagged = [0]
269 |
270 | result = []
271 | for basedate in dates:
272 | for lag in lagged:
273 | date = basedate + datetime.timedelta(hours=lag)
274 | result.append(
275 | (
276 | date.year * 10000 + date.month * 100 + date.day,
277 | date.hour,
278 | ),
279 | )
280 |
281 | return result
282 |
283 | def datetimes(self, step=0):
284 | if self.staging_dates:
285 | assert step == 0, step
286 | dates = []
287 | with open(self.staging_dates) as f:
288 | for line in f:
289 | dates.append(datetime.datetime.fromisoformat(line.strip()))
290 |
291 | return self._datetimes(dates)
292 |
293 | date = self.date
294 | assert isinstance(date, int)
295 | if date <= 0:
296 | date = datetime.datetime.utcnow() + datetime.timedelta(days=date)
297 | date = date.year * 10000 + date.month * 100 + date.day
298 |
299 | time = self.time
300 | assert isinstance(time, int)
301 | if time < 100:
302 | time *= 100
303 |
304 | # assert time in (0, 600, 1200, 1800), time
305 |
306 | full = datetime.datetime(
307 | date // 10000,
308 | date % 10000 // 100,
309 | date % 100,
310 | time // 100,
311 | time % 100,
312 | ) + datetime.timedelta(hours=step)
313 | return self._datetimes([full])
314 |
315 | def print_fields(self):
316 | param, level = self.param_level_pl
317 | print("Grid:", self.grid)
318 | print("Area:", self.area)
319 | print("Pressure levels:")
320 | print(" Levels:", level)
321 | print(" Params:", param)
322 | print("Single levels:")
323 | print(" Params:", self.param_sfc)
324 |
325 | def print_assets_list(self):
326 | for file in self.download_files:
327 | print(file)
328 |
329 | def _print_request(self, verb, request, file=sys.stdout):
330 | r = [verb]
331 | for k, v in sorted(request.items()):
332 | if not isinstance(v, (list, tuple, set)):
333 | v = [v]
334 |
335 | if k in ("area", "grid", "frame", "rotation", "bitmap"):
336 | v = [str(_) for _ in v]
337 | else:
338 | v = [str(_) for _ in sorted(v)]
339 |
340 | v = "/".join(v)
341 | r.append(f"{k}={v}")
342 |
343 | r = ",\n ".join(r)
344 | print(r, file=file)
345 | print(file=file)
346 |
347 | @property
348 | def _requests_extra(self):
349 | if not self.requests_extra:
350 | return {}
351 | extra = [_.split("=") for _ in self.requests_extra.split(",")]
352 | extra = {a: b for a, b in extra}
353 | return extra
354 |
355 | def print_requests(self):
356 | requests = self._requests()
357 |
358 | if self.json:
359 | print(json.dumps(requests, indent=4))
360 | return
361 |
362 | for r in requests:
363 | self._print_request("retrieve", r)
364 |
365 | def _requests_unfiltered(self):
366 | result = []
367 |
368 | first = dict(
369 | target="input.grib",
370 | grid=self.grid,
371 | area=self.area,
372 | )
373 | first.update(self.retrieve)
374 |
375 | for date, time in self.datetimes(): # noqa F402
376 | param, level = self.param_level_pl
377 |
378 | r = dict(
379 | date=date,
380 | time=time,
381 | )
382 | r.update(first)
383 | first = {}
384 |
385 | if param and level:
386 |
387 | # PL
388 | r.update(
389 | dict(
390 | levtype="pl",
391 | levelist=level,
392 | param=param,
393 | date=date,
394 | time=time,
395 | )
396 | )
397 |
398 | r.update(self._requests_extra)
399 |
400 | self.patch_retrieve_request(r)
401 |
402 | result.append(dict(**r))
403 |
404 | # ML
405 | param, level = self.param_level_ml
406 |
407 | if param and level:
408 | r.update(
409 | dict(
410 | levtype="ml",
411 | levelist=level,
412 | param=param,
413 | date=date,
414 | time=time,
415 | )
416 | )
417 |
418 | r.update(self._requests_extra)
419 |
420 | self.patch_retrieve_request(r)
421 |
422 | result.append(dict(**r))
423 |
424 | param = self.param_sfc
425 | if param:
426 | # SFC
427 | r.update(
428 | dict(
429 | levtype="sfc",
430 | param=self.param_sfc,
431 | date=date,
432 | time=time,
433 | levelist="off",
434 | )
435 | )
436 |
437 | self.patch_retrieve_request(r)
438 | result.append(dict(**r))
439 |
440 | return result
441 |
442 | def _requests(self):
443 |
444 | def filter_constant(request):
445 | # We check for 'sfc' because param 'z' can be ambiguous
446 | if request.get("levtype") == "sfc":
447 | param = set(self.constant_fields) & set(request.get("param", []))
448 | if param:
449 | request["param"] = list(param)
450 | return True
451 |
452 | return False
453 |
454 | def filter_prognostic(request):
455 | # TODO: We assume here that prognostic fields are
456 | # the ones that are not constant. This may not always be true
457 | if request.get("levtype") == "sfc":
458 | param = set(request.get("param", [])) - set(self.constant_fields)
459 | if param:
460 | request["param"] = list(param)
461 | return True
462 | return False
463 |
464 | return True
465 |
466 | def filter_last_date(request):
467 | date, time = max(self.datetimes())
468 | return request["date"] == date and request["time"] == time
469 |
470 | def noop(request):
471 | return request
472 |
473 | filter_type = {
474 | "constants": filter_constant,
475 | "prognostics": filter_prognostic,
476 | "all": noop,
477 | }[self.retrieve_fields_type]
478 |
479 | filter_dates = {
480 | True: filter_last_date,
481 | False: noop,
482 | }[self.retrieve_only_one_date]
483 |
484 | result = []
485 | for r in self._requests_unfiltered():
486 | if filter_type(r) and filter_dates(r):
487 | result.append(r)
488 |
489 | return result
490 |
491 | def patch_retrieve_request(self, request):
492 | # Overriden in subclasses if needed
493 | pass
494 |
495 | def peek_into_checkpoint(self, path):
496 | return peek(path)
497 |
498 | def parse_model_args(self, args):
499 | if args:
500 | raise NotImplementedError(f"This model does not accept arguments {args}")
501 |
502 | def provenance(self):
503 | from .provenance import gather_provenance_info
504 |
505 | return gather_provenance_info(self.asset_files)
506 |
507 | def forcing_and_constants(self, date, param):
508 | source = self.all_fields[:1]
509 |
510 | ds = ekd.from_source(
511 | "forcings",
512 | source,
513 | date=date,
514 | param=param,
515 | )
516 |
517 | assert len(ds) == len(param), (len(ds), len(param), date)
518 |
519 | return ds.to_numpy(dtype=np.float32)
520 |
521 | @cached_property
522 | def gridpoints(self):
523 | return len(self.all_fields[0].grid_points()[0])
524 |
525 | @cached_property
526 | def start_datetime(self):
527 | return self.all_fields.order_by(valid_datetime="ascending")[-1].datetime()["valid_time"]
528 |
529 | @property
530 | def constant_fields(self):
531 | raise NotImplementedError("constant_fields")
532 |
533 | def write_input_fields(
534 | self,
535 | fields,
536 | accumulations=None,
537 | accumulations_template=None,
538 | accumulations_shape=None,
539 | ignore=None,
540 | ):
541 | LOG.info("Starting date is %s", self.start_datetime)
542 | LOG.info("Writing input fields")
543 | if ignore is None:
544 | ignore = []
545 |
546 | with self.timer("Writing step 0"):
547 | for field in fields:
548 | if field.metadata("shortName") in ignore:
549 | continue
550 |
551 | if field.datetime()["valid_time"] == self.start_datetime:
552 | self.write(
553 | None,
554 | template=field,
555 | step=0,
556 | )
557 |
558 | if accumulations is not None:
559 | if accumulations_template is None:
560 | accumulations_template = fields.sel(param="msl")[0]
561 |
562 | if accumulations_shape is None:
563 | accumulations_shape = accumulations_template.shape
564 |
565 | if accumulations_template.metadata("edition") == 1:
566 | for param in accumulations:
567 |
568 | self.write(
569 | np.zeros(accumulations_shape, dtype=np.float32),
570 | stepType="accum",
571 | template=accumulations_template,
572 | param=param,
573 | startStep=0,
574 | endStep=0,
575 | date=int(self.start_datetime.strftime("%Y%m%d")),
576 | time=int(self.start_datetime.strftime("%H%M")),
577 | check=True,
578 | )
579 | else:
580 | # # TODO: Remove this when accumulations are supported for GRIB edition 2
581 |
582 | template = """
583 | R1JJQv//AAIAAAAAAAAA3AAAABUBAGIAABsBAQfoCRYGAAAAAQAAABECAAEAAQAJBAIwMDAxAAAA
584 | SAMAAA/XoAAAAAAG////////////////////AAAFoAAAAtEAAAAA/////wVdSoAAAAAAMIVdSoAV
585 | cVlwAAPQkAAD0JAAAAAAOgQAAAAIAcEC//8AAAABAAAAAAH//////////////wfoCRYGAAABAAAA
586 | AAECAQAAAAD/AAAAAAAAABUFAA/XoAAAAAAAAIAKAAAAAAAAAAYG/wAAAAUHNzc3N0dSSUL//wAC
587 | AAAAAAAAANwAAAAVAQBiAAAbAQEH6AkWDAAAAAEAAAARAgABAAEACQQBMDAwMQAAAEgDAAAP16AA
588 | AAAABv///////////////////wAABaAAAALRAAAAAP////8FXUqAAAAAADCFXUqAFXFZcAAD0JAA
589 | A9CQAAAAADoEAAAACAHBAv//AAAAAQAAAAAB//////////////8H6AkWDAAAAQAAAAABAgEAAAAA
590 | /wAAAAAAAAAVBQAP16AAAAAAAACACgAAAAAAAAAGBv8AAAAFBzc3Nzc=
591 | """
592 |
593 | template = base64.b64decode(template)
594 | accumulations_template = ekd.from_source("memory", template)[0]
595 |
596 | for param in accumulations:
597 | self.write(
598 | np.zeros(accumulations_shape, dtype=np.float32),
599 | stepType="accum",
600 | template=accumulations_template,
601 | param=param,
602 | startStep=0,
603 | endStep=0,
604 | date=int(self.start_datetime.strftime("%Y%m%d")),
605 | time=int(self.start_datetime.strftime("%H%M")),
606 | check=True,
607 | )
608 |
609 |
610 | def load_model(name, **kwargs):
611 | return available_models()[name].load()(**kwargs)
612 |
613 |
614 | def available_models():
615 | result = {}
616 | for e in entrypoints.get_group_all("ai_models.model"):
617 | result[e.name] = e
618 | return result
619 |
--------------------------------------------------------------------------------
/src/ai_models/outputs/__init__.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import itertools
9 | import logging
10 | import warnings
11 | from functools import cached_property
12 |
13 | import earthkit.data as ekd
14 | import entrypoints
15 | import numpy as np
16 |
17 | LOG = logging.getLogger(__name__)
18 |
19 |
20 | class Output:
21 | def write(self, *args, **kwargs):
22 | pass
23 |
24 | def flush(self, *args, **kwargs):
25 | pass
26 |
27 |
28 | class GribOutputBase(Output):
29 | def __init__(self, owner, path, metadata, **kwargs):
30 | self._first = True
31 | metadata.setdefault("stream", "oper")
32 | metadata.setdefault("expver", owner.expver)
33 | metadata.setdefault("class", "ml")
34 |
35 | self.path = path
36 | self.owner = owner
37 | self.metadata = metadata
38 |
39 | @cached_property
40 | def grib_keys(self):
41 | edition = self.metadata.pop("edition", self.owner.grib_edition)
42 |
43 | _grib_keys = dict(
44 | edition=edition,
45 | generatingProcessIdentifier=self.owner.version,
46 | )
47 | _grib_keys.update(self.metadata)
48 |
49 | return _grib_keys
50 |
51 | @cached_property
52 | def output(self):
53 | return ekd.new_grib_output(
54 | self.path,
55 | split_output=True,
56 | **self.grib_keys,
57 | )
58 |
59 | def write(self, data, *args, check=False, **kwargs):
60 |
61 | try:
62 | handle, path = self.output.write(data, *args, **kwargs)
63 |
64 | except Exception:
65 | if data is not None:
66 | if np.isnan(data).any():
67 | raise ValueError(f"NaN values found in field. args={args} kwargs={kwargs}")
68 | if np.isinf(data).any():
69 | raise ValueError(f"Infinite values found in field. args={args} kwargs={kwargs}")
70 |
71 | options = {}
72 | options.update(self.grib_keys)
73 | options.update(kwargs)
74 | LOG.error("Failed to write data to %s %s", args, options)
75 | cmd = []
76 | for k, v in options.items():
77 | if isinstance(v, (int, str, float)):
78 | cmd.append("%s=%s" % (k, v))
79 |
80 | LOG.error("grib_set -s%s", ",".join(cmd))
81 |
82 | raise
83 |
84 | if check:
85 | # Check that the GRIB keys are as expected
86 |
87 | if kwargs.get("expver") is None:
88 | ignore = ("template", "check_nans", "expver", "class", "type", "stream")
89 | else:
90 | ignore = ("template", "check_nans")
91 |
92 | for key, value in itertools.chain(self.grib_keys.items(), kwargs.items()):
93 | if key in ignore:
94 | continue
95 |
96 | # If "param" is a string, we what to compare it to the shortName
97 | if key == "param":
98 | try:
99 | float(value)
100 | except ValueError:
101 | key = "shortName"
102 |
103 | assert str(handle.get(key)) == str(value), (key, handle.get(key), value)
104 |
105 | return handle, path
106 |
107 |
108 | class FileOutput(GribOutputBase):
109 | def __init__(self, *args, **kwargs):
110 | super().__init__(*args, **kwargs)
111 | LOG.info("Writing results to %s", self.path)
112 |
113 |
114 | class NoneOutput(Output):
115 | def __init__(self, *args, **kwargs):
116 | LOG.info("Results will not be written.")
117 |
118 | def write(self, *args, **kwargs):
119 | pass
120 |
121 |
122 | class HindcastReLabel:
123 | def __init__(self, owner, output, hindcast_reference_year=None, hindcast_reference_date=None, **kwargs):
124 | self.owner = owner
125 | self.output = output
126 | self.hindcast_reference_year = int(hindcast_reference_year) if hindcast_reference_year else None
127 | self.hindcast_reference_date = int(hindcast_reference_date) if hindcast_reference_date else None
128 | assert self.hindcast_reference_year is not None or self.hindcast_reference_date is not None
129 |
130 | def write(self, *args, **kwargs):
131 | if "hdate" in kwargs:
132 | warnings.warn(f"Ignoring hdate='{kwargs['hdate']}' in HindcastReLabel", stacklevel=3)
133 | kwargs.pop("hdate")
134 |
135 | if "date" in kwargs:
136 | warnings.warn(f"Ignoring date='{kwargs['date']}' in HindcastReLabel", stacklevel=3)
137 | kwargs.pop("date")
138 |
139 | date = kwargs["template"]["date"]
140 | hdate = kwargs["template"]["hdate"]
141 |
142 | if hdate is not None:
143 | # Input was a hindcast
144 | referenceDate = (
145 | self.hindcast_reference_date
146 | if self.hindcast_reference_date is not None
147 | else self.hindcast_reference_year * 10000 + date % 10000
148 | )
149 | assert date == referenceDate, (
150 | date,
151 | referenceDate,
152 | hdate,
153 | kwargs["template"],
154 | )
155 | kwargs["referenceDate"] = referenceDate
156 | kwargs["hdate"] = hdate
157 | else:
158 | referenceDate = (
159 | self.hindcast_reference_date
160 | if self.hindcast_reference_date is not None
161 | else self.hindcast_reference_year * 10000 + date % 10000
162 | )
163 | kwargs["referenceDate"] = referenceDate
164 | kwargs["hdate"] = date
165 |
166 | kwargs.setdefault("check", True)
167 |
168 | return self.output.write(*args, **kwargs)
169 |
170 | def flush(self, *args, **kwargs):
171 | return self.output.flush(*args, **kwargs)
172 |
173 |
174 | class NoLabelling:
175 |
176 | def __init__(self, owner, output, **kwargs):
177 | self.owner = owner
178 | self.output = output
179 |
180 | def write(self, *args, **kwargs):
181 | kwargs["deleteLocalDefinition"] = 1
182 | return self.output.write(*args, **kwargs)
183 |
184 | def flush(self, *args, **kwargs):
185 | return self.output.flush(*args, **kwargs)
186 |
187 |
188 | def get_output(name, owner, *args, **kwargs):
189 | result = available_outputs()[name].load()(owner, *args, **kwargs)
190 | if kwargs.get("hindcast_reference_year") is not None or kwargs.get("hindcast_reference_date") is not None:
191 | result = HindcastReLabel(owner, result, **kwargs)
192 | if owner.expver is None:
193 | result = NoLabelling(owner, result, **kwargs)
194 | return result
195 |
196 |
197 | def available_outputs():
198 | result = {}
199 | for e in entrypoints.get_group_all("ai_models.output"):
200 | result[e.name] = e
201 | return result
202 |
--------------------------------------------------------------------------------
/src/ai_models/remote/__init__.py:
--------------------------------------------------------------------------------
1 | from .api import RemoteAPI
2 | from .model import RemoteModel
3 |
4 | __all__ = ["RemoteAPI", "RemoteModel"]
5 |
--------------------------------------------------------------------------------
/src/ai_models/remote/api.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import sys
4 | import time
5 | from urllib.parse import urljoin
6 |
7 | import requests
8 | from multiurl import download
9 | from multiurl import robust
10 | from tqdm import tqdm
11 |
12 | from .config import API_URL
13 | from .config import CONFIG_PATH
14 | from .config import load_config
15 |
16 | LOG = logging.getLogger(__name__)
17 |
18 |
19 | class BearerAuth(requests.auth.AuthBase):
20 | def __init__(self, token):
21 | self.token = token
22 |
23 | def __call__(self, r):
24 | r.headers["authorization"] = "Bearer " + self.token
25 | return r
26 |
27 |
28 | class RemoteAPI:
29 | def __init__(
30 | self,
31 | input_file: str = None,
32 | output_file: str = "output.grib",
33 | url: str = None,
34 | token: str = None,
35 | ):
36 | config = load_config()
37 |
38 | self.url = url or os.getenv("AI_MODELS_REMOTE_URL") or config.get("url") or API_URL
39 | if not self.url.endswith("/"):
40 | self.url += "/"
41 |
42 | self.token = token or os.getenv("AI_MODELS_REMOTE_TOKEN") or config.get("token")
43 |
44 | if not self.token:
45 | LOG.error(
46 | "Missing remote token. Set it in %s or env AI_MODELS_REMOTE_TOKEN",
47 | CONFIG_PATH,
48 | )
49 | sys.exit(1)
50 |
51 | LOG.info("Using remote server %s", self.url)
52 |
53 | self.auth = BearerAuth(self.token)
54 | self.output_file = output_file
55 | self.input_file = input_file
56 | self._timeout = 300
57 |
58 | def run(self, cfg: dict):
59 | # upload file
60 | with open(self.input_file, "rb") as file:
61 | LOG.info("Uploading input file to remote server")
62 | data = self._request(requests.post, "upload", data=file)
63 |
64 | if data["status"] != "success":
65 | LOG.error(data["status"])
66 | if reason := data.get("reason"):
67 | LOG.error(reason)
68 | sys.exit(1)
69 |
70 | # submit task
71 | data = self._request(requests.post, data["href"], json=cfg)
72 |
73 | LOG.info("Inference request submitted")
74 |
75 | if data["status"] != "queued":
76 | LOG.error(data["status"])
77 | if reason := data.get("reason"):
78 | LOG.error(reason)
79 | sys.exit(1)
80 |
81 | LOG.info("Request id: %s", data["id"])
82 | LOG.info("Request is queued")
83 |
84 | last_status = data["status"]
85 | pbar = None
86 |
87 | while True:
88 | data = self._request(requests.get, data["href"])
89 |
90 | if data["status"] == "ready":
91 | if pbar is not None:
92 | pbar.close()
93 | LOG.info("Request is ready")
94 | break
95 |
96 | if data["status"] == "failed":
97 | LOG.error("Request failed")
98 | if reason := data.get("reason"):
99 | LOG.error(reason)
100 | sys.exit(1)
101 |
102 | if data["status"] != last_status:
103 | LOG.info("Request is %s", data["status"])
104 | last_status = data["status"]
105 |
106 | if progress := data.get("progress"):
107 | if pbar is None:
108 | pbar = tqdm(
109 | total=progress.get("total", 0),
110 | unit="steps",
111 | ncols=70,
112 | leave=False,
113 | initial=1,
114 | bar_format="{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} {unit}{postfix}",
115 | )
116 | if eta := progress.get("eta"):
117 | pbar.set_postfix_str(f"ETA: {eta}")
118 | if status := progress.get("status"):
119 | pbar.set_description(status.strip().capitalize())
120 | pbar.update(progress.get("step", 0) - pbar.n)
121 |
122 | time.sleep(5)
123 |
124 | download(urljoin(self.url, data["href"]), target=self.output_file)
125 |
126 | LOG.debug("Result written to %s", self.output_file)
127 |
128 | def metadata(self, model, model_version, param) -> dict:
129 | if isinstance(param, str):
130 | return self._request(requests.get, f"metadata/{model}/{model_version}/{param}")
131 | elif isinstance(param, (list, dict)):
132 | return self._request(requests.post, f"metadata/{model}/{model_version}", json=param)
133 | else:
134 | raise ValueError("param must be a string, list, or dict with 'param' key.")
135 |
136 | def models(self):
137 | results = self._request(requests.get, "models")
138 |
139 | if not isinstance(results, list):
140 | return []
141 |
142 | return results
143 |
144 | def patch_retrieve_request(self, cfg, request):
145 | cfg["patchrequest"] = request
146 | result = self._request(requests.post, "patch", json=cfg)
147 | if status := result.get("status"):
148 | LOG.error(status)
149 | sys.exit(1)
150 | return result
151 |
152 | def _request(self, type, href, data=None, json=None, auth=None):
153 | response = robust(type, retry_after=30)(
154 | urljoin(self.url, href),
155 | json=json,
156 | data=data,
157 | auth=self.auth,
158 | timeout=self._timeout,
159 | )
160 |
161 | if response.status_code == 401:
162 | LOG.error("Unauthorized Access. Check your token.")
163 | sys.exit(1)
164 |
165 | try:
166 | data = response.json()
167 |
168 | if isinstance(data, dict) and (status := data.get("status")):
169 | data["status"] = status.lower()
170 |
171 | return data
172 | except Exception:
173 | return {"status": f"{response.url} {response.status_code} {response.text}"}
174 |
--------------------------------------------------------------------------------
/src/ai_models/remote/config.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 |
4 | API_URL = "https://ai-models.ecmwf.int/api/v1/"
5 |
6 | ROOT_PATH = os.path.join(os.path.expanduser("~"), ".config", "ai-models")
7 | CONFIG_PATH = os.path.join(ROOT_PATH, "api.yaml")
8 |
9 | LOG = logging.getLogger(__name__)
10 |
11 |
12 | def config_exists():
13 | return os.path.exists(CONFIG_PATH)
14 |
15 |
16 | def create_config():
17 | if config_exists():
18 | return
19 |
20 | try:
21 | os.makedirs(ROOT_PATH, exist_ok=True)
22 | with open(CONFIG_PATH, "w") as f:
23 | f.write("token: \n")
24 | f.write(f"url: {API_URL}\n")
25 | except Exception as e:
26 | LOG.error(f"Failed to create config {CONFIG_PATH}")
27 | LOG.error(e, exc_info=True)
28 |
29 |
30 | def load_config() -> dict:
31 | from yaml import safe_load
32 |
33 | if not config_exists():
34 | create_config()
35 |
36 | try:
37 | with open(CONFIG_PATH, "r") as f:
38 | return safe_load(f) or {}
39 | except Exception as e:
40 | LOG.error(f"Failed to read config {CONFIG_PATH}")
41 | LOG.error(e, exc_info=True)
42 | return {}
43 |
--------------------------------------------------------------------------------
/src/ai_models/remote/model.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import sys
4 | import tempfile
5 | from functools import cached_property
6 |
7 | import earthkit.data as ekd
8 |
9 | from ..model import Model
10 | from .api import RemoteAPI
11 |
12 | LOG = logging.getLogger(__name__)
13 |
14 |
15 | class RemoteModel(Model):
16 | def __init__(self, **kwargs):
17 | self.cfg = kwargs
18 | self.cfg["download_assets"] = False
19 |
20 | self.model = self.cfg["model"]
21 | self.model_version = self.cfg.get("model_version", "latest")
22 | self._param = {}
23 | self.api = RemoteAPI()
24 |
25 | if self.model not in self.api.models():
26 | LOG.error(f"Model '{self.model}' not available on remote server.")
27 | LOG.error("Rerun the command with --models --remote to list available remote models.")
28 | sys.exit(1)
29 |
30 | self.load_parameters()
31 |
32 | super().__init__(**self.cfg)
33 |
34 | def __getattr__(self, name):
35 | return self.get_parameter(name)
36 |
37 | def run(self):
38 | with tempfile.TemporaryDirectory() as tmpdirname:
39 | input_file = os.path.join(tmpdirname, "input.grib")
40 | output_file = os.path.join(tmpdirname, "output.grib")
41 | self.all_fields.save(input_file)
42 |
43 | self.api.input_file = input_file
44 | self.api.output_file = output_file
45 |
46 | self.api.run(self.cfg)
47 |
48 | ds = ekd.from_source("file", output_file)
49 | for field in ds:
50 | self.write(None, template=field)
51 |
52 | def parse_model_args(self, args):
53 | return None
54 |
55 | def patch_retrieve_request(self, request):
56 | if not self.remote_has_patch:
57 | return
58 |
59 | patched = self.api.patch_retrieve_request(self.cfg, request)
60 | request.update(patched)
61 |
62 | def load_parameters(self):
63 | params = self.api.metadata(
64 | self.model,
65 | self.model_version,
66 | [
67 | "expver",
68 | "version",
69 | "grid",
70 | "area",
71 | "param_level_ml",
72 | "param_level_pl",
73 | "param_sfc",
74 | "lagged",
75 | "grib_extra_metadata",
76 | "retrieve",
77 | "remote_has_patch", # custom parameter, checks if remote model need patches
78 | ],
79 | )
80 | self._param.update(params)
81 |
82 | def get_parameter(self, name):
83 | if (param := self._param.get(name)) is not None:
84 | return param
85 |
86 | _param = self.api.metadata(self.model, self.model_version, name)
87 | self._param.update(_param)
88 |
89 | return self._param.get(name)
90 |
91 | @cached_property
92 | def param_level_ml(self):
93 | return self.get_parameter("param_level_ml") or ([], [])
94 |
95 | @cached_property
96 | def param_level_pl(self):
97 | return self.get_parameter("param_level_pl") or ([], [])
98 |
99 | @cached_property
100 | def param_sfc(self):
101 | return self.get_parameter("param_sfc") or []
102 |
103 | @cached_property
104 | def lagged(self):
105 | return self.get_parameter("lagged") or False
106 |
107 | @cached_property
108 | def version(self):
109 | return self.get_parameter("version") or 1
110 |
111 | @cached_property
112 | def grib_extra_metadata(self):
113 | return self.get_parameter("grib_extra_metadata") or {}
114 |
115 | @cached_property
116 | def retrieve(self):
117 | return self.get_parameter("retrieve") or {}
118 |
--------------------------------------------------------------------------------
/src/ai_models/stepper.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 | import logging
9 | import time
10 |
11 | from earthkit.data.utils.humanize import seconds
12 |
13 | LOG = logging.getLogger(__name__)
14 |
15 |
16 | class Stepper:
17 | def __init__(self, step, lead_time):
18 | self.step = step
19 | self.lead_time = lead_time
20 | self.start = time.time()
21 | self.last = self.start
22 | self.num_steps = lead_time // step
23 | LOG.info("Starting inference for %s steps (%sh).", self.num_steps, lead_time)
24 |
25 | def __enter__(self):
26 | return self
27 |
28 | def __call__(self, i, step):
29 | now = time.time()
30 | elapsed = now - self.start
31 | speed = (i + 1) / elapsed
32 | eta = (self.num_steps - i) / speed
33 | LOG.info(
34 | "Done %s out of %s in %s (%sh), ETA: %s.",
35 | i + 1,
36 | self.num_steps,
37 | seconds(now - self.last),
38 | step,
39 | seconds(eta),
40 | )
41 | self.last = now
42 |
43 | def __exit__(self, *args):
44 | if self.num_steps == 0:
45 | return
46 |
47 | elapsed = time.time() - self.start
48 | LOG.info("Elapsed: %s.", seconds(elapsed))
49 | LOG.info("Average: %s per step.", seconds(elapsed / self.num_steps))
50 |
--------------------------------------------------------------------------------
/tests/requirements.txt:
--------------------------------------------------------------------------------
1 | # Empty for now
2 |
--------------------------------------------------------------------------------
/tests/test_code.py:
--------------------------------------------------------------------------------
1 | # (C) Copyright 2023 European Centre for Medium-Range Weather Forecasts.
2 | # This software is licensed under the terms of the Apache Licence Version 2.0
3 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 | # In applying this licence, ECMWF does not waive the privileges and immunities
5 | # granted to it by virtue of its status as an intergovernmental organisation
6 | # nor does it submit to any jurisdiction.
7 |
8 |
9 | def test_code():
10 | pass # Empty for now
11 |
--------------------------------------------------------------------------------