├── data ├── 2019 │ └── .gitignore └── 2020 │ └── .gitignore ├── submission ├── 2019 │ └── .gitignore └── 2020 │ └── .gitignore ├── utils ├── cached_sample_ids │ └── .gitignore ├── evaluate.py ├── w4c_dataloader.py └── data_utils.py ├── images ├── weather4cast_v1000-26.png └── opera_satelite_context_explained.png ├── mk_baseline.sh ├── mk_env.sh ├── LICENSE ├── .gitignore ├── mk_pred_core_3boxi2019.sh ├── mk_pred_core.sh ├── mk_heldout_core.sh ├── mk_pred_transfer.sh ├── mk_heldout_transfer.sh ├── w4cNew.yml ├── models ├── configurations │ ├── config_baseline_stage1.yaml │ ├── config_baseline_stage2-pred.yaml │ └── config_baseline_stage2.yaml ├── unet.patch └── unet_lightning.py ├── train.py ├── w4c.yml ├── README.md └── COPYING /data/2019/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/2020/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /submission/2019/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /submission/2020/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/cached_sample_ids/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/weather4cast_v1000-26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iarai/weather4cast-2022/HEAD/images/weather4cast_v1000-26.png -------------------------------------------------------------------------------- /images/opera_satelite_context_explained.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iarai/weather4cast-2022/HEAD/images/opera_satelite_context_explained.png -------------------------------------------------------------------------------- /mk_baseline.sh: -------------------------------------------------------------------------------- 1 | cd models 2 | rm unet.py 2>/dev/null 3 | wget https://raw.githubusercontent.com/ELEKTRONN/elektronn3/f754796d861f1cfe1c19dfc7819087972573ce40/elektronn3/models/unet.py 4 | patch . 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Emacs backup files 2 | *~ 3 | 4 | #Local files to ignore 5 | *test.py 6 | *initial_eda.ipynb 7 | *old_data_utils.py 8 | *old_visualise.py 9 | *.pdf 10 | *.pkl 11 | split_generation_logs/ 12 | ./plots 13 | *.h5 14 | 15 | # large files 16 | tmp_w4c/ 17 | utils/*lightning_logs/ 18 | *lightning_logs/ 19 | 20 | # Byte-compiled / optimized / DLL files 21 | __pycache__ 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | pip-wheel-metadata/ 43 | share/python-wheels/ 44 | *.egg-info/ 45 | .installed.cfg 46 | *.egg 47 | MANIFEST 48 | 49 | # PyInstaller 50 | # Usually these files are written by a python script from a template 51 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 52 | *.manifest 53 | *.spec 54 | 55 | # Installer logs 56 | pip-log.txt 57 | pip-delete-this-directory.txt 58 | 59 | # Unit test / coverage reports 60 | htmlcov/ 61 | .tox/ 62 | .nox/ 63 | .coverage 64 | .coverage.* 65 | .cache 66 | nosetests.xml 67 | coverage.xml 68 | *.cover 69 | *.py,cover 70 | .hypothesis/ 71 | .pytest_cache/ 72 | 73 | # Translations 74 | *.mo 75 | *.pot 76 | 77 | # Django stuff: 78 | *.log 79 | local_settings.py 80 | db.sqlite3 81 | db.sqlite3-journal 82 | 83 | # Flask stuff: 84 | instance/ 85 | .webassets-cache 86 | 87 | # Scrapy stuff: 88 | .scrapy 89 | 90 | # Sphinx documentation 91 | docs/_build/ 92 | 93 | # PyBuilder 94 | target/ 95 | 96 | # Jupyter Notebook 97 | .ipynb_checkpoints 98 | 99 | # IPython 100 | profile_default/ 101 | ipython_config.py 102 | 103 | # pyenv 104 | .python-version 105 | 106 | # pipenv 107 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 108 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 109 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 110 | # install all needed dependencies. 111 | #Pipfile.lock 112 | 113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 114 | __pypackages__/ 115 | 116 | # Celery stuff 117 | celerybeat-schedule 118 | celerybeat.pid 119 | 120 | # SageMath parsed files 121 | *.sage.py 122 | 123 | # Environments 124 | .env 125 | .venv 126 | env/ 127 | venv/ 128 | ENV/ 129 | env.bak/ 130 | venv.bak/ 131 | 132 | # Spyder project settings 133 | .spyderproject 134 | .spyproject 135 | 136 | # Rope project settings 137 | .ropeproject 138 | 139 | # mkdocs documentation 140 | /site 141 | 142 | # mypy 143 | .mypy_cache/ 144 | .dmypy.json 145 | dmypy.json 146 | 147 | # Pyre type checker 148 | .pyre/ 149 | 150 | 151 | #vsc 152 | .vscode/ -------------------------------------------------------------------------------- /mk_pred_core_3boxi2019.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | cdir=models/configurations/; 4 | sdirDef=submission.3boxi2019; 5 | gpuDef=0; 6 | 7 | sdir=$sdirDef; 8 | gpu=$gpuDef; 9 | 10 | cbase="$1"; shift; 11 | cpt="$1"; shift; 12 | if [ -n "$1" ]; then 13 | sdir="$1"; shift; 14 | fi 15 | if [ -n "$1" ]; then 16 | gpu="$1"; shift; 17 | fi 18 | 19 | out=$sdir.zip; 20 | 21 | 22 | cat <"$cout"; 85 | python train.py --gpus $gpu --mode predict --config_path "$cnew" \ 86 | --checkpoint "$cpt" 87 | rm $cout; 88 | done 89 | done 90 | 91 | if pushd $sdir; then 92 | echo /=== output summary 93 | ls -l */* 94 | fl=`find -type f|grep -v '/[.]'|sed -e 's/ /%20/g'`; 95 | for f in $fl; do 96 | f="${f//%20/ }"; 97 | echo Compressing $f ... 98 | gzip -9f "$f" & 99 | done 100 | wait; 101 | echo ...zip packing $sdir 102 | [ -s "../$out" ] && rm -f "../$out"; 103 | zip -0mr ../$out * -x .\* \*/.\* 104 | popd 105 | rmdir $sdir; 106 | ls -l $out; 107 | else 108 | echo "Cannot change to $sdir - aborting" 109 | exit 110 | fi 111 | echo \\=== done 112 | -------------------------------------------------------------------------------- /mk_pred_core.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | cdir=models/configurations/; 4 | sdirDef=submission.core; 5 | gpuDef=0; 6 | 7 | sdir=$sdirDef; 8 | gpu=$gpuDef; 9 | 10 | cbase="$1"; shift; 11 | cpt="$1"; shift; 12 | if [ -n "$1" ]; then 13 | sdir="$1"; shift; 14 | fi 15 | if [ -n "$1" ]; then 16 | gpu="$1"; shift; 17 | fi 18 | 19 | out=$sdir.zip; 20 | 21 | 22 | cat <"$cout"; 86 | python train.py --gpus $gpu --mode predict --config_path "$cnew" \ 87 | --checkpoint "$cpt" 88 | rm $cout; 89 | done 90 | done 91 | 92 | if pushd $sdir; then 93 | echo /=== output summary 94 | ls -l */* 95 | fl=`find -type f|grep -v '/[.]'|sed -e 's/ /%20/g'`; 96 | for f in $fl; do 97 | f="${f//%20/ }"; 98 | echo Compressing $f ... 99 | gzip -9f "$f" & 100 | done 101 | wait; 102 | echo ...zip packing $sdir 103 | [ -s "../$out" ] && rm -f "../$out"; 104 | zip -0mr ../$out * -x .\* \*/.\* 105 | popd 106 | rmdir $sdir; 107 | ls -l $out; 108 | else 109 | echo "Cannot change to $sdir - aborting" 110 | exit 111 | fi 112 | echo \\=== done 113 | -------------------------------------------------------------------------------- /mk_heldout_core.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | cdir=models/configurations/; 4 | sdirDef=submission.heldout.core; 5 | gpuDef=0; 6 | 7 | sdir=$sdirDef; 8 | gpu=$gpuDef; 9 | 10 | cbase="$1"; shift; 11 | cpt="$1"; shift; 12 | if [ -n "$1" ]; then 13 | sdir="$1"; shift; 14 | fi 15 | if [ -n "$1" ]; then 16 | gpu="$1"; shift; 17 | fi 18 | 19 | out=$sdir.zip; 20 | 21 | 22 | cat <"$cout"; 86 | python train.py --gpus $gpu --mode heldout --config_path "$cnew" \ 87 | --checkpoint "$cpt" 88 | rm $cout; 89 | done 90 | done 91 | 92 | if pushd $sdir; then 93 | echo /=== output summary 94 | ls -l */* 95 | fl=`find -type f|grep -v '/[.]'|sed -e 's/ /%20/g'`; 96 | for f in $fl; do 97 | f="${f//%20/ }"; 98 | echo Compressing $f ... 99 | gzip -9f "$f" & 100 | done 101 | wait; 102 | echo ...zip packing $sdir 103 | [ -s "../$out" ] && rm -f "../$out"; 104 | zip -0mr ../$out * -x .\* \*/.\* 105 | popd 106 | rmdir $sdir; 107 | ls -l $out; 108 | else 109 | echo "Cannot change to $sdir - aborting" 110 | exit 111 | fi 112 | echo \\=== done 113 | -------------------------------------------------------------------------------- /mk_pred_transfer.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | cdir=models/configurations/; 4 | sdirDef=submission.transfer; 5 | gpuDef=0; 6 | 7 | sdir=$sdirDef; 8 | gpu=$gpuDef; 9 | 10 | cbase="$1"; shift; 11 | cpt="$1"; shift; 12 | if [ -n "$1" ]; then 13 | sdir="$1"; shift; 14 | fi 15 | if [ -n "$1" ]; then 16 | gpu="$1"; shift; 17 | fi 18 | 19 | out=$sdir.zip; 20 | 21 | 22 | cat <"$cout"; 85 | python train.py --gpus $gpu --mode predict --config_path "$cnew" \ 86 | --checkpoint "$cpt" 87 | rm $cout; 88 | done 89 | done 90 | for y in 2021; do 91 | d=$sdir/$y; 92 | [ -d "$d" ] || mkdir "$d"; 93 | for r in boxi_0015 boxi_0034 boxi_0076 \ 94 | roxi_0004 roxi_0005 roxi_0006 roxi_0007 \ 95 | roxi_0008 roxi_0009 roxi_0010; do 96 | echo /=== $r $y for $cpt 97 | cin=$cdir$cbase; 98 | cnew=${cbase%.yaml}-$$-$r-$y.yaml; 99 | cout=$cdir$cnew; 100 | sed -e "s/%REGION%/$r/g" -e "s/%YEAR%/$y/" -e "s/%SDIR%/$sdir/" \ 101 | <"$cin" >"$cout"; 102 | python train.py --gpus $gpu --mode predict --config_path "$cnew" \ 103 | --checkpoint "$cpt" 104 | rm $cout; 105 | done 106 | done 107 | 108 | if pushd $sdir; then 109 | echo /=== output summary 110 | ls -l */* 111 | fl=`find -type f|grep -v '/[.]'|sed -e 's/ /%20/g'`; 112 | for f in $fl; do 113 | f="${f//%20/ }"; 114 | echo Compressing $f ... 115 | gzip -9f "$f" & 116 | done 117 | wait; 118 | echo ...zip packing $sdir 119 | [ -s "../$out" ] && rm -f "../$out"; 120 | zip -0mr ../$out * -x .\* \*/.\* 121 | popd 122 | rmdir $sdir; 123 | ls -l $out; 124 | else 125 | echo "Cannot change to $sdir - aborting" 126 | exit 127 | fi 128 | echo \\=== done 129 | -------------------------------------------------------------------------------- /mk_heldout_transfer.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | 3 | cdir=models/configurations/; 4 | sdirDef=submission.heldout.transfer; 5 | gpuDef=0; 6 | 7 | sdir=$sdirDef; 8 | gpu=$gpuDef; 9 | 10 | cbase="$1"; shift; 11 | cpt="$1"; shift; 12 | if [ -n "$1" ]; then 13 | sdir="$1"; shift; 14 | fi 15 | if [ -n "$1" ]; then 16 | gpu="$1"; shift; 17 | fi 18 | 19 | out=$sdir.zip; 20 | 21 | 22 | cat <"$cout"; 85 | python train.py --gpus $gpu --mode heldout --config_path "$cnew" \ 86 | --checkpoint "$cpt" 87 | rm $cout; 88 | done 89 | done 90 | for y in 2021; do 91 | d=$sdir/$y; 92 | [ -d "$d" ] || mkdir "$d"; 93 | for r in boxi_0015 boxi_0034 boxi_0076 \ 94 | roxi_0004 roxi_0005 roxi_0006 roxi_0007 \ 95 | roxi_0008 roxi_0009 roxi_0010; do 96 | echo /=== $r $y for $cpt 97 | cin=$cdir$cbase; 98 | cnew=${cbase%.yaml}-$$-$r-$y.yaml; 99 | cout=$cdir$cnew; 100 | sed -e "s/%REGION%/$r/g" -e "s/%YEAR%/$y/" -e "s/%SDIR%/$sdir/" \ 101 | <"$cin" >"$cout"; 102 | python train.py --gpus $gpu --mode heldout --config_path "$cnew" \ 103 | --checkpoint "$cpt" 104 | rm $cout; 105 | done 106 | done 107 | 108 | if pushd $sdir; then 109 | echo /=== output summary 110 | ls -l */* 111 | fl=`find -type f|grep -v '/[.]'|sed -e 's/ /%20/g'`; 112 | for f in $fl; do 113 | f="${f//%20/ }"; 114 | echo Compressing $f ... 115 | gzip -9f "$f" & 116 | done 117 | wait; 118 | echo ...zip packing $sdir 119 | [ -s "../$out" ] && rm -f "../$out"; 120 | zip -0mr ../$out * -x .\* \*/.\* 121 | popd 122 | rmdir $sdir; 123 | ls -l $out; 124 | else 125 | echo "Cannot change to $sdir - aborting" 126 | exit 127 | fi 128 | echo \\=== done 129 | -------------------------------------------------------------------------------- /utils/evaluate.py: -------------------------------------------------------------------------------- 1 | # Weather4cast 2022 Starter Kit 2 | # 3 | # Copyright (C) 2022 4 | # Institute of Advanced Research in Artificial Intelligence (IARAI) 5 | 6 | # This file is part of the Weather4cast 2022 Starter Kit. 7 | # 8 | # The Weather4cast 2022 Starter Kit is free software: you can redistribute it 9 | # and/or modify it under the terms of the GNU General Public License as 10 | # published by the Free Software Foundation, either version 3 of the License, 11 | # or (at your option) any later version. 12 | # 13 | # The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 14 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 22 | 23 | 24 | from sklearn.metrics import confusion_matrix 25 | import numpy as np 26 | import torch as t 27 | import sys 28 | 29 | def get_confusion_matrix(y_true, y_pred): 30 | """get confusion matrix from y_true and y_pred 31 | 32 | Args: 33 | y_true (numpy array): ground truth 34 | y_pred (numpy array): prediction 35 | 36 | Returns: 37 | confusion matrix 38 | """ 39 | 40 | labels = [0,1] 41 | return confusion_matrix(y_true, y_pred, labels=labels).ravel() 42 | 43 | def recall_precision_f1_acc(y, y_hat): 44 | """ returns metrics for recall, precision, f1, accuracy 45 | 46 | Args: 47 | y (numpy array): ground truth 48 | y_hat (numpy array): prediction 49 | 50 | Returns: 51 | recall(float): recall/TPR 52 | precision(float): precision/PPV 53 | F1(float): f1-score 54 | acc(float): accuracy 55 | csi(float): critical success index 56 | """ 57 | 58 | # pytorch to numpy 59 | y, y_hat = [o.cpu() for o in [y, y_hat]] 60 | y, y_hat = [np.asarray(o) for o in [y, y_hat]] 61 | 62 | cm = get_confusion_matrix(y.ravel(), y_hat.ravel()) 63 | if len(cm)==4: 64 | tn, fp, fn, tp = cm 65 | recall, precision, F1, acc, csi = 0, 0, 0, 0, 0 66 | 67 | if (tp + fn) > 0: 68 | recall = tp / (tp + fn) 69 | 70 | if (tp + fp) > 0: 71 | precision = tp / (tp + fp) 72 | 73 | if (precision + recall) > 0: 74 | F1 = 2 * (precision * recall) / (precision + recall) 75 | 76 | if (tp + fn + fp) > 0: 77 | csi = tp / (tp + fn + fp) 78 | 79 | if (tn+fp+fn+tp) > 0: 80 | acc = (tn + tp) / (tn+fp+fn+tp) 81 | else: 82 | print("FATAL ERROR: cannot create confusion matrix") 83 | print("EXITING....") 84 | sys.exit() 85 | 86 | return recall, precision, F1, acc, csi 87 | 88 | 89 | def iou_class(y_pred: t.Tensor, y_true: t.Tensor): 90 | #y_true, y_pred = [o.cpu() for o in [y_true, y_pred]] 91 | #y_true, y_pred = [np.asarray(o) for o in [y_true, y_pred]] 92 | y_pred = y_pred.int() 93 | y_true = y_true.int() 94 | # Outputs: BATCH X H X W 95 | 96 | intersection = (y_pred & y_true).float().sum() # Will be zero if Truth=0 or Prediction=0 97 | union = (y_pred | y_true).float().sum() # Will be zero if both are 0 98 | 99 | if union>0: 100 | iou = intersection / union 101 | else: 102 | iou = 0 103 | 104 | iou = iou.cpu() 105 | return iou 106 | -------------------------------------------------------------------------------- /w4cNew.yml: -------------------------------------------------------------------------------- 1 | name: w4cNew 2 | channels: 3 | - pytorch 4 | - conda-forge 5 | - defaults 6 | dependencies: 7 | - _libgcc_mutex=0.1=conda_forge 8 | - _openmp_mutex=4.5=2_kmp_llvm 9 | - absl-py=1.2.0=pyhd8ed1ab_0 10 | - aiohttp=3.8.1=py38h0a891b7_1 11 | - aiosignal=1.2.0=pyhd8ed1ab_0 12 | - async-timeout=4.0.2=pyhd8ed1ab_0 13 | - attrs=22.1.0=pyh71513ae_1 14 | - blas=1.0=mkl 15 | - blinker=1.4=py_1 16 | - bottleneck=1.3.5=py38h7deecbd_0 17 | - brotlipy=0.7.0=py38h0a891b7_1004 18 | - bzip2=1.0.8=h7f98852_4 19 | - c-ares=1.18.1=h7f98852_0 20 | - ca-certificates=2022.07.19=h06a4308_0 21 | - cachetools=5.2.0=pyhd8ed1ab_0 22 | - certifi=2022.6.15=py38h06a4308_0 23 | - cffi=1.15.1=py38h4a40e3a_0 24 | - charset-normalizer=2.1.0=pyhd8ed1ab_0 25 | - click=8.1.3=py38h578d9bd_0 26 | - colorama=0.4.5=pyhd8ed1ab_0 27 | - cryptography=37.0.4=py38h2b5fc30_0 28 | - cudatoolkit=11.6.0=hecad31d_10 29 | - ffmpeg=4.3=hf484d3e_0 30 | - freetype=2.10.4=hca18f0e_2 31 | - frozenlist=1.3.1=py38h0a891b7_0 32 | - fsspec=2022.7.1=pyhd8ed1ab_0 33 | - future=0.18.2=py38h578d9bd_5 34 | - gmp=6.2.1=h58526e2_0 35 | - gnutls=3.6.13=h85f3911_1 36 | - google-auth=2.10.0=pyh6c4a22f_0 37 | - google-auth-oauthlib=0.4.6=pyhd8ed1ab_0 38 | - grpcio=1.46.3=py38ha0cdfde_0 39 | - h5py=3.7.0=py38h737f45e_0 40 | - hdf5=1.10.6=h3ffc7dd_1 41 | - idna=3.3=pyhd8ed1ab_0 42 | - importlib-metadata=4.11.4=py38h578d9bd_0 43 | - joblib=1.1.0=pyhd8ed1ab_0 44 | - jpeg=9e=h166bdaf_2 45 | - lame=3.100=h7f98852_1001 46 | - lcms2=2.12=hddcbb42_0 47 | - ld_impl_linux-64=2.36.1=hea4e1c9_2 48 | - lerc=3.0=h9c3ff4c_0 49 | - libblas=3.9.0=12_linux64_mkl 50 | - libcblas=3.9.0=12_linux64_mkl 51 | - libdeflate=1.10=h7f98852_0 52 | - libffi=3.4.2=h7f98852_5 53 | - libgcc-ng=12.1.0=h8d9b700_16 54 | - libgfortran-ng=12.1.0=h69a702a_16 55 | - libgfortran5=12.1.0=hdcd56e2_16 56 | - libiconv=1.17=h166bdaf_0 57 | - liblapack=3.9.0=12_linux64_mkl 58 | - libnsl=2.0.0=h7f98852_0 59 | - libpng=1.6.37=h753d276_4 60 | - libprotobuf=3.19.4=h780b84a_0 61 | - libsqlite=3.39.2=h753d276_1 62 | - libstdcxx-ng=12.1.0=ha89aaad_16 63 | - libtiff=4.3.0=h0fcbabc_4 64 | - libuuid=2.32.1=h7f98852_1000 65 | - libwebp-base=1.2.4=h166bdaf_0 66 | - libzlib=1.2.12=h166bdaf_2 67 | - llvm-openmp=14.0.4=he0ac6c6_0 68 | - lz4-c=1.9.3=h9c3ff4c_1 69 | - markdown=3.4.1=pyhd8ed1ab_0 70 | - markupsafe=2.1.1=py38h0a891b7_1 71 | - mkl=2021.4.0=h8d4b97c_729 72 | - mkl-service=2.4.0=py38h95df7f1_0 73 | - mkl_fft=1.3.1=py38h8666266_1 74 | - mkl_random=1.2.2=py38h1abd341_0 75 | - multidict=6.0.2=py38h0a891b7_1 76 | - ncurses=6.3=h27087fc_1 77 | - nettle=3.6=he412f7d_0 78 | - numexpr=2.8.3=py38h807cd23_0 79 | - numpy=1.23.1=py38h6c91a56_0 80 | - numpy-base=1.23.1=py38ha15fc14_0 81 | - oauthlib=3.2.0=pyhd8ed1ab_0 82 | - olefile=0.46=pyh9f0ad1d_1 83 | - openh264=2.1.1=h780b84a_0 84 | - openssl=1.1.1q=h7f8727e_0 85 | - packaging=21.3=pyhd8ed1ab_0 86 | - pandas=1.4.3=py38h6a678d5_0 87 | - pillow=6.2.2=py38h9776b28_0 88 | - pip=22.2.2=pyhd8ed1ab_0 89 | - protobuf=3.19.4=py38h709712a_0 90 | - pyasn1=0.4.8=py_0 91 | - pyasn1-modules=0.2.7=py_0 92 | - pycparser=2.21=pyhd8ed1ab_0 93 | - pydeprecate=0.3.2=pyhd8ed1ab_0 94 | - pyjwt=2.4.0=pyhd8ed1ab_0 95 | - pyopenssl=22.0.0=pyhd8ed1ab_0 96 | - pyparsing=3.0.9=pyhd8ed1ab_0 97 | - pysocks=1.7.1=py38h578d9bd_5 98 | - python=3.8.13=h582c2e5_0_cpython 99 | - python-dateutil=2.8.2=pyhd3eb1b0_0 100 | - python_abi=3.8=2_cp38 101 | - pytorch=1.12.1=py3.8_cuda11.6_cudnn8.3.2_0 102 | - pytorch-lightning=1.7.1=pyhd8ed1ab_0 103 | - pytorch-mutex=1.0=cuda 104 | - pytz=2022.1=py38h06a4308_0 105 | - pyu2f=0.1.5=pyhd8ed1ab_0 106 | - pyyaml=6.0=py38h0a891b7_4 107 | - readline=8.1.2=h0f457ee_0 108 | - requests=2.28.1=pyhd8ed1ab_0 109 | - requests-oauthlib=1.3.1=pyhd8ed1ab_0 110 | - rsa=4.9=pyhd8ed1ab_0 111 | - scikit-learn=1.1.2=py38h0b08f9b_0 112 | - scipy=1.9.0=py38hea3f02b_0 113 | - setuptools=59.5.0=py38h578d9bd_0 114 | - six=1.16.0=pyh6c4a22f_0 115 | - sqlite=3.39.2=h4ff8645_1 116 | - tbb=2021.5.0=h924138e_1 117 | - tensorboard=2.10.0=pyhd8ed1ab_0 118 | - tensorboard-data-server=0.6.0=py38h2b5fc30_2 119 | - tensorboard-plugin-wit=1.8.1=pyhd8ed1ab_0 120 | - threadpoolctl=3.1.0=pyh8a188c0_0 121 | - tk=8.6.12=h27826a3_0 122 | - torchaudio=0.12.1=py38_cu116 123 | - torchmetrics=0.9.3=pyhd8ed1ab_0 124 | - torchvision=0.13.1=py38_cu116 125 | - tqdm=4.64.0=pyhd8ed1ab_0 126 | - typing-extensions=4.3.0=hd8ed1ab_0 127 | - typing_extensions=4.3.0=pyha770c72_0 128 | - urllib3=1.26.11=pyhd8ed1ab_0 129 | - werkzeug=2.2.2=pyhd8ed1ab_0 130 | - wheel=0.37.1=pyhd8ed1ab_0 131 | - xz=5.2.6=h166bdaf_0 132 | - yaml=0.2.5=h7f98852_2 133 | - yarl=1.7.2=py38h0a891b7_2 134 | - zipp=3.8.1=pyhd8ed1ab_0 135 | - zlib=1.2.12=h166bdaf_2 136 | - zstd=1.5.2=h8a70e8d_4 137 | -------------------------------------------------------------------------------- /models/configurations/config_baseline_stage1.yaml: -------------------------------------------------------------------------------- 1 | experiment: # Settings for the current experiment 2 | name: 'U-NET-252' # name of the current experiment for logging 3 | experiment_folder: 'lightning_logs/' # folder to save logs 4 | sub_folder: 'baseline' # logging sub-folder 5 | precision: 32 # bit precision of weights. 32 or 16 6 | logging: True # Toggle logging on/off 7 | dataset: 8 | # Available bands: 'IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073' 9 | sat_bands: ['IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073'] 10 | regions: [ 'boxi_0015', 'boxi_0034', 'boxi_0076' ] # stage-1 11 | # or, e.g., ['boxi_0015'] if you want to train your model for one region only 12 | input_product: REFL-BT 13 | output_product: RATE 14 | out_channels: 1 15 | in_channels: 11 16 | swap_time_ch: True #swap the time and channels axis - if set to False (B, T, C, H, W) 17 | full_opera_context: 1512 # (105+42+105)*6; 18 | size_target_center: 252 # 42*6; 19 | len_seq_in: 4 # number of input slots per training sequence 20 | len_seq_predict: 32 # output slots; both still hard-coded in places! 21 | data_root: 'data' 22 | years: [ '2019' ] # stage-1 23 | splits_path: 'data/timestamps_and_splits_2019.csv' # stage-1 24 | 25 | preprocess_OPERA: 26 | # # var mean sd min median max length pos.weight.thr_0 27 | # 1 RATE 0.07165331 0.6302647 0 0 127.9399 5011989696 6.114572 28 | RATE: 29 | rainfall_rate-500X500: 30 | mask: [-9999000.0, inf, nan, max128] #, 0range0.1] # Mostly used for loss function: values added here are added to a mask and not used for loss 31 | map: [[lessthan0.0, 0], [greaterthan0.0, 1], [-8888000.0, 0], [-9999000.0, 0], [inf, 0], [nan, 0]] #Mostly used for input preprocessing # 1. map values # stage-1 32 | mean_std: [0.07165331, 0.6302647] 33 | range: [0, 128] # 2. we evaluate only pixels in this range 34 | standardise: False # 3. use log(x+1) instead & normalize (x/max) 35 | bin: False 36 | preprocess_HRIT: # 1: map values, 2: normalise in range per variable if process==True 37 | # # var mean sd min median max length 38 | # 1 IR_016 0.06605569 0.09920627 0 0.006609255 1.018736 4371869376 39 | # 2 IR_039 273.2187 15.98847 -2.968737 276.0403 336.2159 4371869376 40 | # 3 IR_087 268.3977 17.49075 -0.1731693 271.9306 326.3914 4371869376 41 | # 4 IR_097 246.1366 10.81174 -0.05971194 246.4856 301.0066 4371869376 42 | # 5 IR_108 270.1535 18.49373 -0.6266653 274.0552 338.0375 4371869376 43 | # 6 IR_120 268.7993 18.42736 -0.4006808 272.9807 337.3713 4371869376 44 | # 7 IR_134 250.6491 11.70623 -0.5645727 252.9884 300.8559 4371869376 45 | # 8 VIS006 0.06711527 0.1101766 0 0.01692321 1.002381 4371869376 46 | # 9 VIS008 0.08736397 0.1326554 0 0.01656201 1.100475 4371869376 47 | # 10 WV_062 232.1964 5.531017 -2.086555 232.3866 260.9901 4371869376 48 | # 11 WV_073 248.0414 9.495061 -0.4933934 250.0049 289.8742 4371869376 49 | IR_016: 50 | map: [[inf, 0], [nan, 0]] 51 | range: [0, 1.02] 52 | mean_std: [0.06605569, 0.09920627] 53 | standardise: True 54 | IR_039: 55 | map: [[inf, 0], [nan, 0]] 56 | range: [0, 350] 57 | mean_std: [273.2187, 15.98847] 58 | standardise: True 59 | IR_087: 60 | map: [[inf, 0], [nan, 0]] 61 | range: [0, 350] 62 | mean_std: [268.3977, 17.49075] 63 | standardise: True 64 | IR_097: 65 | map: [[inf, 0], [nan, 0]] 66 | range: [0, 350] 67 | mean_std: [246.1366, 10.81174] 68 | standardise: True 69 | IR_108: 70 | map: [[inf, 0], [nan, 0]] 71 | range: [0, 350] 72 | mean_std: [270.1535, 18.49373] 73 | standardise: True 74 | IR_120: 75 | map: [[inf, 0], [nan, 0]] 76 | range: [0, 350] 77 | mean_std: [268.7993, 18.42736] 78 | standardise: True 79 | IR_134: 80 | map: [[inf, 0], [nan, 0]] 81 | range: [0, 350] 82 | mean_std: [250.6491, 11.70623] 83 | standardise: True 84 | VIS006: 85 | map: [[inf, 0], [nan, 0]] 86 | range: [0, 1.02] 87 | mean_std: [0.06711527, 0.1101766] 88 | standardise: True 89 | VIS008: 90 | map: [[inf, 0], [nan, 0]] 91 | range: [0, 1.2] 92 | mean_std: [0.08736397, 0.1326554] 93 | standardise: True 94 | WV_062: 95 | map: [[inf, 0], [nan, 0]] 96 | range: [0, 300] 97 | mean_std: [232.1964, 5.531017] 98 | standardise: True 99 | WV_073: 100 | map: [[inf, 0], [nan, 0]] 101 | range: [0, 300] 102 | mean_std: [248.0414, 9.495061] 103 | standardise: True 104 | 105 | train: # model training settings 106 | batch_size: 16 # 40 107 | max_epochs: 90 108 | n_workers: 8 # 16 109 | loss: BCEWithLogitsLoss # requires pos_weight to be set 110 | pos_weight: 6.114572 111 | early_stopping: True 112 | patience: 5 113 | lr: 1e-4 114 | weight_decay: 2e-2 115 | init_filter_size: 32 116 | dropout_rate: 0.4 117 | 118 | model: # model definition settings 119 | model_name: 3D_UNET_base 120 | in_channels: 11 121 | gradient_clip_val: 2.0 122 | gradient_clip_algorithm: value 123 | 124 | predict: # model prediction settings 125 | region_to_predict: boxi_0015 # must match one of the names defined in 'dataset' / 'regions' 126 | year_to_predict: 2019 127 | -------------------------------------------------------------------------------- /models/configurations/config_baseline_stage2-pred.yaml: -------------------------------------------------------------------------------- 1 | experiment: # Settings for the current experiment 2 | name: 'U-NET-252' # name of the current experiment for logging 3 | experiment_folder: 'lightning_logs/' # folder to save logs 4 | sub_folder: 'baseline' # logging sub-folder 5 | precision: 32 # bit precision of weights. 32 or 16 6 | logging: True # Toggle logging on/off 7 | dataset: 8 | # Available bands: 'IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073' 9 | sat_bands: ['IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073'] 10 | regions: [ '%REGION%' ] 11 | input_product: REFL-BT 12 | output_product: RATE 13 | out_channels: 1 14 | in_channels: 11 15 | swap_time_ch: True #swap the time and channels axis - if set to False (B, T, C, H, W) 16 | full_opera_context: 1512 # (105+42+105)*6; 17 | size_target_center: 252 # 42*6; 18 | len_seq_in: 4 # number of input slots per training sequence 19 | len_seq_predict: 32 # output slots; both still hard-coded in places! 20 | # data_root: 'data/2019' # stage-1 21 | data_root: 'data' # stage-2 22 | years: [ '%YEAR%' ] 23 | # splits_path: 'data/timestamps_and_splits_2019.csv' # stage-1 24 | splits_path: 'data/timestamps_and_splits_stage2.csv' # stage-2 25 | 26 | preprocess_OPERA: 27 | # # var mean sd min median max length pos.weight.thr_0 28 | # 1 RATE 0.07165331 0.6302647 0 0 127.9399 5011989696 6.114572 29 | RATE: 30 | rainfall_rate-500X500: 31 | mask: [-9999000.0, inf, nan, max128] #, 0range0.1] # Mostly used for loss function: values added here are added to a mask and not used for loss 32 | # map: [[lessthan0.0, 0], [greaterthan0.0, 1], [-8888000.0, 0], [-9999000.0, 0], [inf, 0], [nan, 0]] #Mostly used for input preprocessing # 1. map values # stage-1 33 | map: [[lessthan0.2, 0], [greaterthan0.2, 1], [0.2,1], [-8888000.0, 0], [-9999000.0, 0], [inf, 0], [nan, 0]] #Mostly used for input preprocessing # 1. map values # stage-2 34 | # mean_std: [0.07165331, 0.6302647] 35 | range: [0, 128] # 2. we evaluate only pixels in this range 36 | standardise: False # 3. use log(x+1) instead & normalize (x/max) 37 | bin: False 38 | preprocess_HRIT: # 1: map values, 2: normalise in range per variable if process==True 39 | # # var mean sd min median max length 40 | # 1 IR_016 0.06605569 0.09920627 0 0.006609255 1.018736 4371869376 41 | # 2 IR_039 273.2187 15.98847 -2.968737 276.0403 336.2159 4371869376 42 | # 3 IR_087 268.3977 17.49075 -0.1731693 271.9306 326.3914 4371869376 43 | # 4 IR_097 246.1366 10.81174 -0.05971194 246.4856 301.0066 4371869376 44 | # 5 IR_108 270.1535 18.49373 -0.6266653 274.0552 338.0375 4371869376 45 | # 6 IR_120 268.7993 18.42736 -0.4006808 272.9807 337.3713 4371869376 46 | # 7 IR_134 250.6491 11.70623 -0.5645727 252.9884 300.8559 4371869376 47 | # 8 VIS006 0.06711527 0.1101766 0 0.01692321 1.002381 4371869376 48 | # 9 VIS008 0.08736397 0.1326554 0 0.01656201 1.100475 4371869376 49 | # 10 WV_062 232.1964 5.531017 -2.086555 232.3866 260.9901 4371869376 50 | # 11 WV_073 248.0414 9.495061 -0.4933934 250.0049 289.8742 4371869376 51 | IR_016: 52 | map: [[inf, 0], [nan, 0]] 53 | range: [0, 1.02] 54 | mean_std: [0.06605569, 0.09920627] 55 | standardise: True 56 | IR_039: 57 | map: [[inf, 0], [nan, 0]] 58 | range: [0, 350] 59 | mean_std: [273.2187, 15.98847] 60 | standardise: True 61 | IR_087: 62 | map: [[inf, 0], [nan, 0]] 63 | range: [0, 350] 64 | mean_std: [268.3977, 17.49075] 65 | standardise: True 66 | IR_097: 67 | map: [[inf, 0], [nan, 0]] 68 | range: [0, 350] 69 | mean_std: [246.1366, 10.81174] 70 | standardise: True 71 | IR_108: 72 | map: [[inf, 0], [nan, 0]] 73 | range: [0, 350] 74 | mean_std: [270.1535, 18.49373] 75 | standardise: True 76 | IR_120: 77 | map: [[inf, 0], [nan, 0]] 78 | range: [0, 350] 79 | mean_std: [268.7993, 18.42736] 80 | standardise: True 81 | IR_134: 82 | map: [[inf, 0], [nan, 0]] 83 | range: [0, 350] 84 | mean_std: [250.6491, 11.70623] 85 | standardise: True 86 | VIS006: 87 | map: [[inf, 0], [nan, 0]] 88 | range: [0, 1.02] 89 | mean_std: [0.06711527, 0.1101766] 90 | standardise: True 91 | VIS008: 92 | map: [[inf, 0], [nan, 0]] 93 | range: [0, 1.2] 94 | mean_std: [0.08736397, 0.1326554] 95 | standardise: True 96 | WV_062: 97 | map: [[inf, 0], [nan, 0]] 98 | range: [0, 300] 99 | mean_std: [232.1964, 5.531017] 100 | standardise: True 101 | WV_073: 102 | map: [[inf, 0], [nan, 0]] 103 | range: [0, 300] 104 | mean_std: [248.0414, 9.495061] 105 | standardise: True 106 | 107 | train: # model training settings 108 | batch_size: 16 # 40 109 | max_epochs: 90 110 | n_workers: 8 # 16 111 | loss: BCEWithLogitsLoss # requires pos_weight to be set 112 | pos_weight: 2.577389 # stage-2: 2.577389 inverse unmasked rain ratio; 13.32784 inverse rain ratio. Only used for BCEWithLogitsLoss 113 | # loss: mIoULoss 114 | early_stopping: True 115 | patience: 20 116 | lr: 1e-4 117 | weight_decay: 2e-2 118 | init_filter_size: 32 119 | dropout_rate: 0.4 120 | 121 | model: # model definition settings 122 | model_name: 3D_UNET_base 123 | in_channels: 11 124 | gradient_clip_val: 2.0 125 | gradient_clip_algorithm: value 126 | 127 | predict: # model prediction settings 128 | submission_out_dir: %SDIR% 129 | region_to_predict: %REGION% 130 | year_to_predict: %YEAR% 131 | -------------------------------------------------------------------------------- /models/configurations/config_baseline_stage2.yaml: -------------------------------------------------------------------------------- 1 | experiment: # Settings for the current experiment 2 | name: 'U-NET-252' # name of the current experiment for logging 3 | experiment_folder: 'lightning_logs/' # folder to save logs 4 | sub_folder: 'baseline' # logging sub-folder 5 | precision: 32 # bit precision of weights. 32 or 16 6 | logging: True # Toggle logging on/off 7 | dataset: 8 | # Available bands: 'IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073' 9 | sat_bands: ['IR_016', 'IR_039', 'IR_087', 'IR_097', 'IR_108', 'IR_120', 'IR_134', 'VIS006', 'VIS008', 'WV_062', 'WV_073'] 10 | # regions: [ 'boxi_0015', 'boxi_0034', 'boxi_0076' ] # stage-1 11 | regions: [ 'boxi_0015', 'boxi_0034', 'boxi_0076', 12 | 'roxi_0004', 'roxi_0005', 'roxi_0006', 'roxi_0007' ] # stage-2 13 | # or, e.g., ['boxi_0015'] if you want to train your model for one region only 14 | input_product: REFL-BT 15 | output_product: RATE 16 | out_channels: 1 17 | in_channels: 11 18 | swap_time_ch: True #swap the time and channels axis - if set to False (B, T, C, H, W) 19 | full_opera_context: 1512 # (105+42+105)*6; 20 | size_target_center: 252 # 42*6; 21 | len_seq_in: 4 # number of input slots per training sequence 22 | len_seq_predict: 32 # output slots; both still hard-coded in places! 23 | # data_root: 'data/2019' # stage-1 24 | data_root: 'data' 25 | years: [ '2019', '2020' ] # stage-2 26 | # years: [ '2019' ] # stage-1 27 | # splits_path: 'data/timestamps_and_splits_2019.csv' # stage-1 28 | splits_path: 'data/timestamps_and_splits_stage2.csv' # stage-2 29 | 30 | preprocess_OPERA: 31 | # # var mean sd min median max length pos.weight.thr_0 32 | # 1 RATE 0.07165331 0.6302647 0 0 127.9399 5011989696 6.114572 33 | RATE: 34 | rainfall_rate-500X500: 35 | mask: [-9999000.0, inf, nan, max128] #, 0range0.1] # Mostly used for loss function: values added here are added to a mask and not used for loss 36 | # map: [[lessthan0.0, 0], [greaterthan0.0, 1], [-8888000.0, 0], [-9999000.0, 0], [inf, 0], [nan, 0]] #Mostly used for input preprocessing # 1. map values # stage-1 37 | map: [[lessthan0.2, 0], [greaterthan0.2, 1], [0.2,1], [-8888000.0, 0], [-9999000.0, 0], [inf, 0], [nan, 0]] #Mostly used for input preprocessing # 1. map values # stage-2 38 | # mean_std: [0.07165331, 0.6302647] 39 | range: [0, 128] # 2. we evaluate only pixels in this range 40 | standardise: False # 3. use log(x+1) instead & normalize (x/max) 41 | bin: False 42 | preprocess_HRIT: # 1: map values, 2: normalise in range per variable if process==True 43 | # # var mean sd min median max length 44 | # 1 IR_016 0.06605569 0.09920627 0 0.006609255 1.018736 4371869376 45 | # 2 IR_039 273.2187 15.98847 -2.968737 276.0403 336.2159 4371869376 46 | # 3 IR_087 268.3977 17.49075 -0.1731693 271.9306 326.3914 4371869376 47 | # 4 IR_097 246.1366 10.81174 -0.05971194 246.4856 301.0066 4371869376 48 | # 5 IR_108 270.1535 18.49373 -0.6266653 274.0552 338.0375 4371869376 49 | # 6 IR_120 268.7993 18.42736 -0.4006808 272.9807 337.3713 4371869376 50 | # 7 IR_134 250.6491 11.70623 -0.5645727 252.9884 300.8559 4371869376 51 | # 8 VIS006 0.06711527 0.1101766 0 0.01692321 1.002381 4371869376 52 | # 9 VIS008 0.08736397 0.1326554 0 0.01656201 1.100475 4371869376 53 | # 10 WV_062 232.1964 5.531017 -2.086555 232.3866 260.9901 4371869376 54 | # 11 WV_073 248.0414 9.495061 -0.4933934 250.0049 289.8742 4371869376 55 | IR_016: 56 | map: [[inf, 0], [nan, 0]] 57 | range: [0, 1.02] 58 | mean_std: [0.06605569, 0.09920627] 59 | standardise: True 60 | IR_039: 61 | map: [[inf, 0], [nan, 0]] 62 | range: [0, 350] 63 | mean_std: [273.2187, 15.98847] 64 | standardise: True 65 | IR_087: 66 | map: [[inf, 0], [nan, 0]] 67 | range: [0, 350] 68 | mean_std: [268.3977, 17.49075] 69 | standardise: True 70 | IR_097: 71 | map: [[inf, 0], [nan, 0]] 72 | range: [0, 350] 73 | mean_std: [246.1366, 10.81174] 74 | standardise: True 75 | IR_108: 76 | map: [[inf, 0], [nan, 0]] 77 | range: [0, 350] 78 | mean_std: [270.1535, 18.49373] 79 | standardise: True 80 | IR_120: 81 | map: [[inf, 0], [nan, 0]] 82 | range: [0, 350] 83 | mean_std: [268.7993, 18.42736] 84 | standardise: True 85 | IR_134: 86 | map: [[inf, 0], [nan, 0]] 87 | range: [0, 350] 88 | mean_std: [250.6491, 11.70623] 89 | standardise: True 90 | VIS006: 91 | map: [[inf, 0], [nan, 0]] 92 | range: [0, 1.02] 93 | mean_std: [0.06711527, 0.1101766] 94 | standardise: True 95 | VIS008: 96 | map: [[inf, 0], [nan, 0]] 97 | range: [0, 1.2] 98 | mean_std: [0.08736397, 0.1326554] 99 | standardise: True 100 | WV_062: 101 | map: [[inf, 0], [nan, 0]] 102 | range: [0, 300] 103 | mean_std: [232.1964, 5.531017] 104 | standardise: True 105 | WV_073: 106 | map: [[inf, 0], [nan, 0]] 107 | range: [0, 300] 108 | mean_std: [248.0414, 9.495061] 109 | standardise: True 110 | 111 | train: # model training settings 112 | batch_size: 40 # 16 113 | max_epochs: 90 114 | n_workers: 16 # 8 115 | loss: BCEWithLogitsLoss # requires pos_weight to be set 116 | pos_weight: 2.577389 # stage-2: 2.577389 inverse unmasked rain ratio; 13.32784 inverse rain ratio. Only used for BCEWithLogitsLoss 117 | # loss: mIoULoss 118 | early_stopping: True 119 | patience: 20 120 | lr: 1e-4 121 | weight_decay: 2e-2 122 | init_filter_size: 32 123 | dropout_rate: 0.4 124 | 125 | model: # model definition settings 126 | model_name: 3D_UNET_base 127 | in_channels: 11 128 | gradient_clip_val: 2.0 129 | gradient_clip_algorithm: value 130 | 131 | predict: # model prediction settings 132 | region_to_predict: boxi_0015 # must match one of the names defined in 'dataset' / 'regions' 133 | year_to_predict: 2019 134 | -------------------------------------------------------------------------------- /models/unet.patch: -------------------------------------------------------------------------------- 1 | --- unet.py 2022-08-20 12:22:39.713834077 +0200 2 | +++ baseline_UNET3D.py 2022-08-20 12:22:03.482141847 +0200 3 | @@ -1,35 +1,32 @@ 4 | -# ELEKTRONN3 - Neural Network Toolkit 5 | +# Weather4cast 2022 Starter Kit 6 | # 7 | -# Copyright (c) 2017 - now 8 | -# Max Planck Institute of Neurobiology, Munich, Germany 9 | -# Author: Martin Drawitsch 10 | - 11 | -""" 12 | -This is a modified version of the U-Net CNN architecture for biomedical 13 | -image segmentation. U-Net was originally published in 14 | -https://arxiv.org/abs/1505.04597 by Ronneberger et al. 15 | - 16 | -A pure-3D variant of U-Net has been proposed by Çiçek et al. 17 | -in https://arxiv.org/abs/1606.06650, but the below implementation 18 | -is based on the original U-Net paper, with several improvements. 19 | - 20 | -This code is based on https://github.com/jaxony/unet-pytorch 21 | -(c) 2017 Jackson Huang, released under MIT License, 22 | -which implements (2D) U-Net with user-defined network depth 23 | -and a few other improvements of the original architecture. 24 | - 25 | -Major differences of this version from Huang's code: 26 | - 27 | -- Operates on 3D image data (5D tensors) instead of 2D data 28 | -- Uses 3D convolution, 3D pooling etc. by default 29 | -- planar_blocks architecture parameter for mixed 2D/3D convnets 30 | - (see UNet class docstring for details) 31 | -- Improved tests (see the bottom of the file) 32 | -- Cleaned up parameter/variable names and formatting, changed default params 33 | -- Updated for PyTorch 1.3 and Python 3.6 (earlier versions unsupported) 34 | -- (Optional DEBUG mode for optional printing of debug information) 35 | -- Extended documentation 36 | -""" 37 | +# Copyright (C) 2022 38 | +# Institute of Advanced Research in Artificial Intelligence (IARAI) 39 | + 40 | +# Baseline model for the Neurips 2022 Weather4cast Competition - 41 | +# an adaptation of the CNN ELEKTRONN3 model available under MIT license on 42 | +# https://raw.githubusercontent.com/ELEKTRONN/elektronn3/f754796d861f1cfe1c19dfc7819087972573ce40/elektronn3/models/unet.py 43 | +# 44 | +# The adaptations are part of the Weather4cast 2022 Starter Kit. 45 | + 46 | +# The Weather4cast 2022 Starter Kit is free software: you can redistribute it 47 | +# and/or modify it under the terms of the GNU General Public License as 48 | +# published by the Free Software Foundation, either version 3 of the License, 49 | +# or (at your option) any later version. 50 | +# 51 | +# The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 52 | +# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 53 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 54 | +# GNU General Public License for more details. 55 | +# 56 | +# You should have received a copy of the GNU General Public License 57 | +# along with this program. If not, see . 58 | + 59 | +# Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 60 | + 61 | + 62 | +VERBOSE=False 63 | +##VERBOSE=True 64 | 65 | __all__ = ['UNet'] 66 | 67 | @@ -204,12 +201,13 @@ 68 | A helper Module that performs 2 convolutions and 1 MaxPool. 69 | A ReLU activation follows each convolution. 70 | """ 71 | - def __init__(self, in_channels, out_channels, pooling=True, planar=False, activation='relu', 72 | + def __init__(self, in_channels, out_channels, dropout_rate, pooling=True, planar=False, activation='relu', 73 | normalization=None, full_norm=True, dim=3, conv_mode='same'): 74 | super().__init__() 75 | 76 | self.in_channels = in_channels 77 | self.out_channels = out_channels 78 | + self.dropout_rate = dropout_rate 79 | self.pooling = pooling 80 | self.normalization = normalization 81 | self.dim = dim 82 | @@ -232,21 +230,28 @@ 83 | self.pool = nn.Identity() 84 | self.pool_ks = -123 # Bogus value, will never be read. Only to satisfy TorchScript's static type system 85 | 86 | + self.dropout = nn.Dropout3d(dropout_rate) 87 | + 88 | self.act1 = get_activation(activation) 89 | self.act2 = get_activation(activation) 90 | 91 | if full_norm: 92 | self.norm0 = get_normalization(normalization, self.out_channels, dim=dim) 93 | + if VERBOSE: print("DownConv, full_norm, norm0 =",normalization) 94 | else: 95 | self.norm0 = nn.Identity() 96 | + if VERBOSE: print("DownConv, no full_norm") 97 | self.norm1 = get_normalization(normalization, self.out_channels, dim=dim) 98 | + if VERBOSE: print("DownConv, norm1 =",normalization) 99 | 100 | def forward(self, x): 101 | y = self.conv1(x) 102 | y = self.norm0(y) 103 | + y = self.dropout(y) 104 | y = self.act1(y) 105 | y = self.conv2(y) 106 | y = self.norm1(y) 107 | + y = self.dropout(y) 108 | y = self.act2(y) 109 | before_pool = y 110 | y = self.pool(y) 111 | @@ -754,9 +759,10 @@ 112 | """ 113 | def __init__( 114 | self, 115 | - in_channels: int = 1, 116 | - out_channels: int = 2, 117 | - n_blocks: int = 3, 118 | + in_channels: int = 11, 119 | + out_channels: int = 32, ## NEW: number of time slots to predict 120 | + dropout_rate: float = 0.4, 121 | + n_blocks: int = 5, 122 | start_filts: int = 32, 123 | up_mode: str = 'transpose', 124 | merge_mode: str = 'concat', 125 | @@ -815,6 +821,7 @@ 126 | 127 | self.out_channels = out_channels 128 | self.in_channels = in_channels 129 | + self.dropout_rate = dropout_rate 130 | self.start_filts = start_filts 131 | self.n_blocks = n_blocks 132 | self.normalization = normalization 133 | @@ -846,8 +853,9 @@ 134 | down_conv = DownConv( 135 | ins, 136 | outs, 137 | + dropout_rate, 138 | pooling=pooling, 139 | - planar=planar, 140 | + planar=planar, 141 | activation=activation, 142 | normalization=normalization, 143 | full_norm=full_norm, 144 | @@ -877,9 +885,9 @@ 145 | conv_mode=conv_mode, 146 | ) 147 | self.up_convs.append(up_conv) 148 | - 149 | - self.conv_final = conv1(outs, self.out_channels, dim=dim) 150 | - 151 | + self.reduce_channels = conv1(outs*4, ## 4 = experiment / len_seq_in 152 | + self.out_channels, dim=dim) 153 | + self.dropout = nn.Dropout3d(dropout_rate) 154 | self.apply(self.weight_init) 155 | 156 | @staticmethod 157 | @@ -898,9 +906,11 @@ 158 | i = 0 # Can't enumerate because of https://github.com/pytorch/pytorch/issues/16123 159 | for module in self.down_convs: 160 | x, before_pool = module(x) 161 | + before_pool = self.dropout(before_pool) # for skip connections 162 | encoder_outs.append(before_pool) 163 | i += 1 164 | 165 | + x = self.dropout(x) # at bottom of the U, as in the original U-Net 166 | # Decoding by UpConv and merging with saved outputs of encoder 167 | i = 0 168 | for module in self.up_convs: 169 | @@ -909,8 +919,16 @@ 170 | i += 1 171 | 172 | # No softmax is used, so you need to apply it in the loss. 173 | - x = self.conv_final(x) 174 | - # Uncomment the following line to temporarily store output for 175 | + if VERBOSE: print("pre-reshape",x.shape) 176 | + xs = x.shape; 177 | + x = torch.reshape(x,(xs[0],xs[1]*xs[2],1,xs[3],xs[4])); 178 | + if VERBOSE: print("pre-reduce",x.shape) 179 | + x = self.reduce_channels(x) 180 | + if VERBOSE: print("post-reduce",x.shape) 181 | + xs = x.shape; 182 | + x = torch.reshape(x,(xs[0],1,xs[1],xs[3],xs[4])); 183 | + if VERBOSE: print("post-reshape",x.shape) 184 | + # Uncomment the following line to temporarily store output for 185 | # receptive field estimation using fornoxai/receptivefield: 186 | # self.feature_maps = [x] # Currently disabled to save memory 187 | return x 188 | -------------------------------------------------------------------------------- /utils/w4c_dataloader.py: -------------------------------------------------------------------------------- 1 | # Weather4cast 2022 Starter Kit 2 | # 3 | # Copyright (C) 2022 4 | # Institute of Advanced Research in Artificial Intelligence (IARAI) 5 | 6 | # This file is part of the Weather4cast 2022 Starter Kit. 7 | # 8 | # The Weather4cast 2022 Starter Kit is free software: you can redistribute it 9 | # and/or modify it under the terms of the GNU General Public License as 10 | # published by the Free Software Foundation, either version 3 of the License, 11 | # or (at your option) any later version. 12 | # 13 | # The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 14 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 22 | 23 | 24 | # from cv2 import CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT 25 | import numpy as np 26 | from torch.utils.data import Dataset 27 | import os 28 | import sys 29 | import time 30 | from timeit import default_timer as timer 31 | 32 | from utils.data_utils import * 33 | 34 | # folder to load config file 35 | # CONFIG_PATH = "../" 36 | 37 | # VERBOSE = True 38 | VERBOSE = False 39 | 40 | """ 41 | Assumptions: 42 | - the data is already cropped to the right dimensions 43 | - Data format - [Samples, C, T, W, H] 44 | """ 45 | 46 | 47 | class RainData(Dataset): 48 | def __init__( 49 | self, 50 | data_split, 51 | project_root="", 52 | data_root="", 53 | input_product="REFL-BT", 54 | compute_seq=True, 55 | output_product="RATE", 56 | sat_bands=[], 57 | preprocess_OPERA=None, 58 | size_target_center=None, 59 | full_opera_context=None, 60 | preprocess_HRIT=None, 61 | path_to_sample_ids="", 62 | len_seq_in=4, 63 | len_seq_predict=32, 64 | regions=["boxi_0015"], 65 | regions_def={}, 66 | generate_samples=False, 67 | latlon_path="", 68 | altitudes_path="", 69 | splits_path=None, 70 | swap_time_ch=False, 71 | years=None, 72 | **kwargs 73 | ): 74 | start = timer() 75 | # Data Dimensions 76 | self.len_seq_in = len_seq_in 77 | self.len_seq_predict = len_seq_predict 78 | self.channel_dim = 1 # where to concat channels in structure 79 | 80 | # type of data & processing variables 81 | self.sat_bands = sat_bands 82 | self.regions = regions 83 | self.input_product = input_product 84 | self.output_product = output_product 85 | self.preprocess_target = preprocess_OPERA 86 | self.size_target_center = size_target_center 87 | self.full_opera_context = full_opera_context 88 | self.crop = int( 89 | (self.full_opera_context - self.size_target_center) / 2 90 | ) # calculate centre of image to begin crop 91 | self.preprocess_input = preprocess_HRIT 92 | self.path_to_sample_ids = path_to_sample_ids 93 | self.regions_def = regions_def 94 | self.generate_samples = generate_samples 95 | self.path_to_sample_ids = path_to_sample_ids 96 | self.swap_time_ch = swap_time_ch 97 | self.years = years 98 | 99 | # data splits to load (training/validation/test) 100 | self.root = project_root 101 | self.data_root = data_root 102 | self.data_split = data_split 103 | self.splits_df = load_timestamps(splits_path) 104 | # prepare all elements to load - sample idx will use the object 'self.idx' 105 | self.idxs = load_sample_ids( 106 | self.data_split, 107 | self.splits_df, 108 | self.len_seq_in, 109 | self.len_seq_predict, 110 | self.regions, 111 | self.generate_samples, 112 | self.years, 113 | self.path_to_sample_ids 114 | ) 115 | 116 | # LOAD DATASET 117 | self.in_ds = load_dataset( 118 | self.data_root, self.data_split, self.regions, years, self.input_product 119 | ) 120 | if self.data_split not in ["test", "heldout"]: 121 | self.out_ds = load_dataset( 122 | self.data_root, self.data_split, self.regions, years, self.output_product 123 | ) 124 | else: 125 | self.out_ds = [] 126 | 127 | def __len__(self): 128 | """total number of samples (sequences of in:4-out:1 in our case) to train""" 129 | # print(len(self.idxs), "-------------------", self.data_split) 130 | return len(self.idxs) 131 | 132 | def load_in(self, in_seq, seq_r, metadata, loaded_input=False): 133 | in0 = time.time() 134 | input_data, in_masks = get_sequence( 135 | in_seq, 136 | self.data_root, 137 | self.data_split, 138 | seq_r, 139 | self.input_product, 140 | self.sat_bands, 141 | self.preprocess_input, 142 | self.swap_time_ch, 143 | self.in_ds, 144 | ) 145 | 146 | if VERBOSE: 147 | print(np.shape(input_data), time.time() - in0, "in sequence time") 148 | return input_data, metadata 149 | 150 | def load_out(self, out_seq, seq_r, metadata): 151 | t1 = time.time() 152 | # GROUND TRUTH (OUTPUT) 153 | if self.data_split not in ["test", "heldout"]: 154 | output_data, out_masks = get_sequence( 155 | out_seq, 156 | self.data_root, 157 | self.data_split, 158 | seq_r, 159 | self.output_product, 160 | [], 161 | self.preprocess_target, 162 | self.swap_time_ch, 163 | self.out_ds, 164 | ) 165 | 166 | # collapse time to channels 167 | metadata["target"]["mask"] = out_masks 168 | else: # Just return [] if its test/heldout data 169 | output_data = np.array([]) 170 | if VERBOSE: 171 | print(time.time() - t1, "out sequence") 172 | return output_data, metadata 173 | 174 | def load_in_out(self, in_seq, out_seq=None, seq_r=None): 175 | metadata = { 176 | "input": {"mask": [], "timestamps": in_seq}, 177 | "target": {"mask": [], "timestamps": out_seq}, 178 | } 179 | 180 | t0 = time.time() 181 | input_data, metadata = self.load_in(in_seq, seq_r, metadata) 182 | output_data, metadata = self.load_out(out_seq, seq_r, metadata) 183 | 184 | if VERBOSE: 185 | print(time.time() - t0, "seconds") 186 | return input_data, output_data, metadata 187 | 188 | def __getitem__(self, idx): 189 | """load 1 sequence (1 sample)""" 190 | in_seq = self.idxs[idx][0] 191 | out_seq = self.idxs[idx][1] 192 | seq_r = self.idxs[idx][2] 193 | # # print("=== DEBUG in_seq: ",in_seq, file=sys.stderr); 194 | # print("=== DEBUG in_seq: ",in_seq); 195 | return self.load_in_out(in_seq, out_seq, seq_r) 196 | 197 | 198 | class Normalise(object): 199 | """Dataset Transform: "Normalise values for each band.""" 200 | 201 | def __init__(self, mean, std): 202 | """Normalise values for each band 203 | Args: 204 | mean (list): mean value of bands 205 | std (list): standard deviation of bands 206 | """ 207 | self.mean = mean 208 | self.std = std 209 | super().__init__() 210 | 211 | def __call__(self, sample): 212 | """Normalise values for each band 213 | Args: 214 | sample (Tensor, Tensor): sample and labels for sample as tensor 215 | Returns: 216 | sample (Tensor, Tensor): sample and labels for sample normalized 217 | """ 218 | data, labels = sample 219 | # For every channel, subtract the mean, and divide by the standard deviation\ 220 | # possible approach = loop through band dim and access right values in corresponding dims of mean / stdev 221 | for t, m, s in zip(data, self.mean, self.std): 222 | t.sub_(m).div_(s) 223 | return (data, labels) 224 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # Weather4cast 2022 Starter Kit 2 | # 3 | # Copyright (C) 2022 4 | # Institute of Advanced Research in Artificial Intelligence (IARAI) 5 | 6 | # This file is part of the Weather4cast 2022 Starter Kit. 7 | # 8 | # The Weather4cast 2022 Starter Kit is free software: you can redistribute it 9 | # and/or modify it under the terms of the GNU General Public License as 10 | # published by the Free Software Foundation, either version 3 of the License, 11 | # or (at your option) any later version. 12 | # 13 | # The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 14 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 22 | 23 | 24 | import argparse 25 | 26 | import pytorch_lightning as pl 27 | from pytorch_lightning.callbacks import ModelCheckpoint 28 | from pytorch_lightning.plugins import DDPPlugin 29 | from torch.utils.data import DataLoader 30 | from pytorch_lightning import loggers as pl_loggers 31 | from pytorch_lightning.callbacks.early_stopping import EarlyStopping 32 | import datetime 33 | import os 34 | import torch 35 | 36 | from models.unet_lightning import UNet_Lightning as UNetModel 37 | from utils.data_utils import load_config 38 | from utils.data_utils import get_cuda_memory_usage 39 | from utils.data_utils import tensor_to_submission_file 40 | from utils.w4c_dataloader import RainData 41 | 42 | class DataModule(pl.LightningDataModule): 43 | """ Class to handle training/validation splits in a single object 44 | """ 45 | def __init__(self, params, training_params, mode): 46 | super().__init__() 47 | self.params = params 48 | self.training_params = training_params 49 | if mode in ['train']: 50 | print("Loading TRAINING/VALIDATION dataset -- as test") 51 | self.train_ds = RainData('training', **self.params) 52 | self.val_ds = RainData('validation', **self.params) 53 | print(f"Training dataset size: {len(self.train_ds)}") 54 | if mode in ['val']: 55 | print("Loading VALIDATION dataset -- as test") 56 | self.val_ds = RainData('validation', **self.params) 57 | if mode in ['predict']: 58 | print("Loading PREDICTION/TEST dataset -- as test") 59 | self.test_ds = RainData('test', **self.params) 60 | if mode in ['heldout']: 61 | print("Loading HELD-OUT dataset -- as test") 62 | self.test_ds = RainData('heldout', **self.params) 63 | 64 | def __load_dataloader(self, dataset, shuffle=True, pin=True): 65 | dl = DataLoader(dataset, 66 | batch_size=self.training_params['batch_size'], 67 | num_workers=self.training_params['n_workers'], 68 | shuffle=shuffle, 69 | pin_memory=pin, prefetch_factor=2, 70 | persistent_workers=False) 71 | return dl 72 | 73 | def train_dataloader(self): 74 | return self.__load_dataloader(self.train_ds, shuffle=True, pin=True) 75 | 76 | def val_dataloader(self): 77 | return self.__load_dataloader(self.val_ds, shuffle=False, pin=True) 78 | 79 | def test_dataloader(self): 80 | return self.__load_dataloader(self.test_ds, shuffle=False, pin=True) 81 | 82 | 83 | def load_model(Model, params, checkpoint_path=''): 84 | """ loads a model from a checkpoint or from scratch if checkpoint_path='' """ 85 | p = {**params['experiment'], **params['dataset'], **params['train']} 86 | if checkpoint_path == '': 87 | print('-> Modelling from scratch! (no checkpoint loaded)') 88 | model = Model(params['model'], p) 89 | else: 90 | print(f'-> Loading model checkpoint: {checkpoint_path}') 91 | model = Model.load_from_checkpoint(checkpoint_path, UNet_params=params['model'], params=p) 92 | return model 93 | 94 | def get_trainer(gpus,params): 95 | """ get the trainer, modify here its options: 96 | - save_top_k 97 | """ 98 | max_epochs=params['train']['max_epochs']; 99 | print("Trainig for",max_epochs,"epochs"); 100 | checkpoint_callback = ModelCheckpoint(monitor='val_loss_epoch', save_top_k=3, save_last=True, 101 | filename='{epoch:02d}-{val_loss_epoch:.6f}') 102 | 103 | parallel_training = None 104 | ddpplugin = None 105 | if gpus[0] == -1: 106 | gpus = None 107 | elif len(gpus) > 1: 108 | parallel_training = 'ddp' 109 | ## ddpplugin = DDPPlugin(find_unused_parameters=True) 110 | print(f"====== process started on the following GPUs: {gpus} ======") 111 | date_time = datetime.datetime.now().strftime("%m%d-%H:%M") 112 | version = params['experiment']['name'] 113 | version = version + '_' + date_time 114 | 115 | #SET LOGGER 116 | if params['experiment']['logging']: 117 | tb_logger = pl_loggers.TensorBoardLogger(save_dir=params['experiment']['experiment_folder'],name=params['experiment']['sub_folder'], version=version, log_graph=True) 118 | else: 119 | tb_logger = False 120 | 121 | if params['train']['early_stopping']: 122 | early_stop_callback = EarlyStopping(monitor="val_loss_epoch", 123 | patience=params['train']['patience'], 124 | mode="min") 125 | callback_funcs = [checkpoint_callback, early_stop_callback] 126 | else: 127 | callback_funcs = [checkpoint_callback] 128 | 129 | trainer = pl.Trainer(devices=gpus, max_epochs=max_epochs, 130 | gradient_clip_val=params['model']['gradient_clip_val'], 131 | gradient_clip_algorithm=params['model']['gradient_clip_algorithm'], 132 | accelerator="gpu", 133 | callbacks=callback_funcs,logger=tb_logger, 134 | profiler='simple',precision=params['experiment']['precision'], 135 | strategy="ddp" 136 | ) 137 | 138 | return trainer 139 | 140 | def do_predict(trainer, model, predict_params, test_data): 141 | scores = trainer.predict(model, dataloaders=test_data) 142 | scores = torch.concat(scores) 143 | tensor_to_submission_file(scores,predict_params) 144 | 145 | def do_test(trainer, model, test_data): 146 | scores = trainer.test(model, dataloaders=test_data) 147 | 148 | def train(params, gpus, mode, checkpoint_path, model=UNetModel): 149 | """ main training/evaluation method 150 | """ 151 | # ------------ 152 | # model & data 153 | # ------------ 154 | get_cuda_memory_usage(gpus) 155 | data = DataModule(params['dataset'], params['train'], mode) 156 | model = load_model(model, params, checkpoint_path) 157 | # ------------ 158 | # Add your models here 159 | # ------------ 160 | 161 | # ------------ 162 | # trainer 163 | # ------------ 164 | trainer = get_trainer(gpus, params) 165 | get_cuda_memory_usage(gpus) 166 | # ------------ 167 | # train & final validation 168 | # ------------ 169 | if mode == 'train': 170 | print("------------------") 171 | print("--- TRAIN MODE ---") 172 | print("------------------") 173 | trainer.fit(model, data) 174 | 175 | 176 | if mode == "val": 177 | # ------------ 178 | # VALIDATE 179 | # ------------ 180 | print("---------------------") 181 | print("--- VALIDATE MODE ---") 182 | print("---------------------") 183 | do_test(trainer, model, data.val_dataloader()) 184 | 185 | 186 | if mode == 'predict' or mode == 'heldout': 187 | # ------------ 188 | # PREDICT 189 | # ------------ 190 | print("--------------------") 191 | print("--- PREDICT MODE ---") 192 | print("--------------------") 193 | print("REGIONS!:: ", params["dataset"]["regions"], params["predict"]["region_to_predict"]) 194 | if params["predict"]["region_to_predict"] not in params["dataset"]["regions"]: 195 | print("EXITING... \"regions\" and \"regions to predict\" must indicate the same region name in your config file.") 196 | else: 197 | do_predict(trainer, model, params["predict"], data.test_dataloader()) 198 | 199 | get_cuda_memory_usage(gpus) 200 | 201 | def update_params_based_on_args(options): 202 | config_p = os.path.join('models/configurations',options.config_path) 203 | params = load_config(config_p) 204 | 205 | if options.name != '': 206 | print(params['experiment']['name']) 207 | params['experiment']['name'] = options.name 208 | return params 209 | 210 | def set_parser(): 211 | """ set custom parser """ 212 | 213 | parser = argparse.ArgumentParser(description="") 214 | parser.add_argument("-f", "--config_path", type=str, required=False, default='./configurations/config_basline.yaml', 215 | help="path to config-yaml") 216 | parser.add_argument("-g", "--gpus", type=int, nargs='+', required=False, default=1, 217 | help="specify gpu(s): 1 or 1 5 or 0 1 2 (-1 for no gpu)") 218 | parser.add_argument("-m", "--mode", type=str, required=False, default='train', 219 | help="choose mode: train (default) / val / predict") 220 | parser.add_argument("-c", "--checkpoint", type=str, required=False, default='', 221 | help="init a model from a checkpoint path. '' as default (random weights)") 222 | parser.add_argument("-n", "--name", type=str, required=False, default='', 223 | help="Set the name of the experiment") 224 | 225 | return parser 226 | 227 | def main(): 228 | parser = set_parser() 229 | options = parser.parse_args() 230 | 231 | params = update_params_based_on_args(options) 232 | train(params, options.gpus, options.mode, options.checkpoint) 233 | 234 | if __name__ == "__main__": 235 | main() 236 | """ examples of usage: 237 | 238 | 1) train from scratch on one GPU 239 | python train.py --gpus 2 --mode train --config_path config_baseline.yaml --name baseline_train 240 | 241 | 2) train from scratch on four GPUs 242 | python train.py --gpus 0 1 2 3 --mode train --config_path config_baseline.yaml --name baseline_train 243 | 244 | 3) fine tune a model from a checkpoint on one GPU 245 | python train.py --gpus 1 --mode train --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" --name baseline_tune 246 | 247 | 4) evaluate a trained model from a checkpoint on two GPUs 248 | python train.py --gpus 0 1 --mode val --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" --name baseline_validate 249 | 250 | 5) generate predictions (plese note that this mode works only for one GPU) 251 | python train.py --gpus 1 --mode predict --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" 252 | 253 | 6) generate predictions for the held-out dataset (plese note that this mode works only for one GPU) 254 | python train.py --gpus 1 --mode heldout --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" 255 | 256 | """ 257 | -------------------------------------------------------------------------------- /w4c.yml: -------------------------------------------------------------------------------- 1 | name: w4c 2 | channels: 3 | - pytorch 4 | - anaconda 5 | - conda-forge 6 | - defaults 7 | dependencies: 8 | - _libgcc_mutex=0.1=conda_forge 9 | - _openmp_mutex=4.5=2_kmp_llvm 10 | - absl-py=1.0.0=pyhd8ed1ab_0 11 | - aiohttp=3.8.1=py38h0a891b7_1 12 | - aiosignal=1.2.0=pyhd8ed1ab_0 13 | - alsa-lib=1.2.3.2=h166bdaf_0 14 | - anyio=3.5.0=py38h578d9bd_0 15 | - aom=3.3.0=h27087fc_1 16 | - argon2-cffi=21.3.0=pyhd8ed1ab_0 17 | - argon2-cffi-bindings=21.2.0=py38h0a891b7_2 18 | - asttokens=2.0.5=pyhd8ed1ab_0 19 | - async-timeout=4.0.2=pyhd8ed1ab_0 20 | - attr=2.5.1=h166bdaf_0 21 | - attrs=21.4.0=pyhd8ed1ab_0 22 | - babel=2.10.1=pyhd8ed1ab_0 23 | - backcall=0.2.0=pyh9f0ad1d_0 24 | - backports=1.0=py_2 25 | - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 26 | - beautifulsoup4=4.11.1=pyha770c72_0 27 | - bleach=5.0.0=pyhd8ed1ab_0 28 | - blinker=1.4=py_1 29 | - brotli=1.0.9=h166bdaf_7 30 | - brotli-bin=1.0.9=h166bdaf_7 31 | - brotlipy=0.7.0=py38h0a891b7_1004 32 | - bzip2=1.0.8=h7f98852_4 33 | - c-ares=1.18.1=h7f98852_0 34 | - ca-certificates=2022.4.26=h06a4308_0 35 | - cached-property=1.5.2=hd8ed1ab_1 36 | - cached_property=1.5.2=pyha770c72_1 37 | - cachetools=5.0.0=pyhd8ed1ab_0 38 | - cairo=1.16.0=ha12eb4b_1010 39 | - cartopy=0.20.2=py38h51d8e34_4 40 | - cdo=2.0.5=h2e6804c_0 41 | - certifi=2022.5.18.1=py38h06a4308_0 42 | - cffi=1.15.0=py38h3931269_0 43 | - cftime=1.6.0=py38h71d37f0_1 44 | - charset-normalizer=2.0.12=pyhd8ed1ab_0 45 | - click=8.1.3=py38h578d9bd_0 46 | - colorama=0.4.4=pyh9f0ad1d_0 47 | - cryptography=36.0.2=py38h2b5fc30_1 48 | - cudatoolkit=11.5.1=hcf5317a_10 49 | - cudnn=8.2.1.32=h86fa8c9_0 50 | - curl=7.83.1=h7bff187_0 51 | - cycler=0.11.0=pyhd8ed1ab_0 52 | - dbus=1.13.6=h5008d03_3 53 | - debugpy=1.6.0=py38hfa26641_0 54 | - decorator=5.1.1=pyhd8ed1ab_0 55 | - defusedxml=0.7.1=pyhd8ed1ab_0 56 | - eccodes=2.25.0=hc08acdf_0 57 | - entrypoints=0.4=pyhd8ed1ab_0 58 | - executing=0.8.3=pyhd8ed1ab_0 59 | - expat=2.4.8=h27087fc_0 60 | - ffmpeg=4.4.1=hd7ab26d_2 61 | - fftw=3.3.10=nompi_h77c792f_102 62 | - flit-core=3.7.1=pyhd8ed1ab_0 63 | - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 64 | - font-ttf-inconsolata=3.000=h77eed37_0 65 | - font-ttf-source-code-pro=2.038=h77eed37_0 66 | - font-ttf-ubuntu=0.83=hab24e00_0 67 | - fontconfig=2.14.0=h8e229c2_0 68 | - fonts-conda-ecosystem=1=0 69 | - fonts-conda-forge=1=0 70 | - fonttools=4.33.3=py38h0a891b7_0 71 | - freeglut=3.2.2=h9c3ff4c_1 72 | - freetype=2.10.4=h0708190_1 73 | - fribidi=1.0.10=h36c2ea0_0 74 | - frozenlist=1.3.0=py38h0a891b7_1 75 | - fsspec=2022.3.0=pyhd8ed1ab_0 76 | - future=0.18.2=py38h578d9bd_5 77 | - geos=3.10.2=h9c3ff4c_0 78 | - gettext=0.19.8.1=h73d1719_1008 79 | - giflib=5.2.1=h36c2ea0_2 80 | - gmp=6.2.1=h58526e2_0 81 | - gnutls=3.6.13=h85f3911_1 82 | - google-auth=2.6.6=pyh6c4a22f_0 83 | - google-auth-oauthlib=0.4.6=pyhd8ed1ab_0 84 | - graphite2=1.3.13=h58526e2_1001 85 | - grpcio=1.46.1=py38ha0cdfde_0 86 | - gst-plugins-base=1.20.2=hcf0ee16_0 87 | - gstreamer=1.20.2=hd4edc92_0 88 | - h5py=3.6.0=nompi_py38hfbb2109_100 89 | - harfbuzz=4.2.0=h40b6f09_0 90 | - hdf4=4.2.15=h10796ff_3 91 | - hdf5=1.12.1=nompi_h2386368_104 92 | - icu=69.1=h9c3ff4c_0 93 | - idna=3.3=pyhd8ed1ab_0 94 | - importlib-metadata=4.11.3=py38h578d9bd_1 95 | - importlib_metadata=4.11.3=hd8ed1ab_1 96 | - importlib_resources=5.7.1=pyhd8ed1ab_0 97 | - ipykernel=6.13.0=py38h7f3c49e_0 98 | - ipython=8.3.0=py38h578d9bd_0 99 | - ipython_genutils=0.2.0=py_1 100 | - ipywidgets=7.7.0=pyhd8ed1ab_0 101 | - jack=1.9.18=hfd4fe87_1001 102 | - jasper=2.0.33=ha77e612_0 103 | - jbig=2.1=h7f98852_2003 104 | - jedi=0.18.1=py38h578d9bd_1 105 | - jinja2=3.1.2=pyhd8ed1ab_0 106 | - joblib=1.1.0=pyhd3eb1b0_0 107 | - jpeg=9e=h166bdaf_1 108 | - json-c=0.15=h98cffda_0 109 | - json5=0.9.5=pyh9f0ad1d_0 110 | - jsonschema=4.5.1=pyhd8ed1ab_0 111 | - jupyter=1.0.0=py38h578d9bd_7 112 | - jupyter_client=7.3.1=pyhd8ed1ab_0 113 | - jupyter_console=6.4.3=pyhd8ed1ab_0 114 | - jupyter_core=4.10.0=py38h578d9bd_0 115 | - jupyter_server=1.17.0=pyhd8ed1ab_0 116 | - jupyterlab=3.4.1=pyhd8ed1ab_0 117 | - jupyterlab_pygments=0.2.2=pyhd8ed1ab_0 118 | - jupyterlab_server=2.13.0=pyhd8ed1ab_1 119 | - jupyterlab_widgets=1.1.0=pyhd8ed1ab_0 120 | - keyutils=1.6.1=h166bdaf_0 121 | - kiwisolver=1.4.2=py38h43d8883_1 122 | - krb5=1.19.3=h3790be6_0 123 | - lame=3.100=h7f98852_1001 124 | - lcms2=2.12=hddcbb42_0 125 | - ld_impl_linux-64=2.36.1=hea4e1c9_2 126 | - lerc=3.0=h9c3ff4c_0 127 | - libaec=1.0.6=h9c3ff4c_0 128 | - libblas=3.9.0=14_linux64_mkl 129 | - libbrotlicommon=1.0.9=h166bdaf_7 130 | - libbrotlidec=1.0.9=h166bdaf_7 131 | - libbrotlienc=1.0.9=h166bdaf_7 132 | - libcap=2.51=h166bdaf_1 133 | - libcblas=3.9.0=14_linux64_mkl 134 | - libclang=13.0.1=default_hc23dcda_0 135 | - libclang13=14.0.3=default_h3a83d3e_0 136 | - libcups=2.3.3=hf5a7f15_1 137 | - libcurl=7.83.1=h7bff187_0 138 | - libdb=6.2.32=h9c3ff4c_0 139 | - libdeflate=1.10=h7f98852_0 140 | - libdrm=2.4.109=h7f98852_0 141 | - libedit=3.1.20191231=he28a2e2_2 142 | - libev=4.33=h516909a_1 143 | - libevent=2.1.10=h9b69904_4 144 | - libffi=3.4.2=h7f98852_5 145 | - libflac=1.3.4=h27087fc_0 146 | - libgcc-ng=12.1.0=h8d9b700_16 147 | - libgfortran-ng=12.1.0=h69a702a_16 148 | - libgfortran5=12.1.0=hdcd56e2_16 149 | - libglib=2.70.2=h174f98d_4 150 | - libglu=9.0.0=he1b5a44_1001 151 | - libiconv=1.16=h516909a_0 152 | - liblapack=3.9.0=14_linux64_mkl 153 | - liblapacke=3.9.0=14_linux64_mkl 154 | - libllvm13=13.0.1=hf817b99_2 155 | - libllvm14=14.0.3=he0ac6c6_0 156 | - libnetcdf=4.8.1=nompi_h329d8a1_102 157 | - libnghttp2=1.47.0=h727a467_0 158 | - libnsl=2.0.0=h7f98852_0 159 | - libogg=1.3.4=h7f98852_1 160 | - libopencv=4.5.5=py38h2380011_9 161 | - libopus=1.3.1=h7f98852_1 162 | - libpciaccess=0.16=h516909a_0 163 | - libpng=1.6.37=h21135ba_2 164 | - libpq=14.2=hd57d9b9_0 165 | - libprotobuf=3.20.1=h6239696_0 166 | - libsndfile=1.0.31=h9c3ff4c_1 167 | - libsodium=1.0.18=h36c2ea0_1 168 | - libssh2=1.10.0=ha56f1ee_2 169 | - libstdcxx-ng=12.1.0=ha89aaad_16 170 | - libtiff=4.3.0=h542a066_3 171 | - libtool=2.4.6=h9c3ff4c_1008 172 | - libuuid=2.32.1=h7f98852_1000 173 | - libva=2.14.0=h7f98852_0 174 | - libvorbis=1.3.7=h9c3ff4c_0 175 | - libvpx=1.11.0=h9c3ff4c_3 176 | - libwebp=1.2.2=h3452ae3_0 177 | - libwebp-base=1.2.2=h7f98852_1 178 | - libxcb=1.13=h7f98852_1004 179 | - libxkbcommon=1.0.3=he3ba5ed_0 180 | - libxml2=2.9.12=h885dcf4_1 181 | - libzip=1.8.0=h4de3113_1 182 | - libzlib=1.2.11=h166bdaf_1014 183 | - llvm-openmp=14.0.3=he0ac6c6_0 184 | - lz4-c=1.9.3=h9c3ff4c_1 185 | - magics=4.11.0=he381006_1 186 | - magics-python=1.5.6=pyhd8ed1ab_0 187 | - magma=2.5.4=h6103c52_2 188 | - markdown=3.3.7=pyhd8ed1ab_0 189 | - markupsafe=2.1.1=py38h0a891b7_1 190 | - matplotlib=3.5.2=py38h578d9bd_0 191 | - matplotlib-base=3.5.2=py38h826bfd8_0 192 | - matplotlib-inline=0.1.3=pyhd8ed1ab_0 193 | - mistune=0.8.4=py38h497a2fe_1005 194 | - mkl=2022.0.1=h8d4b97c_803 195 | - multidict=6.0.2=py38h0a891b7_1 196 | - munkres=1.1.4=pyh9f0ad1d_0 197 | - mysql-common=8.0.29=haf5c9bc_0 198 | - mysql-libs=8.0.29=h28c427c_0 199 | - nbclassic=0.3.7=pyhd8ed1ab_0 200 | - nbclient=0.5.13=pyhd8ed1ab_0 201 | - nbconvert=6.5.0=pyhd8ed1ab_0 202 | - nbconvert-core=6.5.0=pyhd8ed1ab_0 203 | - nbconvert-pandoc=6.5.0=pyhd8ed1ab_0 204 | - nbformat=5.4.0=pyhd8ed1ab_0 205 | - nccl=2.12.12.1=h0800d71_0 206 | - ncurses=6.3=h27087fc_1 207 | - nest-asyncio=1.5.5=pyhd8ed1ab_0 208 | - netcdf4=1.5.8=nompi_py38h2823cc8_101 209 | - nettle=3.6=he412f7d_0 210 | - ninja=1.10.2=h4bd325d_1 211 | - notebook=6.4.11=pyha770c72_0 212 | - notebook-shim=0.1.0=pyhd8ed1ab_0 213 | - nspr=4.32=h9c3ff4c_1 214 | - nss=3.77=h2350873_0 215 | - numpy=1.22.3=py38h99721a1_2 216 | - oauthlib=3.2.0=pyhd8ed1ab_0 217 | - opencv=4.5.5=py38h578d9bd_9 218 | - openh264=2.1.1=h780b84a_0 219 | - openjpeg=2.4.0=hb52868f_1 220 | - openssl=1.1.1o=h7f8727e_0 221 | - ossuuid=1.6.2=hf484d3e_1000 222 | - packaging=21.3=pyhd8ed1ab_0 223 | - pandas=1.2.5=py38h295c915_0 224 | - pandoc=2.18=ha770c72_0 225 | - pandocfilters=1.5.0=pyhd8ed1ab_0 226 | - pango=1.50.7=hbd2fdc8_0 227 | - parso=0.8.3=pyhd8ed1ab_0 228 | - pcre=8.45=h9c3ff4c_0 229 | - pexpect=4.8.0=pyh9f0ad1d_2 230 | - pickleshare=0.7.5=py_1003 231 | - pillow=9.1.0=py38h0ee0e06_2 232 | - pip 233 | - pixman=0.40.0=h36c2ea0_0 234 | - proj=9.0.0=h93bde94_1 235 | - prometheus_client=0.14.1=pyhd8ed1ab_0 236 | - prompt-toolkit=3.0.29=pyha770c72_0 237 | - prompt_toolkit=3.0.29=hd8ed1ab_0 238 | - protobuf=3.20.1=py38hfa26641_0 239 | - psutil=5.9.0=py38h0a891b7_1 240 | - pthread-stubs=0.4=h36c2ea0_1001 241 | - ptyprocess=0.7.0=pyhd3deb0d_0 242 | - pulseaudio=14.0=hb166930_4 243 | - pure_eval=0.2.2=pyhd8ed1ab_0 244 | - py-opencv=4.5.5=py38h7f3c49e_9 245 | - pyasn1=0.4.8=py_0 246 | - pyasn1-modules=0.2.7=py_0 247 | - pycparser=2.21=pyhd8ed1ab_0 248 | - pydeprecate=0.3.2=pyhd8ed1ab_0 249 | - pygments=2.12.0=pyhd8ed1ab_0 250 | - pyjwt=2.3.0=pyhd8ed1ab_1 251 | - pyopenssl=22.0.0=pyhd8ed1ab_0 252 | - pyparsing=3.0.9=pyhd8ed1ab_0 253 | - pyproj=3.3.1=py38h5b5ac8f_0 254 | - pyqt=5.12.3=py38ha8c2ead_4 255 | - pyrsistent=0.18.1=py38h0a891b7_1 256 | - pyshp=2.3.0=pyhd8ed1ab_0 257 | - pysocks=1.7.1=py38h578d9bd_5 258 | - python=3.8.13=h582c2e5_0_cpython 259 | - python-dateutil=2.8.2=pyhd8ed1ab_0 260 | - python-fastjsonschema=2.15.3=pyhd8ed1ab_0 261 | - python_abi=3.8=2_cp38 262 | - pytorch=1.11.0=cuda112py38habe9d5a_1 263 | - pytorch-gpu=1.11.0=cuda112py38h68407e5_1 264 | - pytorch-lightning=1.6.3=pyhd8ed1ab_0 265 | - pytorch-mutex=1.0=cuda 266 | - pytz=2022.1=pyhd8ed1ab_0 267 | - pyu2f=0.1.5=pyhd8ed1ab_0 268 | - pyyaml=6.0=py38h0a891b7_4 269 | - pyzmq=22.3.0=py38hfc09fa9_2 270 | - qt=5.12.9=h1304e3e_6 271 | - qtconsole=5.3.0=pyhd8ed1ab_0 272 | - qtconsole-base=5.3.0=pyhd8ed1ab_0 273 | - qtpy=2.1.0=pyhd8ed1ab_0 274 | - readline=8.1=h46c0cb4_0 275 | - requests=2.27.1=pyhd8ed1ab_0 276 | - requests-oauthlib=1.3.1=pyhd8ed1ab_0 277 | - rsa=4.8=pyhd8ed1ab_0 278 | - scikit-learn=1.0.2=py38h51133e4_1 279 | - scipy=1.8.0=py38h56a6a73_1 280 | - seaborn=0.11.2=pyhd3eb1b0_0 281 | - send2trash=1.8.0=pyhd8ed1ab_0 282 | - setuptools=59.5.0=py38h578d9bd_0 283 | - shapely=1.8.2=py38h97f7145_1 284 | - simplejson=3.17.6=py38h0a891b7_1 285 | - sip=6.5.1=py38h709712a_2 286 | - six=1.16.0=pyh6c4a22f_0 287 | - sleef=3.5.1=h9b69904_2 288 | - sniffio=1.2.0=py38h578d9bd_3 289 | - soupsieve=2.3.1=pyhd8ed1ab_0 290 | - sqlite=3.38.5=h4ff8645_0 291 | - stack_data=0.2.0=pyhd8ed1ab_0 292 | - svt-av1=0.9.1=h27087fc_0 293 | - tbb=2021.5.0=h924138e_1 294 | - tensorboard=2.9.0=pyhd8ed1ab_0 295 | - tensorboard-data-server=0.6.0=py38h2b5fc30_2 296 | - tensorboard-plugin-wit=1.8.1=pyhd8ed1ab_0 297 | - terminado=0.13.3=py38h578d9bd_1 298 | - threadpoolctl=2.2.0=pyh0d69192_0 299 | - tinycss2=1.1.1=pyhd8ed1ab_0 300 | - tk=8.6.12=h27826a3_0 301 | - toml=0.10.2=pyhd8ed1ab_0 302 | - torchaudio=0.11.0=py38_cu115 303 | - torchmetrics=0.8.2=pyhd8ed1ab_0 304 | - torchvision=0.12.0=cuda112py38h46b2766_1 305 | - tornado=6.1=py38h0a891b7_3 306 | - tqdm=4.64.0=pyhd8ed1ab_0 307 | - traitlets=5.2.0=pyhd8ed1ab_0 308 | - typing-extensions=4.2.0=hd8ed1ab_1 309 | - typing_extensions=4.2.0=pyha770c72_1 310 | - udunits2=2.2.28=hc3e0081_0 311 | - unicodedata2=14.0.0=py38h0a891b7_1 312 | - urllib3=1.26.9=pyhd8ed1ab_0 313 | - voila=0.3.5=pyhd8ed1ab_0 314 | - wcwidth=0.2.5=pyh9f0ad1d_2 315 | - webencodings=0.5.1=py_1 316 | - websocket-client=1.3.2=pyhd8ed1ab_0 317 | - websockets=10.3=py38h0a891b7_0 318 | - werkzeug=2.1.2=pyhd8ed1ab_1 319 | - wheel=0.37.1=pyhd8ed1ab_0 320 | - widgetsnbextension=3.6.0=py38h578d9bd_0 321 | - x264=1!161.3030=h7f98852_1 322 | - x265=3.5=h924138e_3 323 | - xorg-fixesproto=5.0=h7f98852_1002 324 | - xorg-inputproto=2.3.2=h7f98852_1002 325 | - xorg-kbproto=1.0.7=h7f98852_1002 326 | - xorg-libice=1.0.10=h7f98852_0 327 | - xorg-libsm=1.2.3=hd9c2040_1000 328 | - xorg-libx11=1.7.2=h7f98852_0 329 | - xorg-libxau=1.0.9=h7f98852_0 330 | - xorg-libxdmcp=1.1.3=h7f98852_0 331 | - xorg-libxext=1.3.4=h7f98852_1 332 | - xorg-libxfixes=5.0.3=h7f98852_1004 333 | - xorg-libxi=1.7.10=h7f98852_0 334 | - xorg-libxrender=0.9.10=h7f98852_1003 335 | - xorg-renderproto=0.11.1=h7f98852_1002 336 | - xorg-xextproto=7.3.0=h7f98852_1002 337 | - xorg-xproto=7.0.31=h7f98852_1007 338 | - xz=5.2.5=h516909a_1 339 | - yaml=0.2.5=h7f98852_2 340 | - yarl=1.7.2=py38h0a891b7_2 341 | - zeromq=4.3.4=h9c3ff4c_1 342 | - zipp=3.8.0=pyhd8ed1ab_0 343 | - zlib=1.2.11=h166bdaf_1014 344 | - zstd=1.5.2=ha95c52a_0 345 | - pip: 346 | - pyqt5-sip==4.19.18 347 | - pyqtchart==5.12 348 | - pyqtwebengine==5.12.1 349 | - xarray==2022.3.0 350 | prefix: ./ 351 | -------------------------------------------------------------------------------- /models/unet_lightning.py: -------------------------------------------------------------------------------- 1 | # Weather4cast 2022 Starter Kit 2 | # 3 | # Copyright (C) 2022 4 | # Institute of Advanced Research in Artificial Intelligence (IARAI) 5 | 6 | # This file is part of the Weather4cast 2022 Starter Kit. 7 | # 8 | # The Weather4cast 2022 Starter Kit is free software: you can redistribute it 9 | # and/or modify it under the terms of the GNU General Public License as 10 | # published by the Free Software Foundation, either version 3 of the License, 11 | # or (at your option) any later version. 12 | # 13 | # The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 14 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 22 | 23 | 24 | import pytorch_lightning as pl 25 | from sklearn.metrics import confusion_matrix 26 | import torch 27 | import torch.nn as nn 28 | import torch.nn.functional as F 29 | from utils.evaluate import * 30 | import numpy as np; 31 | 32 | #models 33 | from models.baseline_UNET3D import UNet as Base_UNET3D # 3_3_2 model selection 34 | 35 | VERBOSE = False 36 | # VERBOSE = True 37 | 38 | class UNet_Lightning(pl.LightningModule): 39 | def __init__(self, UNet_params: dict, params: dict, 40 | **kwargs): 41 | super(UNet_Lightning, self).__init__() 42 | 43 | self.in_channels = params['in_channels'] 44 | self.start_filts = params['init_filter_size'] 45 | self.dropout_rate = params['dropout_rate'] 46 | self.model = Base_UNET3D(in_channels=self.in_channels, start_filts = self.start_filts, dropout_rate = self.dropout_rate) 47 | 48 | self.save_hyperparameters() 49 | self.params = params 50 | #self.example_input_array = np.zeros((44,252,252)) 51 | 52 | self.val_batch = 0 53 | 54 | self.prec = 7 55 | 56 | pos_weight = torch.tensor(params['pos_weight']); 57 | if VERBOSE: print("Positive weight:",pos_weight); 58 | 59 | self.loss = params['loss'] 60 | self.bs = params['batch_size'] 61 | self.loss_fn = { 62 | 'smoothL1': nn.SmoothL1Loss(), 'L1': nn.L1Loss(), 'mse': F.mse_loss, 63 | 'BCELoss': nn.BCELoss(), 64 | 'BCEWithLogitsLoss': nn.BCEWithLogitsLoss(pos_weight=pos_weight), 'CrossEntropy': nn.CrossEntropyLoss(), 'DiceBCE': DiceBCELoss(), 'DiceLoss': DiceLoss(), 65 | 'mIoULoss': mIoU() 66 | }[self.loss] 67 | self.main_metric = { 68 | 'smoothL1': 'Smooth L1', 69 | 'L1': 'L1', 70 | 'mse': 'MSE', # mse [log(y+1)-yhay]' 71 | 'BCELoss': 'BCE', # binary cross-entropy 72 | 'BCEWithLogitsLoss': 'BCE with logits', 73 | 'CrossEntropy': 'cross-entropy', 74 | 'DiceBCE': 'Dice BCE', 75 | 'DiceLoss': 'Dice loss', 76 | 'mIoULoss': 'Modified IoU' 77 | }[self.loss] 78 | 79 | self.relu = nn.ReLU() # None 80 | t = f"============== n_workers: {params['n_workers']} | batch_size: {params['batch_size']} \n"+\ 81 | f"============== loss: {self.loss} | weight: {pos_weight} (if using BCEwLL)" 82 | print(t) 83 | 84 | def on_fit_start(self): 85 | """ create a placeholder to save the results of the metric per variable """ 86 | metric_placeholder = {self.main_metric: -1} 87 | self.logger.log_hyperparams(self.hparams, metric_placeholder) 88 | 89 | def forward(self, x): 90 | x = self.model(x) 91 | #if self.loss =='BCELoss': 92 | #x = self.relu(x) 93 | return x 94 | 95 | def retrieve_only_valid_pixels(self, x, m): 96 | """ we asume 1s in mask are invalid pixels """ 97 | ##print(f"x: {x.shape} | mask: {m.shape}") 98 | return x[~m] 99 | 100 | def get_target_mask(self, metadata): 101 | mask = metadata['target']['mask'] 102 | #print("mask---->", mask.shape) 103 | return mask 104 | 105 | def _compute_loss(self, y_hat, y, agg=True, mask=None): 106 | 107 | if self.loss == "mIoULoss": 108 | y_hat = 0.5 * torch.tanh(y_hat/2) + 0.5 109 | if mask is not None: 110 | y_hat[mask] = 0 111 | y[mask] = 0 112 | # print("================================================================================") 113 | # print(y_hat.shape, y_hat.min(), y_hat.max()) 114 | # print(y.shape, y.min(), y.max()) 115 | if agg: 116 | loss = self.loss_fn(y_hat, y) 117 | else: 118 | loss = self.loss_fn(y_hat, y, reduction='none') 119 | return loss 120 | 121 | def training_step(self, batch, batch_idx, phase='train'): 122 | x, y, metadata = batch 123 | if VERBOSE: 124 | print('x', x.shape, 'y', y.shape, '----------------- batch') 125 | y_hat = self.forward(x) 126 | if VERBOSE: 127 | print('y_hat', y_hat.shape, 'y', y.shape, '----------------- model') 128 | mask = self.get_target_mask(metadata) 129 | loss = self._compute_loss(y_hat, y, mask=mask) 130 | #recall, precision, F1, acc = recall_precision_f1_acc(y, y_hat) 131 | #LOGGING 132 | #values = {'{phase}_loss': loss, '{phase}_acc': acc, '{phase}_recall': recall, '{phase}_precision': precision, 'F1': F1} 133 | self.log(f'{phase}_loss', loss,batch_size=self.bs, sync_dist=True) 134 | return loss 135 | 136 | def validation_step(self, batch, batch_idx, phase='val'): 137 | #data_start = timer() 138 | x, y, metadata = batch 139 | #data_end = timer() 140 | if VERBOSE: 141 | print('x', x.shape, 'y', y.shape, '----------------- batch') 142 | y_hat = self.forward(x) 143 | mask = self.get_target_mask(metadata) 144 | if VERBOSE: 145 | print('y_hat', y_hat.shape, 'y', y.shape, '----------------- model') 146 | 147 | loss = self._compute_loss(y_hat, y, mask=mask) 148 | 149 | # todo: add the same plot as in `test_step` 150 | 151 | if self.loss == "BCEWithLogitsLoss" or self.loss == "mIoULoss": 152 | print("applying thresholds to y_hat logits") 153 | # set the logits threshold equivalent to sigmoid(x)>=0.5 154 | idx_gt0 = y_hat>=0 155 | y_hat[idx_gt0] = 1 156 | y_hat[~idx_gt0] = 0 157 | 158 | if mask is not None: 159 | y_hat[mask]=0 160 | y[mask]=0 161 | 162 | recall, precision, F1, acc, csi = recall_precision_f1_acc(y, y_hat) 163 | iou = iou_class(y_hat, y) 164 | 165 | #LOGGING 166 | self.log(f'{phase}_loss', loss, batch_size=self.bs, sync_dist=True) 167 | values = {'val_acc': acc, 'val_recall': recall, 168 | 'val_precision': precision, 'val_F1': F1, 'val_iou': iou, 169 | 'val_CSI': csi 170 | # , 'val_N': float(x.shape[0]) 171 | } 172 | self.log_dict(values, batch_size=self.bs, sync_dist=True) 173 | 174 | return {'loss': loss.cpu(), 'N': x.shape[0], 175 | 'iou': iou} 176 | 177 | def validation_epoch_end(self, outputs, phase='val'): 178 | print("Validation epoch end average over batches: ", 179 | [batch['N'] for batch in outputs]); 180 | avg_loss = np.average([batch['loss'] for batch in outputs], 181 | weights=[batch['N'] for batch in outputs]); 182 | avg_iou = np.average([batch['iou'] for batch in outputs], 183 | weights=[batch['N'] for batch in outputs]); 184 | values={f"{phase}_loss_epoch": avg_loss, 185 | f"{phase}_iou_epoch": avg_iou} 186 | self.log_dict(values, batch_size=self.bs, sync_dist=True) 187 | self.log(self.main_metric, avg_loss, batch_size=self.bs, sync_dist=True) 188 | 189 | 190 | def test_step(self, batch, batch_idx, phase='test'): 191 | x, y, metadata = batch 192 | if VERBOSE: 193 | print('x', x.shape, 'y', y.shape, '----------------- batch') 194 | y_hat = self.forward(x) 195 | mask = self.get_target_mask(metadata) 196 | if VERBOSE: 197 | print('y_hat', y_hat.shape, 'y', y.shape, '----------------- model') 198 | loss = self._compute_loss(y_hat, y, mask=mask) 199 | ## todo: add the same plot as in `test_step` 200 | if self.loss == "BCEWithLogitsLoss" or self.loss == "mIoULoss": 201 | print("applying thresholds to y_hat logits") 202 | # set the logits threshold equivalent to sigmoid(x)>=0.5 203 | idx_gt0 = y_hat>=0 204 | y_hat[idx_gt0] = 1 205 | y_hat[~idx_gt0] = 0 206 | 207 | if mask is not None: 208 | y_hat[mask]=0 209 | y[mask]=0 210 | 211 | recall, precision, F1, acc, csi = recall_precision_f1_acc(y, y_hat) 212 | iou = iou_class(y_hat, y) 213 | 214 | #LOGGING 215 | self.log(f'{phase}_loss', loss, batch_size=self.bs, sync_dist=True) 216 | values = {'test_acc': acc, 'test_recall': recall, 'test_precision': precision, 'test_F1': F1, 'test_iou': iou, 'test_CSI': csi} 217 | self.log_dict(values, batch_size=self.bs, sync_dist=True) 218 | 219 | return 0, y_hat 220 | 221 | def predict_step(self, batch, batch_idx, phase='predict'): 222 | x, y, metadata = batch 223 | y_hat = self.model(x) 224 | mask = self.get_target_mask(metadata) 225 | if VERBOSE: 226 | print('y_hat', y_hat.shape, 'y', y.shape, '----------------- model') 227 | if self.loss == "BCEWithLogitsLoss" or self.loss == "mIoULoss": 228 | print("applying thresholds to y_hat logits") 229 | # set the logits threshold equivalent to sigmoid(x)>=0.5 230 | idx_gt0 = y_hat>=0 231 | y_hat[idx_gt0] = 1 232 | y_hat[~idx_gt0] = 0 233 | return y_hat 234 | 235 | def configure_optimizers(self): 236 | if VERBOSE: print("Learning rate:",self.params["lr"], "| Weight decay:",self.params["weight_decay"]) 237 | optimizer = torch.optim.AdamW(self.parameters(), 238 | lr=float(self.params["lr"]),weight_decay=float(self.params["weight_decay"])) 239 | return optimizer 240 | 241 | def seq_metrics(self, y_true, y_pred): 242 | text = '' 243 | cm = confusion_matrix(y_true, y_pred).ravel() 244 | if len(cm)==4: 245 | tn, fp, fn, tp = cm 246 | recall, precision, F1 = 0, 0, 0 247 | 248 | if (tp + fn) > 0: 249 | recall = tp / (tp + fn) 250 | r = f'r: {recall:.2f}' 251 | 252 | if (tp + fp) > 0: 253 | precision = tp / (tp + fp) 254 | p = f'p: {precision:.2f}' 255 | 256 | if (precision + recall) > 0: 257 | F1 = 2 * (precision * recall) / (precision + recall) 258 | f = f'F1: {F1:.2f}' 259 | 260 | acc = (tn + tp) / (tn+fp+fn+tp) 261 | text = f"{r} | {p} | {f} | acc: {acc} " 262 | 263 | return text 264 | 265 | 266 | def main(): 267 | print("running") 268 | if __name__ == 'main': 269 | main() 270 | 271 | #PyTorch 272 | class DiceLoss(nn.Module): 273 | def __init__(self, weight=None, size_average=True): 274 | super(DiceLoss, self).__init__() 275 | 276 | def forward(self, targets, inputs, smooth=1): 277 | 278 | #comment out if your model contains a sigmoid or equivalent activation layer 279 | inputs = F.sigmoid(inputs) 280 | 281 | #flatten label and prediction tensors 282 | inputs = inputs.view(-1) 283 | targets = targets.view(-1) 284 | 285 | intersection = (inputs * targets).sum() 286 | print('intersection', intersection) 287 | print('inputs', inputs.sum()) 288 | print('targets', targets.sum()) 289 | dice = (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth) 290 | print(1-dice) 291 | return 1 - dice 292 | 293 | class DiceBCELoss(nn.Module): 294 | def __init__(self, weight=None, size_average=True): 295 | super(DiceBCELoss, self).__init__() 296 | 297 | def forward(self, inputs, targets, smooth=1): 298 | 299 | #comment out if your model contains a sigmoid or equivalent activation layer 300 | inputs = F.sigmoid(inputs) 301 | 302 | #flatten label and prediction tensors 303 | inputs = inputs.view(-1) 304 | targets = targets.view(-1) 305 | 306 | intersection = (inputs * targets).sum() 307 | dice_loss = 1 - (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth) 308 | BCE = F.binary_cross_entropy(inputs, targets, reduction='mean') 309 | Dice_BCE = BCE + dice_loss 310 | 311 | return Dice_BCE 312 | 313 | 314 | ## adapted from 315 | ## https://github.com/amirhosseinh77/UNet-AerialSegmentation/blob/main/losses.py 316 | ## by Amirhossein Heydarian (GPL 3) 317 | ## 318 | class mIoU(nn.Module): 319 | def __init__(self, n_classes=1): 320 | super(mIoU, self).__init__() 321 | self.classes = n_classes 322 | 323 | def forward(self, inputs, target): 324 | # inputs => N x Classes x H x W 325 | # target_oneHot => N x Classes x H x W 326 | 327 | N = inputs.size()[0] 328 | inter = inputs * target 329 | ## Sum over all pixels N x C x H x W => N x C 330 | inter = inter.view(N,self.classes,-1).sum(2) 331 | #Denominator 332 | union= inputs + target - (inputs*target) 333 | ## Sum over all pixels N x C x H x W => N x C 334 | union = union.view(N,self.classes,-1).sum(2) 335 | loss = torch.nan_to_num(inter/union) 336 | 337 | ## Return average loss over classes and batch 338 | return 1-loss.mean() 339 | 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Title](/images/weather4cast_v1000-26.png?raw=true "Weather4cast competition") 2 | 3 | # [Weather4cast](https://www.iarai.ac.at/weather4cast/) - Super-Resolution Rain Movie Prediction under Spatio-Temporal Shifts 4 | - Predict super-resolution rain movies in various regions of Europe 5 | - Transfer learning across space and time under strong shifts 6 | - Exploit data fusion to model ground-radar and multi-band satellite images 7 | 8 | ## Contents 9 | [Weather4cast: Super-Resolution Rain Movie Prediction under Spatio-Temporal Shifts](#weather4cast-multi-sensor-weather-forecasting-competition--benchmark-dataset) 10 | - [Contents](#contents) 11 | - [Introduction](#introduction) 12 | - [Get the data](#get-the-data) 13 | - [Submission guide](#submission-guide) 14 | - [Starter kit](#starter-kit) 15 | - [Environment](#environment) 16 | - [Training](#training) 17 | - [Validation](#validation) 18 | - [TensorBoard](#tensorboard) 19 | - [Generating a submission](#generating-a-submission) 20 | - [Automated generation of submissions](#automated-generation-of-submissions-helper-scripts) 21 | - [Code and Scientific Abstract](#code-and-scientific-abstract) 22 | - [Cite](#citation) 23 | - [Credits](#credits) 24 | 25 | ## Introduction 26 | The aim of the 2022 edition of the Weather4cast competition is to predict future high resolution rainfall events from lower resolution satellite radiances. Ground-radar reflectivity measurements are used to calculate pan-European composite rainfall rates by the [Operational Program for Exchange of Weather Radar Information (OPERA)](https://www.eumetnet.eu/activities/observations-programme/current-activities/opera/) radar network. While these are more precise, accurate, and of higher resolution than satellite data, they are expensive to obtain and not available in many parts of the world. We thus want to learn how to predict this high value rain rates from radiation measured by geostationary satellites operated by the [European Organisation for the Exploitation of Meteorological Satellites (EUMETSAT)](https://www.eumetsat.int/). 27 | 28 | # Prediction task 29 | Competition participants should predict rainfall locations for the next 8 hours in 32 time slots from an input sequence of 4 time slots of the preceeding hour. The input sequence consists of four 11-band spectral satellite images. These 11 channels show slightly noisy satellite radiances covering so-called visible (VIS), water vapor (WV), and infrared (IR) bands. Each satellite image covers a 15 minute period and its pixels correspond to a spatial area of about 12km x 12km. The prediction output is a sequence of 32 images representing rain rates from ground-radar reflectivities. Output images also have a temporal resolution of 15 minutes but have higher spatial resolution, with each pixel corresponding to a spatial area of about 2km x 2km. So in addition to predicting the weather in the future, converting satellite inputs to ground-radar outputs, this adds a super-resolution task due to the coarser spatial resolution of the satellite data 30 | 31 | ### Weather4cast 2022 - Stage 1 32 | For Stage 1 of the competition we provide data from three Eureopean regions selected based on their preciptation characteristics. The task is to predict rain events 8 hours into the future from a 1 hour sequence of satellite images. The models should output binary pixels, with 1 and 0 indicating *rain* or *no rain* respectively. Rain rates computed from OPERA ground-radar reflectivities provide a ground truth. Although we provide the rain rates, at this stage, only rain/no rain needs to be predicted for each pixel. 33 | 34 | For Stage 1 we provide data from one year only, covering February to December 2019. 35 | 36 | ### Weather4cast 2022 - Stage 2 37 | In Stage 2 additional data will be provided for 2020 and 2021. Years 2019 and 2020 can then be used for training, while test sets from 2021 assess model robustness to temporal shifts. Additional regions with different climatological characteristics test model robustsness under spatial shifts. There are thus additional files for the new regions and years and thus the folder structure for stage 2 has been expanded accordingly to include additional sub-folders with the data for 2020 and 2021. In total there then are 7 regions with full training data in both 2019 and 2020. Three additional regions provide a spatial transfer learning challenge in years 2019 and 2020. For all ten regions, the year 2021 provides a temporal transfer learning challenge. For the seven regions with extensive training data in 2019 and 2020 this constitutes a pure temporal transfer learning challenge. The three additional regions 2021 provide a combined spatial and temporal transfer learning challenge. 38 | 39 | 40 | ## Get the data 41 | You need to register for the competition and accept its Terms and Conditions to access the data: 42 | 43 | - Competition Data: [Join and get the data](https://www.iarai.ac.at/weather4cast/get-data-2022/) 44 | 45 | Data are provided in [HDF-5](https://docs.h5py.org/en/stable/quick.html) files, separately for each year and data type. In our canonical folder structure `year/datatype/` the HRIT folder holds the satellite data and the OPERA folder provides the ground radar data. The file names reflect the different regions (`boxi_####`) and data splits (`train`, `validation`, and `test`). Ground truth for the test data split is of course withheld. 46 | 47 | After downloading the data, your data files should thus be arranged in folders of the following structure: 48 | ``` 49 | 2019/ 50 | +-- HRIT/ ... sub-folder for satellite radiance datasets 51 | +-- boxi_0015.test.reflbt0.ns.h5 52 | +-- boxi_0015.train.reflbt0.ns.h5 53 | +-- boxi_0015.val.reflbt0.ns.h5 54 | +-- boxi_00XX……. 55 | +-- OPERA/ ... sub-folder for OPERA ground-radar rain rates 56 | +-- boxi_0015.train.rates.crop.h5 57 | +-- boxi_0015.val.rates.crop.h5 58 | +-- boxi_00XX……. 59 | 2020/ 60 | +-- HRIT/ ... sub-folder for satellite radiance datasets 61 | +-- boxi_0015.test.reflbt0.ns.h5 62 | +-- boxi_0015.train.reflbt0.ns.h5 63 | +-- boxi_0015.val.reflbt0.ns.h5 64 | +-- boxi_00XX……. 65 | +-- OPERA/ ... sub-folder for OPERA ground-radar rain rates 66 | +-- boxi_0015.train.rates.crop.h5 67 | +-- boxi_0015.val.rates.crop.h5 68 | +-- boxi_00XX……. 69 | ``` 70 | 71 | Each HDF file provides a set of (multi-channel) images: 72 | 73 | - **boxi_00XX.train.reflbt0.ns.h5** provides *REFL-BT*, which is a tensor of shape `(20308, 11, 252, 252)` representing 20,308 images with 11 channels of satellite radiances for region XX. These are the input training data. The order of the channels in the H5 file corresonds to the following order of the satellite channels: `IR_016, IR_039, IR_087, IR_097, IR_108, IR_120,IR_134, VIS006, VIS008, WV_062, WV_073`. 74 | 75 | - **boxi_00XX.train.rates.crop.h5** provides *rates.crop*, which is a tensor of shape `(20308, 11, 252, 252)` representing OPERA ground-radar rain rates for the corresponding satellite radiances from the train dataset. Model output should be 1 or 0 for rain or no-rain predictions respectively. 76 | 77 | - **boxi_00XX.val.reflbt0.ns.h5** provides *REFL-BT*, which is a tensor of shape `(2160, 11, 252, 252)` representing additional measured satellite radiances. This data can be used as input for independent model validation. There are 60 validation sequences and each validation sequence consists of images for 4 input time slots; while in addition we also provide images for the 32 output time slots please note that this is just to aid model development and that model predictions cannot use these. The validation data set thus holds 4x60 + 32x60 = 2,160 images in total. 78 | 79 | - **boxi_00XX.val.rates.crop.h5** provides *rates.crop*, which is a tensor of shape `(2160, 1, 252, 252)` representing OPERA ground-radar rain rates for the corresponding satellite radiances from the validation dataset. Model output should be 1 or 0 for rain or no-rain predictions respectively. 80 | 81 | - **boxi_00XX.test.reflbt0.ns.h5** provides *REFL-BT*, which is a tensor of a shape `(240, 11, 252, 252)` representing additional satellite radiances. This dataset gives the input data for your model predictions for submission to the leaderboard. There are 60 input sequences in total, as each test sequence consists of images for 4 time slots (4x60 = 240). Note that no satellite radiances are provided for the future, so this is a true prediction task. 82 | 83 | Both input satellite radiances and output OPERA ground-radar rain rates are given for 252x252 pixel patches but please note that the spatial resolution of the satellite images is about six times lower than the resolution of the ground radar. This means that the 252x252 pixel ground radar patch corresponds to a 42x42 pixel center region in the coarser satellite resolution. The model target region thus is surrounded by a large area providing sufficient context as input for a prediction of future weather. In fact, fast storm clouds from one border of the input data would reach the center target region in about 7-8h. 84 | 85 | ![Context](/images/opera_satelite_context_explained.png?raw=true "Weather4cast competition") 86 | 87 | - Stage-2 Competition: [Join and get the data](https://www.iarai.ac.at/weather4cast/get-data-2022/) 88 | ## Submission guide 89 | For submissions you need to upload a ZIP format archive of HDF-5 files that follows the folder structure below. Optionally, each HDF-5 file can be compressed by gzip, allowing for simple parallelization of the compression step. You need to include model predictions for all the regions. For each region, an HDF file should provide *submission*, a tensor of type `float32` and shape `(60, 1, 32, 252, 252)`, representing your predictions for the 60 test samples of a region. You need to follow the file naming convention shown in the example below to indicate the target region. Predictions for different years need to be placed in separate folders as shown below. The folder structure must be preserved in the submitted ZIP file. Please note that for Stage 1 we only ask for predictions for the year 2019, and predictions are simply 1 or 0 to indicate *rain* or *no rain* events respectively. For the Stage 2 Core Challenge, we ask for predictions for a total of 7 regions in both 2019 and 2020. For the Stage 2 Transfer Learning Challenge, predictions for 3 regions are required in years 2019 and 2020, and for all 10 regions in 2021. To simplify compilation of predictions, we now provide helper scripts in the Starter Kit. 90 | 91 | ``` 92 | +-- 2019 – 93 | +-- boxi_0015.pred.h5.gz ...1 file per region for 60 test-sequence predictions of 32 time-slots each 94 | +-- boxi_00XX…. 95 | +-- 2020 – 96 | +-- boxi_0015.pred.h5.gz 97 | +-- boxi_00XX…. 98 | ``` 99 | 100 | ## Starter kit 101 | This repository provides a starter kit accompanying the Weather4cast 2022 competition that includes example code to get you up to speed quickly. Please note that its use is entirely optional. The sample code includes a dataloader, some helper scripts, and a Unet-3D baseline model, some parameters of which can be set in a configuration file. 102 | 103 | To obtain the baseline model, you will need the `wget` command installed - then you can run 104 | ``` 105 | ./mk_baseline.sh 106 | ``` 107 | to fetch and patch a basic 3D U-Net baseline model. 108 | 109 | You will need to download the competition data separately. The sample code assumes that the downloaded data are organized in the following folder structure (shown here for Stage-1 data, conversely for Stage-2): 110 | 111 | ``` 112 | +-- data 113 | +-- 2019 – 114 | +-- HRIT -- 115 | +-- boxi_0015.test.reflbt0.ns.h5 116 | +-- boxi_0015.train.reflbt0.ns.h5 117 | +-- boxi_0015.val.reflbt0.ns.h5 118 | +-- boxi_0034.test.reflbt0.ns.h5 119 | +-- boxi_0034.train.reflbt0.ns.h5 120 | +-- boxi_0034.val.reflbt0.ns.h5 121 | +-- boxi_0076.test.reflbt0.ns.h5 122 | +-- boxi_0076.train.reflbt0.ns.h5 123 | +-- boxi_0076.val.reflbt0.ns.h5 124 | +-- OPERA -- 125 | +-- boxi_0015.train.rates.crop.h5 126 | +-- boxi_0015.val.rates.crop.h5 127 | +-- boxi_0034.train.rates.crop.h5 128 | +-- boxi_0034.val.rates.crop.h5 129 | +-- boxi_0076.train.rates.crop.h5 130 | +-- boxi_0076.val.rates.crop.h5 131 | ``` 132 | 133 | The path to the parent folder `data` needs to be provided as the `data_root` parameter in the `config_baseline.yaml` file. 134 | 135 | ### Environment 136 | We provide Conda environments for the sample code which can be recreated locally. An environment with libraries current at release can be recreated from the file `w4cNew.yml`using the following command: 137 | ``` 138 | conda env create -f w4cNew.yml 139 | ``` 140 | If you want to use older libraries for compatibility reasons, we also provide an earlier environment in `w4c.yml`. Finally, if you want to create an environment in the future, we also provide a script `mk_env.sh` to get you started. 141 | Note that all this can easily run for an hour or more, depending on your machine and setup. 142 | 143 | To activate the environment please run 144 | ``` 145 | conda activate w4cNew 146 | ``` 147 | or 148 | ``` 149 | conda activate w4c 150 | ``` 151 | respectively. 152 | 153 | ### Training 154 | 155 | We provide a script `train.py` with all the necessary code to train and explore a modified version of a [3D variant of the U-Net](https://github.com/ELEKTRONN/elektronn3). The script supports training from scratch or fine tuning from a provided checkpoint. The same script can also be used to evaluate model predictions on the validation data split using the flag `--mode val`, or to generate submissions from the test data using the flag `--mode predict`. 156 | In all cases please ensure you have set the correct data path in `config_baseline.yaml` and activated the `w4c` environment. 157 | 158 | *Example invocations:* 159 | - Training the model on a single GPU: 160 | ``` 161 | python train.py --gpus 0 --config_path config_baseline.yaml --name name_of_your_model 162 | ``` 163 | If you have more than one GPU you can select which GPU to use, with numbering starting from zero. 164 | - Fine tuning the model on 4 GPUs starting with a given checkpoint: 165 | ``` 166 | python train.py --gpus 0 1 2 3 --mode train --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" --name baseline_tune 167 | ``` 168 | 169 | ### Validation 170 | Training will create logs and checkpoint files that are saved in the `lightning_logs` directory. To validate your model from a checkpoint you can for example run the following command (here for two CPUs): 171 | ``` 172 | python train.py --gpus 0 1 --mode val --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" --name baseline_validate 173 | ``` 174 | 175 | ### TensorBoard 176 | You can of course also use [TensorBoard](https://www.tensorflow.org/tensorboard) to track and visualize model evaluation metrics during the training process. 177 | The standard TensorBoard command line is: 178 | ``` 179 | tensorboard --logdir ./lightning_logs 180 | ``` 181 | This should confirm that TensorBoard has started. For the default port, you point your browser to http://localhost:6006. 182 | 183 | ### Generating a submission 184 | Submission files can be generated from a trained model based on the model paramters saved in the checkpoint file. To generate predictions from your model checkpoint you can run the `train.py` script as below: 185 | ``` 186 | train.py --gpus 0 --mode predict --config_path config_baseline.yaml --checkpoint "lightning_logs/PATH-TO-YOUR-MODEL-LOGS/checkpoints/YOUR-CHECKPOINT-FILENAME.ckpt" 187 | ``` 188 | The code currently does not support generating a prediction for more than one region/year at a time. 189 | 190 | The results are saved in a single HDF-5 file named `boxi_00XX.pred.h5` in the `./submssion/YEAR/` folder, where *boxi_00XX* is the name of the region defined in the *predict* section your config file. A sample configuration is shown below: 191 | ``` 192 | predict: 193 | region_to_predict: boxi_0015 194 | year_to_predict: 2019 195 | ``` 196 | To generate predictions for multiple regions this needs to be run with a separate configuration file for each region. 197 | 198 | After generating prediction files for all the regions, please pack them into a single ZIP file (keeping the `year/` folder structure) and submit them to the [respective Weather4cast leaderboards](https://www.iarai.ac.at/weather4cast/challenge/). 199 | 200 | ### Automated generation of submissions (helper scripts) 201 | Considering the much increased number of individual predictions to collect for a leaderboard submission in Stage-2, we now provide helper scripts `mk_pred_core.sh` and `./mk_pred_transfer.sh` that can be used to generate and compile all individual predictions from a single model. The scripts display help text and diagnostics. Note that the use of these scripts is entirely optional because you may prefer to apply different models for different regions. You can provide both an output directory and a GPU ID to generate multiple predictions in parallel. The script will typically run for 20-40 minutes on a recent GPU system. 202 | 203 | Example invocation for interactive use: 204 | ``` 205 | ./mk_pred_core.sh config_baseline_stage2-pred.yaml 'lightning_logs/yourModelName/checkpoints/yourCheckPointName.ckpt' yourSubmissionName 0 2>&1 | tee yourSubmission.core.log 206 | ``` 207 | 208 | ## Code and Scientific Abstract 209 | At the end of the competition paricpants are required to provide: 210 | 1. A short scientific paper (Scientific Abstract) with a sufficiently detailed description of your approach (4-6 pages plus references) 211 | 2. The code and models with their learned weights that you used for your predictions, with explanations of how to reproduce you submissions. 212 | 213 | We will notify participants of how to provide their scientific abstract. For the code, you will need to submit it to a public repository like GitHub, providing a link to download the model's learned weights. Ideally, your repository should at least contain: 214 | - a) A list of **dependencies**. In the case of using Python, we suggest using conda/pip to generate them: `conda env export > environment.yml`. Make sure that your code can be executed from a fresh environment using the provided list of requirements: `conda env create -f environment.yml`. 215 | - b) **Code**, **models**, and a **folder with all model weights**. 216 | - c) An **out-of-the-box script** to use your best model **to generate predictions**. The script will read the inputs for the model from a given path and region, using its test folder (like the one used for the leaderboard), and save the outputs on a given path. The path to the folder containing the weights to be loaded by the models can also be an argument of the script. 217 | 218 | 219 | ## Citation 220 | 221 | When using or referencing the Weather4cast Competition in general or the competition data please cite: 222 | ``` 223 | @INPROCEEDINGS{9672063, 224 | author={Herruzo, Pedro and Gruca, Aleksandra and Lliso, Llorenç and Calbet, Xavier and Rípodas, Pilar and Hochreiter, Sepp and Kopp, Michael and Kreil, David P.}, 225 | booktitle={2021 IEEE International Conference on Big Data (Big Data)}, 226 | title={High-resolution multi-channel weather forecasting – First insights on transfer learning from the Weather4cast Competitions 2021}, 227 | year={2021}, 228 | volume={}, 229 | number={}, 230 | pages={5750-5757}, 231 | doi={10.1109/BigData52589.2021.9672063} 232 | } 233 | 234 | @inbook{10.1145/3459637.3482044, 235 | author = {Gruca, Aleksandra and Herruzo, Pedro and R\'{\i}podas, Pilar and Kucik, Andrzej and Briese, Christian and Kopp, Michael K. and Hochreiter, Sepp and Ghamisi, Pedram and Kreil, David P.}, 236 | title = {CDCEO'21 - First Workshop on Complex Data Challenges in Earth Observation}, 237 | year = {2021}, 238 | isbn = {9781450384469}, 239 | publisher = {Association for Computing Machinery}, 240 | address = {New York, NY, USA}, 241 | url = {https://doi.org/10.1145/3459637.3482044}, 242 | booktitle = {Proceedings of the 30th ACM International Conference on Information & Knowledge Management}, 243 | pages = {4878–4879}, 244 | numpages = {2} 245 | } 246 | ``` 247 | 248 | ## Credits 249 | The competition is organized / supported by: 250 | - [Institute of Advanced Research in Artificial Intelligence, Austria](https://iarai.ac.at) 251 | - [Silesian University of Technology, Poland](https://polsl.pl) 252 | - [European Space Agency Φ-lab, Italy](https://philab.phi.esa.int/) 253 | - [Spanish State Meteorological Agency, AEMET, Spain](http://aemet.es/) 254 | -------------------------------------------------------------------------------- /utils/data_utils.py: -------------------------------------------------------------------------------- 1 | # Weather4cast 2022 Starter Kit 2 | # 3 | # Copyright (C) 2022 4 | # Institute of Advanced Research in Artificial Intelligence (IARAI) 5 | 6 | # This file is part of the Weather4cast 2022 Starter Kit. 7 | # 8 | # The Weather4cast 2022 Starter Kit is free software: you can redistribute it 9 | # and/or modify it under the terms of the GNU General Public License as 10 | # published by the Free Software Foundation, either version 3 of the License, 11 | # or (at your option) any later version. 12 | # 13 | # The Weather4cast 2022 Starter Kit is distributed in the hope that it will be 14 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | # Contributors: Aleksandra Gruca, Pedro Herruzo, David Kreil, Stephen Moran 22 | 23 | 24 | from re import VERBOSE 25 | import numpy as np 26 | import pandas as pd 27 | import yaml 28 | import h5py 29 | import pickle 30 | from torch.utils.data import DataLoader 31 | import time 32 | import torch 33 | import os 34 | 35 | from datetime import datetime, timedelta 36 | 37 | VERBOSE = False 38 | # VERBOSE = True 39 | 40 | 41 | # __________________________________________________CREATING/LOADING SAMPLE IDS____________________________________________________ 42 | 43 | 44 | def load_sample_ids( 45 | data_split, splits_df, len_seq_in, len_seq_predict, regions, generate_pkl, years, path="" 46 | ): 47 | """For loading the sample idxs of the dataset. If a pkl file is found, it will be loaded. If not, it will be generated. 48 | If you want to save a .pkl file, set generate_pkl to True in the yaml file. 49 | 50 | Args: 51 | data_split (string): The data split to load the sample idxs for. 52 | splits_df (DataFrame): The dataframe specifying what split each timepoint belongs to. Used to generate samples 53 | len_seq_in (int): The length of the input sequence. 54 | len_seq_predict (int): The length of the prediction sequence. 55 | regions (list): the regions to create samples for 56 | generate_pkl (bool): If True, a pkl file will be generated. If False, a pkl file will be loaded. 57 | path (str, optional): The path to load sample idxs from. Defaults to ''. 58 | 59 | Returns: 60 | dict: A dictionary of the sample idxs. 61 | """ 62 | 63 | print("|YEARS]", years) 64 | 65 | # if generate_pkl: 66 | # idxs_r = generate_and_cache_sequences( 67 | # data_split, splits_df, len_seq_in, len_seq_predict, regions, years, path 68 | # ) 69 | # # elif ".pkl" in path: # read pre-computed (fastest) 70 | # # print("load_sample_ids using pkl cache:", path) 71 | # # idxs_r = read_samples_ids(path, data_split) 72 | # else: 73 | idxs_r = generate_sample_ids( 74 | data_split, splits_df, len_seq_in, len_seq_predict, regions, years 75 | ) 76 | return idxs_r 77 | 78 | 79 | def generate_and_cache_sequences( 80 | split, splits_df, len_seq_in, len_seq_predict, regions, path_name, years 81 | ): 82 | """Generates and saves the the sample idxs for the dataset. This generates the sample idxs for all data splits. 83 | 84 | Args: 85 | split (string): The data split to return the sample idxs for. 86 | splits_df (DataFrame): The dataframe specifying what split each timepoint belongs to. Used to generate samples 87 | len_seq_in (_type_): The length of the input sequence. 88 | len_seq_predict (_type_): The length of the prediction sequence. 89 | regions (_type_): The regions to create samples for 90 | path_name (_type_): The path to save the sample idxs to. 91 | 92 | Returns: 93 | list: A list of the sample idxs. 94 | """ 95 | 96 | samples = {"training": [], "validation": [], "test": []} 97 | 98 | for data_split in ["training", "validation", "test"]: 99 | idxs = generate_sample_ids( 100 | data_split, splits_df, len_seq_in, len_seq_predict, regions, years 101 | ) 102 | samples[data_split] = idxs 103 | if VERBOSE: 104 | print(f"{len(idxs)} {data_split} samples") 105 | 106 | qq = samples.copy() 107 | with open(path_name, "wb") as f: 108 | pickle.dump(qq, f) 109 | return samples[split] 110 | 111 | 112 | def read_samples_ids(path, data_split): 113 | """read in sample idxs if they are already generated 114 | 115 | Args: 116 | path (String): path to pkl file with sample idxs 117 | data_split (String): data split to load sample idxs for 118 | 119 | Returns: 120 | list: list of sample idxs 121 | """ 122 | with open(path, "rb") as f: 123 | loaded_dict = pickle.load(f) 124 | return loaded_dict[data_split] 125 | 126 | 127 | def generate_sample_ids(data_split, splits_df, len_seq_in, len_seq_predict, regions, years): 128 | """generates sample idxs for a given data split 129 | 130 | Args: 131 | data_split (String): data split to load sample idxs for 132 | splits_df (DataFrame): the dataframe specifying what split each timepoint belongs to. Used to generate samples 133 | len_seq_in (int): the length of the input sequence. 134 | len_seq_predict (int): the length of the prediction sequence. 135 | regions (list): the regions to create samples for 136 | 137 | Returns: 138 | list: list of sample idxs for a specific data split 139 | """ 140 | if data_split == "training": 141 | idxs_r = get_training_idxs( 142 | splits_df, len_seq_in, len_seq_predict, data_split, regions[0], years 143 | ) 144 | for r in range(1, len(regions)): # append rest of regions to df 145 | idxs = get_training_idxs( 146 | splits_df, len_seq_in, len_seq_predict, data_split, regions[r], years 147 | ) 148 | idxs_r = idxs_r + idxs 149 | 150 | elif data_split == "validation": # Validation/Testing/Heldout Data 151 | idxs_r = get_validation_idxs( 152 | splits_df, len_seq_in, len_seq_predict, data_split, regions[0], years 153 | ) 154 | for r in range(1, len(regions)): # append rest of regions to df 155 | idxs = get_validation_idxs( 156 | splits_df, len_seq_in, len_seq_predict, data_split, regions[r], years 157 | ) 158 | idxs_r = idxs_r + idxs 159 | else: # testing 160 | idxs_r = get_test_heldout_idxs(splits_df, len_seq_in, data_split, regions[0], years) 161 | for r in range(1, len(regions)): # append rest of regions to df 162 | idxs = get_test_heldout_idxs(splits_df, len_seq_in, data_split, regions[r], years) 163 | idxs_r = idxs_r + idxs 164 | return idxs_r 165 | 166 | 167 | def get_training_idxs(df, len_seq_in, len_seq_predict, data_split, region, years): 168 | """get sample idxs for training data split 169 | Args: 170 | df (DataFrame): _description_ 171 | len_seq_in (int): length of input sequence 172 | len_seq_predict (int): length of prediction sequence 173 | data_split (String): data split to load sample idxs for 174 | region (String): region to create samples for 175 | Returns: 176 | list: list of sample idxs for training data split 177 | """ 178 | idxs = [] 179 | 180 | df = df[df['split'] == data_split] 181 | df = df[df['all_vars'] == 1] 182 | dfs= pd.DataFrame(columns = df.columns); 183 | 184 | print("years //// ", years) 185 | for year in years: 186 | dfs=pd.concat([dfs,df[df['date'].dt.year==int(year)]]); 187 | if VERBOSE: 188 | print(f"Keeping {dfs.shape[0]} {data_split} rows of {df.shape[0]} for {region} in {years}"); 189 | df=dfs; 190 | 191 | # non testing 192 | for i in range(df.shape[0] - len_seq_in - len_seq_predict + 1): 193 | # date check 194 | 195 | s_id = df.iloc[i]["date_time_str"] 196 | e_id = df.iloc[i + len_seq_in + len_seq_predict - 1]["date_time_str"] 197 | 198 | dd1, mm1, yy1 = get_day_month_year(s_id) 199 | h1, m1, s1 = get_hours_minutes_seconds(s_id) 200 | start_dt = datetime(yy1, mm1, dd1, h1, m1, s1) 201 | 202 | dd2, mm2, yy2 = get_day_month_year(e_id) 203 | h2, m2, s2 = get_hours_minutes_seconds(e_id) 204 | end_dt = datetime(yy2, mm2, dd2, h2, m2, s2) 205 | 206 | if start_dt + timedelta(hours=8, minutes=45, seconds=0) == end_dt: 207 | # print(get_future_time(df.iloc[i]['time'], (len_seq_predict * 15))) 208 | in_seq = [i + j for j in range(len_seq_in)] 209 | out_seq = [i + len_seq_in + j for j in range(len_seq_predict)] 210 | idxs.append([in_seq, out_seq, region]) 211 | 212 | return idxs 213 | 214 | 215 | def get_test_heldout_idxs(df, len_seq_in, data_split, region, years): 216 | """get sample idxs for test data split 217 | 218 | Args: 219 | df (DataFrame): _description_ 220 | len_seq_in (int): length of input sequence 221 | len_seq_predict (int): length of prediction sequence 222 | data_split (String): data split to load sample idxs for 223 | region (String): region to create samples for 224 | 225 | Returns: 226 | list: list of sample idxs for test data split 227 | """ 228 | idxs = [] 229 | 230 | split_type = f"{data_split}_in" 231 | df = df[df["split_type"] == split_type] 232 | df = df[df["all_vars"] == 1] 233 | dfs= pd.DataFrame(columns = df.columns); 234 | for year in years: 235 | dfs=pd.concat([dfs,df[df['date'].dt.year==int(year)]]); 236 | if VERBOSE: 237 | print(f"Keeping {dfs.shape[0]} {data_split} rows of {df.shape[0]} for {region} in {years}"); 238 | df=dfs; 239 | 240 | 241 | for start_index in range(0, df.shape[0], len_seq_in): 242 | in_seq = [start_index + i for i in range(len_seq_in)] 243 | test_seq = [in_seq, [], region] 244 | idxs.append(test_seq) 245 | return idxs 246 | 247 | 248 | def get_validation_idxs(df, len_seq_in, len_seq_out, data_split, region, years): 249 | """get sample idxs for validation data split 250 | 251 | Args: 252 | df (DataFrame): timepoint dataframe 253 | len_seq_in (int): length of input sequence 254 | len_seq_predict (int): length of prediction sequence 255 | data_split (String): data split to load sample idxs for 256 | region (String): region to create samples for 257 | 258 | Returns: 259 | list: list of sample idxs for validation data split 260 | """ 261 | idxs = [] 262 | split_type = f"{data_split}_in" 263 | df = df[df["split"] == data_split] 264 | df = df[df["all_vars"] == 1] 265 | dfs= pd.DataFrame(columns = df.columns); 266 | for year in years: 267 | dfs=pd.concat([dfs,df[df['date'].dt.year==int(year)]]); 268 | if VERBOSE: 269 | print(f"Keeping {dfs.shape[0]} {data_split} rows of {df.shape[0]} for {region} in {years}"); 270 | df=dfs; 271 | 272 | for i in range(df.shape[0]): 273 | if df.iloc[i]["split_type"] == split_type: 274 | input_output_seq = get_io_validation_times( 275 | df, i, len_seq_in, len_seq_out, region 276 | ) 277 | if input_output_seq: 278 | idxs.append(input_output_seq) 279 | return idxs 280 | 281 | 282 | def get_io_validation_times(df, start_index, len_seq_in, len_seq_predict, region): 283 | """get input and output times for validation data split. Checks for valid sequences 284 | 285 | Args: 286 | df (int): timepoint dataframe 287 | start_index (int): startng index of sequence 288 | len_seq_in (int): length of input sequence 289 | len_seq_predict (int): length of prediction sequence 290 | region (String): region to create sequences for 291 | 292 | Returns: 293 | list: list of input, output times and region for validation data split 294 | """ 295 | split_type_in = f"validation_in" 296 | end_index = start_index + len_seq_in + len_seq_predict - 1 297 | if end_index < len(df): 298 | seq = df[start_index:end_index] 299 | in_seq = seq[:len_seq_in] 300 | out_seq = seq[len_seq_in:] 301 | # check all input is of the same type 302 | if len(in_seq[in_seq["split_type"] == split_type_in]) != len(in_seq): 303 | return [] 304 | # convert input/output sequence to lists and return 305 | else: 306 | in_seq = [start_index + i for i in range(len_seq_in)] 307 | out_seq = [start_index + len_seq_in + i for i in range(len_seq_predict)] 308 | return [in_seq, out_seq, region] 309 | else: 310 | return [] 311 | 312 | 313 | # ______________________________________LOADING DATA_______________________________________ 314 | 315 | 316 | def load_dataset(root, data_split, regions, years, product): 317 | """load dataset from root folder and return as list 318 | Args: 319 | root (String): root folder to load dataset from 320 | data_split (String): data split to load dataset for 321 | regions (list): list of regions to load dataset for 322 | product (String): product to load dataset for e.g. satellite or radar 323 | Returns: 324 | list : full dataset 325 | """ 326 | dataset = {} 327 | if data_split == "validation": 328 | data_split = "val" 329 | elif data_split == "training": 330 | data_split = "train" 331 | 332 | if VERBOSE: 333 | print(f"Data split {data_split}") 334 | print(f"Regions {regions}") 335 | print(f"Years {years}") 336 | print(f"Product {product}") 337 | 338 | for region in regions: 339 | if VERBOSE: print(f"Region: {region}") 340 | yearly_records = {} 341 | for year in years: 342 | if VERBOSE: print(f"Year: {year}") 343 | if product == "RATE": 344 | file = f"{region}.{data_split}.rates.crop.h5" 345 | path = f"{root}/{year}/OPERA/{file}" 346 | f = h5py.File(path, "r") 347 | ds = f["rates.crop"] 348 | yearly_records[year] = ds 349 | # f.close() 350 | else: 351 | file = f"{region}.{data_split}.reflbt0.ns.h5" 352 | path = f"{root}/{year}/HRIT/{file}" 353 | f = h5py.File(path, "r") 354 | ds = f["REFL-BT"] 355 | yearly_records[year] = ds 356 | # f.close() 357 | # close file memory leak? 358 | # when done reading, close files? 359 | 360 | if VERBOSE: print(f"Done reading {region}... skipping concatenation") 361 | dataset[region] = yearly_records 362 | 363 | if VERBOSE: print(f"{data_split} Data read ... returning to dataset.)") 364 | if VERBOSE: print(f"Read {len(dataset)} regions, with each containing {len(dataset[list(dataset.keys())[0]])} years.") 365 | return dataset 366 | 367 | 368 | def get_sequence( 369 | seq, 370 | root, 371 | data_split, 372 | region, 373 | product, 374 | bands, 375 | preprocess=None, 376 | swap_time_ch=False, 377 | ds=None, 378 | ): 379 | """get data and metadata for a given sequence. 380 | 381 | Args: 382 | seq (list): list containing sequence of idxs to be retrieved 383 | root (String): root for data 384 | data_split (String): data split to load sequence for 385 | region (String): region to load sequence for 386 | product (String): product to load sequence for e.g. satellite or radar 387 | bands (list): list of bands to load sequence for 388 | preprocess (list, optional): preprocessing settings. Defaults to None. 389 | swap_time_ch (bool, optional): swap time and channel axis if set to True. Defaults to False. 390 | ds (numpy array, optional): full dataset to read from. Defaults to None. 391 | Returns: 392 | prod_seq: sequence of data and metadata 393 | mask_seq: corresponding sequence of masks 394 | """ 395 | 396 | prod_seq = [] 397 | mask_seq = [] 398 | for s in seq: 399 | prods, masks = get_file( 400 | s, root, data_split, region, product, bands, preprocess, ds 401 | ) 402 | prod_seq.append(prods) 403 | mask_seq.append(masks) 404 | # return format - time x channels x width x height 405 | mask_seq = np.asarray(mask_seq) 406 | 407 | # Swapping Axes to give shape channels x time x width x height 408 | if swap_time_ch: 409 | prod_seq = np.swapaxes(prod_seq, 0, 1) 410 | mask_seq = np.swapaxes(mask_seq, 0, 1) 411 | return np.array(prod_seq), mask_seq 412 | 413 | 414 | def get_file( 415 | sample_id, root, data_split, region, product, bands, preprocess=None, ds=None 416 | ): 417 | """Read/Preprocess data and metadata for single timepoint. 418 | 419 | Args: 420 | sample_id (int): idx to be retrieved 421 | root (String): root for data 422 | data_split (String): data split to load data point for 423 | region (String): region to load data point for 424 | product (String): product to load data point for e.g. satellite or radar 425 | bands (list): satellite bands to load data point for 426 | preprocess (list, optional): preprocessing settings. Defaults to None. 427 | ds (numpy array, optional): full dataset to read from. Defaults to None. 428 | 429 | Returns: 430 | x(numpy array): data for single timepoint 431 | masks(numpy array): masks for single timepoint 432 | """ 433 | 434 | if VERBOSE: 435 | print("\n", "_____________READING FILE_________________________") 436 | file_t = time.time() 437 | # Get file containing all neede channels for a given time - (1xCxWxH) 438 | prods = [] 439 | masks = [] 440 | 441 | x = read_file(sample_id, ds, region) 442 | x = np.float32(x) 443 | if VERBOSE: 444 | print(time.time() - file_t, "reading file time") 445 | if product == "RATE": 446 | for b in ["rainfall_rate-500X500"]: 447 | if preprocess[product][b]["mask"]: 448 | mask = create_mask(x, preprocess[product][b]["mask"]) 449 | masks.append(mask) 450 | masks = masks[0] 451 | if preprocess is not None: 452 | x = preprocess_OPERA(x, preprocess[product][b]) 453 | if VERBOSE: 454 | print(time.time() - file_t, "OPERA preprocess time") 455 | else: 456 | for j, b in enumerate(bands): 457 | if preprocess is not None: 458 | x[j] = preprocess_HRIT(x[j], preprocess[b]) 459 | if VERBOSE: 460 | print(time.time() - file_t, "HRIT preprocess time") 461 | 462 | # return format - channels x width x height 463 | if VERBOSE: 464 | print(time.time() - file_t, "Total File Read Time") 465 | return x, masks 466 | 467 | 468 | def read_file(sample_id, ds, region): 469 | previous_year_samples = 0 470 | for year in ds[region]: 471 | # print(sample_id, previous_year_samples) 472 | i = sample_id - previous_year_samples; 473 | if i < len(ds[region][year]): 474 | return ds[region][year][i] 475 | previous_year_samples += len(ds[region][year]) 476 | 477 | raise Exception(f"Sample {sample_id} not found for {region}") 478 | 479 | # ___________________PREPROCESSING FUNCTIONS_______________________________________ 480 | 481 | 482 | def crop_numpy(x, crop): 483 | """crop numpy array 484 | 485 | Args: 486 | x (numpy array): array to be cropped 487 | crop (int): crop size 488 | 489 | Returns: 490 | data(numpy array): cropped array 491 | """ 492 | return x[:, :, crop:-crop, crop:-crop] 493 | 494 | 495 | def preprocess_fn(x, preprocess, verbose=False): 496 | """Funciton to precprocess data 497 | 498 | Assumption: the mask has been previously created (otherwise won't be recovered) 499 | # 1. map values 500 | # 2. clip values out of range 501 | Args: 502 | x (numpy array): data to be preprocessed 503 | preprocess (list): preprocessing settings 504 | verbose (bool, optional): verbose preprocessing. Defaults to False. 505 | 506 | Returns: 507 | data(numpy array): preprocessed data 508 | """ 509 | 510 | if verbose: 511 | print(0, np.unique(x)) 512 | # 1 Map values 513 | for q, v in preprocess["map"]: 514 | 515 | if isinstance(q, str): 516 | if q == "nan": 517 | x[np.isnan(x)] = v 518 | elif q == "inf": 519 | x[np.isinf(x)] = v 520 | elif "greaterthan" in q: 521 | greater_v = float(q.partition("greaterthan")[2]) 522 | x[x > greater_v] = v 523 | elif "lessthan" in q: 524 | less_v = float(q.partition("lessthan")[2]) 525 | x[x < less_v] = v 526 | else: 527 | x[x == q] = v 528 | if verbose: 529 | print(1, np.unique(x, return_counts=True)) 530 | 531 | # 2 Clip values out of range 532 | m, M = preprocess["range"] 533 | x[x < m] = m 534 | x[x > M] = M 535 | if verbose: 536 | print(2, np.unique(x, return_counts=True)) 537 | 538 | return x, M 539 | 540 | 541 | def preprocess_HRIT(x, preprocess, verbose=False): 542 | """Preprocess HRIT data - standardize data, map values, clip values out of range 543 | 544 | Assumption: the mask has been previously created (otherwise won't be recovered) 545 | Args: 546 | x (numpy array): data to be preprocessed 547 | preprocess (list): preprocessing settings 548 | verbose (bool, optional): verbose preprocessing. Defaults to False. 549 | 550 | Returns: 551 | x(list): preprocessed data 552 | """ 553 | # 1, 2 554 | if verbose: 555 | print("HRIT file:") 556 | x, M = preprocess_fn(x, preprocess, verbose=verbose) 557 | 558 | # 3 - mean_std - standardisation 559 | if preprocess["standardise"]: 560 | # x = x/M 561 | mean, stdev = preprocess["mean_std"] 562 | x = x - mean 563 | x = x / stdev 564 | if verbose: 565 | print(3, np.uniquze(x, return_counts=True)) 566 | return x 567 | 568 | 569 | def preprocess_OPERA(x, preprocess, verbose=False): 570 | """Precprocess OPERA data - standardize data, map values, clip values out of range 571 | Assumption: the mask has been previously created (otherwise won't be recovered) 572 | # 1. map values 573 | # 2. clip values out of range 574 | 575 | Args: 576 | x (numpy array): data to be preprocessed 577 | preprocess (list): preprocessing settings 578 | verbose (bool, optional): verbose preprocessing. Defaults to False. 579 | 580 | Returns: 581 | x(numpy array): preprocessed data 582 | """ 583 | # 1, 2 584 | if verbose: 585 | print("OPERA file:") 586 | x, M = preprocess_fn(x, preprocess, verbose=verbose) 587 | 588 | # 3 - mean_std - standardisation 589 | if preprocess["standardise"]: 590 | mean, stdev = preprocess["mean_std"] 591 | x = x - mean 592 | x = x / stdev 593 | if preprocess["bin"]: 594 | bins = np.arange(0, 128, 0.2) 595 | x = np.digitize(x, bins) 596 | if verbose: 597 | print(3, np.unique(x, return_counts=True)) 598 | return x 599 | 600 | 601 | # __________________________________GENERAL HELPER FUNCTIONS__________________________________ 602 | 603 | 604 | def standardise_time_strings(time): 605 | if len(time) < 6: 606 | time = time.rjust(6, "0") 607 | else: 608 | return time 609 | return time 610 | 611 | 612 | def get_hours_minutes_seconds(date_time_str): 613 | h = date_time_str[9:11] 614 | m = date_time_str[11:13] 615 | s = date_time_str[13:15] 616 | return int(h), int(m), int(s) 617 | 618 | 619 | def get_day_month_year(date_time_str): 620 | yy = date_time_str[0:4] 621 | mm = date_time_str[4:6] 622 | dd = date_time_str[6:8] 623 | return int(dd), int(mm), int(yy) 624 | 625 | 626 | def time_2_channels(w, height, width): 627 | """collapse time dimension into channels - (B, C, T, H, W) -> (B, C*T, H, W) 628 | 629 | Args: 630 | w (numpy array): data 631 | height (int): image height in pixels 632 | width (int): image width in pixels 633 | 634 | Returns: 635 | w(numpy array): data with time dimension collapsed into channels 636 | """ 637 | w = np.reshape(w, (-1, height, width)) 638 | return w 639 | 640 | 641 | def channels_2_time(w, seq_time_bins, n_channels, height, width): 642 | """Recover time dimension from channels - (B, C*T, H, W) -> (B, T, C, H, W) 643 | 644 | Args: 645 | w (numpy array): data 646 | seq_time_bins (_type_): number of time bins 647 | n_channels (int): number of channels 648 | height (int): image height in pixels 649 | width (int): image width in pixels 650 | 651 | Returns: 652 | _type_: _description_ 653 | """ 654 | w = np.reshape(w, (seq_time_bins, n_channels, height, width)) 655 | return w 656 | 657 | 658 | def load_timestamps( 659 | path, types={"time": "str", "date_str": "str", "split_type": "str"} 660 | ): 661 | """load timestamps from a from csv file 662 | 663 | Args: 664 | path (String): path to the csv file 665 | types (dict, optional): types to cast columns of dataframe to. Defaults to {'time': 'str', 'date_str': 'str', 'split_type': 'str'}. 666 | 667 | Returns: 668 | Dataframe: dataframe with timestamps 669 | """ 670 | 671 | df = pd.read_csv(path, index_col=False, dtype=types) 672 | 673 | df.sort_values(by=["date_str", "time"], inplace=True) 674 | 675 | # to datetime type 676 | df["date"] = pd.to_datetime(df["date"]) 677 | 678 | # convert times to strings 679 | df["time"] = df["time"].astype(str) 680 | df["time"] = df["time"].apply(standardise_time_strings) 681 | 682 | df["date_str"] = df["date_str"].astype(str) 683 | # create date_time string 684 | df["date_time_str"] = df["date_str"] + "T" + df["time"] 685 | 686 | return df 687 | 688 | 689 | def load_config(config_path): 690 | """Load confgiuration file 691 | 692 | Args: 693 | config_path (String): path to configuration file 694 | 695 | Returns: 696 | dict: configuration file 697 | """ 698 | with open(config_path) as file: 699 | config = yaml.safe_load(file) 700 | return config 701 | 702 | 703 | def create_mask(data, mask_values, verbose=False): 704 | """Create a mask from a data array and a list of values to mask out 705 | - " 1's indicate (any kind of) missing value 706 | Args: 707 | data (numpy array): data to be masked 708 | mask_values (list): list of values to mask out 709 | verbose (bool, optional): verbose preprocessing. Defaults to False. 710 | 711 | Returns: 712 | mask(numpy array): array of mask corresponding to the data 713 | """ 714 | 715 | mask = np.full(data.shape, False, dtype=bool) 716 | for m in mask_values: 717 | if isinstance(m, str): 718 | if m == "nan": 719 | filter = np.isnan(data) 720 | elif m == "inf": 721 | filter = np.isinf(data) 722 | elif "max" in m: 723 | max_v = int(m.partition("max")[2]) 724 | filter = data > max_v 725 | elif "range" in m: 726 | range = m.partition("range") 727 | l = float(range[0]) 728 | h = float(range[2]) 729 | filter = (data >= l) & (data < h) 730 | else: 731 | filter = data == m 732 | mask = np.logical_or(mask, filter) 733 | 734 | if verbose: 735 | n_missing = np.unique(filter, return_counts=True) 736 | print("-----> total masked values:", n_missing, "\n") 737 | return mask 738 | 739 | 740 | def get_mean_std(dataset, batch_size=10): 741 | """Get the mean and stdev of the different image bands 742 | Args: 743 | times (list): timepoints to get mean from 744 | batch_size (int, optional): batch size for dataloader. Defaults to 1000. 745 | Returns: 746 | mean (list): list of band means 747 | stdev (list): list of band stdevs 748 | """ 749 | loader = DataLoader(dataset, batch_size=batch_size) 750 | nimages = 0 751 | mean = 0 752 | std = 0 753 | count = 0 754 | for batch, _, _ in loader: 755 | print(count) 756 | count += 1 757 | # Rearrange batch to be the shape of [B, C, T * W * H] 758 | batch = batch.view(batch.size(0), batch.size(1), -1) 759 | # Update total number of images 760 | nimages += batch.size(0) 761 | 762 | # Compute mean of T * W * H 763 | # Sum over samples 764 | mean += batch.mean(2).sum(0) 765 | std += batch.std(2).sum(0) 766 | # Final step - divide by number of images to get average of each band 767 | mean /= nimages 768 | std /= nimages 769 | print(np.array(mean)) 770 | return mean, std 771 | 772 | 773 | def get_mean_std_opera(dataset, batch_size=10): 774 | """Get the mean and stdev of the different image bands 775 | Args: 776 | times (list): timepoints to get mean from 777 | batch_size (int, optional): batch size for dataloader. Defaults to 1000. 778 | Returns: 779 | mean (list): list of band means 780 | stdev (list): list of band stdevs 781 | """ 782 | loader = DataLoader(dataset, batch_size=batch_size) 783 | nimages = 0 784 | mean = 0.0 785 | std = 0.0 786 | count = 0 787 | for _, _, metadata in loader: 788 | print(count) 789 | count += 1 790 | batch = metadata["OPERA_input"]["data"] 791 | # Rearrange batch to be the shape of [B, C, T * W * H] 792 | batch = batch.view(batch.size(0), batch.size(1), -1) 793 | # Update total number of images 794 | nimages += batch.size(0) 795 | 796 | # Compute mean of T * W * H 797 | # Sum over samples 798 | mean += batch.mean(2).sum(0) 799 | std += batch.std(2).sum(0) 800 | 801 | # Final step - divide by number of images to get average of each band 802 | mean /= nimages 803 | std /= nimages 804 | 805 | return mean, std 806 | 807 | 808 | # ------------------------------------- GPU Functions------------------------------------------ 809 | 810 | 811 | def get_cuda_memory_usage(gpus): 812 | """Get the GPU memory usage 813 | 814 | Args: 815 | gpus (list): list of GPUs 816 | """ 817 | for gpu in gpus: 818 | r = torch.cuda.memory_reserved(gpu) 819 | a = torch.cuda.memory_allocated(gpu) 820 | f = r - a # free inside reserved 821 | print("GPU", gpu, "CUDA memory reserved:", r, "allocated:", a, "free:", f) 822 | 823 | 824 | # --------------------------------------- Crop files-------------------------------------------- 825 | 826 | 827 | def crop_xarray(product, x_start, y_start, size): 828 | """Crop an xarray dataset 829 | - crop a squared region size 830 | - provide upper-left corner with (x_start, y_start) 831 | Args: 832 | product (xarray dataset): dataset to crop 833 | x_start (int): x start coordinate 834 | y_start (int): y start coordinate 835 | size (int): size of the crop 836 | Returns: 837 | xarray dataset: cropped dataset 838 | """ 839 | return product.isel( 840 | x=slice(x_start, x_start + size), y=slice(y_start, y_start + size) 841 | ) 842 | 843 | 844 | def prepare_crop(location, opera_k=1): 845 | """prepare the crop for both context and region of interest (roi)""" 846 | 847 | position = np.asarray(location["up_left"]) 848 | context, roi = location["context"], location["roi"] 849 | 850 | # scale if opera 851 | if opera_k != 1: 852 | context, roi, position = [opera_k * s for s in [context, roi, position]] 853 | context_size = context + roi + context 854 | 855 | context_shape = { 856 | "x_start": position[0], 857 | "y_start": position[1], 858 | "size": context_size, 859 | } 860 | position = position + context 861 | roi_shape = {"x_start": position[0], "y_start": position[1], "size": roi} 862 | return context_shape, roi_shape 863 | 864 | # --------------------------------------- Save predictions -------------------------------------------- 865 | 866 | 867 | def tensor_to_submission_file(predictions, predict_params): 868 | """saves prediction tesnor to submission .h5 file 869 | 870 | Args: 871 | predictions (numpy array): data cube of predictions 872 | predict_params (dict): dictionary of parameters for prediction 873 | """ 874 | 875 | path = os.path.join(predict_params["submission_out_dir"], 876 | str(predict_params["year_to_predict"])) 877 | if not os.path.exists(path): 878 | os.makedirs(path) 879 | 880 | submission_file_name = predict_params["region_to_predict"] + ".pred.h5" 881 | submission_path = os.path.join(path, submission_file_name) 882 | h5f = h5py.File(submission_path, "w") 883 | h5f.create_dataset("submission", data=predictions.squeeze()) 884 | h5f.close() 885 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------