"src/vscode:/vscode.git/clone" did not exist on "0677e542115415c3a230f6d7225b679dbd6c92ee"
Commit ef746cfa authored by mashun1's avatar mashun1
Browse files

veros

parents
Pipeline #1302 canceled with stages
coverage:
ignore:
- "veros/_version.py"
codecov:
notify:
after_n_builds: 4
[run]
branch = True
source_pkgs =
veros
[report]
exclude_lines =
pragma: no cover
raise NotImplementedError
if __name__ == .__main__.:
omit =
veros/_version.py
veros/_version.py export-subst
version: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily
timezone: CET
open-pull-requests-limit: 10
name: Build documentation
on:
pull_request:
push:
branches:
- main
jobs:
build-docs:
name: Build documentation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
# make sure tags are fetched so we can get a version
- run: |
git fetch --prune --unshallow --tags
- name: Set up Python
uses: actions/setup-python@v2
with:
# make sure to use the same version as in .readthedocs.yml
python-version: "3.11"
- name: Install requirements
run: pip install -r doc/requirements.txt
- name: Build docs
run: make -C doc html SPHINXOPTS="-W --keep-going"
name: Upload release
on:
release:
types: [published]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
# make sure tags are fetched so we can get a version
- run: |
git fetch --prune --unshallow --tags
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install cython setuptools wheel twine
- name: Build sdist
run: |
python setup.py sdist
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
name: pre-commit
on:
pull_request:
push:
branches:
- main
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: pre-commit/action@v2.0.0
name: Tests
on:
pull_request:
push:
branches:
- main
jobs:
test:
name: Run tests
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
python-version: ["3.8", "3.12"]
backend: [numpy, jax]
env:
PYOM2_DIR: /home/runner/pyom2
PETSC_VERSION: "3.20.0"
PETSC_DIR: /home/runner/petsc
PETSC_ARCH: arch-linux-c-opt
OMPI_MCA_rmaps_base_oversubscribe: "1"
OMPI_MCA_mpi_yield_when_idle: "1"
VEROS_REQUIRE_CYTHON_EXT: "1"
steps:
- uses: actions/checkout@v2
# make sure tags are fetched so we can get a version
- run: git fetch --prune --unshallow --tags
- name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Restore pip cache
uses: actions/cache@v2
id: pip-cache
with:
path: ~/.cache/pip
key: ${{ matrix.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('**/requirements*.txt') }}
restore-keys: |
${{ matrix.os }}-pip-${{ matrix.python-version }}-
- name: Restore PyOM2 build cache
uses: actions/cache@v2
id: pyom2-cache
with:
path: ${{ env.PYOM2_DIR }}/py_src/*.so
key: ${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('vendor/pyom2/**/*') }}-${{ hashFiles('requirements.txt') }}
- name: Restore PETSc build cache
uses: actions/cache@v2
id: petsc-cache
with:
path: ${{ env.PETSC_DIR }}
key: ${{ matrix.os }}-${{ env.PETSC_VERSION }}
- name: Setup Python environment
run: |
python -m pip install --upgrade pip
pip install setuptools wheel
pip install cython
- name: Install system requirements
run: |
sudo apt-get update
sudo apt-get install libopenmpi-dev liblapack-dev libblas-dev
- name: Build PETSc
if: steps.petsc-cache.outputs.cache-hit != 'true'
run: |
git clone -b v$PETSC_VERSION --depth 1 https://gitlab.com/petsc/petsc.git $PETSC_DIR
pushd $PETSC_DIR
./configure --with-debugging=0 -with-shared-libraries --with-precision=double
make all
popd
- name: Install Veros
run: |
pip install mpi4py
if [ ${{ matrix.backend }} == "jax" ]
then
pip install mpi4jax
pip install -e .[test,jax]
else
pip install -e .[test]
fi
pip install petsc4py==$PETSC_VERSION --no-deps --no-build-isolation
# Build PyOM2 after Veros to make sure we have compatible versions of NumPy / f2py
- name: Build PyOM2
if: steps.pyom2-cache.outputs.cache-hit != 'true'
run: |
mkdir -p $PYOM2_DIR
cp -r vendor/pyom2/* $PYOM2_DIR
pushd $PYOM2_DIR
if [ ${{ matrix.python-version }} == "3.8" ]
then
mv pyOM2_site_specific_distutils site_specific.mk_
else
pip install meson ninja
mv pyOM2_site_specific_meson site_specific.mk_
fi
tar xzf pyOM2.1.0.tar.gz
git init
for patchfile in ./patches/*.patch; do
git apply --whitespace=fix $patchfile
done
make -C py_src -j 4
popd
- name: Export paths
run: |
echo "PYOM2_LIB=$(readlink -f $PYOM2_DIR/py_src/pyOM_code.*.so)" >> $GITHUB_ENV
echo "PYOM2_LIB_MPI=$(readlink -f $PYOM2_DIR/py_src/pyOM_code_MPI.*.so)" >> $GITHUB_ENV
- name: Run tests
run: |
pytest . -v --cov --pyom2-lib $PYOM2_LIB --backend ${{ matrix.backend }}
- name: Upload coverage
uses: codecov/codecov-action@v1
name: Test with Conda
on:
pull_request:
push:
branches:
- main
jobs:
test-conda:
name: Test conda env
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
defaults:
run:
shell: bash -l {0}
env:
# requests crashes on OSX without this
no_proxy: "*"
# issue with SciPy on Windows, see https://github.com/scipy/scipy/issues/14002
CONDA_DLL_SEARCH_MODIFICATION_ENABLE: "1"
steps:
- uses: actions/checkout@v2
- name: Cache conda
uses: actions/cache@v2
with:
path: ~/conda_pkgs_dir
key:
${{ runner.os }}-conda-${{hashFiles('conda-environment.yml') }}
- uses: conda-incubator/setup-miniconda@v3
with:
activate-environment: veros
environment-file: conda-environment.yml
use-only-tar-bz2: true
- name: Install test dependencies
run: |
pip install pytest
- name: List
run: |
conda info
conda list
- name: Run tests
run: pytest .
name: Test installation
on:
pull_request:
push:
branches:
- main
jobs:
test-install:
name: Test pip install
defaults:
run:
shell: bash {0}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: ["3.8", "3.12"]
nocc: [false]
include:
# also test whether installation without C compiler works
- os: ubuntu-latest
python-version: "3.8"
nocc: true
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install CUDA
if: runner.os == 'Linux' && matrix.nocc != 'true'
run: |
sudo apt-get update
sudo apt-get install nvidia-cuda-toolkit
- name: Test installing Veros
run: |
if ${{ matrix.nocc }}; then export CC=foobar; fi
python -m pip install .
- name: Build extensions
if: matrix.nocc != 'true'
run: |
export VEROS_REQUIRE_CYTHON_EXT=1
if [ ${{ runner.os }} = "Linux" ]; then
export VEROS_REQUIRE_CUDA_EXT=1
fi
pip install -U setuptools wheel cython
python setup.py build_ext --inplace
- name: Test whether Cython extensions are present
if: matrix.nocc != 'true'
run: |
if [ ${{ runner.os }} = "Windows" ]; then
test -f veros/core/special/tdma_cython_.*.pyd
else
test -f veros/core/special/tdma_cython_.*.so
fi
- name: Test whether CUDA extensions are present
if: runner.os == 'Linux' && matrix.nocc != 'true'
run: |
test -f veros/core/special/tdma_cuda_.*.so
# binary files
*.nc
*.h5
# documentation and profiler output
*.html
# benchmark output
benchmark_*.json
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.c
*.cpp
*.so
*.dll
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
.pytest_cache
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
doc/_build/
doc/_generated/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
# MacOS X file that stores custom attributes of its containing folder
.DS_Store
# VS Code
.vscode/
repos:
- repo: https://github.com/ambv/black
rev: 23.10.1
hooks:
- id: black
language_version: python3
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
args: ['--config=setup.cfg']
exclude: "
^$\
|versioneer\\.py\
|veros/_version.py\
|doc\
"
# .readthedocs.yml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
version: 2
sphinx:
builder: html
configuration: doc/conf.py
fail_on_warning: true
build:
os: ubuntu-22.04
tools:
python: "3.11"
python:
install:
- requirements: doc/requirements.txt
authors:
- family-names: Häfner
given-names: Dion
- family-names: Jacobsen
given-names: René Løwe
- family-names: Nuterman
given-names: Roman
- family-names: Jochum
given-names: Markus
cff-version: 1.2.0
message: "If you use this software, please cite the article from preferred-citation."
title: Veros
url: "https://github.com/team-ocean/veros"
preferred-citation:
type: article
title: "Veros v0.1 – a fast and versatile ocean simulator in pure Python"
authors:
- family-names: Häfner
given-names: Dion
- family-names: Jacobsen
given-names: René Løwe
- family-names: Eden
given-names: Carsten
- family-names: Kristensen
given-names: Mads R. B.
- family-names: Jochum
given-names: Markus
- family-names: Nuterman
given-names: Roman
- family-names: Vinter
given-names: Brian
year: 2018
journal: "Geoscientific Model Development"
volume: 11
issue: 8
pages: "3299-3312"
doi: "10.5194/gmd-11-3299-2018"
url: "https://gmd.copernicus.org/articles/11/3299/2018/"
MIT License
Copyright (c) 2018 Dion Häfner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
include README.md
include requirements.txt
include requirements_jax.txt
include cuda_ext.py
include versioneer.py
include veros/_version.py
global-include *.pyx
global-include *.pxd
global-include *.h
global-include *.cu
global-exclude *.c
# veros
## 论文
**Veros v0.1 – a fast and versatile ocean simulator in pure Python**
* https://gmd.copernicus.org/articles/11/3299/2018/
## 环境配置
### Docker(方法一)
docker pull image.sourcefind.cn:5000/dcu/admin/base/jax:0.4.23-ubuntu20.04-dtk24.04.1-py3.10
docker run --shm-size 10g --network=host --name=veros --privileged --device=/dev/kfd --device=/dev/dri --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v 项目地址(绝对路径):/home/ -v /opt/hyhal:/opt/hyhal:ro -it <your IMAGE ID> bash
pip install -r requirements.txt
python setup.py develop
### Dockerfile(方法二)
docker build -t <IMAGE_NAME>:<TAG> .
docker run --shm-size 10g --network=host --name=idmvton --privileged --device=/dev/kfd --device=/dev/dri --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v 项目地址(绝对路径):/home/ -v /opt/hyhal:/opt/hyhal:ro -it <your IMAGE ID> bash
python setup.py develop
### Anaconda (方法三)
1、关于本项目DCU显卡所需的特殊深度学习库可从光合开发者社区下载安装:
https://developer.hpccube.com/tool/
DTK驱动:dtk24.04
python:python3.10
jax: 0.4.23
Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应
2、其它非特殊库参照requirements.txt安装
pip install -r requirements.txt
python setup.py develop
## 数据集
## 推理
### 快速应用
# 以下是两个基本使用方法,可以查看`veros/setups`中的文件并对命令行进行相应的修改
veros copy-setup acc
veros run acc/acc.py -b jax --device gpu --float-type float32
veros copy-setup global_4deg
veros run global_4deg/global_4deg.py -b jax --device gpu --float-type float32
注意:更多使用方法参考`https://veros.readthedocs.io/en/latest/introduction/introduction.html`
### benchmark
cd benchmarks
python acc_benchmark.py --timesteps 100 --size 30 42 15 -b jax --device gpu --float-type float32
python isoneutral_benchmark.py --timesteps 100 --size 30 42 15 -b jax --device gpu --float-type float32
python pressure_solver_benchmark.py --timesteps 100 --size 30 42 15 -b jax --device gpu --float-type float32
python streamfunction_solver_benchmark.py --timesteps 100 --size 30 42 15 -b jax --device gpu --float-type float32
python tdma_benchmark.py --timesteps 100 --size 30 42 15 -b jax --device gpu --float-type float32
### 数据分析
analyze.ipynb
注意:需要启动`jupyter`运行该程序。
## result
||psi|salt|temp|vsf_depth|
|:---:|:---:|:---:|:---:|:---:|
|K100_AI|![alt text](readme_imgs/image.png)|![alt text](readme_imgs/image-3.png)|![alt text](readme_imgs/image-5.png)|![alt text](readme_imgs/image-7.png)|
|均值/方差|11.8371/26.338|35.00005/0.00026633|8.96047/4.736734|-0.18298379/3.6047194|
|A800|![alt text](readme_imgs/image-1.png)|![alt text](readme_imgs/image-4.png)|![alt text](readme_imgs/image-6.png)|![alt text](readme_imgs/image-8.png)|
|均值/方差|11.838/26.3398|34.99996/0.0003391|8.960432/4.7367105|-0.1834556/3.602966|
### 精度
## 应用场景
`海洋模拟`
### 热点应用行业
`气象,能源,海洋`
## 源码仓库及问题反馈
* https://developer.hpccube.com/codes/modelzoo/veros_jax
## 参考资料
* https://github.com/team-ocean/veros
<p align="center">
<img src="doc/_images/veros-logo-400px.png?raw=true">
</p>
<p align="center">
<i>Versatile Ocean Simulation in Pure Python</i>
</p>
<p align="center">
<a href="http://veros.readthedocs.io/?badge=latest">
<img src="https://readthedocs.org/projects/veros/badge/?version=latest" alt="Documentation status">
</a>
<a href="https://github.com/team-ocean/veros/actions/workflows/test-all.yml">
<img src="https://github.com/team-ocean/veros/actions/workflows/test-all.yml/badge.svg" alt="Test status">
</a>
<a href="https://codecov.io/gh/team-ocean/veros">
<img src="https://codecov.io/gh/team-ocean/veros/branch/main/graph/badge.svg" alt="Code Coverage">
</a>
<a href="https://zenodo.org/badge/latestdoi/87419383">
<img src="https://zenodo.org/badge/87419383.svg" alt="DOI">
</a>
</p>
Veros, *the versatile ocean simulator*, aims to be the swiss army knife of ocean modeling. It is a full-fledged primitive equation ocean model that supports anything between idealized toy models and [realistic, high-resolution, global ocean simulations](https://agupubs.onlinelibrary.wiley.com/doi/10.1029/2021MS002717). And because Veros is written in pure Python, the days of struggling with complicated model setup workflows, ancient programming environments, and obscure legacy code are finally over.
*In a nutshell, we want to enable high-performance ocean modelling with a clear focus on flexibility and usability.*
Veros supports a NumPy backend for small-scale problems, and a
high-performance [JAX](https://github.com/google/jax) backend
with CPU and GPU support. It is fully parallelized via MPI and supports
distributed execution on any number of nodes, including multi-GPU architectures (see also [our benchmarks](https://veros.readthedocs.io/en/latest/more/benchmarks.html)).
The dynamical core of Veros is based on [pyOM2](https://wiki.cen.uni-hamburg.de/ifm/TO/pyOM2), an ocean model with a Fortran backend and Fortran and Python frontends.
To learn more about Veros, make sure to [visit our documentation](https://veros.readthedocs.io/en/latest/).
#### How about a demonstration?
<p align="center">
<a href="https://vimeo.com/391237951">
<img src="doc/_images/veros-preview.gif?raw=true" alt="0.25×0.25° high-resolution model spin-up">
</a>
</p>
<p align="center">
(0.25×0.25° high-resolution model spin-up, click for better
quality)
</p>
## Features
Veros provides
- a fully staggered **3-D grid geometry** (*C-grid*)
- support for both **idealized and realistic configurations** in
Cartesian or pseudo-spherical coordinates
- several **friction and advection schemes**
- isoneutral mixing, eddy-kinetic energy, turbulent kinetic energy,
and internal wave energy **parameterizations**
- several **pre-implemented diagnostics** such as energy fluxes,
variable time averages, and a vertical overturning stream function
(written to netCDF4 output)
- **pre-configured idealized and realistic set-ups** that are ready to
run and easy to adapt
- **accessibility and extensibility** - thanks to the
power of Python!
## Veros for the impatient
A minimal example to install and run Veros:
```bash
$ pip install veros
$ veros copy-setup acc --to /tmp/acc
$ veros run /tmp/acc/acc.py
```
For more detailed installation instructions, have a look at [our
documentation](https://veros.readthedocs.io).
## Basic usage
To run Veros, you need to set up a model --- i.e., specify which settings
and model domain you want to use. This is done by subclassing the
`VerosSetup` base class in a *setup script* that is written in Python. You
should use the `veros copy-setup` command to copy one into your current
folder. A good place to start is the
[ACC model](https://github.com/team-ocean/veros/blob/main/veros/setups/acc/acc.py):
```bash
$ veros copy-setup acc
```
After setting up your model, all you need to do is call the `setup` and
`run` methods on your setup class. The pre-implemented setups can all be
executed via `veros run`:
```bash
$ veros run acc.py
```
For more information on using Veros, have a look at [our
documentation](http://veros.readthedocs.io).
## Contributing
Contributions to Veros are always welcome, no matter if you spotted an
inaccuracy in [the documentation](https://veros.readthedocs.io), wrote a
new setup, fixed a bug, or even extended Veros\' core mechanics. There
are 2 ways to contribute:
1. If you want to report a bug or request a missing feature, please
[open an issue](https://github.com/team-ocean/veros/issues). If you
are reporting a bug, make sure to include all relevant information
for reproducing it (ideally through a *minimal* code sample).
2. If you want to fix the issue yourself, or wrote an extension for
Veros - great! You are welcome to submit your code for review by
committing it to a repository and opening a [pull
request](https://github.com/team-ocean/veros/pulls). However,
before you do so, please check [the contribution
guide](http://veros.readthedocs.io/quickstart/get-started.html#enhancing-veros)
for some tips on testing and benchmarking, and to make sure that
your modifications adhere with our style policies. Most importantly,
please ensure that you follow the [PEP8
guidelines](https://www.python.org/dev/peps/pep-0008/), use
*meaningful* variable names, and document your code using
[Google-style
docstrings](http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html).
## How to cite
If you use Veros in scientific work, please consider citing [the following publication](https://gmd.copernicus.org/articles/11/3299/2018/):
```bibtex
@article{hafner_veros_2018,
title = {Veros v0.1 – a fast and versatile ocean simulator in pure {Python}},
volume = {11},
issn = {1991-959X},
url = {https://gmd.copernicus.org/articles/11/3299/2018/},
doi = {10.5194/gmd-11-3299-2018},
number = {8},
journal = {Geoscientific Model Development},
author = {Häfner, Dion and Jacobsen, René Løwe and Eden, Carsten and Kristensen, Mads R. B. and Jochum, Markus and Nuterman, Roman and Vinter, Brian},
month = aug,
year = {2018},
pages = {3299--3312},
}
```
Or have a look at [our documentation](https://veros.readthedocs.io/en/latest/more/publications.html)
for more publications involving Veros.
#!/usr/bin/env python
"""
This Veros setup file was generated by
$ veros copy-setup acc
on 2024-07-02 12:17:23 UTC.
"""
__VEROS_VERSION__ = '1.5.1+79.gff396e1.dirty'
if __name__ == "__main__":
raise RuntimeError(
"Veros setups cannot be executed directly. "
f"Try `veros run {__file__}` instead."
)
# -- end of auto-generated header, original file below --
from veros import VerosSetup, veros_routine
from veros.variables import allocate, Variable
from veros.distributed import global_min, global_max
from veros.core.operators import numpy as npx, update, at
class ACCSetup(VerosSetup):
"""A model using spherical coordinates with a partially closed domain representing the Atlantic and ACC.
Wind forcing over the channel part and buoyancy relaxation drive a large-scale meridional overturning circulation.
This setup demonstrates:
- setting up an idealized geometry
- updating surface forcings
- basic usage of diagnostics
`Adapted from pyOM2 <https://wiki.cen.uni-hamburg.de/ifm/TO/pyOM2/ACC%202>`_.
"""
@veros_routine
def set_parameter(self, state):
settings = state.settings
settings.identifier = "acc"
settings.description = "My ACC setup"
settings.nx, settings.ny, settings.nz = 30, 42, 15
settings.dt_mom = 4800
settings.dt_tracer = 86400 / 2.0
settings.runlen = 86400 * 365
settings.x_origin = 0.0
settings.y_origin = -40.0
settings.coord_degree = True
settings.enable_cyclic_x = True
settings.enable_neutral_diffusion = True
settings.K_iso_0 = 1000.0
settings.K_iso_steep = 500.0
settings.iso_dslope = 0.005
settings.iso_slopec = 0.01
settings.enable_skew_diffusion = True
settings.enable_hor_friction = True
settings.A_h = (2 * settings.degtom) ** 3 * 2e-11
settings.enable_hor_friction_cos_scaling = True
settings.hor_friction_cosPower = 1
settings.enable_bottom_friction = True
settings.r_bot = 1e-5
settings.enable_implicit_vert_friction = True
settings.enable_tke = True
settings.c_k = 0.1
settings.c_eps = 0.7
settings.alpha_tke = 30.0
settings.mxl_min = 1e-8
settings.tke_mxl_choice = 2
settings.kappaM_min = 2e-4
settings.kappaH_min = 2e-5
settings.enable_kappaH_profile = True
settings.K_gm_0 = 1000.0
settings.enable_eke = True
settings.eke_k_max = 1e4
settings.eke_c_k = 0.4
settings.eke_c_eps = 0.5
settings.eke_cross = 2.0
settings.eke_crhin = 1.0
settings.eke_lmin = 100.0
settings.enable_eke_superbee_advection = True
settings.enable_eke_isopycnal_diffusion = True
settings.enable_idemix = False
settings.eq_of_state_type = 3
var_meta = state.var_meta
var_meta.update(
t_star=Variable("t_star", ("yt",), "deg C", "Reference surface temperature"),
t_rest=Variable("t_rest", ("xt", "yt"), "1/s", "Surface temperature restoring time scale"),
)
@veros_routine
def set_grid(self, state):
vs = state.variables
ddz = npx.array(
[50.0, 70.0, 100.0, 140.0, 190.0, 240.0, 290.0, 340.0, 390.0, 440.0, 490.0, 540.0, 590.0, 640.0, 690.0]
)
vs.dxt = update(vs.dxt, at[...], 2.0)
vs.dyt = update(vs.dyt, at[...], 2.0)
vs.dzt = update(vs.dzt, at[...], ddz[::-1] / 2.5)
@veros_routine
def set_coriolis(self, state):
vs = state.variables
settings = state.settings
vs.coriolis_t = update(
vs.coriolis_t, at[...], 2 * settings.omega * npx.sin(vs.yt[None, :] / 180.0 * settings.pi)
)
@veros_routine
def set_topography(self, state):
vs = state.variables
x, y = npx.meshgrid(vs.xt, vs.yt, indexing="ij")
vs.kbot = npx.logical_or(x > 1.0, y < -20).astype("int")
@veros_routine
def set_initial_conditions(self, state):
vs = state.variables
settings = state.settings
# initial conditions
vs.temp = update(vs.temp, at[...], ((1 - vs.zt[None, None, :] / vs.zw[0]) * 15 * vs.maskT)[..., None])
vs.salt = update(vs.salt, at[...], 35.0 * vs.maskT[..., None])
# wind stress forcing
yt_min = global_min(vs.yt.min())
yu_min = global_min(vs.yu.min())
yt_max = global_max(vs.yt.max())
yu_max = global_max(vs.yu.max())
taux = allocate(state.dimensions, ("yt",))
taux = npx.where(vs.yt < -20, 0.1 * npx.sin(settings.pi * (vs.yu - yu_min) / (-20.0 - yt_min)), taux)
taux = npx.where(vs.yt > 10, 0.1 * (1 - npx.cos(2 * settings.pi * (vs.yu - 10.0) / (yu_max - 10.0))), taux)
vs.surface_taux = taux * vs.maskU[:, :, -1]
# surface heatflux forcing
vs.t_star = allocate(state.dimensions, ("yt",), fill=15)
vs.t_star = npx.where(vs.yt < -20, 15 * (vs.yt - yt_min) / (-20 - yt_min), vs.t_star)
vs.t_star = npx.where(vs.yt > 20, 15 * (1 - (vs.yt - 20) / (yt_max - 20)), vs.t_star)
vs.t_rest = vs.dzt[npx.newaxis, -1] / (30.0 * 86400.0) * vs.maskT[:, :, -1]
if settings.enable_tke:
vs.forc_tke_surface = update(
vs.forc_tke_surface,
at[2:-2, 2:-2],
npx.sqrt(
(0.5 * (vs.surface_taux[2:-2, 2:-2] + vs.surface_taux[1:-3, 2:-2]) / settings.rho_0) ** 2
+ (0.5 * (vs.surface_tauy[2:-2, 2:-2] + vs.surface_tauy[2:-2, 1:-3]) / settings.rho_0) ** 2
)
** (1.5),
)
if settings.enable_idemix:
vs.forc_iw_bottom = 1e-6 * vs.maskW[:, :, -1]
vs.forc_iw_surface = 1e-7 * vs.maskW[:, :, -1]
@veros_routine
def set_forcing(self, state):
vs = state.variables
vs.forc_temp_surface = vs.t_rest * (vs.t_star - vs.temp[:, :, -1, vs.tau])
@veros_routine
def set_diagnostics(self, state):
settings = state.settings
diagnostics = state.diagnostics
diagnostics["snapshot"].output_frequency = 86400 * 10
diagnostics["averages"].output_variables = (
"salt",
"temp",
"u",
"v",
"w",
"psi",
"surface_taux",
"surface_tauy",
)
diagnostics["averages"].output_frequency = 365 * 86400.0
diagnostics["averages"].sampling_frequency = settings.dt_tracer * 10
diagnostics["overturning"].output_frequency = 365 * 86400.0 / 48.0
diagnostics["overturning"].sampling_frequency = settings.dt_tracer * 10
diagnostics["tracer_monitor"].output_frequency = 365 * 86400.0 / 12.0
diagnostics["energy"].output_frequency = 365 * 86400.0 / 48
diagnostics["energy"].sampling_frequency = settings.dt_tracer * 10
@veros_routine
def after_timestep(self, state):
pass
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import xarray as xr\n",
"import numpy as np\n",
"import cmocean"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"OUTPUT_FILES = {\n",
" \"snapshot\": \"acc.snapshot.nc\",\n",
" \"averages\": \"acc.averages.nc\",\n",
" \"overturning\": \"acc.overturning.nc\",\n",
" \"energy\": \"acc.energy.nc\",\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_avg = xr.open_dataset(OUTPUT_FILES[\"averages\"])\n",
"ds_avg"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_avg[\"psi\"] = ds_avg.psi / 1e6\n",
"ds_avg[\"psi\"].attrs[\"units\"] = \"Sv\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_avg[\"psi\"].isel(Time=-1).plot.contourf(levels=50, cmap=\"cmo.balance\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"(\n",
" ds_avg[\"salt\"]\n",
" .isel(Time=slice(-1,None))\n",
" .mean(dim=(\"Time\", \"xt\"))\n",
" .plot.contourf(levels=50, cmap=\"cmo.haline\")\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_snap = xr.open_dataset(OUTPUT_FILES[\"snapshot\"])\n",
"weights = ds_snap[\"area_t\"].fillna(0)\n",
"\n",
"temp_weighted = (\n",
" ds_avg[\"temp\"]\n",
" .isel(Time=-1)\n",
" .weighted(weights)\n",
" .mean(dim=\"yt\")\n",
" .plot.contourf(vmin=-2, vmax=22, levels=25, cmap=\"cmo.thermal\")\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_ovr = xr.open_dataset(OUTPUT_FILES[\"overturning\"])\n",
"\n",
"ds_ovr"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds_ovr[\"vsf_depth\"] = ds_ovr.vsf_depth / 1e6\n",
"\n",
"ds_ovr.vsf_depth.attrs[\"long_name\"] = \"MOC\"\n",
"\n",
"ds_ovr.vsf_depth.attrs[\"units\"] = \"Sv\"\n",
"\n",
"ds_ovr.vsf_depth.isel(Time=-1).plot.contourf(levels=50, cmap=\"cmo.balance\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment