From b529f7716da054aab66ad419cfc0b81d8c53d327 Mon Sep 17 00:00:00 2001 From: Adam Fekete <adam@fekete.co.uk> Date: Fri, 24 Mar 2023 11:45:54 +0100 Subject: [PATCH] build image --- .dockerignore | 2 + .gitignore | 162 ++++++++++++++++++++++++++++ .gitlab-ci.yml | 14 +++ .gitmodules | 3 + Dockerfile | 37 +++++++ README.md | 98 +++-------------- ai4stem | 1 + ai4stem.ipynb | 283 +++++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 514 insertions(+), 86 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 .gitmodules create mode 100644 Dockerfile create mode 160000 ai4stem create mode 100644 ai4stem.ipynb diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..60b028c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +.git +.gitignore \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ef0525 --- /dev/null +++ b/.gitignore @@ -0,0 +1,162 @@ +## Python: https://github.com/github/gitignore/blob/main/Python.gitignore + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..761b2f2 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,14 @@ +build: + stage: build + image: docker:latest + variables: + DOCKER_BUILDKIT: 1 + before_script: + - docker info + - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY + - docker pull $CI_REGISTRY_IMAGE:latest || true + script: + - docker build --tag $CI_REGISTRY_IMAGE:latest . + - docker push $CI_REGISTRY_IMAGE:latest + + diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..15ff4ab --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "ai4stem"] + path = ai4stem + url = https://github.com/AndreasLeitherer/ai4stem.git diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..50aea03 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,37 @@ +FROM jupyter/tensorflow-notebook + + +# ================================================================================ +# Linux applications and libraries +# ================================================================================ + +# USER root +# RUN apt update --yes \ +# && apt install --yes --quiet --no-install-recommends \ +# git \ +# && apt clean \ +# && rm -rf /var/lib/apt/lists/* + + +# ================================================================================ +# Python environment +# ================================================================================ + +WORKDIR /tmp/ + +COPY --chown=${NB_UID}:${NB_GID} ai4stem/ ./ai4stem +RUN pip install --no-cache-dir --requirement ./ai4stem/requirements.txt \ + && pip install --no-cache-dir ./ai4stem \ + && rm -rf ./ai4stem \ + && fix-permissions "${CONDA_DIR}" \ + && fix-permissions "/home/${NB_USER}" + + +# ================================================================================ +# Switch back to jovyan to avoid accidental container runs as root +# ================================================================================ + +WORKDIR ${HOME} +USER ${NB_UID} + +COPY --chown=${NB_UID}:${NB_GID} ai4stem.ipynb . diff --git a/README.md b/README.md index 4a47638..d804bc4 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,18 @@ -# AI4STEM - - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +# tutorial-ai4stem +Build docker image locally: ``` -cd existing_repo -git remote add origin https://gitlab.mpcdf.mpg.de/nomad-lab/ai-toolkits/tutorial-ai4stem.git -git branch -M main -git push -uf origin main +docker build -t gitlab-registry.mpcdf.mpg.de/nomad-lab/ai-toolkits/tutorial-ai4stem . ``` -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.mpcdf.mpg.de/nomad-lab/ai-toolkits/tutorial-ai4stem/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +Push the image to the registry: +``` +docker login gitlab-registry.mpcdf.mpg.de +docker push gitlab-registry.mpcdf.mpg.de/nomad-lab/ai-toolkits/tutorial-ai4stem +``` -## License -For open source projects, say how it is licensed. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +Run docker image: +``` +docker run --rm -v $PWD:/home/jovyan/ -p 8888:8888 gitlab-registry.mpcdf.mpg.de/nomad-lab/ai-toolkits/tutorial-ai4stem +``` \ No newline at end of file diff --git a/ai4stem b/ai4stem new file mode 160000 index 0000000..f54295c --- /dev/null +++ b/ai4stem @@ -0,0 +1 @@ +Subproject commit f54295cda648a74b86e3d8b97f8c2689ca35dd71 diff --git a/ai4stem.ipynb b/ai4stem.ipynb new file mode 100644 index 0000000..05884cf --- /dev/null +++ b/ai4stem.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "223a3d1e", + "metadata": { + "ExecuteTime": { + "end_time": "2023-02-15T09:12:03.774424Z", + "start_time": "2023-02-15T09:12:03.770625Z" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "import os\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "import cv2\n", + "from collections import defaultdict\n", + "from copy import deepcopy\n", + "\n", + "from ai4stem.utils.utils_data import load_pretrained_model, load_example_image\n", + "from ai4stem.utils.utils_fft import calc_fft\n", + "from ai4stem.utils.utils_spm import localwindow\n", + "from ai4stem.utils.utils_nn import predict_with_uncertainty" + ] + }, + { + "cell_type": "markdown", + "id": "826aebaa", + "metadata": {}, + "source": [ + "# Necessary specifications" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e33deed8", + "metadata": { + "ExecuteTime": { + "end_time": "2023-02-15T09:12:03.793233Z", + "start_time": "2023-02-15T09:12:03.775703Z" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# Specify path where to save the results:\n", + "results_folder = '.'\n", + "\n", + "input_image = load_example_image()\n", + "image_name = 'Fe_bcc'\n", + "pixel_to_angstrom = 0.12452489444788318\n", + "window_size = 12.\n", + "stride_size = [36, 36]\n", + "\n", + "# If want to visualize local windows, set to true\n", + "save_local_windows = False\n", + "local_windows_path = '.'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0b0ddbe", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plt.imshow(input_image, cmap='gray')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "827bb9ff", + "metadata": {}, + "source": [ + "The following cells do not have to be changed:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c9f141c", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "filenames = {image_name: (input_image, \n", + " pixel_to_angstrom)}\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "613cee85", + "metadata": { + "ExecuteTime": { + "end_time": "2023-02-15T09:12:04.010767Z", + "start_time": "2023-02-15T09:12:03.796800Z" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# load pretrained model\n", + "model = load_pretrained_model()\n", + "model_name = 'pretrained_model'\n", + "model.summary()" + ] + }, + { + "cell_type": "markdown", + "id": "7c86d9e0", + "metadata": {}, + "source": [ + "# Analyze image" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "12961055", + "metadata": { + "ExecuteTime": { + "end_time": "2023-02-15T09:14:59.134088Z", + "start_time": "2023-02-15T09:12:04.095860Z" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "# FFT HAADF descriptor settings\n", + "sigma = None # optional parameter\n", + "thresholding = True # very important\n", + "n_iter = 100 # MC dropout samples\n", + "\n", + "\n", + "counter = 0\n", + "results_dict = defaultdict(dict)\n", + "for key in filenames:\n", + "\n", + " dx_origin = filenames[key][1]\n", + " filename = filenames[key][0]\n", + " name = key\n", + " \n", + " if type(filename) == str:\n", + " \n", + " img = cv2.imread(filename)\n", + " image = deepcopy(img[:, :, 0])\n", + " else:\n", + " image = filename\n", + " adapted_window_size = window_size * (1. / dx_origin)\n", + " adapted_window_size = int(round(adapted_window_size))\n", + " print('For image called {}, window {} [Angstrom] corresponds to {} pixels'.format(key, window_size, adapted_window_size))\n", + "\n", + " sliced_images, spm_pos, ni, nj = localwindow(image, stride_size=stride_size, pixel_max=adapted_window_size)\n", + " np.save(os.path.join(results_folder, '{}_{}_images.npy'.format(name,\n", + " model_name)), sliced_images)\n", + " \n", + " fft_descriptors = []\n", + " for im in sliced_images:\n", + " fft_desc = calc_fft(im, sigma=sigma, thresholding=thresholding)\n", + " fft_descriptors.append(fft_desc)\n", + " np.save(os.path.join(results_folder, '{}_fft_desc.npy'.format(name)), np.asarray(fft_descriptors))\n", + "\n", + " repeated_images = np.array([np.stack([_]) for _ in fft_descriptors])\n", + " repeated_images = np.moveaxis(repeated_images, 1, -1)\n", + "\n", + "\n", + " prediction, uncertainty = predict_with_uncertainty(repeated_images, \n", + " model=model, \n", + " model_type='classification', \n", + " n_iter=n_iter)\n", + " np.save(os.path.join(results_folder, '{}_{}_predictions.npy'.format(name,\n", + " model_name)), prediction)\n", + " for key in uncertainty:\n", + " np.save(os.path.join(results_folder, '{}_{}_{}.npy'.format(name,\n", + " model_name,\n", + " key)), uncertainty[key])\n", + " argmax_pred = prediction.argmax(axis=-1)\n", + " argmax_pred = np.reshape(argmax_pred, (ni, nj))\n", + " mutinfo = uncertainty['mutual_information']\n", + " mutinfo = np.reshape(mutinfo, (ni, nj))\n", + "\n", + " results_dict[model_name][name] = {}\n", + " results_dict[model_name][name]['Prediction'] = argmax_pred\n", + " results_dict[model_name][name]['Mutual information'] = mutinfo\n", + " results_dict[model_name][name]['Input Image'] = image" + ] + }, + { + "cell_type": "markdown", + "id": "e2e15414", + "metadata": {}, + "source": [ + "# Visualize predictions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0ff4e2b", + "metadata": { + "ExecuteTime": { + "end_time": "2023-02-15T09:14:59.956188Z", + "start_time": "2023-02-15T09:14:59.135324Z" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "import matplotlib\n", + "\n", + "matplotlib.rcParams.update({'font.size': 10})\n", + "\n", + "\n", + "for key in filenames:\n", + " name = key\n", + "\n", + " argmax_pred = results_dict[model_name][name]['Prediction']\n", + " mutinfo = results_dict[model_name][name]['Mutual information']\n", + " image = results_dict[model_name][name]['Input Image']\n", + "\n", + " fig, axs = plt.subplots(1, 3, figsize=(10, 10))\n", + "\n", + "\n", + " im1 = axs[0].imshow(image, cmap='gray')\n", + " fig.colorbar(im1, ax=axs[0], orientation='vertical')\n", + "\n", + " im2 = axs[1].imshow(argmax_pred, cmap='tab20')\n", + " fig.colorbar(im2, ax=axs[1], orientation='vertical')\n", + "\n", + " im3 = axs[2].imshow(mutinfo, cmap='hot', vmin=0.0)\n", + " fig.colorbar(im3, ax=axs[2], orientation='vertical')\n", + " \n", + " axs[0].axis('off')\n", + " axs[1].axis('off')\n", + " axs[2].axis('off')\n", + "\n", + " fig.tight_layout()\n", + " \n", + " plt.show()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6272e851", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} -- GitLab